INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
I want to turn off "Turn off wifi to save power" and "Turn off bluetooth to save power" features in Ubuntu
Okay, so I'm using Ubuntu's latest LTS version as of 5/Dec/2018, and I have this in the gnome settings app:
Settings>Power ![](
How do I get these features off, as turning off these buttons just turns off WiFi or Bluetooth, it won't disable the feature.
1. **How do I keep WiFi and Bluetooth on 24/7?**
2. **_Also, I would like them to remain on during sleep mode (suspend). How do I do that?_** | These are not "Power saving features" but rather the toggles to disable your WiFi/Bluetooth adapters. The text is simply giving you a tip suggesting that you disable your WiFi/Bluetooth adapters to save power when you are not using them.
There is an answer on Ask Ubuntu in regards to keeping network adapters active during suspend: < | stackexchange-superuser | {
"answer_score": 7,
"question_score": 14,
"tags": "ubuntu, wireless networking, bluetooth, sleep, power"
} |
Multibyte characters in URL are not rendering
I have a bugging problem. For a website I made there are search engine friendly URL's generated. The only problem is there are ß-chars in the url too. Chars like ö, ï, ä, ü etc. are placed correct. But with the ß-char there is a diamond-icon with a questionmark in it. ->
I thought it had to do with the charset which is used but i've tried both UTF-8 and iso-8859-1. Both without luck.
I need to have the correct character in the url for the readability of deeplinks. | Thanks for your answers, both + 1. I've solved the problem by using the `iconv` function, which is installed by default. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "character encoding, html entities"
} |
fputcsv() add quotes to every entry?
With this code I create my CSV export file:
foreach ($data_for_export as $row) {
$data = [];
array_push($data, $row->product_id);
array_push($data, $row->product_name);
array_push($data, $row->product_code);
array_push($data, $row->text);
fputcsv($file, $data);
}
fclose($file);
Example output is:
2131,"Toys set 35", TSSET35, "Lorem ipsum dolor sit amet"
I tried it with:
preg_replace("/([a-z0-9]+)/i", '"$1"', $row->product_id)
'"'.$row->product_id.'"'
With "preg_replace" I get some times more quotes then needed...
I need there quotes on all export items, how can I do that? | Convert all data to string by **strval** function, then try to use **fwrite** instead of **fputcsv** :
function push(&$data, $item) {
$quote = chr(34); // quote " character from ASCII table
$data[] = $quote . addslashes(strval($item)) . $quote;
}
foreach ($data_for_export as $row) {
$data = [];
push($data, $row->product_id);
push($data, $row->product_name);
push($data, $row->product_code);
push($data, $row->text);
// separate array items by ',' and add the End-Of-Line character
fwrite($file, implode(',', $data) . PHP_EOL);
}
fclose($file); | stackexchange-stackoverflow | {
"answer_score": 11,
"question_score": 4,
"tags": "php, csv, export to csv, fputcsv"
} |
Getting the aspect from a raster at a specified lat/long in PostGIS
I am looking for a simple example of using `ST_Aspect()` to find the aspect at a specified lat/long pair. | The following example returns the `aspect` of a raster created from a coordinate pair:
SELECT
ST_Aspect(
ST_AsRaster('POINT(-4.45 54.36)',1,1));
----------------------------------------------------------------------------------------------------------------------------------------------
0100000100000000000000F03F000000000000F0BFCDCCCCCCCCCC11C0AE47E17A142E4B400000000000000000000000000000000000000000010001004A00000000000080BF
(1 Zeile)
Check the `ST_AsRaster` documentation to find the set of parameters that suit your use case. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "postgresql, postgis, raster, postgis raster"
} |
How to introduce Let keyword inside Linq statement with Group by
I have the following Linq statement with 'Group by' clause and would like to know how to introduce a let or any other statement to avoid repeating the sub query, `lifecycleEvents.Where(i => i.LifecycleEventId == grouping.Key).First()` in the following example
var completionTimeModels =
from timeline in processTimelines
group timeline by timeline.LifecycleEventId into grouping
select new CompletionTimeViewModel()
{
// How to avoid repeating the same query to find the life cycle event?
Name = lifecycleEvents.Where(i => i.LifecycleEventId == grouping.Key).First().LifecycleEventName,
DisplayName = lifecycleEvents.Where(i => i.LifecycleEventId == grouping.Key).First().LifecycleEventDisplayName
}; | var completionTimeModels =
from timeline in processTimelines
group timeline by timeline.LifecycleEventId into grouping
let foo = lifecycleEvents.First(i => i.LifecycleEventId == grouping.Key)
select new CompletionTimeViewModel()
{
Name = foo.LifecycleEventName,
DisplayName = foo.LifecycleEventDisplayName
}; | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 7,
"tags": "c#, .net, linq, group by"
} |
Healpy default format for lmax
I found in the Healpy documentation that `healpy.anafast` has a default value for lmax of 3*nside-1
Is there a reason for this standard? Is it a standard within HEALPix, a standard for CMB experiments, or may it has physical reasons?
Edited: When I run `anafast` on a sky map `Nside=4`, the number of Cl values I get is of length = 12. That makes me think that lmax should be `lmax=3Nside`.
However, when using generated Cl values, the first two numbers are equal to zero: the monopole is zero, the dipole is zero.
Therefore, when I set the l values by `np.arange(len(Clvalues))`, should I also remove the terms `[0,1]` for the monopole and dipole? | Spherical harmonics discretized using HEALPix (either sampled at pixel centers, or avaraged over pixel areas) form a linearly independent system up to lmax = 3 nsmax -1. (from here: HEALPX anafast) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, numpy, astronomy, healpy"
} |
how can I see the differences in a designated file between a local branch and a remote branch?
How can I see the differences in a designated file between a local branch and a remote branch?
I know this command:
git diff <local branch> <remote-tracking branch>
But it gives the differences in all files between two branches while I only care about changes of one single designated file. | Take a look at `git diff --help`, which shows you:
git diff [options] <commit> <commit> [--] [<path>...]
So, you're almost there. Instead of:
git diff <local branch> <remote-tracking branch>
You can use:
git diff <local branch> <remote-tracking branch> path/to/file | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 4,
"tags": "git, version control, git diff"
} |
Two random numbers from different intervals: compute $P(b \leq a)$
You are given two random natural numbers $a$ and $b$:
* $a$ is chosen from $[1, m]$ interval
* $b$ is chosen from $[3, m+3]$ interval
I need to compute probability of $b \leq a$ case.
Assume $m > 1$.
* * *
There are $m$ different numbers in the interval $a$ is chosen from, and there are $m + 1$ numbers in the second interval that $b$ is chosen from.
The solution from my notes from half a year ago:
$$P(b \leq a) = \underbrace{\sum_{i = 1}^{m - 2} \frac{1}{m+2}\frac{i}{m}}_{\text{confusing part}} = \frac{1}{m(m+2)}\sum_{i=1}^{m-2} i = \frac{(m-1)(m-2)}{2m(m+2)}$$
I don't understand presented solution. Not sure where the 'confusing part' came from.
Would anyone be able to show me how the thinking process looks like in solving such a task? | My result does not match the official solution.
Consider each of the possible values for $b$ which are $≤m$. We have $\\{3,4,\cdots, m\\}$ so there are $m-2$ of them. Each of these has probability $\frac 1{m+1}$ of being chosen (since there are $m+1$ possible values of $b$ with no restrictions). For each choice of $b≤m$ there are $m-b+1$ choices of $a$ that are $≥b$. Each of those can be chosen with probability $\frac 1m$. Thus the answer is $$\sum_{b=3}^{m}\frac 1{m+1}\times \frac 1m\times (m-b+1)=\frac {(m-2)(m-1)}{2m(m+1)}$$
To check, consider the case $m=3$. For that case we have $$a\in \\{1,2,3\\}\quad \&\quad b\in \\{3,4,5,6\\}$$
The only winning case is $a=b=3$ which has probability $\frac 1{12}$. The formula I wrote gives that value, the official solution does not. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "probability, discrete mathematics, summation"
} |
magit: how to set default username?
Is it possible to set a default username (i.e.: my Github user name) for magit? It is prompting for the user every time I have to push a commit.
Don't know if this may help with the answer, but I already have my username and my e-mail in `~/.gitconfig` as per magit's manual:
> The default is determined by the `user.name` and `user.email` git configuration settings. | `user.name` in your .gitconfig is only for authorship of commits, and not used for authentication. It seems you are using password authentication before pushing to github. | stackexchange-emacs | {
"answer_score": 5,
"question_score": 5,
"tags": "magit, git"
} |
Is there a command to move up and down the sidebar file list in sublime text?
I use the sidebar a lot in sublime text and I want some quick way of moving up and down the list ( preferably with a keybinding but if there is some command then I'm sure I can bind it).
For instance if I have 10 files in a folder then I can click on one and view it, but then I have to pick up the mouse to view the next or previous file. I want to be able to move to the next or previous file in the list.
I know I can use ctrl-p to search for the file but I was hoping to have a keyboard shortcut to simply move to the next file. Is there anything like this? | If you focus the sidebar with `Control+0` you can use the arrow keys to move up and down through the files. `Right Arrow` will open a folder and `Left Arrow` will close it. | stackexchange-stackoverflow | {
"answer_score": 37,
"question_score": 15,
"tags": "sublimetext2"
} |
Valid asset_pair for Kraken.com
Im trying to utilize Kraken's API. I'm looking for a list of supported `asset_pair`.
**Example:** `query_public('Ticker', {'pair': 'XETHZEUR'})` will return ticker info for ethereum in relation to euros. The asset pair in this example is `XETHZEUR`.
Does anyone have access to such a list? | the list is found here: <
Also here's a list of assets: < | stackexchange-bitcoin | {
"answer_score": 5,
"question_score": 4,
"tags": "api, kraken"
} |
Reflect a letter horizontally using CSS
I know how to reflect single letters vertically using `transform: rotate();` but not how to reflect them horizontally.
Do you know how I can reflect them horizontally?
I want to use it with the selector `.logo:first-letter {}` for my logo.
<a href="#" class="logo">RR</a>
EDIT: <
Cant use Я because I'm using a font from google which doesn't support it. | Set the `scaleX` property as a transform.
.logo:first-letter {
transform: scaleX(-1);
}
If it's always a specific letter, it might be a better idea to just use unicode for this. In your case, `CYRILLIC CAPITAL LETTER YA` (Я) will work. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 8,
"tags": "css, css transforms"
} |
Is a multi-column index generally worth it if the second column will always only have a few entries long for each entry in the first column?
If I have two columns in a table, and I plan to do lots of queries on those two columns (which would normally suggest creating a multi-column index), but I also know that each unique value in the first column will only have around 3 to 5 values in the second column, is the multi-column index still worth it vs. just having an index on the first column? Assume I don't care about the cost of creating the index, I'm strictly interested in the extent to which the multi-column index will increase the query speed over an index for just the first column. | The issue is whether the multi-column index can cover the query or at least the `where` clause (assuming your queries are referring to filtering in the `where` clause).
In general, the answer is yes. Consider data that looks like this:
x y datapage
a 1 datapage_1
a 2 datapage_2
a 3 datapage_3
b 1 datapage_4
. . .
If your query is:
select x, y
from t
where x = 'a' and y = 2;
Then, with no index, the database has to scan all data pages to find matching rows.
With an index only on `x`, the database can find all the "a" values, but it still has to load three data pages to get the `y` values.
With an index on both `x` and `y`, the database can directly go to "datapage_2". | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "mysql, sql, rdbms"
} |
Best way to clean moldy fermentation bucket
I've just had a major house move. During the move, I noticed my fermentation bucket had developed mold. Quite large mounds (to me anyway) of perhaps 0.25in diameter, in the corner of the base. Clearly I didn't do a good job of cleaning it last time I used it.
So far I've only rinsed with high pressure water - basically to remove the odour for the move. How should I best kill and clean this stuff ready for brewing? Is regular StarSan sufficient? Of course chlorine bleach would really clean it but it would leave a bad taste. Perhaps something else? Or perhaps I should just replace the bucket at chalk it up to "remember to clean the bucket properly". | StarSan is a sanitizer, not a cleaner. I'd use Craftmeister alkaline cleaner. Amazing stuff and makes PBW look weak. Or just buy a new bucket. | stackexchange-homebrew | {
"answer_score": 3,
"question_score": 1,
"tags": "sanitation, bucket, mold"
} |
What is the mean difference between 取引先との付き合い方 and 取引先の付き合い方?
What is the mean difference between and ?
Thank for support me. | If you don't know how , , and so on work yet, please learn it first: Grammar of , what is the meaning / Why can we use after and ?
So, **** means "how to get along with your business partners" or "the way to deal with business partners". Note that is a noun which by itself means something like 'communication methods'. This is the recommended choice if you want to build a formal and unambiguous sentence.
**** is an ambiguous expression since is a generic linking particle that has a wide variety of functions, one of which is to mark the subject of an action. It can mean the same thing as **** , but it can also mean "how the business partner deals with (us or someone else)". | stackexchange-japanese | {
"answer_score": 2,
"question_score": 0,
"tags": "grammar"
} |
What is difference between distinct and group by (without aggregate function)
I want to know, for removing duplicate rows, which query is better ? (faster and more optimized):
select distinct col from table;
OR
select col from table group by col;
As you see, there is not any _aggregate function_ , So which one is better ? Or in other word, what is the difference between them ? | GROUP BY lets you use aggregate functions, like AVG, MAX, MIN, SUM, and COUNT. Other hand DISTINCT just removes duplicates.
You can read this answer too : < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, group by, distinct"
} |
Private Docker registry error
I am new to docker and trying to push some images to `docker registry` which I made using self signed certificates.
docker push
<IP-Address>:5000/hello-world
But it gives following error:
The push refers to a repository
[<IP-Address>:5000/hello-world]
Get x509:
cannot validate certificate for
<IP-Address> because it doesn't contain any IP SANs
If I use Domain in place of IP-Address, docker push
<domain-name.com>:5000/hello-world
it shows error:
The push refers to a repository
[<domain-name.com>:5000/hello-world]
Get x509:
certificate signed by unknown authority
Am I missing something? How to solve this error? | See answer here step by step guide to setup private registry. Hope this will help. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "linux, ssl certificate, docker registry, docker image"
} |
Display query string in asp.net controls
I'm writing an ASP web application with VB back-end. What I'd like to do is generate a url and display this in control on the page. For example if I have a label and a button on the form. The label is blank. When the button is clicked the following code fires:
Protected Sub btnGenerate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGenerate.Click
label1.Text = "Hello"
End Sub
What I'd like to have is a url that would point to my ASP Page with the words "Hello" in the label. Is this possible? | Pass the text in query string e.g. suppose relative path of the page is /pagename.aspx , you can pass the query string as per given example below:
/pagename.aspx?text=hello
in c# write following code in Page_Load event
//You don't have to check the url all the time , so just check it if page is not posting back (first time after user visits the page and ignore all other same page post backs. Label can maintain its control state (text value) after every postback, so assign it only once to increase performance
if (!IsPostBack)
{
//Check if query string is provided or not , if it is not provided take some default text, I am taking empty string as default text.
string givenText = (Request.QueryString["text"] == null)?"":Request.QueryString["text"];
label1.Text = givenText;
}
You can also create a property for text given through query string and default text. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "asp.net, vb.net"
} |
Defining a C# Method Body at runtime (dynamically)
I have a base class that defines (among others) a certain empty virtual method (used as an event handler).
Up to now, all instances are created from a derived type, which overrides the virtual method to fill it with life. This type is generated dynamically and does all it should, but I really wonder whether Reflection (.Emit) or whatever levers the .Net framework has to offer make it possible to just modify the body of the abovementioned method.
Any ideas?
Thanks in advance! | You could make the body call a delegate and then change the delegate instead of making the method virtual and overriding it.
And if the only use of that method is as event handler, why make it a method at all? Just assign the generated function directly to the eventhandler.
You can construct an Expression Tree and then compile it into a delegate which you can then assign to the eventhandler. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c#, reflection, dynamic, proxy"
} |
Xcode 7 white screen when app is built and simulated
When I hit the run button for my app,
> the simulator just shows a white screen
however there should be a button that says "Hello World". Also, for the label,
> an error message saying "Position is ambiguous for "Hello World"
Any ideas what is going wrong here? | You need to add constraints to your hello world label. You can add constraints to a view by selecting it and pressing on one of the constraint buttons on the bottom right side of the view editor. Currently, it sounds like your label is displaying off screen. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ios, xcode"
} |
How can I create WSDL from net.tcp endpoint?
We are trying to test TCP services using SoapUI Pro and all we require to get started is a 'WSDL' or 'URI' in case of REST. Is it possible to create WSDL for/from a TCP endpoint. | If you know the url and its configured to allow showing wsdl then you can append ?`wsdl` at end of url.
Try something like in browser or soapui.
| stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "soapui"
} |
unable to bind to locking port 7054 within 45000 ms webdriver firefox
I am trying to test with selenium webdriver, I got the below error
> unable to bind to locking port 7054 within 45000 ms webdriver firefox
This is my code
IWebDriver driver=new FirefoxDriver();
I'm stuck here, can't go for feature implementation. Any one help me from out of this.
My Firefox version was `42.0` | This bind error usually occurs due to incompatibility between firefox and Selenium. Please check the version of your firefox and selenium. You might be using a older Selenium version. You can download the latest selenium server from here. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, firefox, selenium"
} |
Which design should be used in this scenario?
I have a business logic like below and I would like to know which design pattern should be used here.
Basically I have an input and number of factories which creates objects which are derived from the same base class.
Input => factory1 => Output1
Input => factory2 => Output2
Input => factoty3 => Output3
........
........
The number of factories varies. This is the kind of logic which will be enclosed in a method which will create a collection of Output1, Output2... and returns it.
Which is the right design pattern in this scenario ?
Another most matching real time example..
I have a filename/pattern and there are different Finders. One for finding the word docs matching the pattern, one for finding the excel docs. one for finding the ppt docs matching the pattern. At the end all docs(word,xl,ppts) should be returned. | It seems fairly simple as I see it and you may not need a design pattern.
Lets call this object a Processor instead of Factory so as not to confuse with the Factory pattern.
So your code could be simply like this :
interface Input;
interface Output;
interface Processor {
Output process (Input i);
}
MainClass {
List<Processor> processors = initializeProcessors();
List<Output> process(Input i) {
List<Output> outputs = ...;
foreach (Processor p in processors) {
Output o = p.process(i);
outputs.add(o);
}
return outputs;
}
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": ".net, design patterns"
} |
Grails: how to set data binding to use load method instead of get one?
If i have a form such as bellow
<input type="text" name="someCollection[0].someAssociation.id"/>
<input type="text" name="someCollection[1].someAssociation.id"/>
<input type="text" name="someCollection[2].someAssociation.id"/>
Because Grails provides automatic data binding when it encounters a _.id_ suffix, it seems Grails uses _get_ method instead of _load_ one which implies 3 queries as follows
SELECT * FROM SomeAssociationClass WHERE id = ?
SELECT * FROM SomeAssociationClass WHERE id = ?
SELECT * FROM SomeAssociationClass WHERE id = ?
I just need _load_ method because it does not hit the database unless you use other than getId() (NOT APPLIED). So, how can i customize data binding so that it uses load method ? | To avoid loading an instance of the database, we need to remove the _.id_ suffix and register a custom propertyEditor which takes care of invoking _load_ method
class AppPropertyEditorRegistrar implements PropertyEditorRegistrar {
void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Question, new PropertyEditorSupport() {
@Override
void setAsText(String value) {
setValue(Question.load(value as Long))
}
})
}
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "grails, data binding, lazy loading, grails orm"
} |
Russian characters won't show up in Mozilla
Could some on please check out this URL with Mozilla - < .
As you can see characters is displaying wrong :
!enter image description here
I don't understand where is problem, cause in all other browsers content is displaying right. | Your server response HTTP header has encoding "windows-1251", but the page itself is encoded in "UTF-8".
Here is your header:
HTTP/1.1 200 OK
Server: nginx/0.8.53
Date: Mon, 23 Jan 2012 10:11:44 GMT
Content-Type: text/html; charset=windows-1251
Connection: keep-alive
Last-Modified: Mon, 23 Jan 2012 10:03:18 GMT
ETag: "33c0537-2e1-4b72f23c06580"
Accept-Ranges: bytes
Content-Length: 737
You can either set correct encoding in HTTP response header, or change encoding on the page. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -3,
"tags": "utf 8, character encoding, http headers"
} |
SUM Values within SQL based on a column
I have a table like below:
![enter image description here](
I want to transform the data so that the end product actually looks like this:
![enter image description here](
This is easily done within Excel but i would like to be able to do this via SQL so i can automate a report.
I have tried the below code which doesn't work:
SELECT
SKU,
SUM(totals,ordered = 'Web') as Web_orders,
SUM(totals,ordered = 'App') as App_orders
FROM A
GROUP BY SKU | You can make use of case expressions:
SELECT
sku,
SUM(case when ordered = 'web' then totals else 0 end) as "web",
SUM(case when ordered = 'app' then totals else 0 end) as "app"
FROM A
GROUP BY sku | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "sql, postgresql, conditional aggregation"
} |
Backspace in Google Chrome not "back to last page"?
In the beta version of Chrome on the Mac Backspace is not working as 'back' as in virtually any other browser. It just does nothing. Is there a way to activate that or is that a known but still unresolved bug? | It really is a bug. See this issue in their bug tracker. | stackexchange-superuser | {
"answer_score": 3,
"question_score": 3,
"tags": "macos, google chrome, keymap"
} |
Why is there no parameter for the fail message for Assert.NotNull in xUnit.net?
In constract to e.g. `Assert.False` where I can supply a message to be displayed when the assert fails, e.g. `Assert.NotNull` has only one overload that just takes the object to check. Is there a reason for it?
namespace Xunit
{
public class Assert
{
// ...
public static void False(bool condition, string userMessage);
// ...
public static void NotNull(object @object);
// ...
}
} | Dogma. They believe that you should never have more than one assertion per test, thus you don't need it.
The solution, if you otherwise like xUnit, is to download the source code for just the Assert module and paste it into your project. It is separate from everything else specifically so that you can tailor it to your needs.
* * *
Here is my version of said library with messages added: < | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 6,
"tags": "c#, xunit.net"
} |
Tidally locked, and yet spinning?
Reading about Uranus almost 90° tilt, I was wondering if some rocky planet with mass concentration at one pole could possibly spin around its own axis, while still being locked to its star? Which means the more massive pole always points toward the star? | I think what you are envisioning is having one pole always pointed towards the primary star. So the planet would rotate about that pole, but then the direction of the pole would change over the course of a year to keep the pole pointing towards a star.
This phenomenon of the direction of the pole changing is called "precession". The Earth does it over a period of 26,000 years, but the pole only traces out a fairly small circle in the sky, rather than twisting about a perpendicular line like you envision.
I think your scenario is improbable at best. Planets are like gyroscopes and resist having their axes of rotation be twisted about a perpendicular axis like that. Even a planet with mass concentrations at both poles (maybe a long cigar shape) to maximize tidal force would probably end up losing the perpendicular rotation to tidal friction, and just end up rotating slowly about an axis nearly parallel to the axis of the orbit. | stackexchange-astronomy | {
"answer_score": 5,
"question_score": 3,
"tags": "planet, orbit, tidal locking"
} |
Animating background color of border in Silverlight, State precedence in VisualStateGroups
This is a silverlight/XAML question.
Not sure what I'm doing wrong, this seems to throw an error:
<ColorAnimation
Storyboard.TargetName="btnRemoveBorder"
Storyboard.TargetProperty="Background"
To="#FFDEBA29"
Duration="0" />
2nd question is... rather confused with the Selected and Focused states. Can one state take precedence over another? | Background is not a Color but instead a Brush which is why it can't be animated directly with a ColorAnimation. Instead try the following.
<ColorAnimation
Storyboard.TargetName="btnRemoveBorder"
Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
To="#FFDEBA29"
Duration="0" />
With regard to the VisualStateManager question, one state from each state group can be active. So in the case of a Button for example, it can be in both the Focused and Pressed state. For this reason, you should try to design your states and control templates in such a way that does not depend on which state becomes active first. Usually this means you shouldn't animate the same element/property in two different state groups. But technically speaking, there's nothing preventing you from doing so. Whichever state the control goes to last (using the VisualStateManager.GoToState method) will take precedence. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "silverlight, xaml, visualstategroup"
} |
Is there any PostCSS plugins for sum variables?
I just using `precss` plugin now, but i want to calculate variables in PostCSS like this
$sidebar-width: 50px;
$container-padding-left: 20px;
#sidebar {
position: absolute;
top: 0;
left: 0;
width: $sidebar-width;
z-index: 100;
}
#container {
margin-left: -$sidebar-width;
padding-left: $sidebar-width + $container-padding-left;
}
Is there any plugins for calculate `+` in postCSS?
I also tried `calc($sidebar-width + $container-padding-left);` but it doesn't work.
I looked up for < but I couldn't find that I wanted. | I found `postcss-calc` <
This was what I wanted. plugged calc module after `precss` makes it. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "css, postcss"
} |
Converting Java application to JApplet for online access
I have a difficult dilemma. I implemented a java application using Netbeans while implementing it I used JFrame and now I want to convert it to JApplet so that it can essentially function as a web service. I have lots of classes and I tried Changing JFrame to Japplet as directed in some solutions on this site but then new errors arise because of that... for example ... exit on close method not defined ... pack not defined and so on.
Could anybody give me a better solution.
Thanks a lot Any help appreciated | > ..exit on close method not defined ...
An applet is a guest in a web page and might share a JVM with other applets. Exiting the VM is like 'burning down the guest house'. Instead call `showDocument(thanksForUsingUrl)`.
> ..pack not defined and so on.
`validate()` | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "java, swing, jframe, japplet"
} |
What is the difference between !( i%2) vs (i%2 == 0)?
for (i=0;i<10;i++) {
if (i%2 == 0)
console.log( i + "is even number")
else
console.log(i + "is not even")
}
working, but
for (i=0;i<10;i++) {
if (!i%2)
console.log( i + "is even number")
else
console.log(i + "is not even")
}
not working , why ? and when would i%2 becomes true ? | Try following
for (i=0;i<10;i++) {
if (!(i%2))
console.log( i + "is even number")
else
console.log(i + "is not even")
}
You need to look at operator precedence
**What went wrong?**
As per operator precedence `!i%2` is evaluated as `(!i)%2` Hence, for every value of `i` greater than 0, `!i` becomes `false` and `false%2` is 0 | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "javascript, loops, if statement"
} |
python - how to check if matrix is sparse or not
I have a matrix and I want to check if it is sparse or not.
Things I have tried:
1. isinstance method:
if isinstance(<matrix>, scipy.sparse.csc.csc_matrix):
This works fine if I know exactly which sparse class I want to check.
2. getformat method: But it assumes that my matrix is sparse and give format
But I want a way to know if matrix is sparse or not, and should work irrespective of which sparse class.
Kindly help me. | scipy.sparse.issparse(my_matrix) | stackexchange-stackoverflow | {
"answer_score": 39,
"question_score": 26,
"tags": "python, class, matrix, sparse matrix"
} |
Редирект в .htaccess
Добрый день! Необходимо сделать редирект в .htaccess с /menu.php на /menu.php?id=3. Прописываю такое правило, но оно зацикливается:
Redirect /menu.php /menu.php?id=3
Как правильно сделать? | Параметры не учитываются при разборе. Я бы порекомендовал сделать изменения непосредственно в самом `menu.php`
if (empty($_GET['id'])) {
$id = 3;
} else {
$id = $_GET['id'];
}
А еще правильней, будет вынести эту три в конфиг, и получать это значение из него. Назвать что то типа `MENU_DEFAULT_ID` | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": ".htaccess"
} |
Execute cUrl request
I'm new to php & cUrl's so I was wondering if someone knows how to get the following command executed using php.
curl " -H "Origin: -H "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36" -H "Content-Type: application/x-www-form-urlencoded" -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" -H "Cache-Control: max-age=0" -H "Referer: -H "Connection: keep-alive" --data "confirmed=yes&id=14&from=&to=TestPerson" --compressed
Thanks in advance and sorry if this beginner stuff. I'm just trying to learn | Rewrite like this..
<?php
$ch = curl_init();
$curlconf = array(
CURLOPT_URL => "
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
'confirmed' => 'yes',
'id' => 14,
'from'=>'',
'to'=>'TestPerson',
)
);
curl_setopt_array($ch, $curlconf);
$result = curl_exec($ch);
echo $result;
curl_close($ch); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "php, curl"
} |
Creating a thread for a database in Qt: a reasonnable design or nonsense?
the application I'm trying to design with Qt is quite data intensive; it is essentially a database. I'm looking for a design that would allow me to keep the UI reactive. My guess is I should keep only the UI in the main thread and create a thread for the database.
However:
\- creating a database object inheriting from QThread doesn't seem to be a natural design (what would run() be? )
\- I assume I would need to use signals and slots for UI / core interaction; yet this feature seem to be relatively recent in Qt, so I'm wondering if my "design" is wrong.
\- QObject descendants are apparently designed to live in the thread in which they were created, so I'm concerned the communication of models (from the database thread) to the UI thread will be problematic.
Thanks for your comments. | You might consider using QtConcurrent::run(). You'll pass in the function you want. It'll spool off a thread to run the function and give you a QFuture that you can use to get the eventual result. You could poll the QFuture to see if it `isFinished()`. Better, however, may be to use QFutureWatcher which watches the QFuture for you and emits a signal when it's done. See the example code blurb in QFutureWatcher. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "c++, multithreading, qt"
} |
which are the correct answers?
let$\\{a_n\\}_{n ≥ 1}$ be a sequence of positive numbers such that
$$a_1 >a_2>a_3>...$$ then which of the following are always true ?
1. $\lim_{n \to \infty}a_n=0$
2. $\lim_{n \to \infty}\frac{a_n}{n}=0$
3. $\sum_{n=1}^{\infty}\frac{a_n}{n}$ converges
4. $\sum_{n=1}^{\infty}\frac{a_n}{n^2}$ converges
I suppose all answers are true. Then am I right? | 1. False. Take $a_n=\frac{1}{n}+1\xrightarrow[n\to\infty]{} 1$.
2. True. $0< \frac{a_n}{n} < \frac{a_1}{n} \xrightarrow[n\to\infty]{} 0$ (as $a_1$ is just a constant).
3. False. Take $a_n=\frac{1}{\ln n}$.
4. True. By comparison: $0< \frac{a_n}{n^2} < \frac{a_1}{n^2}$, and the series $\sum_{n=1}^\infty\frac{1}{n^2}$ converges. | stackexchange-math | {
"answer_score": 3,
"question_score": 0,
"tags": "real analysis, sequences and series"
} |
Heroku cron job help
How do I run the task reklamer:runall every 15 minutes in cron.rake?
I have my cron.rake file:
desc "This task is called by the Heroku cron add-on"
task :cron => :environment do
if Time.now.hour % 4 == 0 # run every four hours
puts "Updating feed..."
NewsFeed.update
puts "done."
end | Heroku only provides daily or hourly cron jobs so I think you're out of luck with running cron jobs every 15 minutes.
Instead, you could use delayed_job to run jobs every 15 minutes. At the end of each run, your job code should create another job which will run in 15 minutes. You could calculate 15 minutes from the start or the end of the job, depending on your needs. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "ruby on rails, ruby on rails 3, heroku"
} |
Why does Microsoft Excel change the characters that I copy into it?
I live in Spain and I am using the English version of Microsoft Excel installed with wine on Ubuntu. The problem is that I use my laptop at work and when I copy text into excel (text that is Spanish) the characters that are Spanish (such as é,ñ, á...etc) are changed into weird characters. How can I sort this out?
For example: Martínez José....appears as "MartÃnez José" in my spreadsheet and I really cant have it this way or my boss will kill me. :) | This is an encoding problem anyway it may be hard to solve this issue for you. But you can use **Libreoffice Calc** it looks like **Microsoft office excel** and also you can save in **Microsoft office** formats(xls-xlsx) | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 0,
"tags": "wine, microsoft office"
} |
Is it a bad practice to do redirections out of controller classes?
I'm basically attaching a listener to an event that's triggered when a controller action completes. Said listener has a dependency that calls a 3rd party API client and do some action. I.e: creates a new document in google drive).
Following the example, if the user hasn't authorized through OAuth2, the system should redirect to the OAuth page. This action would be done by the listener.
Is this a bad design? | You risk needing to attach many many listeners for this authorization concern.
Ideally you would make it cross cutting, something that gets check before the controller creating the google drive document gets invoked. If your framework does no provide any means to do this then I would explicitly add 'am I authorized to do this?' invocations at the controller and not use listeners.
When not authorized, the controller can error out with 'not authorized' which can be caught globally somehow to trigger the redirect. | stackexchange-softwareengineering | {
"answer_score": 1,
"question_score": 3,
"tags": "design, web applications"
} |
Convert int days to months and days using joda
Say I have 203 days. I want to convert that number to the string `x months y days` from today. How do I do that using joda time? (of course 203 is just an example, use z if that helps.) | EDIT: Working out the period _starting at a particular date_ is pretty easy with Joda Time. For example:
public Period getMonthsAndDays(int days, LocalDate start) {
LocalDate end = start.plusDays(days);
return new Period(start, end, PeriodType.yearMonthDay().withYearsRemoved());
}
You can then call `Period.getDays()` and `Period.getMonths()`. Just pass in today's date in the relevant time zone (which you need to consider) and you're away. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -2,
"tags": "java, jodatime"
} |
List<> remove item issue
We are using `List<object>` type as datasource for dropdownlist.
Process flow:
1. Assign value (`List<object>`) to the session in the pageload event(`!ispostback`).
2. Retrieve value from session in `ddl_SelectedIndexChanged` event
3. Remove a particular item from the list and bind to the ddl
Code:
List<Loc> locList = new List<Loc>();
locList = (List<Loc>)Session["Loc"];
locID = "xxx";
locList.RemoveAt(locList.FindIndex(FindLocation));
Problem:
Item is getting removed from the base source also (session). | The problem is that you're manipulating the list that is stored in the session, not a copy. Instead, if you do something like this:
List<Loc> locList = new List<Loc>((List<Loc>)Session["Loc"]);
locID = "xxx";
locList.RemoveAt(locList.FindIndex(FindLocation));
you're operating on a copy of the list, and the original won't change. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "c#, asp.net"
} |
Seeking Conflation tool for QGIS?
Is there a tool to do conflation in QGIS?
ArcMap has a tool but I need to use QGIS. < | There is now a plugin call Vector Bender: <
This will give you a solution for rubbersheeting.
For the edgematching, the topology checker plugin should offer a solution, but may invovle extra processing compared to ArcGIS. The plugin will at least flag areas that violate your topology rules and then you may need to manually adjust these areas. There isn't a direct replacement for the edgematching in ArcGIS: < | stackexchange-gis | {
"answer_score": 3,
"question_score": 2,
"tags": "qgis, software recommendations, conflation"
} |
SQL to Access - Sum Case to IFF
I have following SQL code that needs to be converted to MS Access SQL view.
sum(case when DATEDIFF(d, A.DUEDATE, getdate()) < 31
and A.TYPE < 7 then A.AMT
when DATEDIFF(d, A.DOEDATE1, getdate()) < 31
and A.TYPE > 6 then A.AMT *-1
else 0
end) [Current]
I'm stuck after this:
Sum(IIF(Datediff(d, A.DUEDATE, Now())<31 | Is this what you are looking for?
Sum(IIF(Datediff(d, A.DUEDATE, Now()) < 31 AND A.Type < 7, A.AMT,
IIF(DATEDIFF(d, A.DOEDATE1, getdate()) < 31 and A.TYPE > 6, -A.AMT, 0
)
) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "sql, ms access"
} |
Is an eigen recognition model picklable?
I have a python-based face recognition script running several processes (threads?) all doing different things. I am attempting to use one of these to re-train the model once the training images have been changed/updated.
I have tried sending the model through the python pipe function:
pipe.send(model)
I am not hit with any exceptions, it just hangs there indefinitely.
I fear that either the model is either unpicklable, or simply just too big! | `multiprocessing` uses `pickle` (or `cPickle`, depending on the version). Have you tried checking like this?
>>> import pickle
>>> pik = pickle.dumps(model)
>>> _model = pickle.loads(pik)
If that succeeds, it's serializable by `pickle`. If it's not, you might try using a more powerful serializer, and a fork of `multiprocessing` that utilizes said better serializer (i.e. `dill` and `pathos.multiprocessing`). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, pipe, multiprocessing, eigen"
} |
Is it possible to check if pdostatement::fetch() has results without iterating through a row?
I have a page which needs to check for results, and the way I came up with to do it is successful, but iterates through the first row of results. Is there a way I can check without iterating, or to go back to that first row without executing the query again?
I was doing this:
$q = pdo::prepare($SQL);
$q->execute(array(':foo'=> foo, 'bar'=>bar);
if(!q->fetch){
//no results;
}else{
//results;
};
It does pretty much exactly what I hoped, with the unfortunate side affect of skipping the first row of results.
I've resorted to running $q->execute() a second time. Is there a way to avoid doing this? | Just put the result of fetch into a variable:
if($row = $q->fetch()) {
// $row contains first fetched row
echo $row['coloumn_name'];
}
else
// no results | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "php, mysql, pdo"
} |
How to make a button in Xcode that globally stops AVAudioPlayer?
I'm trying to make a tableviewcell stop all sounds in the app when it is clicked. I know how to stop sounds with `soundEffect.stop() soundEffect.currentTime = 0`, but I don't know how to apply this to a cell and this doesn't work if the StopSound button is on another viewController with a different class. How do I make a function that globally stops AVAudioPlayer and apply that to a cell? | The problem is that the player is not alone. Try this.
To stop AVAudioPlayer on another ViewController you may use NotificationCenter.
Example...
First time, add function at VC, where you need to stop AVAudioPlayer.
@objc func stopAVonThisVC() {
AVaudioPlayer.stop()
}
Second, add NotificationCenter observer at this VC, and after just post on tap button.
// At VC, where you need to stop AVAudioPlayer.
NotificationCenter.default.addObserver(self, selector:
#selector(stopAVonThisVC), name: NSNotification.Name("Stop at VC1"), object: nil)
// At VC2
NotificationCenter.default.post(name: NSNotification.Name("Stop at VC1"), object: nil)
Sorry for poor english. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "swift, xcode, avaudioplayer"
} |
How I can get an Android phone to vibrate while shaking it?
I am just curious if my app would work out this way to make it vibrate when the phone is shook:
if(event.values[0] > 1.0) {
vibrator.vibrate(500);
}
else {
if(event.values[1] > 1.0)
vibrator.vibrate(500);
}
What I am doing is `SensorEventListener` and I and combining 2 listeners.
Will this work out doing it this way? I am unable to test it as I don't own an Android phone, so I am asking (programming-wise) if this is possible. | Yes, it will work that way. Just make sure to stop handling the sensor events for the 500 milliseconds the phone is vibrating.
boolean isVibrating = false;
Handler handler = new Handler(Looper.getMainLooper());
if(!isVibrating){
if(event.values[0] > 1.0) {
vibrate(500);
} else if(event.values[1] > 1.0){
vibrate(500);
}
}
void vibrate(long time){
isVibrating = true;
vibrator.vibrate(time);
handler.postDelayed(new Runnable(){
public void run(){
isVibrating = false;
}
},
time)
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "android, performance, sensors, shake, vibration"
} |
JAXB in java 6 not prefixing the correct namespace prefix in marshalled XML file
I have a schema with following attributes in schema element:
<schema xmlns=" xmlns:abc=" targetNamespace=" elementFormDefault="qualified" attributeFormDefault="unqualified">
I could compile it and get java classes. Using these classes, I filled in data in an object and marshalled it to get an XML file.
But the XML elements in this marshalled file is not having the prefix "abc".
I tweaked a little using XMLStreamWriter.setPrefix while marshalling, and I could get the XML file with all elements prefixed as "abc".
Now when I try to unmarshall the same XML file, it throws error saying :
[org.xml.sax.SAXParseException: The prefix "abc" for element "abc:Name" is not bound.]
Please help me in how to let JAXB know that abc is correct prefix.
Thank You Pradeep | The name of the prefix is meaningless. All it does is make a connection between a namespace and the tags that belong to that namespace. Whether the prefix is _abc_ or _namespace01_ or there is no prefix because the default namespace is used doesn't matter. As far as I know you can't force the usage of a prefix or the specific name of a prefix in JAXB. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "namespaces, jaxb, prefix"
} |
Converting data from matrix to vector format
I have huge set of data in an excel file in the following format
School_id percentage year subject
1100 90 2005 maths
1100 95 2006 maths
1100 81 2005 science
2310 45 2007 biology
I want to convert this data to this format
School_id year maths science biology
1100 2005 90 81
1100 2006 95
23100 2007 45
I dont have any idea for how to do this conversion. Will this be possible with excel or mysql or any other tool? Need some suggestions.
Thanks in advance | Yea so like they said pivot tables. To get your results, I had to do it using CONCATENATE function. There might be a better way. But this is how I did it:
first do a CONCATENATE column: !CONATENATE COLUMN
Then insert your pivot table and select the right options: !PIVOT TABLE
Then de-concatenate your School_id and Year !De-Concatenate 1 !De-Concatenate 2
Like I said there might be a better way to do this - but then you would just need to organize your headers the way you want them and you should have what you are looking for. Good Luck. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, excel"
} |
Again a question related to uncorrelatedness and independence.
Consider a random vector $\mathbf{Z}$ of length $N$ whose elements are i.i.d. and zero-mean. We construct two new scalar random variable $X$ and $Y$ from $\mathbf{Z}$ as follows:
$X = \langle\mathbf{a}, \mathbf{Z}\rangle = \mathbf{a}^T\mathbf{Z}$ and $Y = \langle\mathbf{b}, \mathbf{Z}\rangle = \mathbf{b}^T\mathbf{Z}$ where $\langle,\rangle$ indicates the inner product, and $\mathbf{a}$ and $\mathbf{b}$ are deterministic and orthogonal vectors, i.e., $\langle\mathbf{a},\mathbf{b}\rangle=0$.
One can easily show $X$ and $Y$ are uncorrelated, my question is we can generally show that $X$ and $Y$ are also independent!!!
I mean that for the case that $\mathbf{Z}$ follows jointly Gaussian distribution, $X$ and $Y$ are independent but what about other distributions!!!
Best, Farzad | OK, I respond because I need some reputation points...
Counterexample: $N = 2$, $a = (1,1)$, $b = (1,-1)$. Entries of $Z$ are iid uniform on {$-1,1$}. Then $X = 2$ implies $Y = 0$, such that the variables are not independent. | stackexchange-mathoverflow_net_7z | {
"answer_score": 5,
"question_score": 0,
"tags": "pr.probability"
} |
Can I restore a game from Mac to PC using steam backup/restore or by copying?
I have CSGO installed in my MacBook and I don't want to re-download at least the whole file. So I was thinking if it is possible to create a steam backup on my MacBook and restore the file on steam PC or by copying files from PC?
Is it possible for at least some file? | Unfortunately the short answer is **NO** and **NO**.
In theory it's possible to reuse part of the files (textures, audios, etc), because this ones are common between the platforms, however the binaries are completely different and due the steam method of backup (the whole thing in one file) the hash will be different. it's more or less as you try to run a PS4 game into an XBOX.
You may be able to transfer the save games between platforms. But I don't think is the case of CSGO. | stackexchange-gaming | {
"answer_score": 1,
"question_score": 0,
"tags": "steam, counter strike global offensive"
} |
"tcpdump -w 1.pcap" works, but "tcpdump -C 100 -w 1.pcap" - permission denied
I need to limit file size when I run "tcpdump -w 1.pcap". I try to do this with the key "-C", but when I add it I get error "permission denied". So:
> sudo tcpdump -w 1.pcap
tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes
^C821 packets captured
847 packets received by filter
24 packets dropped by kernel
But:
> sudo tcpdump -C 100 -w 1.pcap
tcpdump: 1.pcap: Permission denied
I run the command from my home directory and I tried to remove and create the file before running the command with different permissions, finally I have:
-rwxrwxrwx 1 root root 0 Aug 5 10:30 1.pcap
or
-rwxrwxrwx 1 fd8 users 0 Aug 5 10:30 1.pcap
Could you suggest why in the second case I can't write to the file? | I experienced similar problems when I tried to read from file, like
tcpdump -r example.cap 'icmp[icmptype] = icmp-echo'
For me AppArmor caused the problem I had to switch from 'enforcement' mode to 'complain' mode on 'tcpdump'. Run the following command as root:
aa-complain /usr/sbin/tcpdump | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 12,
"tags": "tcpdump, rights"
} |
Image upload from android app
In my application I'm uploading an image on to the server. Here in the below code I'm uploading an image from the drawable folder. But how can I upload an image from an imageview from the layout xml? similarly like _findviewbyid.imgid_
My layout name is _main.xml_ and image id is _imgid_
kindly help me...
Bitmap bitmap =
BitmapFactory.decodeResource(getResources(),R.drawable.avatar);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str)); | We can upload image using Base64 string and multipart entity
for base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
btMap.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the
byte[] b = baos.toByteArray();
base64String = Base64.encodeBytes(b);
and for multipart
HttpPost httppost = new HttpPost("
File file = new File(yourimagepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity(); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "android, image, image uploading"
} |
How to wrap text in balloon in Perl/Tk
How can I wrap the text displayed in a balloon in Perl/Tk?
my code is something like this
my $balloon1 = $mw->Balloon();
my $txt = "file Name: ".$fileName."\n"."location: ".$path;
$balloon1->attach($button, -balloonmsg=>$txt);
But this help text in balloon goes out of screen boundaries. Is there a way to wrap the text displayed in a balloon? | The Label widget inside the Balloon is advertised as the "message" subwidget and may be accessed directly using:
my $balloon1_label = $balloon1->Subwidget('message');
You can apply all `Tk::Label` configure options here, for example the `-wraplength` option:
$balloon1_label->configure(-wraplength => 100); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "perl, user interface, perltk"
} |
Prove why the shock equation is not linear.
**I need a hint not an answer before answering this question:**
Two part question:
The homogeneous shock equation is given by $u_x$ + $u$$u_y$ = 0
Part 1) Show why the shock equation is not linear. Part 2) Which linearity is the shock equation. (I get it's not linear, but it's not completely non linear).
The definition of linearity is: L(u+v) = L(u) + L(v) c* L(u) = L(c*u) I'm not sure what our operator is. Is it the derivative? Our operator is L but I don't know what our linear operator is. I can't see why this isn't linear. | You have $Lu = u_x + u u_y$, hence:
$$L(a u + b v ) = a u_x + b v_x + (a u + b v) \, (au_y + bv_y)$$
Can you take it from here? | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "partial differential equations"
} |
Saving values of variables in files
I'm making a program that uses a lot of variables and changes them constantly.
How to save those variables into another file from inside the program? | You have to use `io.open(filename, mode)` to create a file handle, then use `:write(linecontent)` and `:read("*line")` to write and read in order. From there you can "load" and "save" variables by keeping track of the line orders for each variable you use:
local f = assert(io.open("quicksave.txt", "w"))
f:write(firstVariable, "\n")
f:write(secondVariable, "\n")
f:write(thirdVariable, "\n")
f:close()
local f = assert(io.open("quicksave.txt", "r"))
firstVariable = f:read("*line")
secondVariable = f:read("*line")
thirdVariable = f:read("*line")
f:close() | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "lua, minecraft, computercraft"
} |
Why do I see plaintext credentials in wireshark using basic auth over http?
I am using Wireshark to analyse network traffic and basic auth on a local server which I set up in my network.
When authenticating with basic auth I can see the passwort and username in the "Authorization" header of my http request in Wireshark. I know that it is not secure to use basic auth over http (and maybe not even over https) but since the credentials get base64 encoded I did not expect to see them in plaintext.
Does wireshark automatically decode the base64 encoding on the credentials or did I get something wrong with how the encoding process works? | Your assumption is correct, Wireshark has decoded the Authorization header for you. You should see both the base64 string, and the decoded results.
Wireshark does more than just show raw packets, it dissects them. That's what makes the tool so convenient and powerful (or scary from a point of view). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "base64, basic authentication, wireshark, decoding"
} |
Override header Content and adding block
I have extended LUMA theme and want to customize header.
I want to add static block before logo and want to move logo to center of page which is on left side.
Final result will be
> [1] static block [2] logo (in center) [3] Search form (this is already on correct position).
Please advice how to achieve this. | **You can do this by putting DIV over your logo and search box**
Also create a "container" for your static block (inside this you can call your static block) in `logo.phtml`.
Now assign a class to each container and give them required width and float them accordingly .
So it will look like `1) Static block 2) Logo 3) Search`
I hope someone else will get idea from here , as I am posting late on question . | stackexchange-magento | {
"answer_score": 10,
"question_score": 10,
"tags": "layout, configuration, xml, header, magento 2.1.2"
} |
Autoprefixer does not work on Sublime
I following this link to add AutoPrefixer plugin to my sublimeText.
Once I press 'Cmd + Shift + P', AutoPrefix CSS is one option of the menu. However, when I choose it nothing happens.
I have a simple css for testing:
div{
transition-delay: 1s;
}
Node.js version is v0.12.5 | It seems like your are based on default settings. AutoPrefixer default version is 2.0.
Go to
> Preferences > Package Settings > Autoprefixer > Settings - User
and paste following to cover more versions.
{
"browsers": ["last 7 versions"],
"cascade": true,
"remove": true
} | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "macos, css, sublime text 3, sublime text"
} |
How to use Log4OM with multiple users?
My household has multiple licensed amateur radio operators that share the equipment (ham radio, computer, etc). We would like to use Log4OM to log our QSQs and to use the program to submit them to LOTW, eLog, QRZ, etc. However, each of us has their own corresponding accounts and we would like to keep our logs separate.
Can this be achieved via different Log4OM profiles? If so is there an easy way to specify what profile to use at start up (i.e. via the command line/shortcut)?
We are using the same Windows user account and do not want to utilize different Windows user accounts. | Loading a specific profile is quite straight forward and documented in this setting screen:
![enter image description here](
Source: <
To configure TQSL to sign with the correct LOTW key, specify a station location for each key:
![enter image description here](
And choose the appropriate location in the LOTW Settings of Log4OM:
![enter image description here]( | stackexchange-ham | {
"answer_score": 1,
"question_score": 1,
"tags": "software, logging"
} |
Why do I get blurry pictures at far distances, but sharp results up close?
I took this picture:
<
and if you look at the details (like the trees on the right side) they are all kinds of muddy. I had the same experience when trying to take some group family photos (I had the camera on a tripod then, so I don't think it was due to vibrations).
However, this picture looks just fine.
And that seems to be pretty par for the course - I've tried different aperture values and zoom lengths, but it just seems like if I'm not focusing on something up close (less than 10' or so) then I just get a trashy image.
Is there anything I can do to fix/help this besides upgrading my equipment? | From the comments, it seems like this is your problem — you're probably focusing _past_ infinity. See Why do some lenses focus past infinity?
Or, if you're not turning the ring all the way and instead relying on the marking, it may just be that the marking isn't precise enough.
Try the suggestions at Where to focus when shooting landscapes? instead. | stackexchange-photo | {
"answer_score": 12,
"question_score": 4,
"tags": "focus, image quality, blur"
} |
撮影により作成したMP4動画のファイル名を、撮影日時へ変更したい
****
MP4Windows10
GUI
**Q1**
MP4
**Q2**
MP4ffmpeg? ExifTool? | ffmpeg
MP4 MP4 - Qiita Pixel3GoogleWindows
!
ffmpeg
...
Metadata:
major_brand : mp42
minor_version : 0
compatible_brands: isommp42
creation_time : 2019-11-18 11:37:24
...
ffmpeg
ffmpeg <
#
ffmpeg -i example.mp4 -c copy -map_metadata 0 -f ffmetadata -loglevel quiet - | stackexchange-ja_stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "windows, mp4"
} |
Как вставить число из .txt файла в переменную?
Если сохранить переменную money в .txt файл, а потом попробавать его загрузить, вместо цифр будет белеберда. Как это испраить?
money = 50
while True:
a = input('выберите действие(save, load, money): ')
if a == 'save':
name_of_file = input("Придумайте название сохранению: ")
completeName = name_of_file + ".txt"
file1 = open(completeName , "w")
toFile = str(money)
file1.write(toFile)
file1.close()
print("Прогресс успешно сохранён!")
if a == 'load':
loadcode = input("Введите название вашего сохранения(Добавьте в конце .txt): ")
save = open(loadcode)
money = save
if a == 'money':
print(money) | money = 50
while True:
a = input('выберите действие(save, load, money, stop): ')
if a == 'save':
name_of_file = input("Придумайте название сохранению: ")
completeName = name_of_file + ".txt"
file1 = open(completeName , "w")
toFile = str(money)
file1.write(toFile)
file1.close()
print("Прогресс успешно сохранён!")
elif a == 'load':
loadcode = input("Введите название вашего сохранения(Добавьте в конце .txt): ")
save = open(loadcode)
money = save.read()
save.close()
elif a == 'money':
print(money)
elif a == 'stop':
break | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python"
} |
Calling function defined with function type interface
Following the interfaces section of the TypeScript docus I'm having problems with the function types. The example given is as below:
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
}
How can I use this new function? I've tried various options but am always given the following error "error TS2346: Supplied parameters do not match any signature of call target."
let isInString = mySearch({source: 'abcdefg', subString: 'c'}) // Error! | The function has 2 strings as parameters and you are passing an object with 2 string properties.
So, `let isInString = mySearch('abcdefg', 'c')` should call the function with proper arguments. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "typescript"
} |
Obtener registro con dos coincidencia en la misma tabla de relaciones
Estimados necesito obtener un registro que tenga dos relaciones, les explico:
Tengo las tablas:
> CONTENIDO: id - titulo - descripcion
>
> CATEGORIA: id - titulo
>
> CONTENIDOS_X_CATEGORIAS: idContenido - idCategoria
Siempre que quiere obtener un "contenido" que esta en una categoria lo hago asi (consulta mysql desde php):
SELECT contenidos.*
FROM contenidos
INNER JOIN contenido_x_categorias
ON contenido_x_categorias.idContenido = contenidos.id
WHERE contenido_x_categorias.idCategoria = $idCategoria
Donde `$idCategoria` es la categoria de filtro.
**La pregunta es, ¿cómo puedo hacer para buscar un contenido que este en dos categorias al mismo tiempo?**
Le agregue un `AND` al `WHERE` y obviamente no me trajo ningun resultado.
Gracias. | Los `join`s se utilizan cuando quieres obtener resultados de varias tablas y trabajar con los datos como si fuse una única tabla.
En este caso quieres obtener un contenido (que esté en dos categorías), por lo que yo haría:
SELECT *
FROM contenidos
WHERE
contenidos.id IN (
SELECT idContenido
FROM contenido_x_categorias
WHERE contenido_x_categorias.idCategoria = $idCategoria1
)
AND
contenidos.id IN (
SELECT idContenido
FROM contenido_x_categorias
WHERE contenido_x_categorias.idCategoria = $idCategoria2
)
Es posible que esta sentencia SQL se pueda optimizar. Si no tienes muchos cambios en las tablas, puedes cachear en PHP los listados de ID de producto por categoría, y así te evitas esas dos consultas extra. | stackexchange-es_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql"
} |
unsupported operand type(s) for +: 'float' and 'str' help me
I am new to python I wanted to print '12.6hellohello' in one line with the input is '4.2 3 2 hello'
This is my code
import sys
words = []
for line in sys.stdin.readlines():
words.append(line.strip())
e1 = input()
e2 = input()
e3 = input()
e4 = input()
e1 = float(e1)
e2 = int(e2)
e3 = int(e3)
word = e3*e4
print(round(e1*e2,1) + word)
I don't understand why when word is separately printed, it works but doesn't work when it is combined | `print` can print a `float` if it's passed to it, that's not the issue. The issue is, as the error message says, there's no `+` operator between a `float` and a `str`. One way to work around this is to explicitly convert the `float` to a string:
print(str(round(e1*e2,1)) + word)
# Here^ | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "python"
} |
Are the Sponsor Eagle prizes dictated by your progress?
Does the reward scale with anything else than the Sponsors perk? What decides the reward you will get from the eagle (and how much views/subs/bucks its gonna give you?) | The Sponsor Eagle randomly decides what prize you get, although Bux are rare and only appear about once a day.
However, the ability to watch an AD to increase how much you get is determined by both the size of the reward compared to your Level, and how many times you've watched an AD to increase it. The biggest prizes (including Bux) do not allow viewing to increase the reward, and once you've watched a set number of ADs in a day, you can't get any more bonuses. | stackexchange-gaming | {
"answer_score": 1,
"question_score": 2,
"tags": "pewdiepie tuber simulator"
} |
Total sql connection consuming by application
I have multiple C# applications and all applications use the same database(SQL server 2014) and same credentials(Same connection string). All application run on the same server.
Now, my question is anyhow can I get the total number of SQL connections consuming(current open connection) by particular application right now?
I.e
1. 3 connections open in Application1
2. 2 connections open in Application2
I tried using "App Name" in connection string but I don't know how to get total connection consuming by "App Name"? | Query the Dynamic Management Views:
SELECT
COUNT(*),
program_name
FROM
sys.dm_exec_connections cn
LEFT JOIN
sys.dm_exec_sessions sn
ON
sn.session_id = cn.session_id
GROUP BY
program_name | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, sql server, database connection, connection string"
} |
Android how to sort and unsorted in same button click event
how can sort and unsorted in list view, when ever i click on list view header i want to sort list of objects after next click i want to unsorted the items, for binding objects to list view i used Adapter, for sorting i used Collection.Sort(list) and | You can use a flag variable and toggle it on each click e.g. true means ascending and false means descending. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, android listview"
} |
Enumeration Type-Safety in D
What is the state and plans on type-safety of enums in D?
I expected
import std.stdio: writeln;
void main(string args[]) {
enum E {x, y, z}
E e;
writeln(e);
e = cast(E)3;
writeln(e);
}
to fail to compile because of D's otherwise strong static type/range checking or at least give an RangeException when run.
To my surprise, it instead prints
cast(E)3
Is this really the preferred default behaviour for the majority of use cases? If so have anybody written some wrapper type providing more stricter range-checking preferrably in compile-time? | `cast` means you're taking matters into your own hands, and you can do anything with it - useful, like ratchet freak said, for combining flags. (Though, in those cases, I like to give an exact type and explicit values to each item to be sure everything does what I want, so enum : ubyte { x = 1, y = 2, z = 4}, that kind of thing)
Anyway, there is a way to get runtime exceptions though in a case like this: use std.conv.to:
import std.conv;
import std.stdio;
void main() {
enum E {x, y, z}
E e;
writeln(e);
e = to!E(2); // gives z, whereas to!E(3) throws an exception
writeln(e);
}
Cool fact: to!E(string) also works. to!E("x") == E.x, and to!string(E.x) == "x". | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "casting, enums, d, enumeration, type safety"
} |
The code is required to make a random number then keepon spouting random numbers until it reaches that number, but its always the same
Here's the idea of the code: The code is required to make a random number then keepon spouting random numbers until it reaches that number, but its always the same. heres the code:
#include <stdio.h>
#include <math.h>
int rdt () {
long long int randomonium;
randomonium=rand();
return randomonium;
}
int main (){
int rd;
int no;
while(1){
rd=rand();
printf("%d\n", rd);
if (rd== rdt()){
break;
}
}
return 0;
} | You can put a `srand(time(NULL));` just before the `while` to change the random seed used by `rand()`. Don't forget to include `time.h` in the code. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c, random"
} |
Memory leaks in an iPhone app
I have the following memory leaks in my code. What does it mean? How can I fix this?
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
**int retVal = UIApplicationMain(argc, argv, nil, nil);**
[pool release];
return retVal;
}
Thanks in Advance. | That code is from your main.m file. It seems odd that this part of your code would leak, if at all??
How did you find this leak?
Are you using the simulator or a real device?
If using the simulator you can sometimes have leaks that are not leaks at all, it is always better to test these kinds of things on a real device (which you have not specified). Double check all of your release, retains etc in your code. You might just spot something you have not released. (in xcode 4 use the assistant editor I find it better to spot these kinds of things alt+cmd+enter).
Your question otherwise is hard to answer, you might want to edit it with how you found it and in what environment.
Hope some of this helps
[EDIT] saw you tagged this with cocos2D (what version are you using of that?) there are some reported issues elsewhere on SO with memory leaks using older versions of cocos2D | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "iphone, objective c, cocos2d iphone"
} |
Graph theory question, Java. Which algorithm to achieve the following
I have a graph, with X nodes and Y edges. Weighted edges. The point is to start at one node, and stop at another. Now here comes the problem;
Visualize the problem. The edges are roads, and the edge weights are the max weight limits for vehicles driving on the roads. We would like to drive the biggest truck possible from A to B. So the maximum allowed weight for a truck taking a given path is the smallest weight of all of the edges in that path. I want the largest maximum allowed weight for all paths from A to B.
Can I use some sort of Dijkstra's algorithm for this problem? I'm not sure how to express this problem in the form of an algorithm that I can implement. Any help is much appreciated.
**Update:** I tested out somethings that didn't work for me. A node would have to have one max truck for every incoming edge. | Dijkstra's algorithm should work, but your "distance" in this case is a bit weird. Your "distance" is the maximum sized truck you can get to a node. Let's call that M[v] for a node v. You need to process nodes in order from largest M[v] to smallest M[v] (opposite of normal Dijkstra), and calculate for each edge e from v to w:
M[w] = max(M[w], min(e.weight, M[v])) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "java, algorithm, graph theory"
} |
Why is ffmpeg bundled with my Electron app?
When I built my Electron app for production, I noticed `ffmpeg.dll` was included. Why is ffmpeg bundled with Electron? | You may know that electron uses chromium for desktop applications building.Chromium has a fork of `FFMPEG` that it builds from source to generate the `ffmpeg.dll` file that goes to Electron builds for Windows. You can read more about it from this link | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "electron, electron builder"
} |
Segmentation Fault when calling free()
I'm building some modular function and I'm not getting why I get a segmentation fault after freeing my module.
**My .h file**
void StringInit(String *this, char const *s)
{
this->str = strdup(s);
printf("%s\n", this->str);
}
void StringDestroy(String *this)
{
if(this == NULL || this->str == NULL)
return;
this->str = NULL;
free(this);
}
int main()
{
char *str;
String test;
str = "hello\n";
StringInit(&test, str);
StringDestroy(&test);
return(0);
} | `free` should be used to free pointers that have been allocated using `malloc`. Your `test` string has been allocated on the _stack_. As Alfe points out:
String* test = (String*)malloc(sizeof(String));
StringInit(test, str);
StringDestroy(test);
And as Adriano's answer points out, you've also allocated a new string with `strdup`. Seems like there are a myriad of issues here! | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c, unix, pointers, memory management, free"
} |
CGRectFromString() for general structs
@"{0, 1.0, 0, 1.0}"
I wish to convert the above string to a struct like this:
struct MyVector4 {
CGFloat one;
CGFloat two;
CGFloat three;
CGFloat four;
};
typedef struct MyVector4 MyVector4;
`CGRectFromString()` does the same thing, only for `CGRect`. How can I do it for my own structs? | If there is a function for rect it means that it is not working by default.
You have to create your own function something like MyVector4FromString.
You may like to to know that you can init struct object like this also.
MyVector4 v1 = {1.1, 2.2, 3.3, 4.4};
This is a very easy C syntax. so I don't think you require to init from string.
See here : 4.7 — Structs
But if you are getting string from server or from other function than yes you have to create your function to do this. You can parse string and init 4 float value.
This link will help you to divide string in multiple part : Split a String into an Array
All the best. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "ios, objective c"
} |
VIM + ctags open too many annoying buffers
I usually only works on two or three files at one time, so after mapping "Shift+H" to ":bn", I can quickly switch among these files by pressing "shift+H" several times (I don't have to use :ls plus :bn). But after jumping to/back the definitions of functions via ctags's ctrl+], it opens many buffers for new files (:ls now shows many buffers). Now as the number of opened buffers increases, it is slow to relocate to new files using "Shift+H"(:bn). Any ideas? Do you have these problems? Is it possible to hidden buffer caused by ctags or at least delete these ctags_caused buffers when code returning from jumping? Thanks.
PS: I don't like the way of using :ls to see the file you want to jump, then using:bn to switch files, since I think pressing "shift+H" is more convenient and faster.
Thanks.
\---Peter | If you are using vim then using tabs instead of buffers may solve the problem.
You can open the two or three files in separate tabs (:tabnew filename), and use the 'gT' and 'gt' normal commands to switch back and forth between the tabs.
You can modify your "shift+H" mapping to either 'gT' or 'gt'.
You can also use ctrl+w ctrl+] to jump to function definition in a new window so that you can close the new window and go back to your original window containing the buffer that you jumped from.
Also related, when I have many buffers loaded I normally rely on the ":b" command completion's feature to quickly switch to the buffer that I want based on the partial filename that I give to it. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "vi, ctags"
} |
Compute $E(\sqrt{X+Y})$ given that $X,Y$ are iid
Compute $E(\sqrt{X+Y})$ given that $X,Y$ are iid.
Assume $X,Y$ are iid both having an Exp($\lambda=1)$ distribution.
Although this is the only information provided in the question, I know that since they are independent, then the joint distribution must be $$f_{X,Y}(X,Y)=e^{-x} e^{-y}$$
Then we must integrate:
$$\int_{0}^{\infty}\int_{0}^{\infty}e^{-x}e^{-y}(x+y)^{1/2}dxdy=\int_{0}^{\infty}e^{-y}\int_{0}^{\infty}e^{-x}(x+y)^{1/2}dxdy$$
This integral seems complicated to evaluate. I tried it out and it seems like I'll have to do parts atleast twice. Wolfram says the answer is $1.32934$ and I have $1.33$ as one of the options to this question.
I want to know if there's an easier way to evaluate this. Do I even need the integral? Or perhaps is there some trick to get the answer with this integral? | One way of getting the integral slightly faster is to see that everything is in terms of $x+y$ only.
So let $z=x+y$, which ranges from $0$ to $\infty$, and then given $z$ we have $x$ ranges from $0$ to $z$. The Jacobian for this is just $1$.
Then the double integral becomes $$ \int_0^{\infty}\int_0^ze^{-z}z^{\frac{1}{2}}\,\mathrm{d}x\,\mathrm{d}z=\int_0^{\infty}e^{-z}z^{\frac{3}{2}}\,\mathrm{d}z=\Gamma\left(\frac{5}{2}\right)=\frac{3\sqrt{\pi}}{4}$$ | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "probability, integration, probability distributions, expected value"
} |
WebClient.DownloadString result is not match with Browser result 2
The following code:
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
string Url = "
return wc.DownloadString(Url);
code returns:
QTMPJA|^D~C"l ;I&3=j=iGH9ȒJ^ jTQ=HH'Qm1hF4*{x\o?
when I visit that URL in any web browser, I get:
12:29:45,A ,3540,3567,3600,3621,3690,3515,140,238204,849582597,1,20140914,122945;;1@2825@3523@3583@1700@1,1@2000@3522@3600@8700@2,1@500@3511@3640@2500@1,;19774,99736,1
is there any way to get right string?
also, I use this online Decoder, but I don't get right answer: Universal Online Decoder | In Linqpad you can run the below code, variation from Webclient. As you can see from the picture, its due to the Gzip compression which browser automatically handles. ![enter image description here](
async void Main()
{
using (var handler = new HttpClientHandler())
{
handler.AutomaticDecompression = DecompressionMethods.GZip;
using (HttpClient client = new HttpClient(handler))
{
var result = await client.GetStringAsync("
result.Dump();
}
}
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, encoding, webclient, downloadstring"
} |
how to know where to draw on the map? (Android)
I'm trying to draw something on a map using overlays. So I have the coordinates of the places I want to draw. I start my map on a certain long/latitude, and I draw using regular screen points like (1,1), (2,3) and so on. But what if the map changes? How can make prevent my drawing from "breaking"? So, to simplify and ilustrate. Lets say that I'm drawing rectangles on the screen. My rectangle has 20px/30px (sides). Do I draw the first one in (0,0). The next one could be (21,0), and the next one (0,31). So, if I slide the screen a bit to the side, how do can I make sure that I'll draw like a forth rectangle in (21,31) relative the way my screen was before.
thank you so much! | You need to associate lat, longs with the corners of your rectangle if you want them to appear at a particular location. It might be easier to do this using Maps APIs Poly line. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, maps, overlay, projection"
} |
Paypal Express Checkout capture large amounts (bigger than 10.000$) in many transactions
we have integrated Paypal Express Checkout as payment method in a website. We have found out that there is a max amount of 10.000$ or 7000€ limit per transaction. Lucky we read it, because this limit is only in Live environment (in Sandbox there isn´t any limit and it´s working fine).
In order to workaround this, what we are trying to do is:
1. Create a single authorization for total amount (i.e 19.000€).
2. Split the capture in many transactions of max. 6.000€
According to this we would have 3 transactions of 6.000€ and one more transaction of 1.000€.
I don´t know if this is the right approach, anyway we capture the first transaction ok. However, we are getting an "Authorization has already been completed" Paypal error when trying to capture the second transaction.
Do we need to send each capture with different transactionID? How should we do it? | See the comments above.
Actually the point is for Andrew Angell. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails, paypal, express checkout"
} |
add html tags in excel sheet for product descriptions
we are planning to upload products using "import products" using csv.
we have lot of descriptions , we have to display description in table format.
is there any way to add html tags in excel sheet.
please help me to find some solution.. | Yes surely you can add that. Create your data in excel sheet, save it as CSV. Excel will automatically add double quotes for that column with string as value, to be sure open csv in notepad and check you data.. | stackexchange-magento | {
"answer_score": 1,
"question_score": 0,
"tags": "product, csv, html"
} |
How to upload 6000 record to Google Datastore from csv file
< is not clearly understand. Where i should call the bulkloader.py or appcfg.py? Should i import the csv file to local Google App Engine SDK first? How to keep the upload and download data process in existing application for datastore synchronization? | Set Up remote_api, the docs have instructions for both java and python and then run bulkloader.py locally :
bulkloader.py --dump --app_id=<app-id> --url= --filename=<data-filename>
if you are using the java sdk, you will need to install the python sdk. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "python, google app engine, google cloud datastore"
} |
Making Javascript resizable handlers on the borders of HTML elements
Dear experts, I am currently working on an code that allows users to drag & resize HTML elements across the pages. I could tackle the draggable no problem. But the problem comes from resizing. I don't know how attach Event Listeners to the "borders" of this elements to trigger the resize, specifically only the "right and bottom" borders.
I am aware of the similar approach on the Jquery UI, but I do not want to use the Jquery UI.
I would like to do it myself with vanilla Javascript and Jquery API.
I have spent the whole day searching on Google for a proper tutorial but failed. If you could point me to the right direction I would really appreciate.
Dennis | jquery ui appends 8 elements on top of your draggable element. south, southwest, west... and so on. Is it what you meant? | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery, ajax"
} |
Replace files in a folder with files in other folder, using powershell
I have two folders.
1. Folder1 contains many files.
2. Folder2 is a service pack for a set of files in folder1.
I want to replace the specific files in Folder1 with the files in Folder2 via PowerShell.
Is `-Replace` the right place to start? How should I approach this?
**Update**
Get-ChildItem $hotfix | ForEach-Object {Copy-Item $_.FullName -Destination $original -force} | Sorry, I am posting the answer late. but here it is !!
so, 1\. Folder1 is named $original 2\. Folder2 is named $hotfix
Get-ChildItem $hotfix | ForEach-Object {Copy-Item $_.FullName -Destination $original -force}
This replces all the common files of $original and $hotfix with the files in $hotfix ! | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "powershell, powershell 2.0, powershell ise"
} |
VBA Macro WeekNum not defined
I'm trying to concancenate Year with WeekNum in VBA. But it said that the WeekNum Sub or Function does not defined. How can I solve this? Here is my code :
For lrow = EndRow To 2 Step -1
CurrentSheet.Cells(lrow, "AC").Value = _
CONCATENATE(Year(CurrentSheet.Cells(lrow, "K").Value), _
"/", Text(WeekNum(CurrentSheet.Cells(lrow, "K").Value), "00"))
Next lrow
*Note that I do this a line only, just using _ just for reading capability
Thanks! :) | Add `Application.WorksheetFunction` in front:
For lrow = EndRow To 2 Step -1
CurrentSheet.Cells(lrow, "AC").Value = _
CONCATENATE(Year(CurrentSheet.Cells(lrow, "K").Value), _
"/", Text(Application.WorksheetFunction.WeekNum(CurrentSheet.Cells(lrow, "K").Value), "00"))
Next lrow | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "vba, excel, week number"
} |
Adding Joptionpane in shutdownHook
Is there any way to show joptionpane in shutdownhook i.e I need to show a confirmdailog in my shutdownhook event | If there is, it won't help you.
The shutdown hooks are invoked asynchronously as part of the JVM shutdown, so a "confirm" dialog won't really confirm anything as you can't halt or reverse the shutdown process. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "java"
} |
What is the difference between getData('name') and getName()
I am using magento 1.8
And I am facing problem when I use below methods
$product->getData('name');
$product->getName();
Is they are same, I sure that they return same value[answer]. When I am using I am getting error
Fatal error: Call to a member function getData() on a non-object in
So may i know the exact difference between these two function.
Thank You, | They may be the same or they may be different. It depends on the object you are using.
If the class you instantiate contains the method `getName()` then the result you get from `getName` and `getData('name')` may be different.
You can even get an error if the class does not extend `Varien_Object` and does not have the method `getData`.
For classes that extend `Varien_Object` and do not contain the method `getName()` the results of the 2 methods are the same.
`Varien_Object` implements the method `__call` that is called if a certain method does not exist. See here how the code looks like.
So it basically maps the call of any method `getSomethingHere()` to `getData('something_here')`. It works the same for "fake" methods that start with `set`, `has` and `uns`.
More details provided here. | stackexchange-magento | {
"answer_score": 11,
"question_score": 7,
"tags": "magento 1.8, model"
} |
perl compilation is opening some manual page
I have been compiling simple perl5 program in bash by typing: perl but output is comming like this:
=over 8
=item atan2 Y,X
ATAN2 ARCTANGENT TAN TANGENT
Returns the arctangent of Y/X in the range -PI to PI.
For the tangent operation, you may use the MATH::TRIG::TAN
function, or use the familiar relation:
sub tan { sin($_[0]) / cos($_[0]) }
The return value for ATAN2(0,0) is implementation-defined; consult
your atan2(3) manpage for more information.
=back
Please help me out! | This is the output of running `perldoc -f atan2`:
atan2 Y,X
Returns the arctangent of Y/X in the range -PI to PI.
For the tangent operation, you may use the "Math::Trig::tan"
function, or use the familiar relation:
sub tan { sin($_[0]) / cos($_[0]) }
The return value for "atan2(0,0)" is implementation-defined;
consult your atan2(3) manpage for more information.
Portability issues: "atan2" in perlport.
You must be running something which dumps the POD. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "perl"
} |
Disable autoremove of old kernel versions on Fedora 37
Somewhy i can't boot on kernel version higher than 6.0.7-301 (more here). Recently Fedora automatically downloaded kernel 6.1.10, and after a few days 6.1.11. Both of them, as i said, i can't use for boot. In menu, where I select a kernel version, there is always a 3 options.
Earlier, before kernel 6.1.10 and 6.1.11 was installed, i had 6.1.7 and 6.1.9, and now they are deleted. So, as i expect, after kernel 6.1.12 will be installed, 6.0.7 will be deleted automatically and i will have no opportunity to boot (if after release of 6.1.12 the problem will not be solved).
Also, It will be useful for me to know what could I do if 6.0.7 will be anyway deleted. | Either lock the kernel, preventing updates (replace `6.0.7-301.fc30` with _your_ specific version, e.g. 6.0.7-301.fc37.x86_64):
sudo dnf versionlock add kernel-6.0.7-301.fc37
Or disable kernel updates:
sudo dnf update --exclude=kernel*
That said, you might try to reinstall Fedora -- 37 seems to be the current version, at this time, and _should_ work with latest kernel.
As for, "what could I do if 6.0.7 will be anyway deleted," **use dd to make a disk image**. You can can recover from almost _any_ new issue by restoring a recent image. | stackexchange-superuser | {
"answer_score": 0,
"question_score": 0,
"tags": "boot, fedora, kernel, linux kernel"
} |
git checkout <branch> <file path> does not match what is on <branch>
I am having a confusing issue with `git`
On `main/development` I have a file that has the most up-to-date changes of `UsersTable.tsx`
On my working branch `chore/add-linting` I am a few commits ahead, but I want to pull the latest code of `UsersTable.tsx` from `main/development`.
I performed:
$ git pull origin main/development
# oh no, I have a couple merge conflicts
# I want this file to be whatever is exactly on `main/development`
$ git checkout main/development path/to/UsersTable.tsx
Updated 1 path from f59fed63
However, the file is NOT what is `main/development`! The version that it checked out for me is still behind `main/development` and has old code.
What is going on here? I did `git fetch` and the `git pull`. | Whenever you need to restore one file, you might consider using the command `git restore` instead of the old and confusing `git checkout`.
In your case:
git fetch
git restore -SW -s origin/main/development -- path/to/UsersTable.tsx
That way, you don't pull, meaning do not merge `origin/main/development` to `chore/add-linting`, so you don't have any merge conflict to manager.
You just restore one file content from a version of another branch. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "git, version control, branch, git checkout"
} |
How to set environment variables in Jenkins?
I would like to be able to do something like:
AOEU=$(echo aoeu)
and have Jenkins set `AOEU=aoeu`.
The _Environment Variables_ section in Jenkins doesn't do that. Instead, it sets `AOEU='$(echo aoeu)'`.
How can I get Jenkins to evaluate a shell command and assign the output to an environment variable?
Eventually, I want to be able to assign the executor of a job to an environment variable that can be passed into or used by other scripts. | This can be done via EnvInject plugin in the following way:
1. Create an "Execute shell" build step that runs:
echo AOEU=$(echo aoeu) > propsfile
2. Create an _Inject environment variables_ build step and set "Properties File Path" to `propsfile`.
**Note** : This plugin is (mostly) not compatible with the Pipeline plugin. | stackexchange-stackoverflow | {
"answer_score": 238,
"question_score": 273,
"tags": "jenkins, continuous integration, environment variables"
} |
Uploading photographs
My question is regarding uploading photographs to a webserver.
I recently observed while uploading a photograph on facebook that it can upload (and by default it does) upload smaller photographs than what we request.
Now, I can think of uploading a full size photograph and compress when it reaches the server.
But how could facebook resize the picture while uploading.
`Is there any request header (I think there is not) that asks browser to upload specific size image and manipulate the exif/jpeg data in the file.`
If not, some plugin/Flash/Javascript has to read the file/images from our system. `Does web standard really allow file reading from the user system?`
Please advise.
Regards,
Mayank | Website / webserver cannot do anything with the image until it is uploaded and saved into target directory. It must receive fullsize image and then resite it to desired size [generate thumbnails, etc.]. There is no request header that you described.
Web standards don't allow reading files from user hard disk. The thing that they allow is to select file from hard disk and then send to server - initiative is on the client's side, not server's.
Is there anything more you would like to know?
**update**
See this: Flash upload image resize client side
As I said - without external mechanisms we can't do anything. But of course, if we take into account Flash, Google Gears and so on, everything is possible. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, security, file upload"
} |
Side-by-side markdown diffs no longer render newlines. Is this deliberate?
Self-explanatory title, I think.
Example here: <
![Yowzer!](
FYI Firefox 26.0 Win XP SP3. | Fixed with a Ctrl+F5 (in both FF26 and IE8, the two browsers I happened to have to hand, and in both of which I witnessed the problem).
Shoddy dependency cache management combined with an adjusted stylesheet?
This still implies the bug would affect other people. | stackexchange-meta | {
"answer_score": 1,
"question_score": 0,
"tags": "bug, status norepro, markdown, revisions list, diff"
} |
Angular Material mat-list-option
Is there a way in Material 2 to detect checkbox is true or false through the event function. Passing $event only detects mouse or keyboard on the typescript side need to detect if it is checked or unchecked.
<mat-selection-list #list >
<mat-list-option *ngFor="let aser of fo; let i = index" (click)="onAreaListControlChanged(aser.ID, aser.Name, aser.Number, $event)" checkboxPosition="before" [value]="aser.Number" [selected]="aser.selected" >
<span style="font-size:11px" >{{aser.selected}} {{aser.first}} - {{aser.Number}}</span>
</mat-list-option>
</mat-selection-list>
typescript
onAreaListControlChanged(sid, sname, snum, $event) { if(checked==true else false} | Use MatSelectionList's `selectionChange` event. The event object is a `MatSelectionListChange` which provides the clicked `MatOption` as the `option` property, which in turn gives you the `selected` (checked) value:
<mat-selection-list #list (selectionChange)="selectionChange($event.option)">
<mat-list-option
*ngFor="let aser of fo; let i = index"
(click)="onAreaListControlChanged(aser.ID, aser.Name, aser.Number, $event)"
checkboxPosition="before"
[value]="aser.Number"
[selected]="aser.selected"
>
<span style="font-size:11px"
>{{ aser.selected }} {{ aser.first }} - {{ aser.Number }}</span
>
</mat-list-option>
</mat-selection-list>
TS
selectionChange(option: MatListOption) {
console.log(option.selected);
} | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "angular, typescript, angular material2"
} |
transposing dataframe pandas
I have following file format:
SA BTSA01_U01 0 0 0 -9 G G T T
SA BTSA01_U02 0 0 0 -9 G G T T
want to transpose it using pandas, following is the code I tried:
import pandas as pd from pandas import DataFrame
def transpose(file1,file2):
source=pd.read_csv(file1,sep=None,engine='python')
dest=source.transpose()
dest.to_csv(file2)
But it did not give me the desire output,following is the output:
0
SA SA
BTSA01_U01 BTSA01_U02
0 0
0.1 0
0.2 0
-9 -9
G G
G.1 G
T T
T.1 T
I tried using some of the options like, `header=False`, `index=False` with `dest.to_csv`, but none is working, I am wondering about addition of "." and "1" in some of the values in first column, | You didn't specify `header=None` so your first line is being interpreted as column names but this will generate duplicate names which isn't allowed so you get `.1` appended.
So you need:
source=pd.read_csv(file1,sep=None,engine='python', header=None) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "pandas, transpose"
} |
TinyXML and preserving HTML Entities
I'm using TinyXml to parse some XML that has some HTML Entities embedded in text nodes. I realize that TinyXML is just an XML parser, so I don't expect or even want TinyXML to do anything to the entities. In fact I want it to leave them alone.
If I have some XML like this:
...
<blah>ü</blah>
...
Calling Value() on the TiXmlText instance I get:
"uuml;"
So TinyXml always seems to remove the ampersand. Is there any way I can get it to leave it alone so it comes out unchanged?
Appreciate any ideas.. | If you look at the TinyXML documentation you'll see that it recognizes only five character entities (`ü` is not one of them), plus Unicode code point syntax ` ` or ` `. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c, xml, html entities, tinyxml"
} |
StructureMap: How to register System.Type implementation
I want to be able to register an implementation by specifying a `System.Type`. Here's how I can do it using Castle Windsor:
var type = typeof(MessageQueueProcessorImpl); // configurable
container.Register(
Component.For<MessageQueueProcessorBase>()
.ImplementedBy(type)
I've tried the obvious with StructureMap:
var type = typeof(MessageQueueProcessorImpl); // configurable
For<MessageQueueProcessorBase>()
.Use(type) // <-- not accepted
Is this possible with StructureMap (2.6.4.1)? | You have to call `Use` and `For` the same way - either the generic versions or the versions that take a type parameter.
IContainer container = new Container(x =>
{
x.For(typeof(MessageQueueProcessorBase))
.Use(typeof(MessageQueueProcessorImpl));
});
or
IContainer container = new Container(x =>
{
x.For<MessageQueueProcessorBase>()
.Use<MessageQueueProcessorImpl>();
}); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "dependency injection, inversion of control, structuremap"
} |