INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to create a SSL certificate for a website being hosted in a IIS 7?
I'm trying to create a SSL certificate for an "old“ website being hosted in an IIS 7 server. The website currently uses `http`, but I will like to start using `https`. I'm trying to find the best and easiest way to do this, but I'm getting confused in what to do and how to do it.
I have tried reference articles like this ` and some other youtube videos, but
1. I cannot event get the application DigiCert to open on the windows machine (to buy a certificate)
2. It seems I have to buy the certificate for ~ $200 ??
Are there any (free ?) or other methods to make my current `http` site use `https`. I know `certbot` does this for me on `nginx` servers, but how to accomplish this on a windows server?
Thanks
|
You can generate a self-signed certificate from <
You can also request a trusted certificate for free from Certbot.
Or you purchase it from a trusted CA. Eg. Sectigo.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "windows, ssl, https, iis 7, certificate"
}
|
Secant and Bisection Method
What would be the example of a function for which a Secant Method fails but Bisection Method converges (to the root). In particular, if we are checking the interval $[a,b]$, then starting points for the Secant Method are $a$ and $b$.
|
Try to find a continuously differentiable function with the following properties:
* $f(a)$ and $f(b)$ have opposite signs and
* $f'(\xi) = 0$ for a $\xi \in [a,b]$
The first point ensures that the bisection methods converges. Whereas if $f'(\xi)=0$, the secant method can fail. See these lecture notes (page 101) for an example.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "numerical methods"
}
|
Where can I print out logs to see immediately in Android Studio?
I'm using Android studio and want to print out errors and warnings to somewhere like console for debugging. How can I do this? I know Logcat, but there is always full of logs and I cannot find mine.
|
Use error log to print your stacktrace. Error log has less messages and you can easily find out your message. If you are using try/catch block:
try
{
//your code
}
catch(Exception e)
{
Log.e("error tag", Log.getStackTraceString(e));
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "android, error handling, logcat"
}
|
Why iOS 7 modify my textField's border on iPad?
i'm setting up borders on my texfields. I put them without borders on
[self.localeField.layer setBackgroundColor: [[UIColor whiteColor] CGColor]];
[self.localeField.layer setBorderColor: [[NVGlobals border4MEColor] CGColor]];
[self.localeField.layer setBorderWidth: 0.5];
The problem is that between iphone and iPad app, the textfield has different border:
correct iPhone view:
!enter image description here
wrong iPad view:
!enter image description here
why?
|
Your border width is 0.5. I'm guessing your iPhone is a retina device whereas your iPad is not. With subpixel sizing on a standard (non retina based) device visual effects gets hairy. I'd avoid it if possible.
Try:
[self.localeField.layer setBorderWidth: 1.0/[UIScreen mainScreen].scale]];
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ios, iphone, ipad, uitextfield"
}
|
PostgreSQL libpq: PQNumber and column aliases
In a Postgres libpq sql there is a function PQfnumber: Returns the column number associated with the given column name.
Lets say I have a select:
select a.*, b.* from a, b where a.id = b.id
now if I will call
number = PQfnumber(pgresult, "a.id");
it will return -1.
Correct way is to call:
number = PQfnumber(pgresult, "id");
which returns position of a.id. So how would I need to call the function to get column number of b.id? The only way around it seems to write a different select:
select a.id as a_id, a.*, b.id as b_id, b.* from a, b where a.id = b.id
number = PQfnumber(pgresult, "b_id");
Any other way around this?
|
No, you've found the right way.
Of course, with `a.id = b.id` in an inner join (as in the example code), why would you care which column you were looking at? Also, there are good reasons _not_ to have just an `id` column as the primary key of every table. Even if a lot of tables have single-column integer keys, if you consistently name columns which hold a primary key to a given table, terser and more efficient syntax like `JOIN ... USING` is available.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "sql, c, postgresql, libpq"
}
|
Lost data in Tar
I had a tar file which was of size 3.5gb which held all my programming code.
I was working with git trying to learn the repositories, so I created this file as a backup, so I could work my code directory and if anything were to go wrong I could just delete and extract it.
I did this a few times and it worked great, then I restarted and remounted my drive and the tar file was not 10kb instead of 3,5gb and all its contents were gone.
What could have happened?
|
What filesystem do you use? It can be a FS failure. Try `fsck` on that partition.
And learn how to press the "accept answer" button, or you'll never get any responces.
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 0,
"tags": "tar"
}
|
Size of structure - padding and alignment
I have an explicitly sized structure as follow:
typedef struct
{
unsigned long A : 4;
unsigned long B : 12;
union
{
unsigned long C1 : 8;
unsigned long C2 : 8;
unsigned long C3 : 8;
};
unsigned long D : 8;
}FooStruct;
The total size of this struct should be 32bit (4 bytes) in theory. However, I get a 12-byte size using `sizeof` so there should be some padding and alignment happening here.
I just don't see why and where. Can someone explain to me how this structure takes 12 bytes in memory?
|
The union forces the start of a new unsigned long, and the member after the union yet another unsigned long. Assuming long is 4 bytes that means your struct will have 3 unsigned longs for a total of 12 bytes. Although a union with three equally sized members also seems odd.
If you want this to have a size of 4 bytes why not change it to:
typedef struct
{
unsigned short A : 4;
unsigned short B : 12;
union
{
unsigned char C1 : 8;
unsigned char C2 : 8;
unsigned char C3 : 8;
};
unsigned char D : 8;
}FooStruct;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c++, sizeof"
}
|
KeyDown Event is not responding till any user control is clicked or setFocus implicitly?
KeyDown Event is not responding till any user control is clicked or setFocus implicitly . I want to fire the key event after the page loads , anytime.
I tried like :
private void Page_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key.ToString() == "Escape")
{
string uri = "/Views/Music/ArtistbyAlbum";
this.NavigationService.Navigate(new Uri(uri, UriKind.Relative));
}
}
void LayoutRoot_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("hi");
}
Please help.
Thanks, Subhen
|
Unless you give focus to a control within the page you cannot get key events, that is essentially what having the focus means. The control that has focus is the control which will receive key events.
In the code behind on the page use the OnNavigatedTo event and call the `Focus` method on the first control that can receive the focus (that is the first control that is visible, enabled and has `IsTabStop` value of true).
Another approach might be to set the page `IsTabStop` to true and call `Focus` on the Page itself.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "c#, silverlight, silverlight 3.0"
}
|
Get job script directory with SGE
With the Sun Grid Engine, how can I get the directory where the job script is located, within the job script?
I need this so I can start the script with
cd script-location
to make sure it'll have access to all the necessary files. So far I have hard-coded the script directory into each script, which makes it much too easy to make mistakes.
|
The `#$ -cwd` option to your job script will guarantee that SGE places you in the submission directory automatically so that you don't have to do `cd script-location` manually. The environment variable `SGE_O_WORKDIR` is defined and available to your job script as the working directory that you submitted it from as well.
These and other things are described in the man page for qsub.
|
stackexchange-scicomp
|
{
"answer_score": 2,
"question_score": 2,
"tags": "hpc"
}
|
Should notify data-set-change out side of adapter?
I'm doing notifying data-set-change inside of `Adapter`.
like,
fun setItems(items: MutableList<IMyModel>) {
list = items
notifyDataSetChanged()
}
fun updateItems(pos: Int: item: IMyModel) {
list[pos] = item
notifyItemChanged(pos)
}
But in many tutorials, I can see they do outside of the `Adapter`.
adapter.setItems(items)
adapter.notifyDataSetChanged()
So I just wondered **if there is any reason I should notify that outside of`Adapter`?** like a bad practice?
|
Usually, you should call notify directly after changing the dataset, no matter in which class that change occurs.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, android adapter"
}
|
imported library not found after npm install
Following steps from : <
I've installed package :
npm install node-pushnotifications --save
+ [email protected]
updated 1 package and audited 244 packages in 14.663s
found 0 vulnerabilities
Using `import PushNotifications from 'node-pushnotifications';`
returns error :
> import PushNotifications from 'node-pushnotifications';
import PushNotifications from 'node-pushnotifications';
^^^^^^^^^^^^^^^^^
I'm unfamiliar with this method of importing a library. For all others I've used such as express the import is as following :
var express = require('express');
Have I missed a step ?
How to install and import PushNotifications ?
|
Node.JS `v10.4.1` does not support ES6 modules. While changing the `import` statement to `require` would work, there are a couple of other options that would also work if you want to keep the `import` syntax.
* Upgrade Node.js to Node.js v12 - With this version, you can enable the `import` syntax by adding `"type: "module"` in your `package.json`. You will also have to add a `--experimental-modules` flag while starting the server.
* Use Babel to enable `import` syntax in your application.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "node.js, npm, npm install, node modules"
}
|
Changing a value in a column to zero when the corresponding value in another column is empty
I have a dataset with 4 columns. If in one column a particular cell is empty, the value in another columns should be replaced with 0. For example:
df <- data.frame(rbind(c('A', '','W','1'),c('A','','W', '3'),c('A', 'BK','R','4'),c('B','BN','T', '12')))
The result should be this dataset:
df <- data.frame(rbind(c('A', '','W','0'),c('A','','W', '0'),c('A', 'BK','R','4'),c('B','BN','T', '12')))
Can someone help me please?
|
Assuming that your data frame really consists of factors, then you can perform following steps:
1) add '0' level to the 4th column 2) on rows where 2nd column empty, write 0 to 4th column
# create the sample data frame
df <- data.frame(rbind(c('A', '','W','1'),c('A','','W', '3'),c('A', 'BK','R','4'),c('B','BN','T', '12')))
# add a new level to the 4th column factor
df[, 4] <- factor(df[, 4], levels=c(levels(df[, 4]), '0'))
# write 0 to 4th column where 2nd column is ''
df[df[, 2] == '',4] <- '0'
If you do not need factors, you could convert the variables to character and make your life a bit easier...
In case your columns are of the class `character` in the first place, you can do just:
`df[df[, 2] == '',4] <- '0'`
As suggested by David in comments to your question
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": -3,
"tags": "r"
}
|
Finding duplicates in C
I'm trying to write a code that checks whether or not a list has duplicates in it. I start with a table of a certain (variable) number of elements (=size). So far so good, no bugs or errors. Then I make the program execute this:
for (i = 0; i < size; i++) {
while ((i + j) < size) {
j = 1;
if (table[i] == table[i + j])
printf("Duplicate: %d", table[i]);
j++;
}
}
After I compile this and run the program, it just continues scanning until infinity. Could somebody help me find the error? Thanks in advance!
|
The error being found in other answers, the proper way to do it is:
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++) // <~~
{
if (table[i]==table[j])
printf("Duplicate: %d",table[i]);
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "c, arrays, list"
}
|
How to move custom marker to front
How to move custom marker to front on google map?
I found moveToTop function for GoogleMaps Flash API, but no one for "standard" API.
|
You can set the zIndex for a new custom marker when you create it, with the zIndexProcess property on the GMarkerOptions constructor parameter.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "google maps"
}
|
Mongoose schema property with specific values
Here's my code:
var userSchema = new mongoose.Schema({
email: String,
password: String,
role: Something
});
My goal is to define the role property to have specific values ('admin', 'member', 'guest' and so on..), what's the better way to achieve this? Thanks in advance!
|
You can do enum.
var userSchema = new mongoose.Schema({
// ...
, role: { type: String, enum: ['admin', 'guest'] }
}
var user = new User({
// ...
, role: 'admin'
});
|
stackexchange-stackoverflow
|
{
"answer_score": 94,
"question_score": 33,
"tags": "javascript, node.js, mongodb, express, mongoose"
}
|
Unable to click button using Selenium JavaScript
I am not able to click the login button, my code is correct and there is no iframe or window:
const { Builder, By, Key, until } = require('selenium-webdriver');
const { expect } = require('chai');
describe('SignupTest', () => {
const driver = new Builder().forBrowser('chrome').build();
it('signup with valid email and valid password', async () => {
await driver.get('
const loginButton = driver.findElement(By.xpath("//button[contains(.,'Log In')]"));
driver.execute("arguments[0].click()",loginButton)
//await driver.findElement(By.xpath("//button[contains(.,'Log In')]")).click();
//name=email
//name=password
//name=name
//xpath=//span[contains(.,'Sign Up')]
//await driver.sleep(20000);
});
|
The element with text as **Log In** is actually within a _child_ `<span>` tag (of the `<button>` tag) and you can use either of the following Locator Strategies:
* Using `CSS_SELECTOR`:
button[data-test='login'][data-testid='login']>span
* Using `XPATH`:
//span[text()='Log In']
**Note** : You need to induce _WebDriverWait_ while you attempt to invoke `click()` on the element with text as **Log In**.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "javascript, selenium, selenium webdriver, xpath, css selectors"
}
|
In nuclear chemistry, how does a neutron split to form a proton and an electron?
I'm studying radioisotopes at the moment and balancing nuclear reactions isn't making sense in that more matter is coming out of the equation in negative β⁻ decay equations:
$$\ce{_6^{14}C -> _7^{14}N + e- + \bar{\nu_e}}$$
Notice how the original element has decayed into a new element with an unchanged mass number but an atomic number that has increased by one.
In positive β⁺ decay equations, it makes sense:
$$\ce{_{12}^{23}Mg -> _{11}^{23}Na + e+ + \nu_e}$$
How can you create something with the same mass but with another proton?
|
One neutron has changed into a proton, that's what has happened. Our convention in chemistry is to identify nuclear species by the proton number (or the "atomic number") and that is why a new nuclide with an _increased_ atomic number is formed. Both the $\beta^+$ and $\beta^-$ decay follow identical paths: in $\beta^-$ decay, a neutron changes into a proton (thus giving _no change_ in mass number and _increase_ in atomic number), whereas in $\beta^+$ decay, a proton decays into a neutron giving _no change_ in the mass number and a _decrease_ in the atomic number.
|
stackexchange-chemistry
|
{
"answer_score": 2,
"question_score": 3,
"tags": "energy, atoms, electrons, nuclear"
}
|
How to show if $f(c) > 0$ there exist a neighborhood over which $f(x)>0$?
Let $f: \mathbb{R} \rightarrow \mathbb{R}$ be a continuous at $c$ and let $f(c)>0$. Show that there exists a neighborhood $V_{\delta}(c)$ of $c$ such that if $x \in V_{\delta}(c)$ then $f(x)>0$.
The above statement is taken as a fact in Wolfe conditions proof so I thought it might be useful to have the proof.
I tried the continuity definition at $c$ to show it
$$\forall \epsilon > 0, \exists \gamma > 0 ; \\\ \forall x \in \mathbb{R}, |x-c| < \gamma \Rightarrow |f(x)-f(c)| < \epsilon$$
For the case $f(x) > f(c)$ it works. I do not know how to proceed for the other way around?
|
Recall that, in general, for $c > 0$,
$\vert b - a \vert = \vert a - b \vert < c \Longrightarrow a -c < b < a + c; \tag 1$
now with $f(x)$ continuous and
$f(c) > 0, \tag 2$
we may choose
$0 < \epsilon < f(c) \tag 3$
and then there exists a $0 < \delta \in \Bbb R$ such that
$\vert x - c \vert < \delta \Longrightarrow \vert f(x) - f(c) \vert < \epsilon; \tag 4$
but in the light of (1) this implies
$0 < f(c) - \epsilon < f(x) < f(c) + \epsilon, \tag 5$
which says that
$\vert x - c \vert < \delta \Longrightarrow f(x) > 0\. \tag 6$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "functions, continuity"
}
|
How do I loop through a list and remove an item in groovy?
I'm trying to figure out how to remove an item from a list in groovy from within a loop.
static main(args) {
def list1 = [1, 2, 3, 4]
for(num in list1){
if(num == 2)
list1.remove(num)
}
println(list1)
}
|
If you want to remove the item with _index_ 2, you can do
list = [1,2,3,4]
list.remove(2)
assert list == [1,2,4]
// or with a loop
list = [1,2,3,4]
i = list.iterator()
2.times {
i.next()
}
i.remove()
assert list == [1,2,4]
If you want to remove the (first) item with _value_ 2, you can do
list = [1,2,3,4]
list.remove(list.indexOf(2))
assert list == [1,3,4]
// or with a loop
list = [1,2,3,4]
i = list.iterator()
while (i.hasNext()) {
if (i.next() == 2) {
i.remove()
break
}
}
assert list == [1,3,4]
|
stackexchange-stackoverflow
|
{
"answer_score": 18,
"question_score": 19,
"tags": "groovy"
}
|
PHP SQL Views counter using PDO prepare()
I have a variable `$id` which gives me the `id` of the current article and this can help me to make an update query in my database on current article.
This is my code:
$vizualizari = $current_views+1;
$sql1= "UPDATE detalii_cantari SET viz = viz WHERE id = {$id};";
$q1 = $dbh->prepare($sql1);
$q1->execute(array(':viz'=>$vizualizari));
I don't get any errors but my code is still not working...
|
Your correct code is here:
$vizualizari = $current_views+1;
$sql1= "UPDATE detalii_cantari SET viz = :viz WHERE id = {$id}";
$q1 = $dbh->prepare($sql1);
$q1->execute(array(':viz'=>$vizualizari));
`;` from the end of sql is not needed here and `viz = viz` must become `viz = :viz` because of PDO.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql, sql, pdo"
}
|
How to specify a set of strings in bash command arguments
I am trying to use a type of set notation in a bash command and can't find the answer anywhere. I want to do something like:
cp combined.[txt|jpg|pdf] ~
Where this will copy all files, named combined, with txt jpg or pdf endings.
How can I do this?
|
From your description, it sounds like you want:
cp combined.{txt,jpg,pdf} ~
But I may be misunderstanding you. I'm not sure why you wrote `*.combined` instead of `combined`, given that your description simply says that the files are "named combined".
Either way, see the _Bash Reference Manual_ , §3.1 "Brace Expansion", for more information.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "linux, bash"
}
|
How rewrite URL?
I'm making a single web app.
I have a form with a POST method and an action value equal to "/login".
<form action="/login" method="POST">
<label for="mail">Email</label><input name="log" id="mail" type="text">
<label for="pass">Pass</label><input name="pass" id="pass" type="text">
<input type="submit">
When the submit button is press, server get the form, then return to the index page. But, in the address bar, I have "local:5050/login" and would have "local:5050".
Can I remove the "login" mention ?
|
Since you are making a SPA, you will not want to have the POST method of the form actually complete. Generally this is done in dart by attaching a listener on the form element, within that listener you would then do a couple of things:
1) Cancel the default action (Also see: How do I prevent an on.submit event from changing/reloading the page?)
2) Get the values you're interested in from the form (or potentially take the entire form itself)
3) Send the values via an AJAX request to the server and listen for the response from the server to verify it was valid etc.
See the Dart tutorials on forms for more information on accomplishing the other steps.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "dart"
}
|
Why is my flag on this question "disputed"?
Curious to know if I did something wrong in flagging this question as I see the flag is disputed?
The answer in question is very clearly not an answer to the question at all - not even remotely related to it. It looks just weird - like someone meant to answer a different question.
I've never seen a disputed flag, and I just read a few meta questions about disputed flags - and the answers covered justification of bad answers, wrong answers etc... but I can't see an answer covering the scenario of a total non-sequitur that isn't just a valid "Not an answer".
The answer in question is here:
How do I stop the Visual Studio Output window displaying the logger name of log4net output?
It seems to fall into the "not an answer" category as described here: "Not an Answer" flag disputed
|
You're right. This does not answer the given question. As such I've voted down and to delete, as well as flag it again. It has been removed.
A disputed flag means that someone counterflagged your flag (with the "This post has invalid flags", and a moderator agreed with him, or that the answer has been edited).
|
stackexchange-meta
|
{
"answer_score": 2,
"question_score": 3,
"tags": "discussion, support, flags, disputed flags"
}
|
C# HttpClient POST request pass already encoded data
I have already encoded data that wants to pass as is the String to HttpClient PostRequest
but FormUrlEncodedContent only accepts a dictonary as parameter
I want something like client.PostAsync(url, plain_string_content)
var content = new FormUrlEncodedContent(values);
using (var client = new HttpClient())
{
try
{
var response = client.PostAsync(url, content).GetAwaiter().GetResult();
string resp=response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return resp;
}
|
You may use `HttpClient.SendAsync`.aspx):
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post);
request.Content = new StringContent(plain_string_content);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
await client.SendAsync(request);
Note that, after all, `PostAsync` and other `HttpClient`'s methods are shortcuts of `SendAsync`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, http"
}
|
What's the best way to store App Data on OSX on a Contacts like App
I'm making a Contacts like App with the following data:
* Contact Name
* Contact Info
* Contact Emails (protected by a password, and this password is part of the Data)
etc...
I need this information at Application startup, and I've searched around and I found out Core Data. But I don't need Core Data versions, or files, no need to undo/redo, etc... I just need this data "inside" the App. At first I thought about NSUserDefaults, but I'm not sure about that.
How should I save this data?
|
Core Data is the best approach in my opponion because it's the most flexible. You could alternatively store the objects in an array and write that out to a file - though not as elegant it should work for a contact like app (since its unlikely that there will be thousands of contacts to manage).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "objective c, xcode, macos, cocoa"
}
|
java closure workaround
I have 5 buttons and I need to iterate over them to carry out some initialization actions as shown in the code below. However, Java prevents me from passing i to the function ScreenFactory.produce() since it is not final due to some closure problem that I read about. I can not make it final since then it would prevent the increment in the loop. What is the solution?
for(int i = 0; i < 5; ++i) {
levelButtons[i].setAction(ActionType.GENERAL_ACTION, new GameAction() {
@Override
public void execute(int screenID) {
Game.instance.changeScreen( ScreenFactory.produce(ScreenFactory.GAME_SCREEN, i));
}
});
TouchHandler.instance.register(levelButtons[i]);
}
|
a simple workaround would be to create a final variable inside of your closure and assign it the value of `i`:
for(int i = 0; i < 5; ++i)
{
final int finalI = i;
levelButtons[i].setAction(ActionType.GENERAL_ACTION, new GameAction()
{
@Override
public void execute(int screenID)
{
Game.instance.changeScreen( ScreenFactory.produce(ScreenFactory.GAME_SCREEN, finalI));
}
});
TouchHandler.instance.register(levelButtons[i]);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java"
}
|
how to find the index for a quantile
I'm using a pandas series and I want to find the index value that represents the quantile.
If I have:
np.random.seed(8)
s = pd.Series(np.random.rand(6), ['a', 'b', 'c', 'd', 'e', 'f'])
s
a 0.873429
b 0.968541
c 0.869195
d 0.530856
e 0.232728
f 0.011399
dtype: float64
And do
s.quantile(.5)
I get
0.70002511588475946
What I want to know is what is the index value of `s` that represents the point just before that quantile value. In this case I know the index value should be `d`.
|
Use `sort_values`, reverse the order, find all that are less than or equal to the quantile calculated, then find the `idxmax`.
(s.sort_values()[::-1] <= s.quantile(.5)).idxmax()
Or:
(s.sort_values(ascending=False) <= s.quantile(.5)).idxmax()
We can functionalize it:
def idxquantile(s, q=0.5, *args, **kwargs):
qv = s.quantile(q, *args, **kwargs)
return (s.sort_values()[::-1] <= qv).idxmax()
idxquantile(s)
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "python, pandas"
}
|
Proposing a change to JavaScript itself?
I am aware of this site:
<
However, I have not been able to find where one would go to offer a proposed change to the JavaScript language. Is doing so even open to the community at large? Finally, does the mentioned site provide a comprehensive list of proposals. I'll do a little research. I'd hate to suggest something for which a similar proposal was already made.
|
Discussions for ECMAscript (old and new proposals): <
Discussions for ECMAscript 5 only (erratas): <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 11,
"tags": "javascript"
}
|
Determining the holomorphic isometries of an open subset of $\mathbb{C}$
Let $U$ be an open and connected subset of $\mathbb{C}$. We call a function distance preserving if $|f(z)-f(w)|=|z-w|$. I wish to classify all distance preserving holomorphic functions $U\to \mathbb{C}$. I already came up with rotations and translations, but are there more and can we find all of them?
|
If $f$ is holomorphic in $U$ with $|f(z)-f(w)|=|z-w|$ for all $z,w\in U$ then $|f'(z)|=1$ for all $z \in U$.
Using the maximum modulus principle (or open-mapping theorem) it follows that $f'$ is constant, and therefore $f(z) = az+b$ with $|a|=1$, i.e. $f$ is a composition of a rotation and a translation.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "complex analysis"
}
|
Share to multiple accounts via Sharekit for iOS?
Is there a way to select multiple accounts to share to using < For example, I want the user to hit the share button, and share to multiple Facebook and Twitter accounts. Is this possible?
|
Yes, It is possible but you need to be logged in the sites before sharing the data on them. You can call function for sharing data on facebook and twitter one by one. And Sharekit provides very easy way of sharing data on multiple sites.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, ios, ipad, ios4"
}
|
How to check my answer in combinatorics problems
Combinatorics problems (combinations and permutations) are an absolutely maddening subject for me. I can seem to work my way to the answer, provided I already know the correct answer. However, I can only rarely get the correct answer on the first try. This is obviously a problem on tests.
In algebra and calculus I can usually verify that an answer is correct by working backwards or plugging the result back in to the original equation.
Is there some way to do the same for enumeration problems?
|
While I appreciate the answers given by others, my question was whether there is a way to directly check the validity of an answer to enumeration problems.
What others have helpfully suggested are more or less heuristics for arriving at the correct answer.
After thinking about this for some time, I've come to the conclusion that simulation is the only suitable answer for directly ascertaining correctness. While this is impossible for some problems due to the enormous amount of computation required to check all possibilities, reducing the problem size should allow one to check a reasonable subset of the problem.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 6,
"tags": "combinatorics, soft question"
}
|
What's the Windows ping -t (continue until interrupted) equivalent in iputils ping
In windows 8 I used to do in run:
ping 166.18.0.1 -t
where 166.18.0.1 is my DNS IP(suppose).
How to do this same thing in ubuntu? I have already tried this in the terminal window but it shows an error:
option requires an argument t
So how to do this?
|
Only `ping 166.18.0.1` would do.
In Ubuntu by default `ping` continues to run indefinitely unless you mention a limit (by the `-c` option), so `ping 166.18.0.1` is the same as windows `ping 166.18.0.1 -t`.
In Ubuntu the `-t` option of `ping` is to set a TTL value, as you have inserted the `-t` option without giving a TTL value you are getting the error saying you need to give a value to `-t`.
If you need to change the ICMP packet size from 64 bytes to 32 bytes:
ping -s 24 166.18.0.1
As 8 byte ICMP header is added so the total packet size would be 24+8=32 bytes.
Check `man ping` to get more idea.
|
stackexchange-askubuntu
|
{
"answer_score": 6,
"question_score": 1,
"tags": "windows, ping"
}
|
Wordpress 404 without trailing slash
I know this has probably been answered as it seems a common question but I am having problems getting the solutions around working for me.
I have a wordpress site in a sub directory of another site. when i try and call < i get redirected and a 404 error but when i call < the page renders as expected.
The solution that keeps coming up seems to be
# and does not end with a slash
RewriteCond %{REQUEST_URI} !/$
# then add a trailing slash and redirect
RewriteRule (.*) $1/ [R=301,L]
but every time i request the page without the trailing slash i get redirected to <
the subfolder the blog has been installed is within the webroot of a cakephp app which i think might have something to do with it?
|
I found the answer to this after more digging around on the net
it was solved for my by adding this to the root .htaccess
RewriteRule ^blog$ blog/ [L]
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "wordpress, .htaccess, cakephp, http status code 404"
}
|
Postgres consecutive time intervals
The table:
timestamp
---------------------
2018-01-15 14:31:23
2018-01-15 14:31:25
2018-01-15 14:31:26
2018-01-15 14:31:28
2018-01-15 14:31:29
2018-01-15 14:31:30
2018-01-15 14:31:35
It would be really helpful if someone shows how to get consecutive time intervals using sql. Consequent means that it has seconds followed one by one, if there is a gap in more than 1 second it is not consequent, and should be counted as separate interval.
The following is expected result:
result
--------
1
2
3
1
|
I see. You can use `row_number()` trick for this:
select grp, count(*)
from (select t.*,
(time_stamp - row_number() over (order by timestamp) * interval '1 second') as grp
from t
) t
group by grp
order by min(timestamp);
The idea is to subtract a sequence of numbers from the timestamp. Timestamps that are in a sequence will all end up with the same value. That appears to be the groups that you want.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "sql, postgresql, time, intervals"
}
|
Code to read xlsx sheet into a table in a SQL Server database
I am trying to read data from an Excel sheet (`.xlsx` file) into a table in SQL Server 2008. I want this to be run everyday as a batch job and hence want to write SQL code in a stored procedure to do so.
Could someone help me? I have admin rights.
~TIA
|
This should do...
SELECT *
FROM OPENROWSET(
'Microsoft.ACE.OLEDB.12.0',
'Excel 8.0;HDR=NO;Database=T:\temp\Test.xlsx',
'select * from [sheet1$]')
But we aware, sometimes this just wont work. I had this working for local admins only.
There is a way to do this using SSIS as well.
|
stackexchange-stackoverflow
|
{
"answer_score": 31,
"question_score": 23,
"tags": "sql server, tsql, xlsx"
}
|
VPN server on Debian with login access from Windows
I have a friend in a closed country that needs a VPN. I want to install a secure VPN server on my dedicated server.
I have looked at PPTPD and OpenVPN, but I am not sure which one would be best? Or if there is a better solution?
He is using Windows and Android, So I want to be sure that he can use my VPN from those devices.
Which VPN server would you recommend, and do you have a complete guide on how to install it?
I have both tried installing PPTPD and OpenVPN, following the many guides I could find via Google. But even though they all seem very straightforward, it's not working for me.
Are there any easy-to-setup VPN servers out there? And maybe with a web interface or something like that to administrate it? The best solution would be without the use of certificates or ssh_keys since I then would need to create these for him or teach him how to do so.
|
I ended up installing a PPTPD server, this seams to work from both Windows and android.
Following this howto: <
Cheers
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 1,
"tags": "linux, debian, vpn"
}
|
How do I show a small sprite being dragged by touch?
In my mobile game, users drag shapes across the screen. Think of it as a classic Lines game, where you drag a dot on the field, or a chess game where you drag and drop pieces.
The problem is that the player's finger totally covers the sprite, making dragging confusing.
Is there a common practice to solve this?
* * *
My best try so far was to move the sprite to be offset from the finger when the dragging starts, then move along with the finger in the offset position until dropped.
The problem with this approach is that users might be left- or right-handed. If I offset the sprite to the top-left of the finger, dragging with the left hand covers the sprite again.
|
If you move elements smaller than your finger, there's something wrong with your game design.
I see several solutions to this:
* Make your elements bigger so you can see that you hold and where you put them, possibly enabling a Zoom gesture.
* Use another method of move, like a two tap movement mode, you tap from and to positions.
* Constraint your moves on one axis. User can move his finger on the whole screen with the element fixed on its own axis, so there's always a way his finger doesn't cover the element.
* Create another element for precise positioning, like a arrow, a cross or a thin line that appears when you start to drag an element.
For the right/left hand problem, people don't change their hand often, what's done most of the time is create a setting to enable or disable left handed mode, so your offset is applied on the right side instead of the left side.
|
stackexchange-gamedev
|
{
"answer_score": 2,
"question_score": 2,
"tags": "animation, mobile, touch, user experience"
}
|
Unexpected output while calling octave script from php
I am calling Octave script from PHP and passing parameters to it. But I get the unexpected output.
The PHP code I'm using to pass arguments and call the Octave script is:
$a=8;
$b=3;
$cmd = "C:\Octave\Octave4\bin\octave-cli C:\wamp\www\dspace\add.m $a $b";
$ex = passthru($cmd, $op);
var_dump($ex);
My Octave script:
arglist = argv();
a = arglist{1};
b = arglist{2};
function f (a,b)
a + b
endfunction
printf(f(a,b));
The output get is:
ans = 107
Expected output is:
11
How can I fix this?
|
You are adding the ASCII codes for the character "8" which is 56 and "3" which is 51 so the result is 107. Convert the strings to numbers:
arglist = argv();
a = str2num (arglist{1});
b = str2num (arglist{2});
function ret = f (a,b)
ret = a + b;
endfunction
printf("%i", f(a,b));
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "php, octave"
}
|
php scientific notation significant digits
In the PHP manual for function sprintf I find:
> e - the argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
Now I'm on PHP 5.4, but would like to format a number with scientific notation and indicate the number of significant digits instead of decimal places. Is there a function for this, or should I write it myself?
|
I looked over the `(one less)` part, that's all I needed. thanks for the help!
This means that I just had to decrease the value of the precision by one to get my function to behave the way I wanted.
See here for the function I came up with tot support scientific notation using sprintf
function sn($number,$precision = 1,$case = 'e'){ //scientific notation
$precision--;
$string = str_replace('+','',sprintf('%.'.$precision.$case, $number))." ";
return $string;
}
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 1,
"tags": "php, format, scientific notation"
}
|
Google analytics in android app - how to track premium upgrade version?
I followed this Android tutorial and successfully added Google Analytics to my app.
It's all working great and I can see that it's automatically tracking the app version number.
My app also features a paid upgrade to premium so I'd like to the app versions to include this - e.g 1.0.1 lite or 1.0.1 premium - how can I do this? Or is there a better way to track this?
Thanks
|
Use the EasyTracker `ga_appVersion` parameter. If for some reason, you can't do this, you can use Custom Dimensions
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, google analytics, in app purchase, in app billing"
}
|
NASM error: parser instruction expected
;**********************************
; Boot1.asm
; - A Simple Bootloader
; Operating System Development
;**********************************
org 0x7c00 ;BIOS loaded at 0x7c00
bits 16 ; We are still in 16 bit real mode
Start:
cli ; clear all interrupts
hlt ; halt the system
times 510 - ($-$$) db 0 ;We have to be 512 bytes.Clear rest of bytes with 0
ddw 0xAA55 ;Boot signature
I have written a simple boot-loader program in nasm on Windows 7 but I am getting an error:
error:parser: instruction expected.
This problem has been solved previously but I am not getting it in my context.
|
The NASM documents do not name an assembler directive `ddw`. I expect that's what the error message is talking about. `ddw` is not an "instruction," so it's confused.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "assembly, compiler errors, nasm"
}
|
Equivalent to bcdiv from php in java
What is the equivalent of `bcdiv(string, string [, int])` in `java`
the function divides two arbitrary precision numbers
I would like for instance to use:
`bcdiv(10000,100, 2)` results in **100.00**
or
`bcdiv(10000,100, 3)` result in **100.000**
I am more interested in the precision it gives.
I would like its equivalent in `java`
link to the php manual
|
The `BigDecimal` class allows arbritary precision math. In particular see the divide method.
BigDecimal a = new BigDecimal(10000);//Can take int
BigDecimal b = new BigDecimal("100");//Or string
BigDecimal answer = a.divide(b);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, php, precision, division"
}
|
Why doesn't Install4J update i4jruntime.jar?
I'm upgrading from Install4J version 4 to version 6. After making the appropriate changes in my code, I ran the newly-built upgrader to update the original software installation, and found that my software launcher is updated but the i4jruntime.jar file is not updated. The result is that my application won't run because of "Error: Could not find or load main class com.install4j.runtime.launcher.UnixLauncher"
When I manually copy i4jruntime.jar (version 6) over i4jruntime.jar (version 4) in the .install4j folder, then my application launches just fine.
I read the help docs on Generated Installers > Updates, but it seems like this is more about updating your software, not updating Install4J itself.
How can I get Install4J to update the i4jruntime.jar file itself?
|
The runtime will be upgraded unless you have set the installer type to "Add-on installer" on the "Installer->Update options" step or if you have deselected the "Install runtime" property on the "Install files" action.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "install4j"
}
|
Swing Dynamical JCombobox detect selection change by user
I would like to know if there is a way to detect if changes in the selection of a item in a swing JCombobox is done by a user (actively) or is causes by repopulating the Jcombobox.
I have to dynamically repopulate the items of the combobox based on other selection, this also invokes the actionPerformed event
so actionPerformed is invoked by:
* selection changed by user
* repopulating the jcombobox items.
how to tell the difference?
Thanks of helping !
|
No, not really.
A possible solution is to disable event notification while the combo box is updated. This can be done in (at least) one of two ways...
Firstly, you could physically remove the listener from the combo box, if you have a reference to it.
Secondly, you set a `boolean` flag, which when `true`, the listener would ignore the event.
For example...
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, swing, events, jcombobox"
}
|
How to make transparent Activity with 50% transparency
I have a transparent theme Activity but this theme will make the Activity 100% transparent. I need a code such that the Activity will be 50% Transparent. This is my code:
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
|
You could apply a transparent theme to the required activity. Create a new style in `/res/values/style.xml`
<resources>
<style name="Transparent">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Translucent</item>
<item name ="android:windowBackground">@color/transparent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:colorForeground">#fff</item>
</style>
</resources>
The value of transparent is
<color name="transparent">#80000000</color>
Now in AndroidManifest.xml declare the theme of the activity to the one you just created.
<activity android:name="MyActivity" android:theme="@style/Transparent"></activity>
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 2,
"tags": "android"
}
|
call stack for code compiled without -g option (gcc compiler)
How do I analyze the core dump (using gdb) which is not compiled with -g GCC option ?
|
Generate a map file. The map file will tell you the address that each function starts at (as an offset from the start of the exe so you will need to know the base address its loaded too). So you then look at the instruction pointer and look up where it falls in the map file. This gives you a good idea of the location in a given function.
Manually unwinding a stack is a bit of a black art, however, as you have no idea what optimisations the compiler has performed. When you know, roughly, where you are in the code you can generally work out what ought to be on the stack and scan through memory to find the return pointer. its quite involved however. You effectively spend a lot of time reading memory data and looking for numbers that look like memory addresses and then checking that to see if its logical. Its perfectly doable and I, and I'm sure many others, have done it lots of times :)
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "c++, c, linux, gcc, gdb"
}
|
Does memory allocated to tmpfs free itself when needed by an application?
I have 8GB of RAM and 4GB is dedicated to the tmpfs on /dev/shm.
There's nothing actually in /dev/shm, so I'm wondering, is this memory still available for applications to use?
If I needed to use 7GB in an application (which I do) would the tmpfs give up part of its allocated memory for this, or would I end up using swap after 4GB?
|
From `Documentation/filesystems/tmpfs.txt`:
> tmpfs ... grows and shrinks to accommodate the files it contains and is able to swap unneeded pages out to swap space.
So unless you needed all 4GB of data stored in `tmpfs` at once, you would get as much RAM for your applications as feasible.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 2,
"tags": "linux, centos, tmpfs"
}
|
How can I find an IndexSet's path in Examine?
In my Umbraco project, I have multiple Examine IndexSets defined in the configuration files. How can I programmatically retrieve an individual IndexSet's path?
I am aware of the `Examine.LuceneEngine.Config.IndexSetCollection` but I cannot seem to get a populated instance of this object.
|
I have found the answer myself, so I thought I would share it:
IndexSetCollection sets = Examine.LuceneEngine.Config.IndexSets.Instance.Sets;
IndexSet set = sets["Set_Name"];
DirectoryInfo dir = set.IndexDirectory;
string path = Path.Combine(dir.FullName, "Index");
And obviously I have all the properties of the set's directory from DirectoryInfo object too.
Hope this helps someone.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, lucene, umbraco, examine"
}
|
why this javscript code giving undefined as a result? (Calculating GCD), I don't know why it's not entering if block
I don't know why its not entering if block.Maybe because of type coercion. Please correct me and tell me what's the mistake in this code.
function calculateGCD(a, b) {
if (b === 0) {
return a;
} else
console.log(a, b);
a > b ? calculateGCD(b, (a % b)) : calculateGCD(a, (b % a));
}
function main() {
let n1, n2, gcd;
n1 = +prompt("enter 1st number?");
n2 = +prompt("enter second number?");
gcd = calculateGCD(n1, n2);
document.write(gcd);
}
main();
|
In the function you should return the result.
function calculateGCD(a, b) {
let result
if (b === 0) {
return a;
} else {
console.log(a, b);
a > b ? result = (b, (a % b)) : result = (a, (b % a));
}
return result
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, greatest common divisor"
}
|
arules/ as/ how to import a coercion method to another package?
I would like to use package arules functionalities in my package but can not import the whole package due to name conflicts. object@datafr is a data frame that needs to be coerced to transactions. How should I deal with the second line in the code below?
showrules <- function(object, support=0.05, confidence=0.5){
combinations <- as(object@datafr, "transactions")
rules <- arules::apriori(combinations, parameter = list(support = support,
confidence = confidence), appearance=list(rhs='target=high', default='lhs'))
arules::inspect(rules)
}
|
I don't know how to call `as()` using a namespace qualifier (`arules::coerce()` does not work), but luckily `apriori()` accepts also data.frames and coerces them internally into transactions. So you can just use:
`rules <- arules::apriori(object@datafr, parameter= list(support = support, confidence = confidence), appearance=list(rhs='target=high', default='lhs'))`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "r, arules"
}
|
Finding a key from values (which are list) in dict
I have a dictionary:
x = {'a': [1, 2, 3], 'b': [4, 5, 6]}
and I have to extract a key based on an input. For example assume it is `3`, so my output should be `'a'`.
Here's my code:
x = {'a': [1, 2, 3], 'b': [4, 5, 6]}
n = 3
output = [k for k, v in x.items() if n in v]
print(output[0])
Can it be done more efficiently?
Elements in the lists are unique, i.e. the value `3` will only be in one list.
|
Given that you only want the first match, it would be more efficient to stop when you reach it:
output = next(key for key, value in x.items() if n in value)
Note that this will throw a `StopIteration` exception if there is no matching key, rather than the `IndexError` your current code throws.
If you need to do this multiple times, you could build a reverse map:
x_reversed = {num: key for key, value in x.items() for num in value}
then the lookup is a trivial `x_ reversed[n]` However, note the error case changes again, to `KeyError`.
|
stackexchange-codereview
|
{
"answer_score": 6,
"question_score": 0,
"tags": "python, python 3.x"
}
|
Is the phrase "keeping the flat tidy and in good nick" grammatical?
> Our cleaning staff is keeping the flat tidy and in good nick. For your convenience.
Does that read correctly?
|
The message seems grammatically correct.
But the OALD states that the expression you used, ( _in good nick_ ), is informal. Considering the whole message, which appears to be a staff communication, informal language should be avoided.
You can simply say, for example:
> "Our cleaning staff is keeping the flat tidy and in good condition. For your convenience."
|
stackexchange-english
|
{
"answer_score": 1,
"question_score": 1,
"tags": "grammaticality"
}
|
Replace certain elements in lists of lists
How to replace certain elements, if I may have lists of lists in python? I am only interested to change individual elements
def replace_item(the_list,toBeReplaced,toBeReplacedBy):
for each_item in the_list:
if isinstance(each_item,list):
replace_item(each_item,toBeReplaced,toBeReplacedBy)
else:
if each_item == toBeReplaced:
each_item=toBeReplacedBy
return the_list
Like if I have a list
[[2,3],[[2,3,5,6],2,6,3],[1,2]]
and if I want to replace 2 by say zero then resultant should be
[[0,3],[[0,3,5,6],0,6,3],0,6,3,[1,0]]
|
by assigning toBeReplacedBy to each_item you are not changing the item in the_list. This is how you do it.
def replace_item(the_list,toBeReplaced,toBeReplacedBy):
for index,each_item in enumerate(the_list):
if isinstance(each_item,list):
replace_item(each_item,toBeReplaced,toBeReplacedBy)
else:
if each_item == toBeReplaced:
the_list[index]=toBeReplacedBy
return the_list
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "python, list"
}
|
How to show ℃ in the legend of matplotlib, python?
Below are some pieces of code, but I really do not know how to let ℃ shows as it should be. I think matplotlib is powerful enough to do tihs kind of job. Any experts can help me out of this dilemma
if i==12:
plot(strain,stress,'1-',label="$1200℃$")
xlabel(r"strain/$\epsilon$",fontsize=18)
ylabel("stress/MPa",fontsize=18)
legend(bbox_to_anchor=(1.01, 1.0,0.8,0.0), loc=2, borderaxespad=0.0)
show()
|
This solution is completely separate to the font/unicode issues discussed in the duplicate, but you can use Latex-style commands to get this working:
plt.plot(1, 3, '1-', label=u"$1200^{\circ}C$")
plt.legend()
plt.show()
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "python, matplotlib, legend"
}
|
Can XML DTD force different values for two attributes on same element?
**Is there a way in XML DTD to force two attributes of the same element to have different values?**
I'm writing an XML application representing a graph, using DTD and not XML Schema.
I declared the element `Link`, having two attributes `host1` and `host2` referring to the attribute `hostName` of the `Host` element with `IDREF`.
I would like to add a kind of constraint (if any) to forbid `host1` and `host2` having the same value (referring to the same host).
|
No, DTD can't express that constraint. Other options include:
* XSD
* Schematron [Credit: Thanks, @C.M.Sperberg-McQueen]
* Application-level validation
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "xml, xml validation, dtd"
}
|
Solving the equation $\sin 40^{\circ}=\cos x$
How to solve this equation (finding $x$ ):
$$\sin 40^\circ=\cos x$$
|
**HINT** $$\sin(y^{\circ}) = \cos(90^{\circ}-y^{\circ})$$
|
stackexchange-math
|
{
"answer_score": 7,
"question_score": 1,
"tags": "trigonometry"
}
|
comando getWindow() não é reconhecido
**Alguém me ajuda pelo amor de desu, to usando SDK 29 então o problema não é esse ao menos...**
, but it does not seem that Braintree error ever gets there.
|
I was able to solve this when I manually applied this patch , I hope this will be merged soon :)
|
stackexchange-magento
|
{
"answer_score": 0,
"question_score": 0,
"tags": "magento2, checkout, magento2.2, onepage checkout, braintree"
}
|
How to view .img files?
I'm trying find **software** to view `.img` files. But its not expected. `.img` file its not all images, it contains some values too. So I would like to view the `.img` file. Please advise any **software** like that.
|
If you want to open .img files, you can use 7-zip, which is freeware...
<
Once installed, right click on the relevant img file, hover over "7-zip", then click "Open Archive". Bear in mind, you need a seperate program, or Windows 7 to burn the image to disc!
Hope this helps!
Edit: Proof that it works (not my video, credit to howtodothe on YouTube).
|
stackexchange-stackoverflow
|
{
"answer_score": 26,
"question_score": 22,
"tags": "image, image processing, uiimageview"
}
|
Can you outfriend your pig's ability to find truffles?
On Stardew Valley's official wiki's Pig page there is a passage:
> Warning: Pigs will NOT PRODUCE ANYTHING if they are at a high enough mood and friendship to produce a "Deluxe Product", because the animal type cannot produce Large or Deluxe products.
My question is based off that - **does maximizing your pig's friendship reduce their ability/chance to find truffles?** If yes what is the most optimal friendship level?
|
This is actually a glitch in the game to be fixed soon. The optimal friendship level can be achieved by not petting your pigs and just letting them outside and making sure they have enough grass. It's actually easier than what is intended for it to be.
It has been now fixed in 1.2.
|
stackexchange-gaming
|
{
"answer_score": 5,
"question_score": 7,
"tags": "stardew valley"
}
|
British expatriate travelling to U.K. with only a few months left on passport
I'm travelling to the U.K. from the States as a U.S. permanent resident in mid-July. I still have my British passport, but it expires in mid-October.
For the life of me I can't find any expiry eligibility requirements for this situation, so I was hoping someone here may be in the know.
|
If you have a valid UK passport, UK immigration control will let you into the country even if your passport expires the next day.
If you're intending to return to the US before your passport expires, you will also want to ensure that your passport is still valid for at least the minimum time required by the US officials at the time you re-enter (I'm not sure what that is for permanent residents).
|
stackexchange-travel
|
{
"answer_score": 8,
"question_score": 3,
"tags": "uk, passports"
}
|
Check if array contains values which are the same
How can i check if two or more values in the same array are the same?
just looking for an explanation thanks
|
Here's a simple way to check if any value exists twice:
function hasDuplicate(array:Array):Boolean {
var keys:Dictionary = new Dictionary();
for each(var item:* in array){
if(keys[item])
return true;
keys[item] = true;
}
return false;
}
trace(hasDuplicate(["a", "b", "c"])); // false
trace(hasDuplicate(["a", "b", "c", "b"])); // true
This works by looping through all values using `for each`, then storing each value as a key in a `Dictionary`. If any value already has a key in the dictionary, it's a duplicate.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "actionscript 3"
}
|
iOS (12.1) google shows "title" in address bar, how?
Using HTML, JS, or anything that can be loaded into the iOS browser, Im trying to find a way to modifiy the URL bar to show something other than the URL (title, text, anything).
From what I have read (its been asked on here a lot) and elsewhere it appears this is **not** possible.
I accepted this for a while until now as I have just seen on my iphone running 12.1 that a google search changes the URL bar to the searched term, even when you click in the URL bar, it just shows the searched term?
So what magic are they doing?
|
I dont think it is to do with google, it is to do with the iOS default search engine integration.
To change your search engine:
_Settings_ -> _Safari_ -> _Search Engine_
Shown in the picture below:
:
""" first line
HELLO THERE@
ME TOO
DOC STRING HERE
"""
return 1
>>> help(test)
Help on function test in module __main__:
test()
first line
HELLO THERE@
ME TOO
DOC STRING HERE
>>> def test2():
"""
DOC string
text here"""
return 5
>>> help(test2)
Help on function test2 in module __main__:
test2()
DOC string
text here
So while you can refer to PEP 8 for usual conventions, you can also just decide what format you like and just try to be consistent within your application.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, docstring"
}
|
Is it possible to clone a Cloud Foundry / Bluemix space? How?
We are using IBM Bluemix PaaS which is based on Cloud Foundry. We have been working in a DEV space for some time and have two apps and a dozen of services. Now we are in the phase of deploying a PROD version which should be very similiar to what we have in DEV. So instead of creating the PROD space manually, that includes creating apps, binding services, loading data etc., is there a easy way, or a CF command, that can allow us to simply clone the DEV space and rename it PROD?
Edit: I have confirmed with some Bluemix experts from within IBM, and it is not possible to clone the entire space. However, pushing apps to multiple spaces is doable using DevOp Build & Deploy or Delivery Pipeline service. Manifest.yml can also help like the comment says below. Services associated to the app will have to be re-created manually in new spaces.
|
The easiest way to do this is using the Delivery Pipeline Service on Bluemix.
This allows you to configure automated build, test and deployment stages based on changes to your git repository (or manually triggered).
If you have a pipeline already set up for your dev space you have two options:
1. Change the target space for all of the deploy stages and run them
2. Clone the delivery pipeline to a new project - these can be replicated using a pipeline.yml file. Here is a sample pipeline configuration file
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "cloud, ibm cloud, cloud foundry"
}
|
asp .net @Html.ActionLink dynamic id (parameter)
In JS and ASP.NET, how to make the route id dynamic @ Html.ActionLink ("Edit", "Edit", new {id: item.Id})?
below the corresponding image: enter image description here
|
you are mixing backend (Razor) and fronted (javascript) execution, which have different execution time, hence not working.
Razor will be fired to create the html before javascript has ever be hit and once javascript hit, Razor has no way of interacting with it (in your case the `item.Id` because it is generated by javascript, which by that time Razor has already finished)
One way to achieve what you want is generate the base url using Razor and append the id in javascript.
so, change the part you highlighted in your image to:
var url = '@Url.Action("Editer", "Edit")' + '?id=' + item.Id;
src += '<td><a href="'+ url +'">Edit</a></td>'
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, asp.net, dynamic, html.actionlink"
}
|
If $X$ is compact metric space, then $X$ is bounded
Assume that $X$ is metric space and compact. We must proof that $X$ is bounded.
Now, at first we notice that $X$ is sequentially compact. But then what?
We must find some $W\geq 0 $ such that $d(x,y)< W$ by all $x,y\in X$.
How I can do that? Need a hint.
|
Pick $p \in X$. Then $O_n = B(p,n)$, $n \in \mathbb{N}$ is a cover of $X$. There is a finite subcover of the $O_n$, and as $O_1 \subset O_2 \subset O_3 \ldots$, already one of them (the largest index) already covers $X$ and so $X$ is bounded.
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 2,
"tags": "general topology"
}
|
Adding images, buttons and text programmatically
I want to make application which will load images from web and display it on a TabControl. First panel displays sourc of page (I've done this). On the second panel it should display images from current webpage and some buttons (For example "save this image"). Im getting every url for images, but i don't know how to display them on the second tab item with some buttons. What is the best solution for that?
|
I'm not sure what you trying to achieve but I guess you should use ItemsControl.
You can set a ItemsSource which you update programmatically.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c#, wpf, image, tabs"
}
|
Change sha1 hash of files
Lets say I have two files with two different sha1 hashes. Is there a way to change the hash of one file to the hash from the other file so they both have the same hash value?
The two files have different values in it.
|
Yes.
Either:
* Change the content of the file so the two files are identical _or_
* Find another set of data (you'll probably have to brute force search this so it would take a lot of computing power) which happens to hash to the same value
You can't change the hash without changing the content of the file. The hash is just what you get after doing some calculations on the content of the file.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -2,
"tags": "hash, sha1"
}
|
Haskell: why is a multi-line let expression a syntax error?
Given the following,
module Foo where
main = do
let foo = case 0 of
0 -> 4
return ()
GHC insists that I have a syntax error:
Make.hs:5:5: parse error (possibly incorrect indentation)
Why? I've used Haskell for a while, and it looks correct to me.
|
Multiline expressions in do syntax must be indented beyond the variable name:
main = do
let foo = case 0 of
0 -> 4
return ()
is ok but
main = do
let foo = case 0 of
0 -> 4
return ()
is not.
|
stackexchange-stackoverflow
|
{
"answer_score": 24,
"question_score": 16,
"tags": "haskell, syntax error"
}
|
Expression of $\cos^{-1}\left(4x^3-3x\right)$
**The Original question :** (translated from French)
Let $f$ be the function $$ f\left(x\right)=\cos^{-1}\left(4x^3-3x\right) $$
1. * Find the definition domain of $f$.
2. * Compute $f'\left(x\right)$. Find an expression of $f\left(x\right)$ in terms of $\cos^{-1}\left(x\right)$.
My attempt : $f$ is defined on $\left[-1;1\right]$ and $$ f'\left(x\right)=\frac{3-12x^2}{\sqrt{1-\left(4x^3-3x\right)^2}} $$ To answer the question I thought i could express it as $$ f'\left(x\right)=\frac{3-12x^2}{\sqrt{-1+3x-4x^3}\sqrt{1-3x+4x^3}} $$ and try a kind of decomposition to find it as $$ f'\left(x\right)=a\frac{3-12x^2}{\sqrt{-1+3x-4x^3}}+b\frac{3-12x^2}{\sqrt{1-3x+4x^3}} $$ What am I missing ?
|
Since the domain is $[-1,1]$, you can let $t=\cos^{-1} x \implies x=\cos t$. Why? Because $4\cos^3 t -3\cos t = \cos 3t $. $$f(t) = \cos^{-1} (\cos 3t) $$
The range of $\cos^{-1} x$ is $[0,\pi] $, and so you need to be careful and divide $f(t)$ into suitable pieces as follows:
$$f(t) =\begin{cases} 3t, & 0\le t\le \pi/3 \\\ 2\pi-3t, & \pi/3 \le t \le 2\pi/3 \\\ 3t -2\pi, & 2\pi/3 \le t \le \pi \end{cases} $$
Now just replace $t$ while noting that $0\le \cos^{-1} x \le \pi/3 \iff \frac 12 \le x\le 1$ and $\pi/3 \le \cos^{-1} x \le 2\pi/3 \iff -\frac 12 \le x \le \frac 12$ and $2\pi/3 \le \cos^{-1} x \le \pi \iff -1\le x\le -\frac 12$.
$$f(x) =\begin{cases} 3\cos^{-1} x, & \frac 12 \le x \le 1 \\\ 2\pi-3\cos^{-1} x, & -\frac 12 \le x \le \frac 12 \\\ 3\cos^{-1} x -2\pi, & -1 \le x \le -\frac 12 \end{cases} $$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "real analysis, trigonometry"
}
|
Android in-app products not appearing in app
I have created an app with in-app products. I've added the licensing key and billing permission in my app and created in-app products in the developer console. And I'm using Android In-App Billing v3 Library to handle all purchases operations
The products in the play console are active and I've published the app and I can now see it and download it in the Google Play Store.
The problem is I can't get the in-app products when I try to list any products! They're not showing up in the Play Store, and I get the error: BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE and error value :3
My google play app is updated and is connected with Gmail account
Is there any restrictions for in-app products to show up based on location (I live in Palestine, Gaza) or the problem is pure technical ?? Please help
|
After several days of searching, I figured out that Palestine in not supported by google play, so I did the following to overcome this issue:
1. I downloaded a VPN app on my mobile
2. I have cleared the cash and data of my google play (this is from settings/apps/ google play/storage)
3. I selected a European country and turned the VPN on
4. When restarting google play app, in the profile, choose the country that you have previously selected in the VPN app
5. Now Google play app runs from this selected country
6. When I have run my app, everything works fine and all errors disappeared
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, in app billing, google play console"
}
|
Pandas Dataframe filter based on time
From the datetime object in the dataframe I created two new columns based on month and day.
data["time"] = pd.to_datetime(data["datetime"])
data['month']= data['time'].apply(lambda x: x.month)
data['day']= data['time'].apply(lambda x: x.day)
The resultant data had the correct month and day added to the specific columns.
Then I tried to filter it based on specific day
data = data[data['month']=='9']
data = data[data['day']=='2']
This values were visible in the dataframe before filtering.
This returns an empty dataframe. What did I do wrong?
|
Compare by `9,2` like integers, without `''`:
data = data[(data['month']==9) & (data['day']==2)]
Or:
data = data[(data['time'].dt.month == 9) & (data['time'].dt.day == 2)]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, pandas, datetime"
}
|
Problem using "-" inside \textbf
I hope you can help me with this. I have the following in my code:
\textbf{Legendre–Fenchel transformation}
The problem is that the `-` doesn't show up after compilation. Instead it comes out as LegendreFenchel. How can I remedy this?
|
This is probably some input encoding issue, as I could reproduce it by cut and pasting into a minimal. If you cut and paste this:
\textbf{Legendre--Fenchel transformation},
it works.
|
stackexchange-tex
|
{
"answer_score": 2,
"question_score": 2,
"tags": "bold, punctuation"
}
|
Como enviar e receber imagem pelo json?
eu fiz um app em Xamarin que a pessoa terá que assinar e preciso mandar essa imagem para o servidor Se possível deixar o código para realizar tal tarefa
|
O que eu tenho é uma Stream que preciso mandar para o servidor então ficou assim
Atendimento_ViewModel.Assinatura = await Pad.GetImageStreamAsync(SignatureImageFormat.Png) as MemoryStream;
app local
byte[] imageBytes = Assinatura.ToArray();
pedido.Assinatura = Convert.ToBase64String(imageBytes);
Servidor
byte[] bytes = Convert.FromBase64String(pedido.Assinatura);
MemoryStream stream = new MemoryStream(bytes);
Image Image1 = Image.GetInstance(System.Drawing.Image.FromStream(stream),System.Drawing.Imaging.ImageFormat.Png);
o código acima é para pegar a assinatura escrita e ser mandada para o servidor, atenção se a intenção for mandar a imagem em um pdf a mesma deve ser .pdf
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, json"
}
|
wrap elements in single quotes in Tcl list for sqlite insertion
I'm trying to format a string for SQLite insertion, so we need to wrap a list of strings in single quotes depending on their type
so if I have a list as such
set list1 [list a b 1]
How would I easily convert that into a list where each string element is single quoted but the numbers are not like this
'a' 'b' 1
Is there some string formatting command that will accomplish this simply?
|
I'm not sure if you really need this quoting. Sqlite interface in tcl is very flexible. If you describe your main task in detail, you could get more useful advice.
But I can give the direct answer for your question. Here it is.
set list1 [list a b 1 2 c]
set list_quoted [lmap a $list1 {
if {[string is integer -strict $a]} {
set a
} else {
subst {'$a'}
}
}]
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sqlite, tcl"
}
|
How can I find the thieves' caches in Riften?
I read in a guide that they exist, but I'd like to know where to find them/what type of containers I'm looking for.
|
Thieves caches are located all over Skyrim. The Riften cache is located in the garden of the house you can buy there. In the back of the garden you should find there are some **barrels** , one of which is the Thief Cache appropriately named "Thief Cache" :)
The house is located at number **7** (top-left) on the map below if you don't know where it is.
> !enter image description here
Also keep a look out for this "shadow-mark", it's means there is a thieves cache somewhere nearby.
> !enter image description here
You can learn more about the Thieves Guild shadow-marks **here**.
|
stackexchange-gaming
|
{
"answer_score": 5,
"question_score": 4,
"tags": "the elder scrolls v skyrim"
}
|
Chance of two people picking same numbers
Lets say two people pick $5$ different numbers out of a subset of $35$) numbers, what is the chance these $2$ people have $2$ or more picked numbers in common?
This is the chance of $1 - p$ (have nothing in common) $- p$ (have $1$ in common)
However how do I calculate $p(0)$ and $p(1)$?
Thx for the help.
|
By symmetry, you can just assume the first person picked $1,2,3,4,5$ and ask how many of those the second person has picked. The chance the second person has picked $k$ of them is $$\frac {{5 \choose k}{30 \choose 5-k}}{35 \choose 5}$$
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 1,
"tags": "probability, combinatorics, combinations"
}
|
JavaScript - How do I make sure a jQuery is loaded?
I have a web page. When this web page is loaded, I want to execute some JavaScript. This JavaScript uses JQuery. However, it appears that when the page is loaded, the jQuery library has not been fully loaded. Because of this, my JavaScript does not execute properly.
What are some best practices for ensuring that your jQuery library is loaded before executing your JavaScript?
|
The jQuery library should be included in the `<head>` part of your page:
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>
Your own code should come after this. JavaScript is loaded linearly and synchronously, so you don't have to worry about it as long as you include the scripts in order.
To make your code execute when the DOM has finished loading (because you can't really use much of the jQuery library until this happens), do this:
$(function () {
// Do stuff to the DOM
$('body').append('<p>Hello World!</p>');
});
If you're mixing JavaScript frameworks and they are interfering with each other, you may need to use jQuery like this:
jQuery(function ($) { // First argument is the jQuery object
// Do stuff to the DOM
$('body').append('<p>Hello World!</p>');
});
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 21,
"tags": "javascript, jquery"
}
|
is there any way to integrate Alert rules with Azuredevops WorkItems-bugs
Looking for some way to create the ADO workitem type-bugs, whenever any created Azure alert rules trigger alerts.
Is there any inbuilt mechanisam available either in ADO or Azure loganalytic workspaces, where we created the alert rules.
|
I don't think there's any built-in way to do it.
You could create an Azure Logic App that creates a task in DevOps and then make it an Action for your Alert.
Connecting the ticket state back to alert state (i.e. to mark the alert as resolved once the bug is fixed) should be possible, but a lot trickier.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "azure devops, azure log analytics, azure devops extensions, azure devops server 2019, azure monitor"
}
|
Combining parts of a list inside a list
Given a list like:
[['james',100,200,300],['james',200,300,400], ['charles',200,200,100]]
I need to add the components of the two lists that have the same first index like so:
[['james',300,500,700],['charles',200,200,100]]
Thanks for the answers. Just found out I have to do so without importing any modules. Is there a way to do so? I've tried using for-loops but cannot find out what to index for.
|
data=[['james',100,200,300],['james',200,300,400], ['charles',200,200,100]]
dic={}
for sample in data:
if sample[0] in dic.keys():
dic[sample[0]] = [x+y for x,y in zip(dic[sample[0]],sample[1:])]
else:
dic[sample[0]] = sample[1:]
data= [[x]+y for x,y in dic.items()]
Explanation: The for loop iterates over all elements of the list. Using the 1st element of each list, we check if 'dic' has this name as a key or not. If yes, we add to previous values of the key else create the key with the values 'sample[1:]'.The last step converts dictionary 'dic' to the desired list
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "python, python 3.x, list, for loop, indexing"
}
|
How to get the current_user in a model observer?
Given the following models:
Room (id, title)
RoomMembers (id, room_id)
RoomFeed, also an observer
When a Room title is updated, I want to create a RoomFeed item, showing who the user is who made the update.
@room.update_attributes(:title => "This is my new title")
Problem is in my observer for RoomFeed:
def after_update(record)
# record is the Room object
end
The is no way for me to get the user.id of the person who just made the update. How do I go about doing that? is there a better way to do the update so I get the current_user?
|
I think what you are looking for is, room.updated_by inside your observer. If you don't want to persist the updated_by, just declare it as an attr_accessor. Before you push the update, make sure you assign the current_user to updated_by, may be from you controller.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "ruby on rails, ruby on rails 3, activerecord, observer pattern"
}
|
Scalatest run code before and after specific test
I want to ask a quick question.
Is there a way to run some code before and after a specific test?
Imagine for a moment that I want some environment-setup code to be executed before and after a specific test, but not in all tests.
I've tried to define a function to do that for me and just call that function ant the beginning and the end of my test. It works fine but if the test fails, the function I call at the end isn't called (since the test failed).
Is there a way to restrict the beforeAndAfter trait to be executed only at specific tests?
Thanks.
|
You can do this (or a variation of this):
def beforeAfterT(t: =>T) = {
before
try t
finally after
}
Then
beforeAfter(before = action1, after = action2) {
test
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "scala, scalatest"
}
|
How to make a dialog with content from a string?
Is it possible to make a dialog with content from a string defined in your OnCreate? Because the only way to define the content of the dialog, which I could find, is with text or a string defined in values/strings.xml like this:
builder.setMessage(R.string.dialog_fire_missiles)
I hope there is someone who can help me, please tell me if my question is clear enough.
|
use `getString` method of `Context` to get String from strings.xml:
builder.setMessage(Your_Activity.this.getString(R.string.dialog_fire_missiles))
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 5,
"tags": "android, dialog, android alertdialog"
}
|
What is electrical code for number of wires in a breaker?
US, Georgia I am adding some new ciruits to add some additional outlets. The closest place is to run a wire to the main panel box.
My question is, can I connect more than one wire to a breaker and still meet code or do I need to get a new breaker. Both the wires and plugs are the same rating as the breaker - 15 amp.
Making the assumption that only one wire can be under each screw in the breaker, can I make a junction in the panel box? IE, one wire to breaker, but two wires to a wire nut connecting them together, or does the junction need to be in a separate box?
|
There should only be one wire per screw terminal. One of my wiring books says that some local codes allow splices inside a service panel, and some don't, so you should check with your local authority to make sure it's OK in your area.
However, regular circuit breakers are only a few dollars, so even if it's allowed in your area, my advice would be to just install the extra breakers for the new circuits.
|
stackexchange-diy
|
{
"answer_score": 8,
"question_score": 16,
"tags": "electrical, circuit breaker, code compliance"
}
|
What is the stack size of MATLAB?
What is the default stack size of MATLAB R2018a (64-bit)?
It seems that the stack-size is larger than an 64-bit C# program.
**Why I'm asking that**
I'm asking this question because I'm calling Intel MKLs LAPACKE_dtrtri which is heavily recursive.
I'm using that function inside .NET application and I'm getting a stack overflow error when calling it from C#, see What is the stack size of a BackgroundWorker DoWork Thread? Is there way to change it?
On the other side if I call my .NET application from MATLAB I'm not getting a stack overflow error. That's the reason I wanted to know what the stack size of MATLAB.
|
Using the dumpbin command I can take look at the header of the `MATLAB.exe`.
dumpbin /headers "C:\Program Files\MATLAB\R2018a\bin\win64\MATLAB.exe"
This returns
Dump of file C:\Program Files\MATLAB\R2018a\bin\win64\MATLAB.exe
PE signature found
File Type: EXECUTABLE IMAGE
FILE HEADER VALUES
8664 machine (x64)
...
OPTIONAL HEADER VALUES
...
4000000 size of stack reserve
1000 size of stack commit
100000 size of heap reserve
1000 size of heap commit
The `size of stack reserve` is the stack size in hex.
So the stack size of MATLAB is 67108864 Bytes which is 64 Mega Bytes.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 4,
"tags": "matlab, windows 10, 64 bit, stack size"
}
|
Dynamically sorting a DbDataReader using LINQ
I am very new to LINQ and have a class method, which when called, returns a DbDataReader object. How would I sort this dynamically using a LINQ query expression where the sort expression is provided as a string (e.g. "LastName DESC")
|
Can't take any credit - links in this question to Dynamic Linq and how to do it without:
Dynamic LINQ OrderBy on IEnumerable<T>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linq, ado.net"
}
|
Can I modify email headers in an IMAP folder?
My email provider anti-spam system adds a tag before the subject of emails when it detects spam or viruses.
It looks like `*** PROBABLY SPAM *** What a night we had !`
It's not very accurate and results in many false positive tags.
I archive some emails (like the one in the example) and these tags look dirty.
Do you know a way to get rid of them occasionally, without disabling the filter on the server ?
Thank you,
Stéphane.
|
Not directly, but you can download the messages, process them, and upload them back to IMAP folders. Any good IMAP client will let you do that.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 0,
"tags": "email, imap"
}
|
Bison/EBNF parse list with at least two elements
I am currently trying to parse a comma seperated list with at least two elements using bison. I know how to parse a list using this:
list : list "," element
| element
but how can I make sure that the list has at least two elements?
|
At the risk of being _two_ obvious:
list : list "," element
| element "," element
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "parsing, bison, ebnf, lalr"
}
|
How to use a rest api in express
I am new to express and have made a rest API in it. I don't know how to implement a rest API in express.So if I want to implement this API in my other applications I don't know how to do it and if I search the web I only get how to build a rest API. Help would be really appreciated
|
Get an http request library such as `got()` or any of the choices listed here. Then, use that library to make http requests from your application backend to your rest API server and get the response back.
Example:
const got = require('got');
got(someRestURL).json().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "rest, express"
}
|
Pegar o valor de uma string dentro de uma variavel PHP
$a = " A=1 B=2";
Preciso usar `echo` em `$a` e exibir o valor de B. Não quero usar array. É porque eu vou criar uma coluna no banco de dados aonde ela vai abrigar todas as opções ativas. E não quero ter o trabalho de criar mais de 10 colunas só pra opções. Então ficaria assim, o valor da COLUNA `opcoes` irá ter _option1=true_ option2=false ...
|
Você pode usar parse_str(), mas teria que fazer `replace` de espaços em branco para `&`:
<?php
$a = " A=1 B=2";
$a = str_replace(' ','&',$a);
parse_str($a, $valor);
echo $valor['B'];
?>
Veja no **Ideone**.
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, mysql, html5"
}
|
Calculating an Angle from $2$ points in space
Given two points $p_1$ , $p_2$ around the origin $(0,0)$ in $2D$ space, how would you calculate the angle from $p_1$ to $p_2$?
How would this change in $3D$ space?
|
Assuming this is relative to the origin (as John pointed out): Given two position vectors $\vec p_1$ and $\vec p_2$, their dot product is:
$$\vec p_1\cdot \vec p_2 = |\vec p_1| \cdot |\vec p_2| \cdot \cos \theta$$
Solving for $\theta$, we get:
$$\theta = \arccos\left(\frac{\vec p_1 \cdot \vec p_2}{|\vec p_1| \cdot |\vec p_2|}\right)$$
In a 2D space this equals:
$$v = \arccos\left(\frac{x_1x_2 + y_1y_2}{\sqrt{(x_1^2+y_1^2) \cdot (x_2^2+y_2^2)}}\right)$$
And extended for 3D space:
$$v = \arccos\left(\frac{x_1x_2 + y_1y_2 + z_1z_2}{\sqrt{(x_1^2+y_1^2+z_1^2) \cdot (x_2^2+y_2^2+z_2^2)}}\right)$$
|
stackexchange-math
|
{
"answer_score": 12,
"question_score": 10,
"tags": "linear algebra, geometry"
}
|
Deleting everything after a pattern in Unix
I have a string `replenishment_category string,Date string`, I want to delete everything starting with `Date` (including it), also the comma before it if it is present.
I have the string to be replaced stored in a variable:
PARTITION_COLUMN='Date'
I tried `sed` to replace everything after the variable `PARTITION_COLUMN`
echo "replenishment_category string,Date string" | sed "s/"$PARTITION_COLUMN".* //g"
but the output still has the string that follows the date:
replenishment_category string,string
How do I remove the `string` part and also the comma preceding the `Date`?
|
Try this:
echo "replenishment_category string,Date string" | sed "s/$PARTITION_COLUMN.*//"
Notice the space removed after `.*` and the double quote around the entire command.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "regex, unix, sed, substitution"
}
|
Issue on sprintf in Matlab
How to print in Matlab Like following....
0.01000E+02
I have tried
sprintf('%12.5e',[0.01000E+02])
it is giving me
1.00000e+000
|
You format is a bit specific. You should consider writing your own output function.
But a few pointers:
* Make e large with `upper`
* only 2 digits in exp number through a regexp. `new_string = regexprep(old_string,'\d(\d{2})$','\1')`
* the thing with leading 0 in exp representation is not standard - so maybe multiply with `1e2`, print the float and later attach the `E+02`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "matlab, printf, number formatting, scientific notation"
}
|
replace exact match in php
im new to regular expressions in php.
I have some data in which some of the values are stored as zero(0).What i want to do is to replace them with '-'. I dont know which value will get zero as my database table gets updated daily thats why i have to place that replace thing on all the data.
$r_val=preg_replace('/(0)/','-',$r_val);
The code im using is replacing all the zeroes that it finds for eg. it is even replacing zero from 104.67,giving the output 1-4.56 which is wrong. i want that data where value is exact zero that must be replaced by '-' not every zero that it encounter. Can anyone please help!!
Example of the values that $r_val is having :-
10.31, 391.05, 113393, 15.31, 1000 etc.
|
This depends alot on how your data is formatted inside `$r_val`, but a good place to start would be to try:
$r_val = preg_replace('/(?<!\.)\b0\b(?!\.)/', '-', $r_val);
Where `\b` is a 0-length character representing the start or end of a 'word'.
Strange as it may sound, but the Perl regex documentation is actually really good for explaining the regex part of the `preg_*` functions, since Perl is where the functionality is actually implemented.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "php, mysql, regex"
}
|
PHP: Are these statements equivalent? (file_exists())
Aren't these equivalent?
==SCRIPT A==
if (file_exists($file) == false) {
return false;
}
==SCRIPT B==
if(!file_exists($file)) {
return false;
}
|
Plain answer: **Y E S**
They evaluate to the same thing.
That first one might be even better suited like this:
if (file_exists($file) === false) { // === checks type and value
return false;
}
OR:
return file_exists($file);
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 1,
"tags": "php, function"
}
|
Git commit -am does not work on initial commit. Why?
Why does `git commit -am` not work on my initial commit, but works thereafter?
$ touch test.txt
$ ls -a
. .. .git test.txt
$ git commit -am "Initial commit"
# On branch master
#
# Initial commit
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# test.txt
nothing added to commit but untracked files present (use "git add" to track)
$
|
You have to first `git add` your file to the repo. `git commit` only commits changes to tracked files, `git commit -a` will commit all changes to tracked files. But untracked files will not be committed at any point.
You'll find that even on commits after the initial, if you create a new file it will not be committed with `git commit -a` until you `git add` it.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 6,
"tags": "git"
}
|
Illegal lottery problem (Merging dependent bernoulli trials)
Suppose I am in a town that playing lottery is illegal. If I buy a ticket for 1 dollar, I will win the lottery with probability $p$. Each time I buy a ticket, the police may catch me and confiscate the ticket and charge me a penalty of $N$ dollars for playing. Assume this occurs with probability $q$. I am fully adamant that I will eventually win the lottery (and it's worth it), hence I keep playing till I win. What is the expected amount of money I need to spend (including in fines), in order to win the lottery? Any other comments on how to formulate or approach the problem are of interest too.
Note that $p$ and $q$ are independent. Therefore I win with probability $p(1-q)$, get fined with probability $q=pq+q(1-p)$ and nothing happens with probability $(1-p)(1-q)$ (except for spending a dollar).
|
You're certain to spend $\$1$. You also spend an expected $qN$ on a potential fine this time around. And then with probability $1-p(1-q)$ you have to do the whole thing all over again. So the expected cost $E$ satisfies
$$E=1+qN+\left[1-p(1-q)\right]E\;,$$
with the solution
$$E=\frac{1+qN}{p(1-q)}\;.$$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "probability, stopping times"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.