INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Calc/Spreadsheet: combine/assign/migrate cols
Sorry, i can't use the right terms but i try to explain my task:
In Calc, or Spreadsheet I have two worksheets with columns like this:
| ID|
| 32|
| 51|
| 51|
| 63|
| 70|
and
| ID|Name |
| 01|name1 |
| 02|name2 |
...
| 69|name69 |
| 70|name70 |
i need to combine/assign/migrate these together, like:
| ID|Name |
| 32|name32 |
| 51|name51 |
| 51|name51 |
| 63|name63 |
| 70|name70 |
I have no idea how can is start to solve it. Please help!
|
Thank you @PsysicalChemist, the VLookup function is working in Calc to.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "excel, google sheets, openoffice calc"
}
|
Java for Loop evaluation
I want to know if the condition evaluation is executed in `for` and `while` loops in Java every time the loop cycle finishes.
Example:
int[] tenBig = new int[]{1,2,3,4,5,6,7,8,9,10};
for(int index = 0;index < tenBig.length;index++){
System.out.println("Value at index: "+tenBig[index]);
}
Will the `index < tenBig.length` be execute every time the loop cycle finishes?
Assumption and experience tells me yes.
I know that in this example the `tenBig.length` is a constant, so there won't be a performance impact.
But lets assume that the condition operation takes long in a different case. I know the logical thing to do then is to assign the `tenBig.length` to a variable.
Still I want to be sure that its evaluated every time.
|
Yes, it will logically evaluate the whole of the middle operand on every iteration of the loop. In cases where the JIT knows better, of course, it can do clever things (even potentially removing the array bounds check within the loop, based on the loop conditions).
Note that for types that the JIT doesn't know about, it may not be able to optimize specifically like this - but may still inline things like fetching the `size()` of an `ArrayList<T>`.
Finally, I generally prefer the enhanced for loop for readability:
for (int value : tenBig) {
...
}
Of course, that's assuming you don't need the index for other reasons.
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 12,
"tags": "java, loops"
}
|
quicksight average count, receiving 'unavailable' on all rows
I have a table like this on my spice:
schema name deal_id
a 1
a 1
a 2
b 1
b 2
b 3
I need to generate a diagram showing the average number of deals per each schema,
this is what I think should make it work:
avgOver(count({deal_id}), [{schema_name}])
but it doesn't in the dataset I see the column with all 'unavailable' values.
I get the same result with this:
avgOver(countOver({deal_id}, [{schema_name}]), [{schema_name}])
I'm not sure what's the problem,
the calculated result I need for my chart would be like (with the data above):
schema name average number of deals
a 1,5
b 1.0
|
Choose a visualisation that has a group by field well and put the schema name here, put the deal_id in the value field well and choose the aggregation type of average to achieve what you want
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "amazon web services, amazon quicksight"
}
|
Do I need to run ForestPrep and DomainPrep after uninstalling Exchange Server 2003?
We've migrated our email to Office 365, so I now need to remove our one and only on-premises Exchange Server (2003 Standard).
The documentation that I've read suggests that I:
1. Go to a command prompt (running as Administrator)
2. With the Exchange Server 2003 installation CD in the drive, go to the D:\Setup\i386\ directory and run Update.exe /removeorg
3. Run Setup.exe /forestprep
4. Run Setup.exe /domainprep
5. Done?
Why should I need to run setup.exe /forestprep and setup.exe /domainprep? There is no explanation of this in what I've read and when I look up what these do, it appears that they prepare for an **installation** of Exchange, not an **uninstallation**.
|
I recommend you visit Technet documentation on uninstalling Exchange. Simply uninstalling an Exchange server is different from uninstalling the last Exchange server in your environment. If you need/want to uninstall Exchange **and** then remove it from AD, visit this article, which lays out the proper order in which to do it.
Rerunning the forest and domain prep operations is recommended, with the intent of allowing Exchange to be reinstalled or installed at a later date. If you're certain you won't, then, strictly speaking, you don't need to prep the domain and forest again, but given the triviality of the operation (and the fact that your schema has already been extended to allow the Exchange install in the first place), I see no reason not to.
Rerun the forest and domain prep to leave the environment in a proper, pristine state for the next guy or your future self, because it's a good idea, and there's no drawback to doing so.
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 0,
"tags": "exchange 2003, microsoft office 365"
}
|
How to select rows in a dataframe based on an "or" operator of values of a column
Say I have a dataframe `df` which contains the variable `'Age'`.
I know if I want to select rows with `'Age' >= 25` and `'Age' <= 35` then I can use:
df1 = df[(df['Age']>=25) & (df['Age']<=35)]
What if I want to select rows with `'Age' <= 10` or `'Age' >= 40`. Is there an equivalent `or` sign just like how `and` sign is `&`? I have tried the code below and it doesn't work:
df1 = df[(df['Age']<=10) or (df['Age']>=40)]
|
You can use the OR operators which is | (pipe). From the pandas docs.
> Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.
<
This worked for me
df1 = df[(df['Age']<=10) | (df['Age']>=40)]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, dataframe, operators"
}
|
Jenkins2 Pipeline detect SCM changes
I have a pipeline that runs a bunch of jobs. In this case for the subversion trunk. It lets me select the option to poll SVN with a cron-job, but not which repo location to poll.
How can I specify that? Do I need to specify it? Would I rather start a sub job?
|
Solution as in here:
1. Put the pipeline script into a Jenkinsfile in your repo's root directory (commit it)
2. Change the pipeline definition to "Pipeline from SCM script", add the repo URL, add the credentials
3. Set the polling interval
4. Make a manual commit to your SCM to check if it is picked up correctly
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "svn, jenkins, jenkins pipeline, jenkins 2"
}
|
Jquery .get function returns [Object object]
function getsession(){
var data = $.get('../session', function(data)
{
return data;
});
return data;
}
alert(getsession());
returns `[object Object]`
I want it to return the data from the GET.
|
try this instead
function getAndProccessSession(){
$.get('../session', function(returnedSessionData)
{
console.log(returnedSessionData);
});
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ajax, jquery"
}
|
Slashes in a query string parameter?
How can I send a file path as a query string parameter?
This is my string parameter:
> //domain/documents/Pdf/1234.pdf
I have tried that:
[HttpPost]
[Route("documents/print/{filePath*}")]
public string PrintDocuments([FromBody] string[] docs,string filePath)
{
.....
}
But this is not working, I guess because of the double slashes in the beginning of the parameter.
Any idea?
|
If, like you say, that entire string is the parameter, and not a route, you will need to URL encode it. You should always do this anyway:
System.Net.WebUtility.UrlEncode(<your string>);
// %2F%2Fdomain%2Fdocuments%2FPdf%2F1234.pdf
> Update
Since that is not working, I would suggest you Base64 encode it instead of URL encode it:
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(<your string>);
var encodedFilePath = System.Convert.ToBase64String(plainTextBytes);
..and in your controller decode it:
byte[] data = Convert.FromBase64String(filepath);
string decodedString = Encoding.UTF8.GetString(data);
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 14,
"tags": "c#, asp.net mvc, url routing"
}
|
Absolute sizing using CSS
I know there are some absolute-size units available in CSS. For example, cm, in, mm... But when I use them in my webpage, they are rarely honored.
The information about screen physical size and pixel resolution should be available from the EDID - so the browser can access them and calculate the amount of pixels in 1 cm on that particular device. I am talking about ordinary CRT/LED/Plasma screens, not projectors.
I want ot use it with mobile devices. A common standard is for every touch target to be at least 9 mm in size. But when I use `height: 9mm` in my CSS code, then the real size is about 3 mm on my HTC Desire HD.
So how can I make browsers display elements using the absolute size?
|
I figured a way: most browsers send the device type along the HTTP request in user-agent header. Based on that information, I then can on the server find out the real DPI and send it back along in the response (as a modified CSS, for example).
However, it is costly to keep and maintain a database of devices to get the precise DPI. I ended up using approximate DPI from a set of common parameters. The 1mm in not constant in that case, but the differences should be minimized (generally).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "javascript, android, html, css, android browser"
}
|
Can cookies sent by PHP be disabled from the server?
Can cookies sent by PHP be disabled from server?
|
Yes, they can. You can do this using `.htaccess` by setting the following values:
Header unset Cookie
Header unset Set-Cookie
Please note that if the server has sent cookies to a browser in the past, then the browser might still be sending back cookies to the server.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "php, apache, http, .htaccess, cookies"
}
|
Проблемы указания пути в java
Смотрите, у меня есть переменная
os = new FileOutputStream(MWBank.DataFolder + "\\Log.txt", true);
(MWBank.DataFolder - возвращает путь к Desktop/wer/plugins)
но по итогу в ubuntu происходит это (на винде этого нет) . The first text-box is for the caption, and its source is
=IIf([record] Is Null,"","Caption:")
The second is the record value itself. If record is null then the value of both text-boxes is "" and null and they do not appear nor take any space in the form.
Two question:
1. This doesn't seem like the smartest way to do it. Anyone has a better idea?
2. The report also contains check-boxes, and this method only works if I check/uncheck at least one check-box before I generate the report. Otherwise all captions appear anyway. This is very weird - anyone has any idea why it happens?
|
This will only work properly with Print Preview, not MS Access 2010 report or layout view. You will need Can Shrink on the control to close up the gaps. In Access 2010, "*_Label" is the default name assigned to labels of controls.
Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
Dim ctl As Control
For Each ctl In Me.Controls
If ctl.ControlType = acLabel And ctl.Name Like "*_Label" Then
ctl.Visible = Not IsNull(ctl.Parent)
''Bound checkboxes are never null, so hide false
If ctl.Parent.ControlType = acCheckBox Then
ctl.Visible = ctl.Parent
ctl.Parent.Visible = ctl.Parent
End If
End If
Next
End Sub
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ms access"
}
|
True color CImageList
How do I load a true color image into a CImageList?
Right now I have
mImageList.Create(IDB_IMGLIST_BGTASK, 16, 1, RGB(255,0,255));
Where `IDB_IMGLIST_BGTASK` is a 64x16 True color image. The ClistCtrl I am using it in shows 16 bpp color. I don't see a Create overload that allows me to specify both the bpp and the resource to load from.
|
Needs 4 lines of code, but this works:
CBitmap bm;
bm.LoadBitmap(IDB_IMGLIST_BGTASK);
mImageList.Create(16, 16, ILC_COLOR32 | ILC_MASK, 4, 4);
mImageList.Add(&bm, RGB(255,0,255));
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "c++, mfc"
}
|
Potential spam: Recovery Toolbox for Access
Question: Microsoft Office Access has detected corruption in this file. To try to repair the corruption, first make a backup copy of the file.
Oddly, the person asking the question joined Database SE and SO recently. But the person asked on SO.
More oddly, the person asking the question is `williamr86`. And the person answering is `geraldh88`. They joined within hours of one another.
I'm bringing it up in case its spam ring behavior, and the spam filters could be tuned.
|
Our spam blockers are largely fed by user flags and moderator actions. So in this case, I spam-flagged the questions, destroyed the users, and that should help out a bit. Naturally, both of them came in via TOR, so take that with a grain of salt.
Thanks for the heads up and don't be afraid to use those spam flags in the future. :)
|
stackexchange-meta_stackoverflow
|
{
"answer_score": 20,
"question_score": 21,
"tags": "discussion, spam"
}
|
How to uninstall VMware Player?
I want to uninstall VMware Player on my Ubuntu 12.04 LTS system. How should I uninstall it?
|
sudo vmware-installer -u vmware-player
This issue has been discussed previously over here: <
|
stackexchange-askubuntu
|
{
"answer_score": 198,
"question_score": 117,
"tags": "vmware player, software uninstall"
}
|
create new None object in embedded python
I am writing a simple C wrapper for a Python module. What I need to do is create a new `PyObject*` that represents `None`. I can't figure out how to do this. Is there a simple function that will return a `PyObject*` pointing to `None`, similar to how `PyTuple_New` returns a `PyObject*` pointing to a new tuple or PyString_FromString` returns one pointing to a python string?
**Note** Is it possible that, when calling a function as below, passing a C `NULL` will work? example:
//pFunc points to a function with 2 arguments
PyObject *pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, PyString_FromString("hello"));
PyTuple_SetItem(pArgs, 1, NULL); // <--- will this create a python object representing None?
pValue = PyObject_CallObject(pFunc, pArgs);
|
According to the documentation, `None` is a singleton, and is accessible from C code as `Py_None`.
> `PyObject* Py_None` The Python `None` object, denoting lack of value. This object has no methods. It needs to be treated just like any other object with respect to reference counts.
>
> `Py_RETURN_NONE` Properly handle returning `Py_None` from within a C function.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 5,
"tags": "python, c, null, embedding"
}
|
How do I open the attachment txt file from server response using perl?
sorry if, this question seems simple, but I have been searching for a while now and have not found an answer that can be applied to my situation.
I wrote a little perl script that uploads a file to a server. This server responds with a:
> HTTP/1.1 200 OK
It wasn't until I read the response as string:
print $res->as_string, "\n";
that I saw that the server seemed to have attached his response in a file:
> Content-Disposition: attachment; filename=filename.txt
**How do I get to the content of this .txt file using perl?**
|
The `Content-Disposition` header in the HTTP response is mainly a hint for browsers to save the file as download named `filename.txt`. You can access the file just like the content of every other HTTP response:
$res->content
or
$res->decoded_content
I assume you use `LWP::UserAgent`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "perl, attachment, mime, content disposition"
}
|
How to tell which product did user bought in server for IAP
I want to do receipt validation on server, which is quite normal for security concern. But I my case, there is a database on my server recording which products user purchased and provide services according to those records on server. So, I tried to read data from receipt from apple server response to find out what,when,how much user bought the items. But according to apple docs It seems that apple reserved the right to change the json keys for each data field.
So, what's the right way to inform server about receipt information on server side securely?
|
I haven't seen the bit about fields changing in any docs. In the response to the server validation request there is a receipt object. Each object has fields including "product_id", "quantity", "purchase_date" and several other pieces of information. These fields contain the information you want. My server validation code makes active use of the product_id so I am confident it works. Haven't used the others.
My response is based on < and my server side code.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, in app purchase"
}
|
PHP Date() error after upgrading to 5.3.8
I'm getting the following error all over my websites after upgrading to PHP 5.3.8:
> Warning: strtotime() [function.strtotime]: It is not safe to rely on the system's timezone settings. You are _required_ to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/Chicago' for 'CDT/-5.0/DST' instead in ....
My php.ini file has date.timezone = "America/Chicago" so I'm not sure why this warning is being thrown.
## Note
Defining on a per page basis is not feasible at this point. This is impacting several websites and thousands of pages. I have checked phpinfo() for the site and see the following response:
<
|
double check that the php.ini that has the timezone setting is the one php is loading. you can check phpinfo() for which one is being used. Also, maybe restart apache.
although, defining on a per page basis is not feasible as you stated, although not idea, if using apache, you can set the value in a .htaccess or the httpd.conf file. php_value date.timezone America/Chicago even if just a temp fix.
So you can accept and close the question. Thanks.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "php"
}
|
Formulating a LP minimization problem
 = \sum_{i=1}^7 x_i$. The constraints:
$$ x_1 \leq 17 $$ $$ x_1 + x_2 \leq 13 $$ $$ x_1 + x_2 + x_3 \leq 15 $$ $$ x_1+x_2+x_3+x_4 \leq 19 $$ $$x_1 + x_2 + x_3 + x_4 + x_5 \leq 14 $$ $$ x_2 +x_3 + x_4 + x_5 + x_6 \leq 16 \; \; \; \text{day 1 needs 2 days off} $$ $$ x_3 + x_4 + x_5 + x_6 + x_7 \leq 11 $$ $$ x_i \geq 0 $$
Is this a correct formulation?
|
Not really.
Guide:
The nurse who are present on day $1$ are the ones who start from day $4,1,5,6,7$. Hence,
$$x_1 + x_4 + x_5 + x_6 + x_7 \ge 17.$$
Use the same strategies on various days.
Also, we have to impose nonnegative integer constraints and remember to write down the objective function.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "linear programming"
}
|
how to find tags near to mouse click in tkinter python gui
How can i identify a tag near to mouse click. here my definition "identify" should identify tag very near to mouse click.
from Tkinter import *
root = Tk()
f=Frame(root)
f.grid()
w=Canvas(f)
line1=w.create_line(50,50,150,150, width=5, tags="line1")
line2=w.create_line(100,100,100,350, width=3, tags="line2")
line3=w.create_line(150,150,150,450, width=3, tags="lines")
w.grid(row=0, column=0)
w.bind("<Button-1>", identify)
def identify(event): ## this should identify the tag near to click
u=Frame(f)
u.grid(row=0, column=1)
root.mainloop()
Thanks
|
Use `find_closest` and `gettags`:
def identify(event):
item = w.find_closest(event.x, event.y)[0]
tags = w.gettags(item)
print tags
By the way, you have to define the function before you bind it to the event.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "python, user interface, tkinter"
}
|
What does char* assignment do?
I have a char* and I'm assigning another char* to it. I want to know what all is going to happen through that instruction?
For example:
char* foo; // suppose it is initialized and defined
char* bar = foo // I am defining bar
What all would happen(to foo and bar) after calling the assignment operation wrt values, memory etc.
I am new to C, maybe very trivial question for some of you.
|
Lets say we have two pointers initialized to point to different strings:
const char *foo = "abcd";
const char *bar = "efgh";
If we "draw" how they would look in memory, it would be something like this:
+-----+ +--------+
| foo | ---> | "abcd" |
+-----+ +--------+
+-----+ +--------+
| bar | ---> | "efgh" |
+-----+ +--------+
Then we assign to `bar`:
bar = foo;
Then it would look something like this instead:
+-----+ +--------+
| foo | -+-> | "abcd" |
+-----+ | +--------+
|
+-----+ | +--------+
| bar | -/ | "efgh" |
+-----+ +--------+
Now both `foo` and `bar` are pointing to the same location.
In shorter form, that's what a definition with initialization like:
const char *bar = foo;
will do.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "c, char"
}
|
sping boot - how to configure application class in a different package, and controllers and services in other package
We generally define our main application class in a root package above other classes.
The **Spring Boot Application** annotation in the main application class implicitly loads other classes as its the base package.
MY Question my main class is in com.example.main my controller class package is com.example.controller
when i run as Spring boot app, application is loaded but the rest API throws 404, how to configure parallel
|
As your main class is not in root package, you need to annotate `@componentScan` in your main class as below.
@SpringBootApplication
@ComponentScan({"com.example.controller"})
public class SpringBootApplication {
//...your code.
}
In case you want to scan all the sub-class you need to pass the root package path in componentScan
@ComponentScan({"com.example"})
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "spring boot"
}
|
how to retrieve same image to android phones with different screen densities+json
I am a beginner to android development field.I need to create an app in which the contents are taken from web.So i need to retrieve images from a url using json.I know how to retrieve image using JSON.But my problem is my app should supports phones and tablets.So the image should fit into the appropriate devices.So my question **how do i retrieve same image into different screen densities using JSON?**. ** _So do i need to keep different sized images URL's for retrieving images into corresponding device(by using some checking to find whether the device is tablet or phone) or storing only single large image in URL and after retrieving it,and croping it to fit the container?_**.Please help me to find a solution?
|
You should use different images for different devices as recommended by android. You can place images for different densities e.g hdpi, xhdpi, xxhdp etc on your server.
Now check density and download image accordingly. Here is example how you can check density of device
switch (getResources().getDisplayMetrics().densityDpi) {
case DisplayMetrics.DENSITY_LOW:
// ...
break;
case DisplayMetrics.DENSITY_MEDIUM:
// ...
break;
case DisplayMetrics.DENSITY_HIGH:
// ...
break;
case DisplayMetrics.DENSITY_XHIGH:
// ...
break;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "android, json, image"
}
|
Recursive :include in Rails ActiveRecord
Say I have these models
class Project < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :project
belongs_to :user
end
class User < ActiveRecord::Base
has_many :comments
end
So that I can do
p = Project.find(1, :include => :comments)
p.comments.collect(&:user).collect(&:name) # this executes select for each user
How do I say I want to also include comment's user?
|
I believe `:include => {:comments => :user}` should work.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 4,
"tags": "ruby on rails, activerecord"
}
|
I need to make a programm that prints not only the result but also how that amount is calculated
I have to make a program that calculates the sum of consecutive numbers 1 + 2 + 3 + ... until its value is at least the number entered by the user and also prints not only the result but also how that amount is calculated.
Here is my code
where_to=int(input("Number: "))
number=1
sum=1
while sum < where_to:
number += 1
sum += number"
|
You can make this quite simple:
where_to=int(input("Number: "))
number=1
sum=1
out = "1"
while sum < where_to:
out = out + " + " + str(number)
number += 1
sum += number
print(out)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "python"
}
|
How to contribute to Stack Overflow besides asking and answering?
Besides contributing great questions and answers, are there any other ways that I can contribute to Stack Overflow and its family of websites?
I would be happy to
1. give a PayPal donation
2. contribute code
SFOU has been helping me tremendously, so it's only fair if I can give back something.
|
Clean up other people's contributions. Additionally, flag inappropriate postings, and vote to close/migrate questions when necessary.
Sporting your flair elsewhere brings more attention to SO as well.
|
stackexchange-meta
|
{
"answer_score": 40,
"question_score": 41,
"tags": "discussion, contribution"
}
|
Extract separate non-zero blocks from array
having an array like this for example:
[1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1]
What's the fastest way in Python to get the non-zero elements organized in a list where each element contains the indexes of blocks of continuous non-zero values?
Here the result would be a list containing many arrays:
([0, 1, 2, 3], [9, 10, 11], [14, 15], [20, 21])
|
>>> L = [1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1]
>>> import itertools
>>> import operator
>>> [[i for i,value in it] for key,it in itertools.groupby(enumerate(L), key=operator.itemgetter(1)) if key != 0]
[[0, 1, 2, 3], [9, 10, 11], [14, 15], [20, 21]]
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 9,
"tags": "python, numpy, extract"
}
|
Computing an integral in spherical coordinates
!enter image description here
Here, $x$ is in $\mathbb{R}^n$.
Could you explain why we can change coordinate in this way? What's the geometric interpretation of $x=r\omega$? (What does $r$ stand for?) Thanks!!!
|
Integral $\displaystyle \int\limits_{{|x|}\leqslant{1}}{x^{\alpha}{|x|}^{\lambda}\,dx}$ is a multiple integral over the unit closed ball $$B=\\{x\in{\mathbb{R}^n}\colon\;\;\; |x|\leqslant{1}\\}=[0,\;1]\times{S^{n-1}}.$$ In spherical coordinates for $x =r\omega \in B$, we have $r=|x|\in[0,\;1], \;\;\; \omega \in S^{n-1}, \;\;\;dx=r^{n-1}\, dr \, d{\omega}.$
I suppose that integral $\color{red} {\int\limits_{0}^{\infty}{r^{|\alpha|+\lambda+n-1}\,dx}}$ in your book must be written as $\int\limits_{0}^{1}{r^{|\alpha|+\lambda+n-1}\,dr}$ since $r$ varies from $0$ to $1$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "multivariable calculus"
}
|
Flying through Sheremetyevo airport in Moscow considering current situation?
At the end of next month I will be going from Asia through Sheremetyevo airport in Moscow to some other European country. The carrier of choice is Aeroflot.
Considering what is happening now between Russia and Ukraine (including rest of those involved) should I reconsider using this carrier/route? Are there any problems right now with flights using Sheremetyevo international airport?
Update: Thank you all for the answers. It's good to know, that there are no problems at this moment with flights going through Sheremetyevo.
|
There should be no problems, unless you're on a Ukrainian passport, according to the Russian in my team here. Even then it should be fine, you may just experience some questions on your reason for your trip. Of course, as you're just continuing on to Europe, you're going to get very little attention.
In terms of the city, it's far from Ukraine and the situation in Crimea. At present, it's fine. Sure, _something_ might happen between now and then, but it seems unlikely at present.
Your best bet is to make sure you have travel insurance, just in case - but it's unlikely that it'll need to come into play.
Also check with your country's travel advisory alerts for Russia. For example Australia's advisory points out that in addition to the Crimea incidents, there have been bombings in recent months, including terrorist attacks in Moscow. But again, it's unlikely, and right now, flights through Sheremetyevo are proceeding as normal.
|
stackexchange-travel
|
{
"answer_score": 8,
"question_score": 8,
"tags": "air travel, safety, russia, moscow, svo"
}
|
Event fees not showing on info page or registration page
Have set up an event with fees and pay later option (no payment processor installed yet)
The fee list does not show on the event info page,
And when following the register now link no fee option is given there either...
But if you complete the registration and billing contact details, you get an error message...
Please correct the following errors in the form fields below: Select at least one option from Event Fee(s).
Running D7, and Civi 5.13.4
Checked on dmaster- can't replicate
Checked on another site running 5.13.4 and got the same error
Anyone else seen this?
Are there permissions I've not checked?
|
This was an issue with the CiviCalendar extension < Disabled the extension and it works. New update to CiviCalendar 3.30 fixes the issue.
|
stackexchange-civicrm
|
{
"answer_score": 2,
"question_score": 0,
"tags": "civievent"
}
|
Preserve objects when saving image using FastStone Capture Image Editor
The FastStone Capture Image Editor ("FastStone Draw") allows you to annotate images with arrows, text, shapes etc. All these objects remain as vector-type objects and can be moved, resized, etc. You can close/open the "Draw" part of the editor and all the objects are retained, allowing further adjustment.
However, as soon as you save the image, it is "flattened" into a single raster image. (Even whilst the image is still open in the editor.)
Is there any way to save/export the image in a format that preserves all the annotation objects for later editing?

|
This missing feature has finally been added in FastStone Capture version 9.7 (September 10, 2021):
> * Introduced a new image format called FastStone Capture format (*.fsc). This loss-less format preserves annotation objects together with image data for future re-editing
>
Source: <
(I've tried it and it seems to work well!)
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 2,
"tags": "image editing, faststone capture"
}
|
Harddisk with >10k bad sectors
My computer has two drive : SSD for C drive ,HDD for D drive My Windows OS is installed in C drive
Recently ,when I click the folders ,the File Manager always hangs. I cant even turn off the computer (with deadloop). Cant turn on the computer as well ,it goes windows diskcheck (I spent >48 hrs on it and can't finish ).
Then I use HDD-SCAN to scan my HD(d drive) .It shows more than 5k bad sectors.
What should I do now ? Just reinstall the OS ? Buy a new HDD?Any HD repairing software ?
(noted that I cannot drag and drop to backup the file in d drive now )
 .It shows more than 5k bad sectors.
This drive is in such bad shape (many errors) that you should not use it. It will not be reliable.
So you should recover any data you can (put on an external USB drive). If you cannot do this because of the errors, you need to consider using a local data recovery agency to see if they can recover the data.
Then replace the drive.
Consider using a large, good quality SSD for replacement as that will likely work better.
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 0,
"tags": "windows, windows 10, hard drive, ssd, hard drive failure"
}
|
Exposing relational models to backgrid.js
I want to expose some attributes from relational model (builded via backbone-relational) to my backgrid (builded via backgrid.js). As I understand backgrid receives collection and mapped model as columns object. So I need to change model when the model initialised, e.g. something like:
initialize: function() {
this.fetchRelated('myRelatedModel');
this.set({relatedName:this.get('myRelatedModel').get('name')});
}
The problem is that when I do this, my model receives 'changed' state. But I don't want to change model, I only want to expose related model's attributes to my backgrid.
What should I do?
|
**JavaScript**
this.set({relatedName:this.get('myRelatedModel').get('name')}, {silent: true});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "backbone.js, backbone relational, backgrid"
}
|
Using Pyperclip to copy and paste a 2d array
I am using pyperclip in Python 3.6
If i have a giant 2D array(640X480) how can I copy it in one program and paste it another program using pyperclip copy() and paste() functions.
|
In the 1st program use the following code:
pyperclip.copy(array)
In the 2nd program use this:
array=eval(pyperclip.paste())
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "python, arrays, pyperclip"
}
|
Reflection to get value of class property in class
I have 2 type of class.
public class Info
{
public string name {get; set;}
public Address address {get; set;}
}
public class Address
{
public string addressInfo {get;set;}
public string country {get;set;}
}
**
> Edit:
Info info = new Info();
string subClass="address";
Type subType = info .GetType().GetProperty(subClass).PropertyType;
string val = typeof(subType).GetType().GetProperty("addressInfo").GetValue(data, null)?.ToString() ?? "";
> This is what I want to achieve but I cannot code in this way, cause it got error. **
Now I want to get the value of addressInfo in Address class that inside Info class by Reflection dynamically. How can I achieve this? Thanks!!!
|
You could try
var info = new Info();
var property = info
.GetType()
.GetProperty("address");
string val = (string)property
.PropertyType
.GetProperty("addressInfo")
.GetValue(property.GetValue(info));
_**Note** : This is lacking suitable error checking and fault tolerance, add pepper and salt to taste_
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "c#, class, reflection, properties"
}
|
How can I prevent form submissions until previous onFormSubmit is finished.
I have written a form script that eliminates the chosen answer. This means it has to process a function onFormSubmit. While the script works, the end-user has to wait 30 seconds before they click resubmit or else the choice will not be eliminated.
Is there a way I can prevent submissions until the onFormSubmit function is completed?
|
I was able to accomplish this (thank you AdamL) using setAcceptingResponses(enabled).
function onFormSubmit(){
var af = FormApp.getActiveForm();
var defaultClosedFor = af.getCustomClosedFormMessage();
af.setCustomClosedFormMessage("The form is currently processing a submission, please refresh the page.");
af.setAcceptingResponses(false);
<put your script stuff here>
af.setAcceptingResponses(true);
af.setCustomClosedFormMessage(defaultClosedFor);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "google apps script, triggers, google forms"
}
|
Simplify the expression $\frac{z^2-iz-1}{2iz}$
there is shown expression
If I have the statement $z=e^{iθ}$, then i don't need to rewrite $z$ as $x+iy$, do I? I can write $z^2-iz-1$ as $(z-i)^2$, but I got stuck at this point, what should I do next, which formulas should I use?
????
|
$(a-b)^2 \ne a^2 - ab + b^2$
$\dfrac{z^2-iz-1}{2iz} =\dfrac{z-z^{-1}}{2i}-\dfrac12 = \dfrac{e^{i\theta}-e^{-i\theta}}{2i}-\dfrac12 = \sin\theta - \dfrac12$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": -1,
"tags": "complex analysis, complex numbers"
}
|
How to reload/refresh html page in browser automatically after change? on Windows
Is there any way how to refresh (local?) page in browser (Chrome?) during development after change and save on disk? I think node.js is the direction?
|
Yes, you can use gulp for that. Install gulp (`npm install gulp --save-dev`) and use gulp.watch to watch file changes, then use `browser-sync` (npm install...) to reload the browser when files change.
Note that gulp takes some getting used to. See < for more info.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "html, node.js"
}
|
auto complete jQuery com 2 input
Tenho o seguinte autocomplete que funciona no 1º input, ao o completar ele preenche o 2º input.
O problema e que se apago a tag `<p>` ele não funciona. Alguém sabe me dizer o porque?
Segue o código:
$().ready(function() {
$("#singleBirdRemote").autocomplete("search.php", {
width: 260,
selectFirst: false
});
$("#singleBirdRemote").result(function(event, data) {
if (data)
$(this).parent().next().find("#xx").val(data[0]);
});
});
<p>
<input type="text" id="singleBirdRemote">
</p>
<p>
<input name="asdad" id="xx">
</p>
|
Acredito que isso ocorra por você recuperar a referência do segundo input de modo relativo, percorrendo a árvore do DOM.
Ou seja, você se baseia em **#singleBirdRemote** , busca o pai **p** , navega para o próximo elemento e busca pelo input **xx**. Quando remove **p** você quebra essa hierarquia.
$(this).parent().next().find("#xx").val(data[0]);
Pode substituir o trecho simplesmente por
$("#xx").val(data[0]);
Acredito que apenas isso já ajudará.
Tome cuidado ao navegar de modo relativo, qualquer alteração no código poderá te causar problemas. O ideal é ter referências precisas, por id, name ou class, dependendo da necessidade.
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery, autocompletar"
}
|
Neo4j embedded: filter on node properties using graph algorithm
I am using Neo4j embedded from eclipse and want to navigate through a network of trips and stations. They are connected the following way:
(t:Trip)-[:STOPS {arrival:"10:12:00", departure:"10:13:00"}]->(s:Station)
As a trip has several stops and there are several trips which stop at one station there are many connections. Sometimes it is not possible to get from one station to another without changing to a different trip. For that reason I use the following graph algo
PathFinder<Path> finder = GraphAlgoFactory.shortestPath(PathExpanders.forType(RelTypes.STOPS), depth);
ArrayList<Path> path = (ArrayList<Path>) finder.findAllPaths(source,target);
But I can't find if there are ways to filter on my properties `arrival` and `departure` because I want to find only trips which depart after a given time.
|
Instead of `PathExpanders.forType()` you need to use your custom implementation of `PathExpander`.
Your implementation would basically filter `path.endNode().getRelationships(RelTypes.STOPS)` for those having correct arrival and departure properties.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "properties, filter, neo4j, neo4j embedded"
}
|
Query all Machines with Printer ports -Like "*WSD*"
Some computers on my domain have had printers installed with the incorrect PortName. I have a list of all machines on my domain, and I can list all printers on a machine where the portname is like WSD using
Get-Printer -ComputerName $Computer | Where PortName -like "*WSD*"
But I want to have this run on every machine in my computer list and then create a CSV or text file with a list of every computer that has a printer with an incorrect port name.
This is what I have so far:
$ComputerList = Get-Content "c:\Temp\Computers.CSV"
foreach ($Computer in $ComputerList) {
$WSD = Get-Printer -ComputerName $Computer | Where PortName -like "*WSD*" }
I don't quite know how to finish the script to accomplish what I want. Please let me know if I've made anything unclear. Any help would be greatly appreciated.
|
Well first of all, you should import data from a `.csv` using `Import-Csv` so you don't get problems with the headers.
Second, you are on a right track, but maybe try it like this:
$ComputerList = Import-Csv -Path "c:\Temp\Computers.CSV"
$WSD = @()
foreach ($Computer in $ComputerList.<EnterHeaderNameHere>)
{
if (Get-Printer -ComputerName $Computer | Where-Object {$_.Portname -like "*WSD*"})
{
$WSD += $Computer
}
}
This would check if the result of your query returns a hit, and if so it would append the ComputerName to the Array `$WSD`.
You can then just forward to the array to an file by using either `Out-File` or `Export-Csv` if you want.
e.g.:
$WSD | Out-File -Path "c:\Temp\WSD.txt"
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "powershell"
}
|
how fputc affect file size?
I am using fputc (in C/C++) to output some data into a file, and the file size matters to me in my project. But the size of resutling file seems incorrect, a simple code example:
FILE *fp = fopen( "123.txt", "w" );
for( int i=0; i<64; i++ )
fputc( i, fp );
fclose( fp );
After excuting this code, the file's size is 65B, not 64B, but if I use `fputc(1,fp)`, the file size is 64B. Is there any trick? or anything I can do to control the size of output file?
|
I'd guess you're doing this on Windows.
Since you opened the file in translated (text) mode, new-lines are converted to a carriage-return/line-feed pairs. The character code 10 happens to be treated as a new-line, so you end up with an extra byte compared to what you wrote.
If you open the file in binary mode instead, this won't happen.
FILE *fp = fopen( "123.txt", "wb" );
Note the `b` added to the open mode-string.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "c++, c, filesize"
}
|
Equality and inheritance in python
When reading about how to implement `__eq__` in python, such as in this SO question, you get recommendations like
class A(object):
def __init__(self, a, b):
self._a = a
self._b = b
def __eq__(self, other):
return (self._a, self._b) == (other._a, other._b)
Now, I'm having problems when combining this with inheritance. Specifically, if I define a new class
class B(A):
def new_method(self):
return self._a + self._b
Then I get this issue
>>> a = A(1, 2)
>>> b = B(1, 2)
>>> a == b
True
But clearly, `a` and `b` are not the (exact) same!
What is the correct way to implement `__eq__` with inheritance?
|
If you mean that instances of different (sub)classes should not be equal, consider comparing their types as well:
def __eq__(self, other):
return (self._a, self._b, type(self)) == (other._a, other._b, type(other))
In this way `A(1, 2) == B(1,2)` returns `False`.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "python, inheritance, equality"
}
|
Javascript: regex escaped space
I have a directory with space on unix, so the space is backslashed. And I need to replace the backslashed space with semicolon. Tried multiple regex'es but not able to find the answer
var str = '/test\ space/a.sh -pqr';
So I am looking to get this after the replace /test;space/a.sh -pqr
console.log("replace: ", str.replace(/\\\s+/g, ";")); //This one doesn't work, (formatting is taking out one backslash)
|
Your regular expression is correct.
It's your example string that is incorrect - the `\` is not properly escaped:
var str = '/test\\ space/a.sh -pqr';
See the fiddle and read more special characters in JavaScript strings.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, regex, node.js"
}
|
How do I start a new dialog following a conversation from an old dialog in Choregraphe?
I'm trying to create a dialog flow in Choregraphe where when the output in the 'Dialog' topic gets triggered (eg. $next=1), a new dialog 'Dialog(1)' gets activated and the new topic can be used by the user.
What happens is the visual on the cable flows to 'Dialog(1)' box, but the bot still only accepts the input patterns from the original topic.
simple example: <
How do I make the bot listen to the Dialog(1) topic once the 'next' output is triggered?
|
You must change the nature of the output "next" of the emitting box "dialog" from "punctual" to the "onStopped" type. So the box will be stopped just after emitting.
Right click on the output, then "edit output", then "nature" dropbox.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "dialog, topic modeling, nao robot, choregraphe"
}
|
Android Turn on/off Camera Flash Programmatically with Camera2
I am making a simple application that acts as a flashlight. I need to be able to turn on and off the flash from a button in the application with the Camera2 API, as I get errors with the old camera API. I would like to use a "torch" flashlight, where the camera doesn't have to open in order for the flash to turn on. I know it's possible, as lots of phones have a flash on/off in the quick settings menu, but I can't find any code or tutorials about how to do this.
Code:
Camera cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
I am running on a Nexus 6P with Android 6.0.1.
EDIT: I need to use the Camera2 API. I haven't found a good tutorial for this yet, and after getting an answer, I will create one in Q/A format on here.
|
I'll be addressing you to the Android Dev. documentation about the CameraManager since more code will be required but this is the basic code to activate the Flash on the camera in API's above 21.
CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position.
camManager.setTorchMode(cameraId, true);
Android CameraManager documentation.
Android.hardware.camera2 documentation.
very important thing to remember that you will need to use try/catch to discard possible errors and ofcourse check that no other higher priority application is using the camera at the moment.
|
stackexchange-stackoverflow
|
{
"answer_score": 21,
"question_score": 4,
"tags": "android, android camera, android camera2"
}
|
Calling a method using strings
I have an object like so:
var x = {
"fx": function() {...}
}
I have the name of the object (`y = "x"`) and the function (`z = "fx"`) and have them as strings.
I know I can call the function through the use of eval through the following method or similar:
eval(y.z)
However, I would like to avoid using eval to accomplish this. I know the `apply` prototype method takes a function and applies it to an object, however searching for the function reference is impossible as the function is contained within the object.
I know this problem is not a new one and hence must have a solution, but I cannot find it. Any help would be appreciated.
|
You can use
x[y]()
to call the function with a variable
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript"
}
|
What's the token field in the Order response from the Shopify API?
When fetching an order from the Shopify API a field called `token` is included. There's no details for this filed in the documentation page or the wiki page.
What is this field? Is it a token from a payment processor?
|
This is unique identifier for the Order object that is used during checkout. It is not a field from a payment processor.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "shopify"
}
|
Getting aggregate by other property than ID in Prooph
How simplest get aggregate from aggregate repository without know his ID but knowing of other unique property? For example I have `Cart` which has ID as AggregateId and `ownerId` as other property.
|
In CQRS (assuming you have such a system), when transacting against an aggregate root, you need the state of the aggregate to make the decision in order to preserve the invariants.
On the read side, the typical pattern is to project/denormalise/index the data as appropriate to facilitate querying as you'll need it.
So typically, you'll have a projection track each event and index based on the `OwnerId` to facilitate the querying. If this is only for the purpose of lookup to run some decision processing command, that can be as simple as a map of `OwnerId` to owned `CartIds`.
* * *
You haven't provided much context; it depends whether you're trying to build an order history system or a shipping etc. You're much likely to get a good answer to any followup question if you explain more about what you're trying to achieve overall
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, cqrs, event sourcing, prooph"
}
|
Manage keypress
I'm using MASM syntax , and I want to get a keyboard key press then store it to use it later in code , I've tried using : int 21h interrupt but it seems that it doesn't work under 32-bit.
Is there any other way to achieve that ?
thanks.
|
If you want to switch to Windows, you could probably use the `GetKeyboardState` function to find out if one or more keys are being pressed. Even easier than using `GetKeyboardState` would be to use something like the following:
.486
.model flat,stdcall
option casemap : none
include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
include \masm32\include\msvcrt.inc
include \masm32\macros\macros.asm
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\msvcrt.lib
.data?
key dd ?
.code
start:
printf("Press a key..")
call crt__getch
mov key,eax
printf("\nYou pressed key number %d", key)
invoke ExitProcess,0
END start
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "assembly, 32 bit, masm, masm32"
}
|
Is "An unfathomable chaos" grammatically correct?
I am writing a blog where I describe a problem as leading to "an unfathomable chaos", which is being underlined by Grammarly plugin for Chrome. Is it a mistake on my behalf or Grammarly is getting it wrong?
|
It appears that Grammarly objects to the use of the word "chaos" as a countable noun, with a singular article "an". Indeed "chaos" is normally uncountable.
It is possible to use chaos as a countable noun. So "an unfathomable chaos" is perfectly good English, and Grammarly is indeed getting it wrong. But perhaps you should consider rephrasing. It's not very clear how a problem could be "a chaos".
|
stackexchange-ell
|
{
"answer_score": 1,
"question_score": 0,
"tags": "grammar"
}
|
Value of $\int_{-\infty}^\infty\frac{\cos x}{1+x^2} \, dx$
I am a bit puzzled by the expression $\displaystyle I=\int_{-\infty}^\infty\frac{\cos x}{1+x^2}\,dx$.
If I try solving it using Cauchy's formula, I arrive to $I=2\pi i \frac{\cos i}{2i} = \pi\cos i$.
**EDIT** : In detail, I am trying the common trick of calculating the integral over a semi-circumference of radii $r$ and the line from $-r$ to $r$. Since the integral over the semi-circunference goes to zero as r goes to infinity, I can use that to calculate the integral over the real line.
But the result I expected is $\frac{\pi}{e}$, since that is what i get if I first substitute $\cos x$ by $e^{ix}$ in the expression, which should be a legal move since $e^{ix}= \cos x + i \sin x$ and $\sin x$ is an odd function, so its integral from $-\infty$ to $\infty$ is $0$.
What is going on?
|
Yes what you used should be a bit modified as ,
$$ I = \int_{-\infty}^\infty \frac{\cos x}{1+x^2} \, dx = \operatorname{Re} \left(\int_{-\infty}^\infty \frac{e^{ix}}{1+x^2} \, dx\right) $$
Now if you compute the residue you would get the value as $\displaystyle 2\pi i \left(\frac{1}{2ie}\right) = \frac{\pi}{e}$ which is the desired answer using complex analysis.
It is well know example to convert trigo problems in exponential forms so as it vanishes under the semicircular arc.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "integration, hyperbolic functions, cauchy integral formula"
}
|
selenium fails to open intended new window
I am trying to automate web based application (asp.net) through selenium web driver.
Web application has login page and once I log in, I need to click on a button that opens a new window and then perform operations on this new window. So far, my code is able to login and click the button. Two problems here:
* instead of opening desired window on click, it opens the login page
* this login page is opened in the same window, not new one
I have used below statement to switch to new window:
webDriver.SwitchTo().Window("newwindowname");
|
Have you tried to use the window handle?
Get the window handles
ReadOnlyCollection<string> handles = webDriver.getWindowHandles();
String myWindowHandle = handles.LastOrDefault();
And use the last one in the swtichTo statement
webDriver.switchTo().window(myWindowHandle );
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, selenium, webdriver"
}
|
Software suggestion: hand tracing photo to vector on tablet
I am looking for software that let's me _trace_ a photo by hand on an android device and then have the result saved as vectors (EPS, SVG, whatever).
The task is trivial
The only reference I could find was "morpholio", but that seems to be available for iOS only. (And trust me, I had a _very_ thorough look around the PlayStore).
Basically, I would like to use my android tablet as a poor-mans' Wacom.
|
You could use the Adobe Illustrator Draw app. It works on Android devices, and is available in the Google Play store.
To add an image, begin a new project. Tap the Layers icon, tap the + icon to add a new layer. Choose "Image Layer", select an image from your gallery or take a photo, or use select one from your cloud files, etc.
If you tap on the image layer icon, you can set the layer opacity low, so you can trace over it.
When you have finished, press the Upload icon, and send the project to Adobe Illustrator (desktop version) - make sure you have the application open already on your computer before doing this, and from there you can export as SVG, or whatever format you want. Obviously you'd need to have an Adobe CC account for this last step.
|
stackexchange-graphicdesign
|
{
"answer_score": 2,
"question_score": 0,
"tags": "vector, software recommendation, android, applications, tracing"
}
|
`c('q01') %in% c('q01','q04')` should be TRUE,but doesn't work in condition loop
target<-data.frame(q01=1,q03=1:10)
total<-list(t1=c('q02','q05'),t2=c('q01','q04'),t3=c('q03','q06'))
for(m in colnames(target)){
for(j in seq_along(total)) {
if(m %in% total[j])
print(names(total)[j])
}
}
As `c('q01') %in% c('q01','q04')` is TRUE,the expect result of above script is:
t2
t3
But I cannot get any output,where is the problem?
|
Alternatively you could achieve this with
names(total)[sapply(total, function(x) any(x %in% colnames(target)))]
[1] "t2" "t3"
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "r"
}
|
What's the "Thumbs up" setting in Motorola Camera app
I have Motorola Moto Z Play phone. **When switching to front-camera** in Camera app, there is a setting that I haven't figured out it's purpose. It has three possible options:
* Off
* Manual (shows a slider which its value can be chosen from 1 to 7).
* Auto
Here is a screenshot of this setting:
. I came up with the above regex but unfortunately not the right output that I would like to. CD3 should be matched as it starts it letters and the dash(-) in between the numbers should not.
Appreciate the help!
|
I would use this pattern:
(?<=^|\s)[^0-9].*?(?=$|\s)
Rather than using word boundaries, I use lookarounds instead. These lookarounds assert that a word ends if what precedes is whitespace or the start of the input, and what proceeds is either whitespace or the end of the input. The reason for this is that using `\b` might fail for terms such as `a10-333`.
## Demo
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "regex"
}
|
S3 Hosting + Api Gateway
I'm trying to host a static site in S3 with ability to handle some dynamic content using Lambda/Api Gateway. Can't seem to be able to do that. I want URLs to look like this:
example.com/index.html
example.com/images/*
example.com/css/*
example.com/api/* -> API Gateway
Also, when redirecting I'd like to keep the example.com as a root domain. I tried RoutingRules in S3, but redirects from the client. I need this to be transparent from the user, like proxying requests.
|
You can configure this by putting a CloudFront distribution in front of both the API Gateway API and the S3 bucket for static content. This would also allow you to take advantage of CloudFront's edge caching.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 9,
"tags": "redirect, amazon s3, aws lambda, aws api gateway"
}
|
Azure SQL Database or SQL Server in a Virtual Machine?
I'm exploring whether to use Azure SQL Database or SQL Server in Virtual Machine. What are the pros and cons each of them?
Thank You.
|
Well...SQL Azure is PaaS, and Sql Server in VM is IaaS. Just to highlight some differences.
1. Control & Features - You got a greater control and features in IaaS where else in PaaS you got to stick with the features they have.
2. Redundancy & Backup - By default, SQL Azure comes with 3 copies of redundancy and you can enable geo-replication to nearest datacenter too. Backup is automatically done for 7 days and onwards depending on the pricing tier.
3. Cost & Ownership - Basic DB in SQL Azure cost you USD5, however in VM, you can host as many db possible albeit more expensive to rent a single VM.
Check this link out to find out more details
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "sql server, azure, azure sql database"
}
|
How to get radio button selection in Rebol 3?
How do I get the value a user selects in a radio button group? Here is a simple code, what should I add in order to be able to retrieve the user selection? I couldn't find it in the docs.
view [
radio "First"
radio "Second"
radio "Third"
]
|
probably not the only way, but you can set an external variable, as in
x: 0
view [
radio "First" on-action [set 'x 1]
radio "Second" on-action [set 'x 2]
radio "Third" on-action [set 'x 3]
]
print x
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "rebol, rebol3, r3 gui"
}
|
Unable to generate ssh public key when installing Redmine
I am trying to set up a Redmine on my server, and I am following THIS setup guide. I have used this guide before on my VPS and it worked perfectly however on this server I get following error when I try to generate public key.
aristotle:~# sudo su - redmine
No directory, logging in with HOME=/
redmine@aristotle:/$ ssh-keygen -t rsa -N '' -f ~/.ssh/gitolite_admin_id_rsa
Generating public/private rsa key pair.
open //.ssh/gitolite_admin_id_rsa failed: No such file or directory.
Saving the key failed: //.ssh/gitolite_admin_id_rsa.
redmine@aristotle:/$
|
Ok solved ... I just had to do
`sudo mkdir .ssh` in that directory
|
stackexchange-unix
|
{
"answer_score": 0,
"question_score": 0,
"tags": "debian, ssh, redmine"
}
|
Required Field Validator For RadioButton Columns Inside Gridview
I have `GridView` and one columns is a `RadioButton` for select. How can I set a validator for columns to check that at least one `RadioButton` is selected?
|
I posted to a similar question the other day with a solution that should work for you:
How to check that at least one RadioButtonList has an item selected?
It uses a `CustomValidator` with a server side check to ensure at least one item is selected. You will need to substitute looking for a `RadioButton` instead of the `RadioButtonList` and maybe a few other tweeks but the code should work for what you need. It searchs for all of one type of control and checks for a specific critera. In your case look for all `RadioButton` controls and ensure at least one is checked.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "asp.net, gridview, radio button, validation"
}
|
how to know the version of .NET? or convert a project from 4.0 to 4.5.1?
I had a project which first target was .NET4.0 but now I change the project to 4.5.1, and I would like to know how to check the version of .NET, because I run the application in a fresh win7 and the application runs.
I try to use this code to check the version of .NET that is used:
string version = System.Reflection.Assembly
.GetExecutingAssembly()
.GetReferencedAssemblies()
.Where(x => x.Name == "System.Core").First().Version.ToString();
MessageBox.Show(version);
And the result is 4.0.0.0, so how I am thinking that the application is still 4.0. How can I change the target of the application?
Thanks.
|
Check this if it helps. I have tested it in a web application. It's showing correct values.
var targetFrameWork = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Runtime.Versioning.TargetFrameworkAttribute),false);
var frameWork = ((System.Runtime.Versioning.TargetFrameworkAttribute)(targetFrameWork[0])).FrameworkName;
It returns '.NETFramework,Version=v4.5'.
Note:
Environment.Version returns '4.0.30319.18444'.
System.Reflection.Assembly.GetExecutingAssembly()
.GetReferencedAssemblies()
.Where(x => x.Name == "System.Core").First().Version.ToString();
It returns '4.0.0.0'.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c# 4.0"
}
|
MYSQL Syntax error for Insert / Update query linked to a secondary table
I have a query which is suppose to either update or insert based upon whether the row exists.
I then also connect it to a secondary table so i can link them on the correct id's but im getting a syntax error and am unsure how to fix it.
This is my query:
INSERT INTO resources as r (r.quantity,r.tid)
SELECT r.quantity+?,u.tid
FROM users u WHERE u.uid = ?
ON DUPLICATE KEY UPDATE
r.quantity = r.quantity+?, r.tid = u.tid
The error is
You have an error in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'as r (r.quantity,r.tid) SELECT
r.quantity+'0',u.tid FR' at line 1
Any one able to explain the what I have misunderstood and how i fix it?
|
The `insert` statement doesn't take aliases. I think you want something like this:
INSERT INTO resources(quantity, tid)
SELECT ?, u.tid
FROM users u
WHERE u.uid = ?
ON DUPLICATE KEY
UPDATE quantity = quantity+?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, pdo"
}
|
Saving data to a json file using python
I have JSON data stored in a file ( **Movies.json** ). i want to read the file and do some process and then save the output in new file
with open("Movies.json",'r') as f:
movies = json.loads(f.read())
// doing some process
How can i save the output?
Currently, I am trying this but it's not working:
json.dump(movies, f)
|
for output you need to use 'w' instead of 'r'
import json
# Opening JSON file
f = open('movies.json')
# returns JSON object as
# a dictionary
movies = json.load(f)
# Iterating through the json
# list
for i in movies:
print(i['id'])
# output
with open("Movies.json", 'w') as f:
json.dump(movies, f)
# Closing file
f.close()
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python"
}
|
CoreLocation capturing speed
I am capturing location data using CLLocationManager. I am less concerned about horizontal accuracy, but I want the speed to be as accurate as possible.
Anyone know if kCLLocationAccuracyThreeKilometers will be sufficient for my use case or do I have to use kCLLocationAccuracyBest to get the most accurate speed?
Thanks.
|
AFAIK `kCLLocationAccuracyThreeKilometers` works using cell towers (and doesn't use GPS), which doesn't give you every second's information (that's why it's good for battery), nor it uses core Motion. Without GPS or coreMotion any speed calculated won't be considered accurate
So to answer your question, no it won't give you an accurate speed, but just to be on the safe side, just jump into a car and start logging. (Though remember to turn location services off for all other apps, because sometimes other apps with better accuracy could increase your app's accuracy)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, swift"
}
|
Definition of direct sum of Banach spaces
Given a family $\\{A_i\\}_{i\in I}$ of Banach spaces, can anyone please provide me with the definitions of the following concepts
i) $c_0-$ direct sum
ii) $l^{\infty}$ direct sum
iii) algebraic direct sum
What's difference between these three concepts? Can anyone please elaborate with an example taking a particular family of Banach spaces $\\{B(H_i)\\}_{i \in I}$ where $H_i$'s are Hilbert spaces of finite dimension, say, $n_i$?
|
It appears be that (i) requires a _sequence_ of spaces $(E_n)_{n\in\Bbb N}$:
(i) $c_0$ direct sum: $$\\{(x_n)_{n\in\Bbb N}\in\prod_{n\in\Bbb N}E_n :\lim_{n\to\infty}\|x_n\| = 0\\}.$$
(ii) $l^\infty$ direct sum: $$\\{(x_i)_{i\in I}\in\prod_{i\in I}E_i :\sup_{i\in I}\|x_i\|<\infty\\}.$$
(iii) Algebraic direct sum: $$\\{(x_i)_{i\in I}\in\prod_{i\in I}E_i : x_i\ne 0\hbox{ for only a finite number of indices $i$}\\}.$$
Source for (i) and (ii) : Measure Theory and Functional Analysis
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "functional analysis"
}
|
Automating cf login refresh
Does the CloudFoundry UAA support token refresh for logged in user. I'm currently logged in using the "cf-cli" via the SSO passcode. After a week or so the session expires and I have to log in again. Is it possible to refresh the token in the $HOME/.cf/config.json upon expiry ? As per this < , we should be able to refresh the token by passing grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA options. However, it expects the client_id or client_secret to be present i.e use BASIC Auth. Can we do with a currently logged in user ?
|
You can refresh an access token, but you cannot refresh a refresh token. When your refresh token expires, you must login again.
The `refresh_token` from `config.json` is a JWT token, so you can use a tool like < to view the token and see when it expires. Your refresh token _will_ expire at some point, it just depends on how long your administrator allows it to last. A week sounds pretty standard.
Hope that helps!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "cloud foundry, cf cli"
}
|
WDS Unattended File (Language and WDS Authentication)
I want to be able to automate the initial language selection and WDS auth credentials. I am guessing I can't set that in an answer file to be provided by WDS? How can I achieve this?
|
In WDS there are two unattend files. One for the install image and one for the boot image. You set the settings that you're asking about in the WinPE section of the answer file for the boot image.
|
stackexchange-serverfault
|
{
"answer_score": 4,
"question_score": 0,
"tags": "windows, wds, windows pe"
}
|
Как сделать удаление и добавление класса для элемента интерфейса Выкл./Вкл. звука?
Здравствуйте.
Делаю включение и выключение звука, но вот как менять картинку колоночки (включено) на колоночку выключенной - это сделал, но вот при повторном клике ВКЛЮЧЕНИИ непонятно.
Код пример выключения:
<
**ВСЕ СДЕЛАЛ! ПРОСТО НУЖНО БЫЛО СДЕЛАТЬ ELSE**
<
|
Вопрос решил сам, решение простое.
Посмотреть тут: <
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "javascript"
}
|
How to delete a part of a string from pandas DataFrame in Python
I have this dataframe :
df=pd.DataFrame({'a': [2, 6, 8, 9],
'date': ['2021-07-21 04:34:02',
'test_2022-17-21 04:54:22',
'test_2020-06-21 04:34:02',
'2023-12-01 11:54:52']})
df["date"].replace("test_", "")
df
I would like to delete 'test_' from the column date. Maybe, you can help
|
Use `str.strip(<unnecessary string>)` to remove the unnecessary string:
df.date = df.date.str.strip('test_')
OUTPUT:
a date
0 2 2021-07-21 04:34:02
1 6 2022-17-21 04:54:22
2 8 2020-06-21 04:34:02
3 9 2023-12-01 11:54:52
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -1,
"tags": "python 3.x, pandas, dataframe"
}
|
using update with multiple select statments
update opportunitysrcfact set [Last_Amount]= (select c.amount from
(select a.amount,b.id from
( Select * from OpportunitySrcFact where fiscalweekqtr = '2013 Q3 5') a
inner join
( Select * from opportunitysrcfact where fiscalweekqtr = '2013 Q3 6') b
on a.id = b.id
where a.amount != b.amount ) c )
where opportunitysrcfact.id = c.id and opportunitysrcfact.fiscalweekqtr ='2013 Q3 6'
Above is the query which gives an error coz c.id is a multilevel identifier and cant be used in th last where clause. I needto update the selected amount in the row with the given opportunity ID
|
Since you are using sql server you can use a 'With' clause with an update statement.
TRY THIS:
with c as
(
select a.amount as amount,b.id as id from
( Select * from OpportunitySrcFact where fiscalweekqtr = '2013 Q3 5') a
inner join
( Select * from opportunitysrcfact where fiscalweekqtr = '2013 Q3 6') b
on a.id = b.id
and a.amount != b.amount
)
update opportunitysrcfact
set Last_Amount= c.amount
from opportunitysrcfact inner join c
on opportunitysrcfact.id = c.id and opportunitysrcfact.fiscalweekqtr ='2013 Q3 6';
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, sql server"
}
|
Let $\omega= \cos \frac{2\pi}{10}+i\sin \frac{2\pi}{10}$, let $K=\mathbb{Q}(\omega^2)$ and $L=\mathbb{Q}(\omega)$.
Let $\omega= \cos \frac{2\pi}{10}+i\sin \frac{2\pi}{10}$. Let $K=\mathbb{Q}(\omega^2)$ and $L=\mathbb{Q}(\omega)$. Then
A. $[L,\mathbb{Q}]=10$
B. $ [L,K]=2$
C. $[K,\mathbb{Q}]=4$
D. $L=K$
|
You have that $\omega ^2=e^{\frac{2 i\pi}{5}}$, and thus $$X^5-1=(X-1)(X^4+X^3+X^2+X+1).$$ Is an annihilator polynomial. The fact that $$X^4+X^3+X^2+X+1$$ is irreducible is a famous result.
Moreover, $\mathbb Q(\omega ^2)\subset \mathbb Q(\omega )$. By the way $X^5+1$ is an annihilator polynomial of $\omega $. With all these remarks, you will have no problem to show that $L=K$ and $[K:\mathbb Q]=4$.
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 4,
"tags": "abstract algebra, field theory"
}
|
SQL - how to remove whole row if one of the column in subquery return NULL
I am stuck in 1 SQL query
SELECT u.*,
um2.meta_value as parent_user_id,
( select u.user_email FROM wp_users u WHERE u.ID = um2.meta_value ) AS parent_user_email
FROM
wp_users u
JOIN wp_usermeta um2 ON u.ID = um2.user_id
AND um2.meta_key = 'parent_user_id'
GROUP BY
u.ID
This query return 4 row ( As shown in the screenshot )
I want a scenario like : If subquery return NULL , then the whole row will not be shown. So in this example **" childthree"** should not be shown , as **" parent_user_email"** is NULL , so the whole 3rd row need to remove
 {
$("#stylePreview").html( $('#WidgetviewCustomCSS').val() );
}
HTML:
<style id="stylePreview">
...
</style>
<textarea name="data[Widgetview][customCSS]" cols="30" rows="6"
onchange="updateWidgetStyling()" id="WidgetviewCustomCSS">...</textarea>
This works in Chrome, Firefox, & IE9, but not in IE7.
Any idea how to get this working there? It's unfortunate, but we're a B2B and require IE7 support.
Thanks in advance.
|
Instead of updating the stylesheet, remove it from the DOM and insert a new one. This should trigger a full re-rendering of the page.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "jquery, css, internet explorer 7, styles, dhtml"
}
|
Extracting 3 best matches using sklearn module
I'm working on sample code which uses face_recognition python library:
everything's fine except i want to fetch 3 best candidate instead of only the best one which is the result of
clf.predict([test_image_enc])
I expect output of `[4411, 4455, 5566]` instead of `4411`
|
Use the `decision_function` method to get the likelihood measure for each class. This computes the distance from the separating hyperplanes (higher this value, more likely the datapoint belonging to the corresponding class). Then you can pick the `top_n` number of classes as you wish.
top_n = 3
sort_inds = clf.decision_function([test_image_enc]).argsort()
clf.classes_[sort_inds[0][-top_n:][::-1]]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, scikit learn, svm"
}
|
\listoftodos in Todo list missing hyperlinks and colors in my document
I'm trying to add a `\listoftodos` using the `todonotes` package to a template file I have. I've added two todos with `\todo[inline]{Write abstract \ldots}` and `\todo{Fill in these details \ldots}`. I'm using TextMate to render my document on Mac Osx.
My list of todos in my document looks like this:  looks like this (I think it might be interfering with the styling): 
Do you have any ideas how to debug the styling issues with rendering todos?
|
Add the option `[colorinlistoftodos]` to your documentclass, see 1.2 Package options,p.4:colorinlistoftodos.
colorinlistoftodos:
> Adds a small colored square in front of all items in the Todo list.
For hyperlinks you nedd `\usepackage{hyperref}` or without box `\usepackage[hidelinks]{hyperref}`.
.
I used a basic recipe:
cod fillets
olive oil
garlic
parsley
salt, pepper
Baked in pre-heated oven @ 180C/fanned air for 10-15 minutes
How can I prevent this loss of water?
|
As the cod fillets were two different batches, chances are you just where unlucky with the second batch. Even within expiry-date, the amount of water food loses while cooking can vary vastly with age and quality. And even good fish shops can have watery batches at times.
To generally avoid this soaking happening, I would rest the cod on a cooking grate or - this is a personal preference - on some pre-cooked potatoes.
A small factor may be oversalting, but chances are it is actually the cod.
|
stackexchange-cooking
|
{
"answer_score": 6,
"question_score": 0,
"tags": "baking, fish, cod"
}
|
IE compatibility: My Mini-Chat is Overflowing (Validated Markup)
IE cross-compatibility issue. My website, www.zerozaku.com, is compatible with Chrome and Firefox, but IE has an issue with my Mini-Chat overflowing out of the box. Could anyone help?
P.S. I've only tested it on IE8, Firefox, Chrome
|
Seems to be something about the `position:relative` throughout those elements.
Remove `position:relative` from the hb_container class on those inner divs and see if you can work from there. This will at least make the messages stay within the container, but the images still seem to have an issue.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "html, css, internet explorer"
}
|
display tag is too ambiguous, better be burninated
I don't think there's any reason for any question to have the display tag. It's ambiguous and many times just wrong, e.g. here where design tag is the correct one to use.
Many other cases actually need information-display and in some, there's just no point in display.
So I hereby summon Trogdor the Burninator!
|
There are no longer any questions with the display tag.
|
stackexchange-meta
|
{
"answer_score": 4,
"question_score": 6,
"tags": "discussion, burninate request"
}
|
Server side JSON minification .net Core
I want to minify all json responses to single line instead of formatting. I heard Newtonsoft Json has some specific settings for this, but I am not sure where to put and what to put? Do I have to put it in Startup.cs and what is the setting?
|
You add it in the startup.cs like this
services.AddMvc().AddJsonOptions(o=>o.SerializerSettings.Formatting=Newtonsoft.Json.Formatting.None);
You can also configure any other settings you want.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "c#, asp.net core"
}
|
Is it bad practice to use unicode symbols or shapes in a app?
There have been a few times where I've used unicode symbols in place of small icons in one of my Cocoa apps, either because it's easier to draw inline with text or because I didn't feel like firing up Photoshop to draw a simple arrow. I've wondered though, could there be issues with localization or fonts I might not be aware of? Are there any cases where these symbols might not match what I'm seeing on my workstation?
|
I don't see anything really wrong with this shortcut approach, especially given Apple's concern for typographic quality. In your shoes, I would consult the Unicode Code Charts, and make sure I'm very carefully specifying a programmatic unicode character rather than relying on typing it in my editor.
Since cocoa uses unicode extensively internally, and since most API methods that don't specify encoding have been deprecated for the last couple iterations of OS X, I think you're pretty safe. As you're writing a desktop/iphone app, rather than a webapp where the deployed fonts are unknown, you should be OK from a bitmap rendering standpoint if you stick to unicode characters that can be rendered by the known default fonts that ship as part of the system.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 16,
"tags": "objective c, cocoa, macos, unicode"
}
|
Как найти букву в верхнем регистре в строке?
Есть строка, где нет пробелов, например: `ИвановПетрСидорович`
Надо найти позиции букв в верхнем регистре, чтобы отделить слова.
|
Код решения я скорее всего не приведу, так как давно не практиковал Delphi...
Но общий ход алгоритма такой:
Перебираешь посильно строку.
Затем на каждой итерации цикла анализируешь букву на регистр. Не помню, есть ли специальная функция в Delphi для этого. Если есть, то используешь эту функцию, а если нет, то пишешь свою.
Если посмотреть таблицу ASCII , то можно увидеть, что большие буквы находятся в одном кодовом диапазоне, а мельнькие в другом.
**UPD**
В комментарии подсказывают, что есть спец. функции
> myStr[i], AnsiUpperCase (сравниваем myStr[i] c AnsiUpperCase(myStr[i])), Copy, Delete (последнее - может и не использоваться, зависит от реализации). В последних версиях Delphi можно использовать и другие функции, но эти есть в любой версии.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "delphi, строки"
}
|
Solve $\displaystyle\lim_{x \to 0}{(1 - \sqrt{\cos 4x})\cot^2x}$
I just use L'Hospital's Rule (by changing into $\dfrac{1}{\tan^2x}$ first) for this, but it makes me even more confusing to solve. Could anyone help me to figure this out please?
|
Note,
$$1-\sqrt{\cos4x}={1-\cos4x\over1+\sqrt{\cos4x}}={1-(\cos^22x-\sin^22x)\over1+\sqrt{\cos4x}}={2\sin^22x\over1+\sqrt{\cos4x}}={8\sin^2x\cos^2x\over1+\sqrt{\cos4x}}$$
Consequently, for the limit as $x\to0$, we have
$$(1-\sqrt{\cos4x})\cot^2x={8\sin^2x\cos^2x\over1+\sqrt{\cos4x}}\cdot{\cos^2x\over\sin^2x}={8\cos^4x\over1+\sqrt{\cos4x}}\to{8\cdot1^4\over1+\sqrt1}={8\over2}=4$$
The key thing here, really, is that multiplying by the conjugate $1+\sqrt{\cos4x}$ eliminates any difficulty with the problematic square root, since $1+\sqrt{\cos4x}$ tends to a nice _non-zero_ limit.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "limits, trigonometry, limits without lhopital"
}
|
How to modify a line after every 6 lines in vim
I have a file with these lines:
aaa
aaa
aaa
aaa
aaa
aaa
bbb
bbb
bbb
bbb
bbb
bbb
ccc
ccc
ccc
ccc
ccc
ccc
ddd
ddd
ddd
ddd
ddd
ddd
i want to convert this into:
aaa;100;
aaa
aaa
aaa
aaa
aaa
bbb;100;
bbb
bbb
bbb
bbb
bbb
ccc;100;
ccc
ccc
ccc
ccc
ccc
ddd;100;
ddd
ddd
ddd
ddd
ddd
Is this possible in vim in one command ?
|
Yet another one
:g/^/ if !((line('.')-1)%6)|s/$/;100;
**Breakdown**
* `g/^/` Global command to apply next expression on each line
* `if !((line('.')-1)%6)` If the modulus of the current line equals 0
* `s/$/;100;` Replace the line ending with `;100;`
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "vim"
}
|
How to disappear text or figures by printing?
As you know, the option `ocgcolorlinks` of the `hyperref` package disables **colors** of all links presented in a PDF file by printing it from Adobe Reader (and by compiling with e.g. **pdflatex** ); as a result, they are printed in a default color.
My questions are:
1. Is it possible to disable not the color, but entire text (of the link), i.e. that it would be completely disappeared on the printed paper?
2. Is it possible to do the same with an arbitrary text (i.e. not with the text of the link) or with an arbitrary figure?
|
What you're looking for is the various `ocg*` packages, as this kind of features is referred to as »Optical Content Group«. You may want to try out this trippy showcase. What's nice about this method is that the affected passages aren't simply turned white, but are disabled properly. So this is even going to work on a more sophisticated background (such as an image, a gradient fill, etc.).
This is an example using the `ocg-p` package:
\documentclass{scrartcl}
\usepackage{ocg-p,hyperref}
\begin{document}
Print me!
\begin{ocg}[printocg=never]{name}{id1}{1}
Print me! \url{
\end{ocg}
\end{document}
Note the print preview:
. However, if I try to embed more than one script, only the first one appears in the inbox (each script is correct and shows up properly when it is the only one).
|
Only one action is currently supported and if you include multiple actions, the first one will be used. The user experience for exposing multiple actions would be really different, so if/how to handle them is still being discussed.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "google schemas"
}
|
Immutable SQL columns
Is it possible to mark a column `immutable` in MSSQL?
Seems like it would be a useful DDL feature; once a value is set in a row ('row' being defined as a specific relation of values to a primary key), it could not be changed without deletion of the row.
Obviously (like most things) this is more than doable in the application layer, but half the fun of SQL DDL is error-checking your application code.
|
If the user doing the DML is not the owner of the objects and not "db_owner" in the database itself, you can just grant "insert" privilege, but not update privilege for that table:
Assuming a table with `id, col1, col2`
grant insert, select, delete on the_table to the_user;
grant update (id, col2) on the_table to the_user;
With these grants _the_user_ can insert rows and supply values for all three columns. He can also update the `id` and the `col2` column, but not the `col1` column.
The db_owner (and possibly the creator/owner of the table) can always update all columns. I don't know if there is a way to revoke that privilege from those rolws.
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 13,
"tags": "sql, sql server, sql server 2008, ddl"
}
|
making a noty notification a clickable hyperlink
noty({
layout: 'topRight',
type: 'alert',
text: 'Number of Alerts:'+count,
template: '<div class="noty_message"><span class="noty_text"></span></div>',
closeWith: ['button'],
dismissQueue: true,
animation: {
open: {height: 'toggle'},
close: {height: 'toggle'},
easing: 'swing',
speed: 500
},
timeout: false
});
Is there any way of making the notification a clickable hyperlink. I have considered the `callback onClose()` but as I don't want the notification to close I can't use this. Is there a callback which is `onclick`? or will I have to do it another way. like putting a hyperlink into the text?
|
You could make use of the `buttons` option to create a button which would open a URL in a new window.
noty({
layout: 'topRight',
type: 'alert',
text: 'Number of Alerts:'+count,
template: '<div class="noty_message"><span class="noty_text"></span></div>',
closeWith: ['button'],
dismissQueue: true,
animation: {
open: {height: 'toggle'},
close: {height: 'toggle'},
easing: 'swing',
speed: 500
},
timeout: false,
buttons: [
{
addClass: 'css-class-for-the-btn', text: 'Link', onClick: function ($noty) {
window.open("
}
}
]
});
And you could customize the CSS for the button by defining the class in `addClass`
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, jquery plugins, noty"
}
|
How to zip files from folder but keep it separated
I have 1 folder that contains many txt files. I want to zip them but separated.
Example:
In this folder I have _A.txt_ , _B.txt_ , _C.txt_.
I want to zip all the files but separated so the result will be _A.zip_ , _B.zip_ , _C.zip_.
string outputPath = "C:\\Users\\Desktop\\VA";
string path = outputPath + "\\VA_" + tglskrg;
foreach (string dirFile in Directory.GetDirectories(path))
{
foreach (string fileName in Directory.GetFiles(dirFile))
{
using (ZipFile zip = new ZipFile())
{
zip.UseUnicodeAsNecessary = true;
zip.AddFile(); //dont know what to put
zip.Save(); //dont know what to put
}
}
}
Any help will be appreciated.
I'm using dotnetzip (Ionic.zip) and C# Visual Studio Express 2010.
|
You could do that as follows:
foreach (string fileName in Directory.GetFiles(dirFile))
{
var zipFile = Path.Combine(outputPath, Path.ChangeExtension(fileName, ".zip"));
using (ZipFile zip = new ZipFile())
{
zip.AddFile(fileName); // add A.txt to the zip file
zip.Save(zipFile); // save as A.zip
}
}
This takes all the files found in the folder `dirFile`, and saves them under `outputPath`, with the same file name but replacing the extension with `.zip`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, dotnetzip"
}
|
Is this the correct way to initialize static data members of template classes?
Is this the correct way to initialize static data members of template classes?
template <typename T>
class Temp
{
public:
static unsigned int x;
};
template <typename T>
unsigned int Temp<T>::x = 0;
|
Yes. Yes, it is.
> `[C++11: 14.5.1.3/1]` A definition for a static data member may be provided in a namespace scope enclosing the definition of the static member’s class template. _[ Example:_
>
>
> template<class T> class X {
> static T s;
> };
>
> template<class T> T X<T>::s = 0;
>
>
> _—end example ]_
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 6,
"tags": "c++"
}
|
Is there anyway to activate numpad on MacBook Pro?
How do we activate the numeric keypad on a MacBook Pro?
The `Fn` key doesn't seem to work. Neither does `Fn``F6`.
|
Newer model Macbook (Pro)s don't have numpads, I think since they changed the F-key assignments so that `F6` had a special function.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mac, macbook, macbook pro, numpad"
}
|
Functional inequality $f(x_1+x_2)\ge f(x_1)+f(x_2)$
> Given a function $f$ on the interval $0\le x \le 1$. We know that this function is non-negative and $f(1)=1$. Moreover, for any two numbers $x_1$ and $x_2$ such that $x_1\ge 0, x_2 \ge 0$ and $x_1+x_2\le 1$ the inequality $$f(x_1+x_2)\ge f(x_1)+f(x_2).$$ a) Prove that $f(x)\le 2x$
>
> b) Is it true that for all $x:$ $f(x)\le 1.9x$?
### My work so far:
a) The function increases monotonically. Really, if $x_2\ge x_1$ and $x_2\le 1$, that $f(x_2)\ge f(x_1)+f(x_2-x_1)$ and $f(x_2-x_1)\ge 0$. Hence, $f(x_2)\ge f(x_1)$.
_I need help here_.
b) _I need help here too_.
|
Here's part a:
You showed $f$ is monotone, so in particular $f(x) \le 1$ for all $x \in [0,1]$. In particular, if $x\ge 1/2$ then $f(x) \le 1 \le 2x$ automatically.
Now suppose $x \in [1/4,1/2)$ and $f(x) > 2x$. Then $2x < 1$ so $f(2x)$ is defined, but on the other hand $f(2x) \ge 2f(x) > 2\cdot 1/2 = 1$, contradicting that $f(x) \le 1$.
Next, if $x \in [1/8,1/4)$ and $f(x) > 2x$. Then $4x < 1$ so $f(4x)$ is defined. But then $f(4x) \ge 4f(x) > 4 \cdot 1/4 = 1$, contradicting that $f(x) \le 1$.
And so on.
For part b, we the answer is no. Let $f(x) = 1$ if $x \ge 1/2$ and $f(x)=0$ otherwise.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "functions, functional equations"
}
|
Antiproton production efficiency
according to Fermilab articles and a few physics books at my library, for every million collisions of protons accelerated on a target, only 1 to 30 antiprotons are created.
Why is the efficiency so low? I mean, I know it's very expensive to accelerate protons on the target, but for one collision, there is a chance out of up to a million to get an antiproton...
Is it because there is empty space between the atoms in the target?
Thanks in advance
|
When one goes to the atomic and particle level, one has to use quantum mechanics and special relativity to make sense of the data and the efficiencies.
In quantum mechanics there is a calculable probability for producing a proton-antiproton pair whenever in particle scattering there exists enough energy, but this probability is small. Antiporotns have to come from pair creation because of baryon number conservation ( another quantum mechanical rule). Thus the crossection of producing antiprotons is energy dependent and gets higher with energy but it is still much smaller than the probability of generating other particles. See figure 5 here .
|
stackexchange-physics
|
{
"answer_score": 2,
"question_score": 2,
"tags": "antimatter, pair production"
}
|
Thai Language Not displaying Correctly on Iphone
I have one thai language string  FROM TABLE1` but what do i do for all of them?
I tried: `SELECT SUM( table1.Revenue+ table2.Revenue + table3.Revenue ) FROM table1, table2, table3'` but it doesn't work...
Any ideas? Thanks!
|
select sum(rev) as trev
from
(
SELECT SUM( Revenue) as rev FROM table1
union all
SELECT SUM( Revenue) as rev FROM table2
union all
SELECT SUM( Revenue) as rev FROM table3
) as tmp
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "mysql, sum"
}
|
Do water filters expire even if underused?
This filter rates a 3 month lifespan with 1210 liter capacity, but I expect to filter only 300 liters in 3 months. Is it still expired after 3 months - if so, why? What degrades a filter while it's unused?
|
Many things are aging even if not used, like lithium ion power cells.
There is filter aging independent of the passed water volume. There is eventual growth of chemical and microbial stuff. E.g. chemical sediments on the active surface of antimicrobial silver causes deterioration of antimicrobial effect. Active carbon for organic traces and ionex resin of ion exchange can be affected by this as well.
The life span with 2 criteria is very generally – not limited to filters nor chemistry – always meant "whichever one is reached sooner".
In a funny analogy, 1.5 L of bottled water have criteria e.g. ( illustratively ) 2 days after opening, or 1.5 L of provided water, whatever comes first. If you drink just 500 mL, the left 1 L does not have an eternal lifespan either but 2 days are still valid.
|
stackexchange-chemistry
|
{
"answer_score": 2,
"question_score": -1,
"tags": "everyday chemistry, water"
}
|
Should raw response time data be transformed?
I am a statistician and doing some data analysis in cognitive sciences. I noticed that the distribution of response time (RT) is chisq-squared-like, and I want to do Box-cox transformation to make it look normal distributed. Because before I did not think much for this transform, my question is:
* Does a box-cox transformation need to be applied to response times?
* If so, what do the results mean?
* For t-test, ANOVA and other tests, will the result be valid for the original response time data?
* If not, should we transform the data since analysis of these data is based on the normality hypothesis?
|
This article by Whelan (2010) is one of the best introductory papers I've found on the subject. Normalization is covered quite clearly and extensively, including the caveats and "gotchas".
### References
* Whelan, R. (2010). Effective analysis of reaction time data. The Psychological Record, 58(3), 9.
|
stackexchange-cogsci
|
{
"answer_score": 2,
"question_score": 4,
"tags": "statistics, reaction time"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.