qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
12,529,023 |
I have a `<textarea>` in HTML. When I put cursor in it, it's not starting from the beginning, but is blinking in middle.
### HTML
```
<TD width="21%">
<textarea class="txtarea" style="height:30px;" rows="3" name="Text" Id="Text" value=""> </textarea>
</TD>
```
### CSS
```
.txtarea{
border-right: #646464 ;
border-top: #646464;
border-left: #646464;
border-bottom: #646464;
width:100%;
background: #ffffcc;
}
```
|
2012/09/21
|
[
"https://Stackoverflow.com/questions/12529023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495475/"
] |
```
<textarea class="txtarea" style="height:30px;" rows="3" name="Text" Id="Text" value=""> </textarea>
```
What you have is a space between `<textarea>` and `</textarea>` tags.
|
17,842,296 |
I have the following excel table:
```
StartDate YTDActual
1/1/2013 100
2/1/2013 200
3/1/2013 99
4/1/2013 33
5/1/2013 45
6/1/2013 0
7/1/2013 0
```
Is there a formula that returns, for each StartDate, the associated value in YTDActual, if it is different than 0, otherwise it would return the last YTDActual value different than 0 in the previous rows.
So, basically the formula would produce the following values in the NewValue column:
```
StartDate NewValue
1/1/2013 100
2/1/2013 200
3/1/2013 99
4/1/2013 33
5/1/2013 45
6/1/2013 45
7/1/2013 45
```
Note that in Jun & Jul the values are 45 because May had the last non-zero YTDActual value 45.
Thanks
Update: Just a clarification, the second table goes onto another sheet, they are not side by side.
|
2013/07/24
|
[
"https://Stackoverflow.com/questions/17842296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832783/"
] |
This would do it:
```
Col A Col B Col C
StartDate YTDActual NewValue
1/1/2013 100 =if(B2<>0,B2,C1)
...
```
Then just drag down the formula in Column C
|
7,222,443 |
I have a 9 million rows table and I'm struggling to handle all this data because of its sheer size.
What I want to do is add IMPORT a CSV to the table without overwriting data.
Before I would of done something like this; INSERT if not in(select email from tblName where source = "number" and email != "email") INTO (email...) VALUES ("email"...)
But I'm worried that I'll crash the server again. I want to be able to insert 10,000s of rows into a table but only if its not in the table with source = "number".
Otherwise I would of used unique on the email column.
In short, I want to INSERT as quickly as possible without introducing duplicates to the table by checking two things. If email != "email" AND source != "number" then insert into table otherwise do nothing. And I dont want errors reports either.
I'm sorry for my bad wording and the question sounding a little silly.
I'm just having a hard time adabting to not been able to test it out on the data by downloading backups and uploading if it goes wrong. I hate large datasets :)
Thank-you all for your time
-BigThings
|
2011/08/28
|
[
"https://Stackoverflow.com/questions/7222443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/761501/"
] |
If you have unique keys on these fields you can use LOAD DATA INFILE with IGNORE option. It's faster then inserting row by row, and is faster then multi-insert as well.
Look at <http://dev.mysql.com/doc/refman/5.1/en/load-data.html>
|
39,761,575 |
In my app I generate a QR name in Arabic and then scan and I use `zxing` library to generate but it seems that `zxing` library doesn't support Arabic language because when I scan the generated name it gives me `????`. What is the solution?
This is my code to generate:
```
BitMatrix bitMatrix = multiFormatWriter.encode(text2QR, BarcodeFormat.QR_CODE, 500, 500);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
bitmap = barcodeEncoder.createBitmap(bitMatrix);
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
```
|
2016/09/29
|
[
"https://Stackoverflow.com/questions/39761575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4347233/"
] |
I found solution:
```
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map<EncodeHintType, Object> hintMap = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hintMap.put(EncodeHintType.MARGIN, 1); /* default = 4 */
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
BitMatrix bitMatrix = multiFormatWriter.encode(text2QR, BarcodeFormat.QR_CODE, 500, 500, hintMap);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
bitmap = barcodeEncoder.createBitmap(bitMatrix);
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
```
|
48,243,404 |
I'm curious what the design argument for `doParallel:::doParallelSNOW()` giving a warning when globals are explicitly specified in `.export` could be? For example,
```
library("doParallel")
registerDoParallel(cl <- parallel::makeCluster(2L))
a <- 1
y <- foreach(i = 1L, .export = "a") %dopar% { 2 * a }
## Warning in e$fun(obj, substitute(ex), parent.frame(), e$data) :
## already exporting variable(s): a
```
Is it possible to disable above warnings in doParallel?
I'd argue that such a warning would suggest the user/developer *not* to specify `.export` and rely fully on foreach adaptors to take care of globals. However, the success of identification of globals differ among adaptors.
Package versions: doParallel 1.0.11, iterators 1.0.9, foreach 1.4.4
**CLARIFICATION 2018-01-14**: [These warnings occur after doParallel first having identified globals automatically and then appending the ones the developer list in `.export`](https://github.com/cran/doParallel/blob/b843662b9c49fb610434ae22713fbc188a06b1c3/R/doParallel.R#L414-L434) - my question is on why it doesn't not accept the deliberate choice that was done by the developer? Warning about correct globals is a bit misleading.
|
2018/01/13
|
[
"https://Stackoverflow.com/questions/48243404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1072091/"
] |
So it turns out that the solution to this question requires a bit of scripting using `groovy`.
Below is the updated process model diagram, in it I start a new instance of the `Complete Task` process using a script task then if the user wishes to add more tasks the exclusive gateway can return the user to the Create task (user task) **OR** finish the process.
I clear down any values in the fields held within the user task within the script task before I pass the scope back to the user task.
[](https://i.stack.imgur.com/yV5m7.png)
The image below shows my *Complete Task* process that gets called by the main process using a script
[](https://i.stack.imgur.com/oo51d.png)
Here I avoid using `parallel gateways` in preference of creating a new instance of the *Create Task* (user task) and a new instance of the *Complete task* process (not subprocess) via means of the script.
To start a new instance of the Complete Task process we have to start the process using the function `startProcessInstanceByKeyAndTenantId()` under a `runtimeService` instance for the process, although I could also use `startProcessInstanceByIdAndTenantId()`:
```
//Import required libraries
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
//instantiate RunTimeService instance
RuntimeService runtimeService = execution.getEngineServices().getRuntimeService();
//get tenant id
String tenantId = execution.getTenantId();
//variables Map
Map<String, Object> variables = runtimeService.getVariablesLocal(execution.getProcessInstanceId());
//start process (processId, variables, tenantId)
ProcessInstance completeTask = runtimeService.startProcessInstanceByKeyAndTenantId("CompleteTask", variables, tenantId);
//Clear variables to create a fresh task
execution.setVariable("title", "");
execution.setVariable("details", "");
```
Using this approach I avoid creating multiple subprocesses from the parent process and instead create multiple processes that run separate from the parent process. This benefits me as if the parent process completes the others continue to run.
|
72,041,403 |
The input boxes move up when the error message appears at the bottom . The error message is enclosed in a span tag
When the input boxes are blank and the user tries to hit enter the error message should appear below the input box asking the user to enter the valid input , however when the input appears it moves the boxes up no longer aligning the two boxes when one is valid and the other invalid . I want it so that the error message occurs without moving changing the position of the input boxes
```css
.inputs-account > label {
font-size: 16px;
}
.name-inputs {
display: flex;
justify-content: flex-start;
align-items: end;
}
.first-name-input {
margin-right: 15px;
}
.inputs > .required {
float: none;
}
.inputs > * {
float: left;
clear: both;
}
.inputs.reversed > * {
float: none;
}
.inputs input[type="text"],
.inputs input[type="password"],
.inputs input[type="email"],
.inputs input[type="tel"],
.inputs select,
.inputs textarea {
height: 45px;
color: #12110C;
border-radius: 3px;
width: 100%;
vertical-align: middle;
border: 1px solid #D1DCE1;
padding-left: 10px;
}
```
```html
<div class="name-inputs inputs-account">
<div class="inputs inputs-account first-name-input">
<label for="FirstName">First name</label>
<input class="key-change valid" type="text" data-val="true" data-val-
required="First name is required." id="FirstName" name="FirstName"
value="userName" aria-describedby="FirstName-error" aria-invalid="false">
<span class="field-validation-valid" data-valmsg-for="FirstName" data-
valmsg-replace="true"></span>
</div>
<div class="inputs inputs-account">
<label for="LastName">Last name</label>
<input class="key-change input-validation-error" type="text" data-val="true"
data-val-required="Last name is required." id="LastName" name="LastName"
value="" aria-describedby="LastName-error" aria-invalid="true">
<span class="field-validation-error" data-valmsg-for="LastName" data-
valmsg-replace="true">
<span id="LastName-error" class="">Last name is required.</span>
</span>
</div>
</div>
```
|
2022/04/28
|
[
"https://Stackoverflow.com/questions/72041403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12993416/"
] |
Update Columns
--------------
```
Option Explicit
Sub UpdateMin()
Const FirstCellAddress As String = "N2"
Const ColumnOffset As Long = 22
Const ColumnsCount As Long = 100
Const MinCriteria As Double = 8
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
Dim fCell As Range: Set fCell = ws.Range(FirstCellAddress)
Dim rg As Range
Dim lCell As Range
Dim rCount As Long
With fCell.Resize(ws.Rows.Count - fCell.Row + 1, _
(ColumnsCount - 1) * ColumnOffset + 1)
Set lCell = .Find("*", , xlFormulas, , , xlPrevious)
If lCell Is Nothing Then Exit Sub
rCount = lCell.Row - .Row + 1
Set rg = .Resize(rCount, 1)
End With
Dim Data As Variant
Dim cValue As Variant
Dim r As Long
Dim c As Long
For c = 1 To ColumnsCount
With rg.Offset(, (c - 1) * ColumnOffset)
'Debug.Print .Address
Data = .Value
For r = 1 To rCount
cValue = Data(r, 1)
If VarType(Data(r, 1)) = vbDouble Then
If cValue < MinCriteria Then
Data(r, 1) = MinCriteria
End If
End If
Next r
.Value = Data
'.Interior.Color = vbYellow
End With
Next c
MsgBox "Columns updated.", vbInformation
End Sub
```
|
23,371,582 |
I created [this website](http://www.oooysterfestival.com) with the original intention of having it be mobile. However I've had to take that function out and for the time being just wanted to have it so when you visit the site on a mobile device you just see the website as you would see on the screen. Not mobile friendly as you would want it to be but zoomed out so you can see the whole thing.
I've already placed in the code to make it behave the way I'd like it to but something is happening and it's not working. Ive looked into the HTML 5 shim and other options for the viewport but I can't figure it out.
I've tried a few different variations of the viewport tag
```
<meta name="viewport" content="width=device-width" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<meta name="viewport" content="width=500, initial-scale=1">
```
This is what the website looks like right now on mobile devices

This is what I was hoping to make it look like

Can you see what I'm missing?
|
2014/04/29
|
[
"https://Stackoverflow.com/questions/23371582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1140019/"
] |
In your case you should not use any of the suggested meta viewport tags. If you leave the page without any meta viewport tags you should get the desired result in most mobile browsers.
You could add `<meta name="viewport" content="width=980">` to tell the browser that you content is 980 px, if that is the case. You seem to have a 960 px wide page but it may look nicer to have some spacing on the sides.
**[I find this to be a nice article to explain the meta viewport tag](http://blog.javierusobiaga.com/stop-using-the-viewport-tag-until-you-know-ho)**
**[And this is another article about using the meta viewport tag for non-responsive pages](http://webdesignerwall.com/tutorials/viewport-meta-tag-for-non-responsive-design)**
The meta viewport tags that you have tried tells the browser a few different things:
---
```
<meta name="viewport" content="width=device-width" />
```
This tells the browser that content width should fit in the device width. In order to use this successfully your page width should be adjustable to the device.
---
```
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
```
This tells the browser that it should zoom the page so that 1 CSS pixel from the page equals 1 viewport pixel on the screen (not physical pixels on e.g. Retina displays). This results in your page being zoomed in as it is wider then a normal mobile screen. Maximum-scale also tells the browser not to let you zoom the page any further than that.
---
```
<meta name="viewport" content="width=500, initial-scale=1">
```
This tells the browser that the content is 500 px wide and that you should zoom the page.
|
49,970,283 |
Consider this example:
```
import numpy as np
a = np.array(1)
np.save("a.npy", a)
a = np.load("a.npy", mmap_mode='r')
print(type(a))
b = a + 2
print(type(b))
```
which outputs
```
<class 'numpy.core.memmap.memmap'>
<class 'numpy.int32'>
```
So it seems that `b` is not a `memmap` any more, and I assume that this forces `numpy` to read the whole `a.npy`, defeating the purpose of the memmap. Hence my question, can operations on `memmaps` be deferred until access time?
I believe subclassing `ndarray` or `memmap` could work, but don't feel confident enough about my Python skills to try it.
Here is an extended example showing my problem:
```
import numpy as np
# create 8 GB file
# np.save("memmap.npy", np.empty([1000000000]))
# I want to print the first value using f and memmaps
def f(value):
print(value[1])
# this is fast: f receives a memmap
a = np.load("memmap.npy", mmap_mode='r')
print("a = ")
f(a)
# this is slow: b has to be read completely; converted into an array
b = np.load("memmap.npy", mmap_mode='r')
print("b + 1 = ")
f(b + 1)
```
|
2018/04/22
|
[
"https://Stackoverflow.com/questions/49970283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/880783/"
] |
You can use `nextTick` which will call a function after the next DOM update cycle.
```
this.datepicker = true;
Vue.nextTick(function () {
$(".jquery-date-picker").datepicker();
})
```
And here is it's page in the documentation [VueJS Docs](https://v2.vuejs.org/v2/api/#Vue-nextTick)
|
383,744 |
I am trying print data in rows and columns using bash script as follows.
```
#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
echo "$line"
done < "$1"
{
awk 'BEGIN { print "Points"}
/Points/ { id = $1; }'
}
```
My txt file looks like this:
```
Team Played Wins Tied
england 4 3 2
america 9 5 3
```
The output on terminal should looks like this:
```
Team Played Wins Tied Points
england 4 3 2 16
america 9 5 3 26
```
Here is calculation a team won 1 match so awarded 4 points and for a tie, 2 points are awarded. But I don't know how to perform mathematical operations so unable to do.
|
2017/08/03
|
[
"https://unix.stackexchange.com/questions/383744",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/244887/"
] |
You don't need a shell loop for this, at all:
```
awk '{$(NF+1) = NR==1 ? "Points" : $3*4 + $4*2; print}' OFS='\t' input.txt
Team Played Wins Tied Points
A 2 1 1 6
B 2 0 1 2
```
|
7,998 |
I'm replacing the floor in my bathroom, which was previously a vinyl sheet. Prior to that (and I think original to the house, built in early 70's) it was some peel and stick-type tiles, except they're very hard (they remind of me what would be sold as commercial tiles now). There were some tiles left under the old vanity, and since I'm replacing it with a differently-sized vanity, I figure I'll put the new floor underneath it as well, which means the subfloor has to be flat.
After I scraped up the old tiles, the floor is all black, presumably from the adhesive in the tiles. The rest of the floor though, that was covered by the vinyl sheet, looks like it's had the adhesive cleaned off.


How was this cleaned, and why is it all white now?
The floor was cut exactly to the outline of the vanity, and from the old paint on the wall, it looks like prior to the vanity there was just a wall-mounted sink. I'm going to guess the vanity was installed, and then sometime later the vinyl flooring was installed, as otherwise I can't see how the tiles got cut to this pattern.
I'm putting a floating vinyl plank tile floor in place, and this part will be underneath the vanity anyways (the new vanity is slightly bigger). Should I bother trying to clean this part as well, or just put the new floor over top?
---
Update: I added a whole bunch of screws to reinforce the floor to the joists below, and help reduce some of the squeaking. In one spot, right along an edge of the plywood, the white stuff flaked off - so it seems rather than being 'cleaned', there's actually a really thin layer of something on top of the black adhesive. There's no noticeable difference between the height of the two sections.
I've since laid the new floor on top, I didn't do anything extra to this subfloor.
|
2011/08/01
|
[
"https://diy.stackexchange.com/questions/7998",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/157/"
] |
A 1 1/4" female FIP adapter worked perfectly. As soon as I saw it, I was embarassed for not having thought of it earlier.

I used some teflon tape, screwed the FIP adapter onto the adapter coming out of the wall, then just glued my 1 1/4" pipe directly into it. No reduction in pipe sizes, and 100% ABS parts.

|
14,064,932 |
I wrote this piece of code but not sure why it doesn't print the second sentence, it just prints the first part of it which is "Some string concat is like".
I was expecting to see the rest of the sentence from TalkToMe method too.
```
object1 = Object.new
def object1.TalkToMe
puts ("Depending on the time, they may be in one place or another.")
end
object1.TalkToMe
puts "Some string concat is like " #{object1.TalkToMe} "
```
|
2012/12/28
|
[
"https://Stackoverflow.com/questions/14064932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320724/"
] |
`AccessLevel` is meant to represent a set of individual access rights. To check for specific right you should use something like this:
```
(object.getAccessAllowed() & AccessRight.DELETE_AS_INT) == AccessRight.DELETE_AS_INT
```
|
42,449,250 |
I am working on a class assignment (which is why only relevant code is being displayed). I have assigned an array of pointers to an array of random numbers and have to use the bubble sort technique.
The array is set up as follows:
```
int array[DATASIZE] = {71, 1899, 272, 1694, 1697, 296, 722, 12, 2726, 1899};
int *arrayPointers = array; // donation array
```
The function call comes from main and looks is the following:
```
bubbleSort(arrayPointers);
```
I have to do the swapping of the pointers in a separate function :
```
void pointerSwap( int *a , int *b)
{
// swap the pointers and store in a temp
int temp = *a; // temp storage of pointer a while being reassigned
*a = *b;
*b = temp;
}// end of pointerSwap
```
from the actual bubble sort:
```
void bubbleSort (int *toStore)
{
//sort each of the pointers successively
int i,j; // counters
for (i=DATASIZE-1;i>1;i--)
{
for (j=0;j<DATASIZE-1;j++)
{
if (toStore[j]>toStore[j+1])
{
pointerSwap(toStore[j],toStore[j+1]);
}// end of if?
}// end of j for loop
}// end of i for loop
}// end of buubleSort
```
My issue is that when I try to compile the code, I get the following errors when I call the pointer swap:
---
**passing argument 1 of ‘pointerSwap’ makes pointer from integer without a cast**
note: expected ‘int \*’ but argument is of type ‘int’
**passing argument 2 of ‘pointerSwap’ makes pointer from integer without a cast**
note: expected ‘int \*’ but argument is of type ‘int’
---
I am not sure what I am doing incorrectly, I have tried "&toStore[j]" and "&toStore[j+1]" but the list sorts the original instead of the pointed array (which is to be expected).
In advance any help is much appreciated,
~Joey
|
2017/02/24
|
[
"https://Stackoverflow.com/questions/42449250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5553114/"
] |
In the call:
```
pointerSwap(toStore[j],toStore[j+1]);
```
you are passing an `int` (`toStore[j]` is equivelent to `*(toStore + j)`) to a function that expects a pointer. You need to pass a pointer, namely:
```
pointerSwap(toStore + j, toStore + j + 1);
```
The second question pertains to sorting out of place. Your function signiture does not allow for anything else:
```
void bubbleSort (int *toStore)
```
You are not returning anything and you don't give a reference to a second array so you cant do anything but sort in place. If you really need a separate array, you can do something like this:
```
int *bubbleSort (int *input) {
int* toStore = malloc(DATASIZE * sizeof(int));
memcpy(toStore, input, DATASIZE);
...
//sort toStore
...
return toStore
}
```
This will then return a sorted array and will not touch the original.
|
47,656,329 |
I created a react component that I want to use twice(or more) inside my page, and I need to load a script tag for it inside the head of my page but just once! I mean even if I use the component twice or more in the page it should add the script tag just once in the head.
The Problem is that this script tag should be absolutely a part of the component and not statically inserted in the head of my page.
Can anyone help me to make the magic happens? Thanks a lot in advance!
|
2017/12/05
|
[
"https://Stackoverflow.com/questions/47656329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9056870/"
] |
Here what I did to fix my issue:
In Git Settings, Global Settings in Team Explorer, there is an option to choose between OpenSSL and Secure Channel.
Starting with Visual Studio 2017 (version 15.7 preview 3) use of SChannel in Git Global settings fixed my issue.
|
60,980,163 |
This is very simple example of what I want to get. My question is about @returns tag. What should I write there?
```js
class Base{
/**
* @returns {QUESTION: WHAT SHOUL BE HIRE??}
*/
static method(){
return new this()
}
}
class Sub extends Base{
}
let base= Base.method() // IDE should understand that base is instance of Base
let sub= Sub.method() // IDE should understand that sub is instance of Sub
```
|
2020/04/01
|
[
"https://Stackoverflow.com/questions/60980163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3011740/"
] |
I did it for you with MU Grids and media queries, if you have questions, ask. I am always ready to help. This is codesandbox link. Let me know if it help you.
<https://codesandbox.io/s/charming-shirley-oq6l5>
|
92,235 |
I've been taught that a carbocation mainly rearranges because of:
* increasing degree (1 to 2, 1 to 3, or 2 to 3)
* +M stabilization
* ring expansion (in an exceptional case, ring contraction as well).
However, I've never been taught whether the following carbocation **A** would rearrange:
[](https://i.stack.imgur.com/QBYmn.png)
My professor would say that this carbocation would *not* rearrange, since at the alpha position we only have two hydrogen atoms, and either of the hydride shifts would still yield a two degree carbocation **B**:
[](https://i.stack.imgur.com/m2jKT.png)
However I believe that **B** is stabilized by the **strong inductive effect of three extra methyl groups** (at the alpha position) that were absent in **A**. I believe this is a strong enough driving force for rearrangement.
So, can we say **A** will rearrange into **B**? Is there experimental evidence to support the fact that **A** rearranges/does not rearrange into **B**? Finally, based on these, can inductive effect be the sole driving force for carbocation rearrangement?
|
2018/03/13
|
[
"https://chemistry.stackexchange.com/questions/92235",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/5026/"
] |
The answer to this question is quite difficult to deduce logically. In the first place, the carbocation that is formed is secondary. Rearranging will only change the position of the carbocation, but it will be still secondary. But then there is also a stabilising +I effect.
Instead, if we take into account that that these carbocations are intermediates to form alkenes, a conclusion can be drawn. So, the best way is to consider the thermodynamic favour of the rearrangements.
Prior to rearrangement, the carbocation is secondary. If you consider that this carbocation is going to form an alkene, the major product from it (Saytzeff product) will be **4-methyl pent-2-ene**, which is of the form $\ce{RCH=CHR}$. After rearrangement, this will be still a secondary carbocation, so there is a significant energy required for this hydride shift. This energy is not really compensated by the +I effect of the isopropyl group. But if we consider that this carbocation is an intermediate for the alkene formation, the major alkene (Saytzeff product) will be **2-methyl pent-2-ene**, which is of the form $\ce{R2C=CHR}$, which is thermodynamically more favourable.
So it is seen that in the rearrangement, the energy of the intermediate is increased, but the overall energy of the product is decreased. So, I think that, at higher temperatures, this rearrangement can be possible, because the ultimate product (if we think this as an alkene) is thermodynamically favourable, while at normal temperature this rearrangement is energetically restricted a bit.
|
30,354,168 |
I have an HTML page (`courses.html`) that shows a list of courses. These courses are loaded from a database by an AJAX call into the array "courses" defined as global variable in `script_1.js`. Once I go to the page of a specific course in `course.html` I want to be able to pass this array to `script_2.js` to mantain the order of the courses and navigate them without having to perform the AJAX call again.
How I can pass this global variable or how I can manage this?
|
2015/05/20
|
[
"https://Stackoverflow.com/questions/30354168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4347551/"
] |
You have the following option for passing data from one page to the next:
1. **Cookie.** Store some data in a cookie in page1. When page2 loads, it can read the value from the cookie.
2. **Local Storage.** Store some data in Local Storage in page1. When page2 loads, it can read the value from the Local Storage.
3. **Server Storage.** Store some data on your server on behalf of user1 on page1. When page2 loads, the server can either place that user1 data on page2 or page2 can request that data from the server via ajax.
4. **Query Parameter.** When page2 is loaded from page1, a query parameter can be placed onto the URL as in <http://www.example.com/page2?arg=foo> and page2 can parse that query parameter from the URL when it loads.
5. **Common Parent Frame.** If your page is framed by a common origin and you are not changing the top level URL, but just the framed URL, then you can store global data in the top level parent and that data can be accessed from the framed page, even as it goes from page1 to page2.
You can often use JSON as a string-based storage format for more complex data items like an array. JSON can be put into any of the above storage options.
|
64,600,292 |
I'm trying to build a new WebApi secured using access tokens from azure active directory.
I'm using .net core v3.1 and visual studio 2019.
I created a new project using the "Asp.net core web application" template and picked an "API" project and changed the authentication type to "Work or School Accounts" and set the App ID Url to Api://Automation/TestApi
Visual Studio then scaffolded me a web API with a mock weather forecast service which, if I comment out the [Authorize] attribute spins up nicely in a browser as expected. It also created me an Application Registration in AzureActive Directory.
With the [Authorize] attribute back in place I had trouble calling the API from a client app so I decided to call the API using postman to see what's going on.
I added a client secret to the app registration visual studio created and put a postman request together as below using the Application (client) Id and api://Automation/TestApi/.default as the scope.
[](https://i.stack.imgur.com/cZQjG.png)
This works fine and returns an access token however when I try to use that access token to call the default weatherforcast endpoint I get an HTTP 401 unauthorized error with the following in the WWW-Authenticate response header
"Bearer error="invalid\_token", error\_description="The audience 'api://Automation/TestApi' is invalid"
Is there something I'm missing? I cannot find any clue as to what the audience is expected to be and no obvious way of controlling that.
As Requested here is the content of the expose an API screen
[](https://i.stack.imgur.com/5U1Co.png)
and the decoded jwt token I am using
[](https://i.stack.imgur.com/eB8Aa.png)
**Update**
I tried out @CarlZhao s answer below and it didn't really work. However I remembered [a question I asked a while ago about the wrong issuer in the token](https://stackoverflow.com/questions/59790209/issuer-in-access-token-from-azure-active-directory-is-https-sts-windows-net-wh) the outcome from this is to manually edit the manifest json in the registration for the API and set "accessTokenAcceptedVersion": 2
Now I get a v2 function with the clientId guid as the audience
[](https://i.stack.imgur.com/zUwW8.png)
However, using this token still doesn't work!! I now get an error about the issuer:
`Bearer error="invalid_token", error_description="The issuer 'https://login.microsoftonline.com/{{guid}}/v2.0' is invalid`
|
2020/10/29
|
[
"https://Stackoverflow.com/questions/64600292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428280/"
] |
You missed some important steps, your access token is also wrong, it lacks the necessary permissions. You can try to follow my method:
You need to create 2 applications, one representing the client application and the other representing the api application, and then use the client application to call the Web api application.
First, you need to expose the api of the application representing the web api, you can configure it according to the following process:
Azure portal>App registrations>Expose an API>Add a scope>Add a client application
Because you are using the **client credential flow**, next, you need to define the **manifest** of api applications and grant application permissions to your client applications (this is the role permissions you define yourself, you can find it in **My APIs** when you add permissions).Then you need to click the **admin consent** button to grant administrator consent for this permission.
[This](https://stackoverflow.com/questions/57379397/why-is-application-permissions-disabled-in-azure-ads-request-api-permissions/57385729#57385729) is the process of defining the manifest.
[](https://i.stack.imgur.com/sBCPH.png)
This is to grant permissions for the client application:
[](https://i.stack.imgur.com/qLVGs.png)
Finally, you can request a token for your api application:
[](https://i.stack.imgur.com/nRUgJ.png)
Parse the token and you will see:
[](https://i.stack.imgur.com/qmoyS.png)
|
38,473,994 |
I am using webapi-avplay to play video on samsung tizen tv web app.
Video starts buffering when I am forwarding the video and after the completion of buffering, video starts playing.
At the time when buffering in progress, I am trying to forward/backward video but unfortunately unable to forward/backward video.
So I want to forward/backward video during buffering. I have searched and read doc but not found any help related to my problem.
So Please help us to getting out from here.
|
2016/07/20
|
[
"https://Stackoverflow.com/questions/38473994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4264085/"
] |
Have you tried coding inside **onbufferingprogress** method. Like:
```
var listener = {
onbufferingprogress: function(percent) {
console.log("Buffering in progress");
loadingObj.setPercent(percent);
/* Move 5 seconds back */
var back_button = document.getElementById("v-back"); /* Back button */
back_button.addEventListener("click", function() {
video.currentTime -= 5
}, false);
}
}
webapis.avplay.setListener(listener);
```
Thank you.
|
47,965,975 |
While using google map activity in my android application I get this error.
**"Could not resolve com.google.android.gms:play-services:11.8.0."**
**Project level** Gradle file:
```
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
```
**Application level** Gradle file:
```
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.google.android.gms:play-services:11.8.0'
}
```
|
2017/12/25
|
[
"https://Stackoverflow.com/questions/47965975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4601864/"
] |
So, finally I got the answer,
I've turned on gradle offline mode that's why it could not find out cached files for that version play-service.
I turned it off (under File-Settings-Build,Execution,Deployment-Gradle) and again sync project and some files have been downloaded then it works now.
|
1,578,322 |
I am so confused that I thought to ask you for your opinion.
I have written few jquery code with asp.net. But there is group of developer in my company who think that javascript/jquery can be turned off and is insecure
* if javascript is insecure, why to use it at the first place
* what are the advantages of using jquery with asp.net apart from cross-browser. why not use javascript?
* should i use jquery in my asp.net applications?
There were a few posts over here that contained similar question, but not even one that contained good explanation. Please share your thoughts.
|
2009/10/16
|
[
"https://Stackoverflow.com/questions/1578322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84950/"
] |
>
> if javascript is insecure, why to use it at the first place
>
>
>
To provide advanced browsing experience to those who have it on.
>
> what are the advantages of using jquery with asp.net apart from cross-browser. why not use javascript?
>
>
>
Rapid development. If you're not comfortable with jQuery, code in JavaScript directly, see no problem here.
>
> should i use jquery in my asp.net applications?
>
>
>
That's up to you to decide. Give it a try and see if you'll like it.
|
66,067,834 |
I am using this template:
<https://codepen.io/xweronika/pen/abBdXGp>
I created several components like this, in which instead of text there are also tables, buttons and many elements. When it's full screen everything looks fine:
[](https://i.stack.imgur.com/8IXM8.png)
But when I reduce size of the window - text inside "cut off" and the scroll is blocked, so I can't scroll down to see the rest of the text:
[](https://i.stack.imgur.com/PfQfc.png)
And when I reduce the size of the window even more - the text completely disappears:
[](https://i.stack.imgur.com/JZXaB.png)
Please help me, this looks terrible :(
HTML:
```
<nav class="navbar navbar-expand-lg navbar-light fixed-top">
<div class="container">
<a class="navbar-brand" href="#">Mouri</a>
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Portfolio</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Services</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block w-100" src="https://i.postimg.cc/bNQp0RDW/1.jpg" alt="First slide">
<div class="carousel-caption d-none d-md-block">
<h5>Slider One Item</h5>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime, nulla, tempore. Deserunt excepturi quas vero.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime, nulla, tempore. Deserunt excepturi quas vero.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime, nulla, tempore. Deserunt excepturi quas vero.</p>
</div>
</div>
<div class="carousel-item">
<img class="d-block w-100" src="https://i.postimg.cc/pVzg3LWn/2.jpg" alt="Second slide">
<div class="carousel-caption d-none d-md-block">
<h5>Slider One Item</h5>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime, nulla, tempore. Deserunt excepturi quas vero.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime, nulla, tempore. Deserunt excepturi quas vero.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime, nulla, tempore. Deserunt excepturi quas vero.</p>
</div>
</div>
<div class="carousel-item">
<img class="d-block w-100" src="https://i.postimg.cc/0y2F6Gpp/3.jpg" alt="Third slide">
<div class="carousel-caption d-none d-md-block">
<h5>Slider One Item</h5>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime, nulla, tempore. Deserunt excepturi quas vero.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime, nulla, tempore. Deserunt excepturi quas vero.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime, nulla, tempore. Deserunt excepturi quas vero.</p>
</div>
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
```
CSS:
```
.carousel-item {
height: 100vh;
min-height: 300px;
background: no-repeat center center scroll;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
.carousel-caption {
top: 190px;
}
.carousel-caption h5 {
font-size: 45px;
text-transform: uppercase;
letter-spacing: 2px;
margin-top: 25px;
}
.carousel-caption p {
width: 75%;
margin: auto;
font-size: 18px;
line-height: 1.9;
}
.navbar-light .navbar-brand {
color: #fff;
font-size: 25px;
text-transform: uppercase;
font-weight: bold;
letter-spacing: 2px;
}
.navbar-light .navbar-nav .active > .nav-link, .navbar-light .navbar-nav .nav-link.active, .navbar-light .navbar-nav .nav-link.show, .navbar-light .navbar-nav .show > .nav-link {
color: #fff;
}
.navbar-light .navbar-nav .nav-link {
color: #fff;
}
.navbar-toggler {
background: #fff;
}
.navbar-nav {
text-align: center;
}
.nav-link {
padding: .2rem 1rem;
}
.nav-link.active,.nav-link:focus{
color: #fff;
}
.navbar-toggler {
padding: 1px 5px;
font-size: 18px;
line-height: 0.3;
}
.navbar-light .navbar-nav .nav-link:focus, .navbar-light .navbar-nav .nav-link:hover {
color: #fff;
}
```
|
2021/02/05
|
[
"https://Stackoverflow.com/questions/66067834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12933680/"
] |
Remove the `d-none` class from `<div class="carousel-caption d-none d-md-block">`
Check the example [here](https://codepen.io/gionic/pen/yLVewXg)
Display property bootstrap 4 doc [here](https://getbootstrap.com/docs/4.0/utilities/display/)
|
39,164,187 |
I have two columns which I want to combine and show the data, I tried like below
```
select
case
when status = 'R'
then 'Resign'
when status = 'A'
then 'Active'
end as status1,
Program_name + ' ' + emp_card_no as program_details,
*
from
GetEmployeeDetails
where
emp_name = 'ABHAY ASHOK MANE'
and STATUS = 'A'
order by
EMP_NAME
```
but I am getting an error:
>
> Error converting data type varchar to numeric.
>
>
>
Here is the sample data available
[](https://i.stack.imgur.com/k9Ks0.png)
|
2016/08/26
|
[
"https://Stackoverflow.com/questions/39164187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1216804/"
] |
Try this :
```
select
case when status='R' then 'Resign'
when status='A' then 'Active'
end as status1,
Program_name + ' (' + convert(varchar, emp_card_no) + ') ' as program_details,
*
from GetEmployeeDetails
Where emp_name ='ABHAY ASHOK MANE'and STATUS= 'A' ORDER BY EMP_NAME
```
|
11,851,938 |
So I have a page with about 60 of links on it, with random URL's, each one needs to be clicked and downloaded individually.
I'm working on the fundamental script to tab over to the next link, hit enter, and then 'ok' to download to desktop.
I'm new, but I cannot seem to get the 'floating' window which pops up, to let me keystroke 'return' or click on 'OK'. I'm looking to save the file to desktop, but I can't seem to reference the window by title in the app, or guess the index number or window ID.
Any help is much appreciated..
I've also seen the dictionary, in script editor, and many of the properties of 'window' for Firefox, throw syntax and other errors.
```
tell application "System Events"
tell application "Firefox" to activate
tell window "$thewindowtitle"
keystroke tab
delay 1.0
keystroke return
end tell
tell application "Firefox"
tell window visible
click button "OK"
end tell
end tell
end tell
end tell
```
Thanks!
|
2012/08/07
|
[
"https://Stackoverflow.com/questions/11851938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1169758/"
] |
Try passing `fastIframe: false` in the colorbox configuration. It makes colorbox wait until all contents of the iframe are loaded before attempting to show anything.
```
$('a').colorbox({ iframe: true, fastIframe: false });
```
|
17,702,895 |
I have the following code in a batch file:
```
set /p user="Enter username: " %=%
cd w:\Files
@echo off
setLocal EnableDelayedExpansion
set /a value=0
set /a sum=0
set /a valA=0
FOR /R %1 %%I IN (*) DO (
set /a value=%%~zI/1024
set /a sum=!sum!+!value!
set /a sum=!sum!/1024
)
@echo Size of "FILES" is: !sum! MB
@echo off
FOR /R %1 %%I IN (*) DO (
set /a sum=!sum!/1024
set /a valA=!sum!
)
@echo Size of "FILES" is: !sum! GB
cd W:\Documents and Settings\%user%\Desktop
@echo off
setLocal EnableDelayedExpansion
set /a value=0
set /a sum=0
set /a valB=0
FOR /R %1 %%I IN (*) DO (
set /a value=%%~zI/1024
set /a sum=!sum!+!value!
set /a sum=!sum!/1024
)
@echo Size of Desktop is: !sum! MB
@echo off
FOR /R %1 %%I IN (*) DO (
set /a sum=!sum!/1024
set /a valB=!sum!
)
@echo Size of Desktop is: !sum! GB
```
There are a few other folders it checks, but you should get the idea.
I get this output:
```
C:\Users\pprescott\Desktop>cd w:\Files
Size of "FILES" is: 215 MB
Size of "FILES" is: 0 GB
Size of Desktop is: 215 MB
Size of Desktop is: 0 GB
Size of Favorites is: 215 MB
Size of Favorites is: 0 GB
Size of Documents is: 215 MB
Size of Documents is: 0 GB
Total size is: 0 MB
Total size is: 0 GB
Press any key to continue . . .
```
This is designed to count folder size on an old xp machine to prepare for a data transfer. The xp machine is mapped to drive W.
|
2013/07/17
|
[
"https://Stackoverflow.com/questions/17702895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2252537/"
] |
try to remove the `for /r` parameter `%1`:
```
FOR /R %%I IN (*) DO (
```
---
Try this code:
```
@ECHO OFF &SETLOCAL
FOR /R "w:\Files" %%I IN (*) DO set /a asum+=%%~zI
SET /a sum=asum/1048576
echo Size of "FILES" is: %sum% MB
set /a sum=asum/1073741824
echo Size of "FILES" is: %sum% GB
FOR /R "W:\Documents and Settings\%user%\Desktop" %%I IN (*) DO set /a asum+=%%~zI
SET /a sum=asum/1048576
echo Size of "DESKTOP" is: %sum% MB
set /a sum=asum/1073741824
echo Size of "DESKTOP" is: %sum% GB
```
|
24,809,965 |
I noticed a weird thing when I was writing an angular directive. In the isolated scope of the directive, if I bind an attribute using `myAttr: '@'` to the parent scope variable with the same name, and then use that attribute in the html template, there will be an extra space trailing the attribute value. If the attribute is bound to the parent scope variable with a different name using `myAttr: '@thatAttr'`, however, there is no extra space and the world is happy.
Please see [this jsFiddle](http://jsfiddle.net/EEpv2/2/) for a demonstration. As you can see, the css rules under `div[bad=foo]` is not applied because of the extra space, while `div[good=bar]` is perfectly fine.
The fiddle uses Angular 1.3 by the way. Does anyone know why this is the case?
|
2014/07/17
|
[
"https://Stackoverflow.com/questions/24809965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264587/"
] |
[Known bug](https://github.com/angular/angular.js/issues/8132) in Angular, likely will not be fixed
|
9,675 |
I am starting some tests for building a game on the Android program.
So far everything is working and seems nice.
However I do not understand how to make sure my game looks correct on all phones as they all will have slightly different screen ratios (and even very different on some odd phones)
What I am doing right now is making a view frustum (could also be ortho) which I set to go from -ratio to +ratio (as I have seen on many examples) however this causes my test shape to be stretched and sometimes cut off by the edge of the screen.
I am tilting my phone to landscape to do my tests (a bit extreme) but it should still render correctly if I have done things right.
Should I be scaling by some ratio before drawing or something?
An example would be greatly appreciated.
PS. I am doing a 2D game .
|
2011/03/12
|
[
"https://gamedev.stackexchange.com/questions/9675",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/6053/"
] |
From a high-level perspective there's only a handful of options, depending on which is more important, maintaining a consistent aspect ratio, or ensuring that no one to see more than someone else just because they have a wider or taller screen.
Your options are:
1. Cropping the parts that don't fit.
2. Stretching the screen to fit, which has the issue you're seeing of stretched images.
3. "[Letterboxing](http://en.wikipedia.org/wiki/Letterbox)" which maintains both aspect ratio and ensures that no player sees more than any other player because of their screen size,
|
52,443,412 |
i have to insert data with ajax into database, now it insert data in to database,but not upload the image.
**ajax Code**
```
$(document).on("click","#save", function(){
jQuery.ajax({
method :'post',
url:''+APP_URL+'/products/add_product',
data:$("#product_form").serialize(),
success: function(response){
$("#product_list").load("<?php echo url('products/tblproducts');?>").fadeIn("slow")
}
});
});
```
"product\_form" is ID of form.
**Route**
```
Route::post('products/add_product','admin\ProductsController@add_new_product');
```
**Controller Function**
```
public function add_new_product(Request $request){
try{
DB::beginTransaction();
$product_image = NULL;
if ($request->hasFile('product_photo')){
$ext = $request->product_image->getClientOriginalExtension();
$product_image = uniqid().".".$ext;
$file = $request->file('product_image');
$destinationPath = public_path("products");
$file->move($destinationPath, $product_image);
}
$bdata['product_photo']=$product_image;
$bdata['product_name']= $request->item_name;
$bdata['product_barcode']= $request->barcode;
DB::table('tbl_products')->insert($bdata);
DB::commit();
$this->CreateMessages('add');
}catch(\Exception $v){
DB::rollback();
$this->CreateMessages('not_added');
throw $v;
}
```
}
|
2018/09/21
|
[
"https://Stackoverflow.com/questions/52443412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8648172/"
] |
```
Try below code to upload image:
`$(document).on("click","#save", function(){
var fd = new FormData();
fd.append('product_photo',$('#id_of_image_uploader').prop('files')[0]);
fd.append('item_name', $('#id_of_item_name').val());
fd.append('barcode', $('#id_of_barcode').val());
jQuery.ajax({
method :'post',
url:''+APP_URL+'/products/add_product',
data: fd,
cache: false,
contentType: false,
processData: false,
success: function(response){
$("#product_list").load("<?php echo url('products/tblproducts');?>").fadeIn("slow")
}
});
});`
```
|
73,750,583 |
Here's what i have at the moment:
```
let userTeams = ['Liverpool', 'Manchester City', 'Manchester United'];
let object = {
teams: {
'Liverpool': {
player:
['Salah',
'Nunez']
},
'Manchester United': {
player:
['Ronaldo',
'Rashford']
},
'Manchester City': {
player:
['Haaland',
'Foden']
},
},
};
let userTeam = userTeams[Math.floor(Math.random() * 3)];
```
I need the team selection to be directly but randomly from the object rather than from the userTeams array.
How would i go about that?
|
2022/09/16
|
[
"https://Stackoverflow.com/questions/73750583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17265256/"
] |
I'm guessing that the OP really aims to get a random team name (key) and that team's data (value) in an object. Abstractly, in a few steps:
Here's how to get a random element from an array:
```
const randomElement = array => array[Math.floor(Math.random()*array.length)];
```
That can be used to get a random key from an object:
```
const randomKey = object => randomElement(Object.keys(object));
```
And that can be used to get a random key-value pair:
```
const randomKeyValue = object => {
const key = randomKey(object);
return { [key] : object[key] };
};
```
All together:
```js
let object = {
teams: {
'Liverpool': {
player:
['Salah',
'Nunez']
},
'Manchester United': {
player:
['Ronaldo',
'Rashford']
},
'Manchester City': {
player:
['Haaland',
'Foden']
},
},
};
const randomElement = array => array[Math.floor(Math.random() * array.length)];
const randomKey = object => randomElement(Object.keys(object));
const randomKeyValue = object => {
const key = randomKey(object);
return {
[key]: object[key]
};
};
console.log(randomKeyValue(object.teams))
```
|
33,973,634 |
I am getting some peculiar behavior in Firefox with localForage. I set up a page to load two arrays using the standard 'setItem' form:
```
<script src="localforage.js"></script>
<body>
<script>
var data = [1,2,3,4,5];
localforage.setItem("saveData", data, function(err, value) {
if (err) {
console.error('error: ', err);
} else {
console.log("Data Saved");
}});
localforage.getItem("saveData", function (err, value) {
if (err) {
console.error('error: ', err);
} else {
console.log('saveData is: ', value);
localforage.keys(function(err, keys) {
console.log("Keys: " + keys);
console.log("Number of keys: " + keys.length);
});
}});
</script>
</body>
</html>
```
The array was saved correctly.
I then made a second page, using exactly the same "getItem" function.
In Chrome, the data showed up, but in Firefox it was not listed at all, and could not be opened.
Has anyone else experienced this? In Firefox, even opening the second page in the same session fails to find the saved file. I have tried changing security.fileuri.strict\_origin\_policy, but it made no difference.
I would rather use Firefox, but I can't if it keeps losing saved data.
|
2015/11/28
|
[
"https://Stackoverflow.com/questions/33973634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4370702/"
] |
I also had the same issue but solved it after some researching, trials and discussions. Extensions like FireStorage Plus! and simple session storage do not work flawlessly for detecting this data, especially if it is being performed on a page/file other than the original root page/file.
The solution for me was to use the native FF Storage Inspector. Only then could I see ALL of the data I was missing. Those extensions did not show the data, even though it was being set.
Refer to: [localForage setItem/getItem unreliable in Firefox / FireStorage Plus](https://stackoverflow.com/questions/36482778/localforage-setitem-getitem-unreliable-in-firefox-firestorage-plus)
[](https://i.stack.imgur.com/LRGwz.png)
In addition, **for future assistance with localForage issues, try their IRC chat** **#localforage** at <https://webchat.freenode.net/> and look for **tofumatt**. He is the guru you want to confer with. ^5
|
18,125 |
When you gain five pounds in one day people always say "water retention from sodium" and undigested food. To see if this is plausible, I want to get a sense for the scale of the effect. Suppose you consumed an additional 2300 mg of sodium (one US RDA, also the amount of sodium in one 11-ounce bag of Doritos, so it's a common real-world scenario for me). How many pounds of water would this cause the average person to retain?
|
2014/07/09
|
[
"https://fitness.stackexchange.com/questions/18125",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/8332/"
] |
While I agree with Greg, I did some digging and came up with this information:
[An extra 400 milligrams of sodium in your body results in a 2-pound weight increase.](http://healthyeating.sfgate.com/much-sodium-per-day-lose-weight-7850.html) Now, to me, this statistic is questionable, as the author does not site a source, and 2 pounds seems like a lot for that amount, but I cannot find any other discussion which offers a number, so take from it what you will.
If you are really curious, conduct a test yourself, where you maintain a constant diet for a couple days taking frequent weight measurements, then add some sodium to the diet and take more measurements. While this might not be exact, it will be adjusted to your body type, and will give you the best idea of how your body responds to additional sodium. Make sure to hydrate well before starting the experiment, as all the sources I came across say fulfilling your hydration needs results in a loss of the excess water weight, and so this would allow you a clean slate from which to gather results.
|
279,840 |
Let's consider a function with evaluated and unevaluated arguments inside:
```
list1 = {1,2,3}
list2 = {x,y,z}
fun[list_]:={list,ToString@Unevaluated@list}
```
When I use Map over `fun` I expect to get result like this:
```
{fun[list1],fun[list2]}
(*{{{1, 2, 3}, "list1"}, {{x, y, z}, "list2"}}*)
```
But instead I get this:
```
fun /@ {list1, list2}
{{{1, 2, 3}, "{1, 2, 3}"}, {{x, y, z}, "{x, y, z}"}}
```
This is surely connected with my misunderstanding of evaluation behaviour, but no obvious answer was found in Robby Villegas notebook <https://library.wolfram.com/infocenter/Conferences/377/> , nor here in StackExchange. How to solve this problem?
ver. 12.1, Windows 10
**EDIT**
Setting attribute `Listable` help a bit making unnecessary to use `Map`:
```
SetAttributes[fun, {HoldAll, Listable}];
fun[{list1,list2}]
``
(*{{{1, 2, 3}, "list1"}, {{x, y, z}, "list2"}} *)
```
|
2023/02/11
|
[
"https://mathematica.stackexchange.com/questions/279840",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/72560/"
] |
```
sol1 = {#[[1]] - 172, #[[2]]} & /@ points ;
sol2 = points - Threaded[{172, 0}];
sol3 = MapAt[Subtract[#, 172] &, points, {All, 1}];
sol4 = {#1 - 172, #2} & @@@ points;
sol1 == sol2 == sol3 == sol4
(* True *)
```
|
236,424 |
I have the data stored in the textfile like this:
0.5 0.5 -0.7 -0.8
0.51 0.51 -0.75 -0.85
0.6 0.1 0.1 1.00
and so on
4 numbers in each row.
Two first numbers means coordinates (x0,y0), two last - (x1,y1). This determines the coordinates of a line. So, the first row tells, that I have a line starting from (0.5, 0.5) and finishing in (-0.7, -0.8). The aim is to plot all of these lines. How can I do this? Explain it for beginner, please.
|
2020/12/12
|
[
"https://mathematica.stackexchange.com/questions/236424",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/76234/"
] |
```
data = Import["/Users/roberthanlon/Downloads/lines.txt", "Data"]
(* {{0.5, 0.5, -0.7, -0.8}, {0.51, 0.51, -0.75, -0.85}, {0.6, 0.1, 0.1, 1.}} *)
Graphics[Line /@ (Partition[#, 2] & /@ data), Axes -> True]
```
[](https://i.stack.imgur.com/vTHRm.png)
Highlight any function or operator and press `F1` for help.
|
272,779 |
I wrote an answer to this question on [Distinct States](https://physics.stackexchange.com/questions/272556/schroeders-thermal-physics-multiplicity-of-a-single-ideal-gas-molecule/272585#272585), but I am not happy with the answer I gave to the short question at the end.
Hopefully this question is self contained, but please read the link above for full details, thanks.
The problem is set in momentum space, and deals with the multiplicity of a monotonic ideal gas. From my textbook:
>
> The number of independent wavefunctions is finite, if the total available position space and momentum space are limited.
>
>
>
[](https://i.stack.imgur.com/5DU6Q.jpg)
L/$\Delta x$ is the number of distinct position states and L$\_p$/$\Delta p$
is the number of distinct momentum states, (in a 1 dimensional system). The total number of distinct states is the product:
$\frac {L} {\Delta (x)}$$\frac {L\_p} {\Delta (p )}$ =$\frac {LL\_p} {h}$
Using the uncertainty principle.
My question is, what does this physically represent?
I am fairly familiar with Q.M., it is the momentum space concepts in thermodynamics that I am just starting to study.
My interpretation is that it simply represents the fact the particle could be at any distinct position within the space, and can have a distinct momentum at that position. So $X = 5$, $P = 7$, or any other combination of these distinct variables.
I self study, (with no one else to check with, so please excuse the confirm my idea aspect). If it's as simple as that explanation, I shall be excruciatingly embarrassed, but at least happy that I have it sorted out.
|
2016/08/05
|
[
"https://physics.stackexchange.com/questions/272779",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/-1/"
] |
**OBJECTIVE:** **how to Wick rotate a path integral using Cauchy's theorem**. I like the approach of using Cauchy's theorem and I must admit I haven't seen the finite-time problem approached from this viewpoint before, so it seemed like a fun thing to think about (on this rainy Sunday afternoon!).
When I started thinking about this I was more optimistic than I am now (it's now Wednesday). I start by stating my conclusions (details of all claims will follow):
**1.** There is a local obstruction that enforces the quantity you call
$$
e^{-i\int\_C dz\,\mathcal{L}(z)},
$$
to contribute non-trivially. This is the first hint that the whole approach is creating more problems than it solves. (There is an easier way to do the analytic continuation.)
**2.** Your choice of contour does not make your life easy. If instead of the first quadrant you continued into the fourth quadrant of the complex-$z$ plane you would get the correct minus sign in the suppression factor (but not quite the expected integrand).
[](https://i.stack.imgur.com/2M6ng.png)
**3.** The assumption of holomorphicity is justified, in that there exists a complete basis expansion for $\tilde{x}(t)$ (and its analytically continued extension, $\tilde{x}(z)$) such that the quantity:
$$
\oint\_{L\_R}dz\,\mathcal{L}(z)+\oint\_{L\_I}dz\,\mathcal{L}(z)+\oint\_{C}dz\,\mathcal{L}(z),
$$
indeed vanishes, so that the closed contour can be contracted to a point.
**4.** Boundary conditions are important: it is the quantum fluctuations terms involving $\tilde{x}(t)$ that need continuing, not the zero mode (classical) piece, $x\_{\rm cl}(t)$, where
$$
x(t)=x\_{\rm cl}(t)+\tilde{x}(t),
$$
subject to $x\_{\rm cl}(0)=x\_i$, $x\_{\rm cl}(T)=x\_f$, $\tilde{x}(0)=\tilde{x}(T)=0$. The last two conditions make your life slightly easier.
**5.** It is much more efficient and natural to analytically continue $\tilde{x}(t)$ in problems such as these, when there are finite time intervals involved. This is also true in QFT.
**6.** When you expand $\tilde{x}(t)$ as a Fourier series subject to the above boundary conditions (I'm forgetting about interactions because these are irrelevant for Wick rotations, at least within perturbation theory),
$$
\tilde{x}(t) = \sum\_{n\neq0}a\_n\psi\_n(t),\qquad {\rm with}\qquad \psi\_n(t)=\sqrt{\frac{2}{T}}\sin\frac{n\pi t}{T},
$$
it becomes clear that the (unique) analytically continued expression, obtained from the above by replacing $t\rightarrow z$, does not have a well-behaved basis: $\{\psi\_n(z)\}$ is no longer complete, nor orthonormal and in fact diverges for large enough $\beta$, where $z=t+i\beta$. But it is holomorphic within its radius of convergence, and then you might expect Cauchy's theorem to come to the rescue because for any closed contour:
$$
\oint dz\,\psi\_n(z)\psi\_m(z)=0,
$$
and so given that $\int\_0^Tdt\,\psi\_n(t)\psi\_m(t)=\delta\_{n,m}$ one can say something meaningful about the integrals in the remaining regions of the complex plane.
And a comment (which is mainly addressed to some of the comments you have received @giulio bullsaver and @flippiefanus): the path integral is general enough to be able to capture both finite and infinite limits in your action of interest, in both QM and QFT. One complication is that sometimes it is not possible to define asymptotic states when the limits are finite (the usual notion of a particle only makes sense in the absence of interactions, and at infinity the separation between particles can usually be taken to be large enough so that interactions are turned off), and although this is no problem of principle one needs to work harder to make progress. In quantum mechanics where there is no particle creation things are simpler and one can consider a single particle state space.
As I mentioned above this is just a taster: when I find some time I will add flesh to my claims.
---
**DETAILS:**
------------
Consider the following path integral for a free non-relativistic particle:
$$
\boxed{Z= \int \mathcal{D}x\,e^{\frac{i}{\hbar}\,I[x]},\qquad I[x]=\int\_0^Tdt\,\Big(\frac{dx}{dt}\Big)^2}
$$
(We set the mass $m=2$ throughout to avoid unnecessary clutter, but I want to keep $\hbar$ explicit. We can restore $m$ at any point by replacing $\hbar\rightarrow \hbar 2/m$.)
This path integral is clearly completely trivial. However, the question we are aiming to address (i.e. to understand Wick rotation in relation to Cauchy's theorem) is (within perturbation theory) independent of interactions. Stripping the problem down to its ''bare bones essentials'' will be sufficient. Here is my justification: **will not perform any manipulations that we would not be able to also perform in the presence of interactions within perturbation theory**. So this completely justifies considering the free theory.
For pedagogical reasons I will first describe how to go about evaluating such path integrals unambiguously, including a detailed discussion of how to use Cauchy's theorem to make sense of the oscillating exponential, and only after we have reached a result will we discuss the problems associated to following the approach suggested in the question.
**How to Wick Rotate Path Integrals Unambiguously:**
To compute any path integral the first thing one needs to do is **specify boundary conditions**. So suppose our particle is at $x\_i=x(0)$ at $t=0$ and at $x\_f=x(T)$ at $t=T$. To implement these let us factor out a classical piece and quantum fluctuations:
$$
x(t) = x\_{\rm cl}(t)+\tilde{x}(t),
$$
and satisfy the boundary conditions by demanding that quantum fluctuations are turned off at $t=0$ and $t=T$:
$$
\tilde{x}(0)=\tilde{x}(T)=0,
$$
so the classical piece must then inherit the boundary conditions of $x(t)$:
$$
x\_{\rm cl}(0)=x\_i,\qquad x\_{\rm cl}(T)=x\_f.
$$
In addition to taking care of the boundary conditions, the decomposition into a classical piece and quantum fluctuations plays the following very important role: integrating out $x(t)$ requires that you be able to invert the operator $-d^2/dt^2$. This is only possible when what it acts on is not annihilated by it, i.e. when the eigenvalues of this operator are non-vanishing. We call the set of things that are annihilated by $-d^2/dt^2$ the *kernel of* $-d^2/dt^2$, so then the classical piece $x\_{\rm cl}(t)$ is precisely the kernel of $-d^2/dt^2$:
\begin{equation}
-\frac{d^2}{dt^2}x\_{\rm cl}(t)=0.
\end{equation}
This is of course precisely the classical equation of motion of a free non-relativistic particle with the unique solution (subject to the above boundary conditions):
$$
x\_{\rm cl}(t) = \frac{x\_f-x\_i}{T}t+x\_i.
$$
So now we implement the above into the path integral, starting from the action. The decomposition $x(t) = x\_{\rm cl}(t)+\tilde{x}(t)$ leads to:
\begin{equation}
\begin{aligned}
I[x]&=\int\_0^Tdt\Big(\frac{dx}{dt}\Big)^2\\
&=\int\_0^Tdt\Big(\frac{dx\_{\rm cl}}{dt}\Big)^2+\int\_0^Tdt\Big(\frac{d\tilde{x}}{dt}\Big)^2+2\int\_0^Tdt\frac{dx\_{\rm cl}}{dt}\frac{d\tilde{x}}{dt}\\
\end{aligned}
\end{equation}
In the first term we substitute the solution to the equations of motion given above. In the second term we integrate by parts taking into account the boundary conditions on $\tilde{x}(t)$. In the third term we integrate by parts taking into account the boundary conditions on $\tilde{x}(t)$ and use the fact that $d^2x\_{\rm cl}/dt^2=0$ for all $t$. All in all,
\begin{equation}
I[x]=\frac{(x\_f-x\_i)^2}{T}+\int\_0^Tdt\,\tilde{x}(t)\Big(-\frac{d^2}{dt^2}\Big)\tilde{x}(t),\quad{\rm with}\quad \tilde{x}(0)=\tilde{x}(T)=0,
\end{equation}
and now we substitute this back into the path integral, $Z$, in order to consider the Wick rotation in detail:
\begin{equation}
\boxed{Z= e^{i(x\_f-x\_i)^2/\hbar T}\int \mathcal{D}\tilde{x}\,\exp\, \frac{i}{\hbar}\int\_0^T\!\!\!dt\,\tilde{x}(t)\Big(-\frac{d^2}{dt^2}\Big)\tilde{x}(t),
\quad{\rm with}\quad \tilde{x}(0)=\tilde{x}(T)=0}
\end{equation}
Clearly, given that we have fixed the boundary values of $x(t)$, we also have that: $\mathcal{D}x=\mathcal{D}\tilde{x}$. That is, *we are only integrating over quantities that are not fixed by the boundary conditions on $x(t)$*.
So the first point to notice is that only the quantum fluctuations piece might need Wick rotation.
**Isolated comment:**
Returning to a point I made in the beginning of the DETAILS section: if our objective was to simply solve the free particle theory we'd be (almost) done! We wouldn't even have to Wick-rotate. We would simply introduce a new time variable, $t\rightarrow t'=t/T$, and then redefine the path integral field at every point $t$, $\tilde{x}\rightarrow \tilde{x}'=\tilde{x}/\sqrt{T}$. The measure would then (using zeta function regularisation) transform as $\mathcal{D}\tilde{x}\rightarrow =\mathcal{D}\tilde{x}'=\sqrt{T}\mathcal{D}\tilde{x}$, so the result would be:
$$
Z=\frac{N}{\sqrt{T}}e^{i(x\_f-x\_i)^2/\hbar T},
$$
the quantity $N$ being a normalisation (see below). But as I promised, we will not perform any manipulations that cannot also be performed in fully interacting theories (and within perturbation theory). So we take the long route. There is value in mentioning the shortcut however: it serves as an important consistency check for what follows.
**Wick Rotation:** Consider the quantum fluctuations terms in the action,
$$
\int\_0^T\!\!\!dt\,\tilde{x}(t)\Big(-\frac{d^2}{dt^2}\Big)\tilde{x}(t),
\quad{\rm with}\quad \tilde{x}(0)=\tilde{x}(T)=0,
$$
and search for a complete (and ideally orthonormal) basis, $\{\psi\_n(t)\}$, in which to expand $\tilde{x}(t)$. We can either think of such an expansion as a Fourier series expansion of $\tilde{x}(t)$ (where it is obvious the basis will be complete), or we can equivalently define the basis as the full set of eigenvectors of $-d^2/dt^2$. There are three requirements that the basis must satisfy (and a fourth optional one):
**(a)** it must not live in the kernel of $-d^2/dt^2$ (the kernel has already been extracted out and called $x\_{\rm cl}(t)$).
**(b)** it must be real (because $\tilde{x}(t)$ is real);
**(c)** it must satisfy the correct boundary conditions inherited by $\tilde{x}(0)=\tilde{x}(T)=0$;
**(d)** it is convenient for it to be orthonormal with respect to some natural inner product, $(\psi\_n,\psi\_m)=\delta\_{n,m}$, but this is not necessary.
The unique (up to a constant factor) solution satisfying these requirements is:
$$
\tilde{x}(t)=\sum\_{n\neq0}a\_n\psi\_n(t),\qquad {\rm with}\qquad \psi\_n(t)=\sqrt{\frac{2}{T}}\sin \frac{n\pi t}{T},
$$
where the normalisation of $\psi\_n(t)$ is fixed by our *choice* of inner product:
$$
(\psi\_n,\psi\_m)\equiv \int\_0^Tdt\,\psi\_n(t)\,\psi\_m(t)=\delta\_{n,m}.
$$
(In the present context this is a natural inner product, but more generally and without referring to a particular basis, $(\delta \tilde{x},\delta \tilde{x})$ is such that it preserves as much of the classical symmetries as possible. Incidentally, not being able to find a natural inner product that preserves *all* of the classical symmetries is the source of potential anomalies.)
This basis $\{\psi\_n(t)\}$ is real, orthonormal, satisfies the correct boundary conditions at $t=0,T$ and corresponds to a complete set of eigenvectors of $-d^2/dt^2$:
$$
-\frac{d^2}{dt^2}\psi\_n(t)=\lambda\_n\psi\_n(t),\qquad {\rm with}\qquad \lambda\_n=\Big(\frac{n\pi}{T}\Big)^2.
$$
From the explicit expression for $\lambda\_n$ it should be clear why $n=0$ has been omitted from the sum over $n$ in $\tilde{x}(t)$.
To complete the story we need to define the **path integral measure**. I will mention two equivalent choices, starting from the pedagogical one:
$$
\mathcal{D}\tilde{x}=\prod\_{n\neq0}\frac{d a\_n}{K},
$$
for some choice of $K$ which is fixed at a later stage by any of the, e.g., two methods mentioned below (we'll find $K=\sqrt{4T}$). (The second equivalent choice of measure is less transparent, but because it is more efficient it will also be mentioned below.)
To evaluate the path integral we now rewrite the quantum fluctuations terms in $Z$ in terms of the basis expansion of $\tilde{x}(t)$, and make use of the above relations:
\begin{equation}
\begin{aligned}
\int \mathcal{D}\tilde{x}\,&\exp\, \frac{i}{\hbar}\int\_0^T\!\!\!dt\,\tilde{x}(t)\Big(-\frac{d^2}{dt^2}\Big)\tilde{x}(t)\\
&=\int \prod\_{n\neq0}\frac{d a\_n}{K}\,\exp\, i\sum\_{n\neq0}\frac{1}{\hbar}\Big(\frac{n\pi}{T}\Big)^2a\_n^2\\
&=\prod\_{n\neq0}\Big( \frac{T\sqrt{\hbar}}{K\pi |n|}\Big)\prod\_{n\neq0}\Big(\int\_{-\infty}^{\infty} d a\,e^{ia^2}\Big),
\end{aligned}
\end{equation}
where in the last equality we redefined the integration variables, $a\_n\rightarrow a=\frac{|n|\pi}{\sqrt{\hbar}T}a\_n$.
The evaluation of the infinite products is somewhat tangential to the main point of thinking about Wick rotation, so I leave it as an
**Exercise:** Use zeta function regularisation to show that:
$$
\prod\_{n\neq0}c=\frac{1}{c},\qquad \prod\_{n\neq0}|n| = 2\pi,
$$
for any $n$-independent quantity, $c$. (Hint: recall that $\zeta(s)=\sum\_{n>0}1/n^s$, which has the properties $\zeta(0)=-1/2$ and $\zeta'(0)=-\frac{1}{2}\ln2\pi$.)
All that remains is to evaluate:
$$
\int\_{-\infty}^{\infty} d a\,e^{ia^2},
$$
which is also a standard exercise in complex analysis, but I think there is some value in me going through the reasoning as it is central to the notion of Wick rotation: the integrand is analytic in $a$, so for any closed contour, $C$, Cauchy's theorem ensures that,
$$
\oint\_Cda\,e^{ia^2}=0.
$$
Let us choose in particular the contour shown in the figure:
[](https://i.stack.imgur.com/pPzTB.png)
Considering each contribution separately and taking the limit $R\rightarrow \infty$ leads to:
$$
\int\_{-\infty}^{\infty} d a\,e^{ia^2}=\sqrt{i}\int\_{-\infty}^{\infty}da\,e^{-a^2}=\sqrt{\pi i}
$$
(Food for thought: what is the result for a more general choice of angle, $\theta\in (0,\frac{\pi}{2}]$? which in the displayed equation and figure is $\theta=\pi/4$.) An important conclusion is that Gaussian integrals with oscillating exponentials are *perfectly well-defined*. There was clearly no need to Wick rotate to imaginary time at any point of the calculation. The whole analysis above was to bring the original path integral into a form that contains a product of well-defined ordinary integrals. Using this result for the $a$ integral, zeta function regularisation for the infinite products (see above), and rearranging leads to:
\begin{equation}
\begin{aligned}
\int \mathcal{D}\tilde{x}\,&\exp\, \frac{i}{\hbar}\int\_0^T\!\!\!dt\,\tilde{x}(t)\Big(-\frac{d^2}{dt^2}\Big)\tilde{x}(t)=\frac{1}{2\pi}\frac{K\pi}{T\sqrt{\hbar}}\frac{1}{\sqrt{\pi i}}.
\end{aligned}
\end{equation}
Substituing this result into the boxed expression above for the full path integral we learn that:
$$
Z[x\_f,T;x\_i,0]=\frac{e^{i(x\_f-x\_i)^2/\hbar T}}{\sqrt{\pi i\hbar T}}\,\frac{K}{\sqrt{4 T}}.
$$
**Normalisation:** Although somewhat tangential, some readers may benefit from a few comments regarding the normalisation: $K$ may be determined by demanding consistent factorisation,
$$
Z[x\_f,T;x\_i,0] \equiv \int\_{-\infty}^{\infty}dy\,Z[x\_f,T;y,t]Z[y,t;x\_i,0],
$$
(the result is independent of $0\leq t\leq T$) or, if one (justifiably) questions the uniqueness of the normalisation of the $\int dy$ integral one may instead determine $K$ by demanding that the path integral reproduce the Schrodinger equation: the (position space) wavefunction at $t=T$ given a wavefunction at $t=0$, $\psi(x\_i,0)$, is by definition,
$$
\psi(x,t) = \int\_{-\infty}^{\infty}dy\,Z[x,t;y,0]\psi(y,0),
$$
and then Taylor expanding in $t$ and $\eta$ upon redefining the integration variable $y\rightarrow \eta=x-y$ leads to Schrodinger's equation,
$$
i\hbar \partial\_t\psi(x,t)=-\frac{\hbar^2}{4}\partial^2\_x\psi(x,t),
$$
provided the normalisation, $K=\sqrt{4T}$, (recall $m=2$). (A more boring but equivalent method to determine $K$ is to demand consistency with the operator approach, where $Z=\langle x\_f,t|x\_i,0\rangle$, leading to the same result.)
So, the full correctly normalised path integral for a free non-relativistic particle (of mass $m=2$) is therefore,
$$
\boxed{Z[x\_f,T;x\_i,0]=\frac{e^{i(x\_f-x\_i)^2/\hbar T}}{\sqrt{\pi i\hbar T}}}
$$
(Recall from above that to reintroduce the mass we may effectively replace $\hbar\rightarrow 2\hbar/m$.)
**Alternative measure definition:**
I mentioned above that there is a more efficient but equivalent definition for the measure of the path integral, but as this is not central to this post I'll only list it as an
**Exercise 1:** Show that, for any constants $c,K$, the following measure definitions are equivalent:
$$
\mathcal{D}\tilde{x}=\prod\_{n\neq0}\frac{d a\_n}{K},
\qquad \Leftrightarrow\qquad \int \mathcal{D}\tilde{x}e^{\frac{i}{\hbar c}(\tilde{x},\tilde{x})}=\frac{K}{\sqrt{\pi i\hbar c}},
$$
where the inner product was defined above.
**Exercise 2:** From the latter measure definition one has immediately that,
$$
\int \mathcal{D}\tilde{x}e^{\frac{i}{\hbar }(\tilde{x},-\partial\_t^2\tilde{x})}=\frac{K}{\sqrt{\pi i\hbar }}\,{\rm det}^{-\frac{1}{2}}\!(-\partial\_t^2).
$$
Show using zeta function regularisation that ${\rm det}^{-\frac{1}{2}}\!(-\partial\_t^2)\equiv(\prod\_{n\neq0}\lambda\_n)^{-1/2}=\frac{1}{2T}$, thus confirming (after including the classical contribution, $e^{i(x\_f-x\_i)^2/\hbar T}$) precise agreement with the above boxed result for $Z$ when $K=\sqrt{4T}$. (Notice that again we have not had to Wick rotate *time*, and the path integral measure is perfectly well-defined if one is willing to accept zeta function regularisation as an interpretation for infinite products.)
---
**WICK ROTATING TIME? maybe not..**
Having discussed how to evaluate path integrals without Wick-rotating rotating time, we now use the above results in order to understand what might go wrong when one does Wick rotate time.
**So we now follow your reasoning (but with a twist):** We return to the path integral over fluctuations. We analytically continue $t\rightarrow z=t+i\beta$ and wish to construct a contour (I'll call the full closed contour $C$), such that:
$$
\oint\_C dz\,\tilde{x}(z)\Big(-\frac{d^2}{dz^2}\Big)\tilde{x}(z)=0.
$$
Our work above immediately implies that any choice of $C$ can indeed can be contracted to a point without obstruction. This is because using the above basis we have a unique analytically continued expression for $\tilde{x}(z)$ given $\tilde{x}(t)$:
$$
\tilde{x}(z)=\sqrt{\frac{2}{T}}\sum\_{n\neq0}a\_n\sin \frac{n\pi z}{T}.
$$
This is clearly analytic in $z$ (as are its derivatives) with no singularities except possibly outside of the radius of convergence. The first indication that this might be a bad idea is to notice that by continuing $t\rightarrow z$ we end up with a bad basis that ceases to be orthonormal and the sum over $n$ need not converge for sufficiently large imaginary part of $z$. So this immediately spells trouble, but let us try to persist with this reasoning, in the hope that it might solve more problems than it creates (it doesn't).
Choose the following contour (note the different choice of contour compared to your choice):
[](https://i.stack.imgur.com/2M6ng.png)
I chose the fourth quadrant instead of the first, because (as you showed in your question) the first quadrant leads to the wrong sign Gaussian, whereas the fourth quadrant cures this.
So we may apply Cauchy's theorem to the contour $C=a+b+c$. Using coordinates $z=re^{i\theta}$ and $z=t+i\beta$ for contour $b$ and $c$ respectively,
\begin{equation}
\begin{aligned}
\int\_0^T& dt\,\tilde{x}\Big(-\frac{d^2}{dt^2}\Big)\tilde{x}\\
&=- \int\_0^{-\pi/2}(iTe^{i\theta}d\theta)\,\tilde{x}(Te^{i\theta})\frac{1}{T^2e^{2i\theta}}\Big(\frac{\partial^2}{\partial \theta^2}-i\frac{\partial}{\partial \theta}\Big)\tilde{x}(Te^{i\theta})\\
&\qquad+i\int\_{-T}^0d\beta\,\tilde{x}(i\beta)\Big(-\frac{d^2}{d\beta^2}\Big)\tilde{x}(i\beta)
\end{aligned}
\end{equation}
where by the chain rule, along the $b$ contour:
$$
dz|\_{r=T}=iTe^{i\theta}d\theta,\qquad {\rm and}\qquad -\frac{d^2}{dz^2}\Big|\_{r=T} = \frac{1}{T^2e^{2i\theta}}\Big(\frac{\partial^2}{\partial \theta^2}-i\frac{\partial}{\partial \theta}\Big),
$$
are evaluated at $z=Te^{i\theta}$.
Regarding the integral along contour $b$ (i.e. the $\theta$ integral) there was the question above as to whether this quantity actually contributes or not. That it *does* contribute follows from an elementary theorem of complex analysis: the Cauchy-Riemann equations. Roughly speaking, the statement is that if a function, $f(z)$, is holomorphic in $z$ then the derivative of this function with respect to $z$ at any point, $p$, is independent of the *direction* of the derivative. E.g., if $z=x+iy$, then $\partial\_zf(z) = \partial\_xf(z)=-i\partial\_yf(z)$ at any point $z=x+iy$. Applying this to our case, using the above notation, $z=re^{i\theta}$, this means that derivatives along the $\theta$ direction evaluated at any $\theta$ and at $r=T$ equal corresponding derivatives along the $r$ direction at the same $\theta$ and $r=T$, which in turn equal $z$ derivatives at the same $z=Te^{i\theta}$. So we conclude immediately from this that the integral along the $b$ contour is:
\begin{equation}
\begin{aligned}
- \int\_0^{-\pi/2}(iTe^{i\theta}d\theta)&\,\tilde{x}(Te^{i\theta})\frac{1}{T^2e^{2i\theta}}\Big(\frac{\partial^2}{\partial \theta^2}-i\frac{\partial}{\partial \theta}\Big)\tilde{x}(Te^{i\theta})\\
&=- \int\_bdz\,\tilde{x}(z)\Big(-\frac{d^2}{dz^2}\Big)\tilde{x}(z)\Big|\_{z=Te^{i\theta}}\\
&=- \sum\_{n,m\neq0}\Big(\frac{n\pi}{T}\Big)^2a\_na\_m\int\_bdz\,\psi\_n(z)\psi\_m(z)\Big|\_{z=Te^{i\theta}},
\end{aligned}
\end{equation}
where we made use of the analytically-continued basis expansion of $\tilde{x}(z)$. We have an explicit expression for the integral along the $b$ contour:
\begin{equation}
\begin{aligned}
\int\_bdz\,\psi\_n(z)\psi\_m(z)\Big|\_{z=Te^{i\theta}}&=2i\int\_0^{-\pi/2}d\theta \,e^{i\theta}\sin (n\pi e^{i\theta})\sin (m\pi e^{i\theta})\\
&=-\frac{2}{\pi}\frac{m\cosh m\pi \sinh n\pi-n\cosh n\pi \sinh m\pi}{(m-n)(m+n)}
\end{aligned}
\end{equation}
where we took into account that $m,n\in \mathbb{Z}$. It is worth emphasising that this result follows directly from the analytic continuation of $\tilde{x}(t)$ with the physical boundary conditions $\tilde{x}(0)=\tilde{x}(T)=0$. Notice now that the basis $\psi\_n(z)$ is no longer orthogonal (the inner product is no longer a simple Kronecker delta as it was above), and the presence of hyperbolic sines and cosines implies the sum over $n,m$ is not well defined. Of course, we can diagonalise it if we so please, but clearly this analytic continuation of $t$ is not making life easier. It is clear that the integral along the $\theta$ direction contributes non-trivially, and this follows directly and inevitably from the Cauchy-Riemann equations which links derivatives of holomorphic functions in different directions. Given $\partial\_t^m\psi\_n(t)$ do not generically vanish at $t=T$, the $\theta$ integral along the $b$ contour cannot vanish identically and will contribute non-trivially, as we have shown by direct computation. Notice furthermore, that in the path integral there is a factor of $i=\sqrt{-1}$ multiplying the action $I[x]$, so from the above explicit result it is clear the exponent associated to the $b$ contour *remains oscillatory*.
Finally, consider the action associated to the $c$ contour. From above:
\begin{equation}
\begin{aligned}
i\int\_{-T}^0d\beta\,&\tilde{x}(i\beta)\Big(-\frac{d^2}{d\beta^2}\Big)\tilde{x}(i\beta).
\end{aligned}
\end{equation}
In the path integral this contributes as:
$$
\exp -\frac{1}{\hbar}\int\_{-T}^0d\beta\,\tilde{x}(i\beta)\Big(-\frac{d^2}{d\beta^2}\Big)\tilde{x}(i\beta),
$$
so we seemingly might have succeeded in obtaining an exponential damping at least along the $c$ contour. What have we gained? To bring it to the desired form we shift the integration variable, $\beta\rightarrow \beta'=\beta+T$,
$$
\exp -\frac{1}{\hbar}\int\_0^Td\beta'\,\tilde{x}(i\beta'-iT)\Big(-\frac{d^2}{d{\beta'}^2}\Big)\tilde{x}(i\beta'-iT)
$$
This looks like it might have the desired form, but we must remember that the $\tilde{x}(i\beta)$ is already determined by the analytic continuation of $\tilde{x}(t)$, and as a consequence of this it is determined by the analytic continuation of the basis $\psi\_n(t)$. This basis along the $\beta$ axis is no longer periodic, so we have lost the good boundary conditions on $\tilde{x}(i\beta)$. In particular, although $\tilde{x}(0)=0$, we have $\tilde{x}(iT)\neq0$, so we can't even integrate by parts without picking up boundary contributions. One might try to redefine the path integral fields, $\tilde{x}(i\beta)\rightarrow \tilde{x}'(\beta)$, and then Fourier series expand $\tilde{x}'(\beta)$, but then we loose the connection with Cauchy's theorem.
I could go on, but I think a conclusion has already emerged: analytically continuing time in the integrand of the action is generically a bad idea (at least I can't see the point of it as things stand), and it is much more efficient to analytically continue the full field $\tilde{x}(t)$ as we did above. (Above we continued the $a\_n$ which is equivalent to continuing $\tilde{x}(t)$.) I'm not saying it's wrong, just that it is inefficient and one has to work a lot harder to make sense of it.
I want to emphasise one point: Gaussian integrals with oscillating exponentials are perfectly well-defined. There is no need to Wick rotate to imaginary time at any point of the calculation.
|
63,419,309 |
MISRA c++:2008 was published in 2008. It was written for C++03.
Does this refer to just the syntax of C++2003 standard or do have to use the compiler as well.
We have written our code base in VS2017 and we only have available for the Language Standard:
* ISO C++14 Standard
* ISO C++17 Standard
* ISO C++ Latest Draft Standard
There is no ISO C++03 for VS2017.
|
2020/08/14
|
[
"https://Stackoverflow.com/questions/63419309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767829/"
] |
It will be very hard to argue and say that you are MISRA-C++ compliant when not even compiling in C++03 mode. MISRA-C++ is a safe subset of C++03, so it bans a lot of things from that standard. If you run off and compile for C++11 or later, all bets are off.
Visual Studio is not suitable for the kind of mission-critical applications that MISRA was designed for. Nor is C++11 or later. I'd avoid C++ entirely for such applications, even though it is theoretically possible to write safe C++ programs, if you have lots of knowledge about what machine code the compiler generates.
|
969,986 |
Okay, this is an example from *Challenge and Trill of Pre-college Mathematics* by Krishnamurthy et al.
>
> In how many ways can we form a committee of three from a group of 10 men and 8 women, so that our committee consists of at least one woman?
>
>
>
I know howit usualy goes: let the answer be *$N$*. The number of committees with no restrictions is $18\choose 3$, and we subtract the number of committees with no women from it, giving
$$N = {{18}\choose{3}} - {{10}\choose{3}} = 816 - 120 = 696$$
However, why is this wrong?
We must choose at least *one* woman, which we can do in $8$ ways. We have to choose two more members, which we can then do in ${17\choose 2}$ ways. Hence
$$N = 8\times {17\choose 2} = 1088 \color{red}{\ne 696} $$
Where's the mistake hiding?
|
2014/10/12
|
[
"https://math.stackexchange.com/questions/969986",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/42814/"
] |
Your first way is absolutely correct, and the easiest way to do it.
Another, more cumbersome, way, is to consider cases:
1. exactly one woman: ${8 \choose 1}{10 \choose 2} = 8 \times 45 = 360$ ways.
2. exactly two women: ${8 \choose 2}{10 \choose 1} = 28 \times 10 = 280$ ways.
3. exactly three women: ${8 \choose 3} = 56$ ways.
All in all: $360+280+56 = 696$ ways, confirming your own way.
The second way you propose does double counting (which seems logical, as it's more). Namely, whenever there are two or more women in the committtee. If there are, say, exactly two women in the committee, A and B, you can pick A first as one of the 8, and then B as one of the remaining 17. **Or** you can pick B first as one of the eight, and A as one of the 17. So you count that committee twice. For comittees with 3 women, you count them thrice, depending on which one is chosen as one of the 8. If there is one woman only there is no double counting. So you count $360 + 2\times 280 + 3 \times 56 = 1088$..
|
126,659 |
The $10$ generators of the Poincare group $P(1;3)$ are $M^{\mu\nu}$ and $P^\mu$. These generators can be determined explicitly in the matrix form. However, I have found that $M^{\mu\nu}$ and $P^\mu$ are often written in terms of position $x^\mu$ and momentum $p^\mu$ as
$$ M^{\mu\nu} = x^\mu p^\nu - x^\nu p^\mu $$
and
$$ P^\mu = p^\mu$$
How do we get these relations?
|
2014/07/15
|
[
"https://physics.stackexchange.com/questions/126659",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/21270/"
] |
One obtains those expressions by considering a particular action of the Poincare group on fields.
Consider, for example, a single real scalar field $\phi:\mathbb R^{3,1}\to\mathbb R$. Let $\mathcal F$ denote the space of such fields. Define an action $\rho\_\mathcal F$ of $P(3,1)$ acting on $\mathcal F$ as follows
\begin{align}
\rho\_\mathcal F(\Lambda,a)(\phi)(x) = \phi(\Lambda^{-1} (x-a))
\end{align}
Sometimes people will write this as $\phi'(x) = \phi(\Lambda^{-1} x)$ for brevity. Now let $G$ denote a generator of the Lie algebra of the Poincare group (namely an element of a chosen basis for this Lie algebra). We can use this generator to define a corresponding infinitesimal generator for group action $\rho\_\mathcal F$ as follows:
\begin{align}
G\_\mathcal F(\phi) = i\frac{\partial}{\partial\epsilon}\rho\_\mathcal F(e^{-i\epsilon G})(\phi)\bigg|\_{\epsilon = 0}
\end{align}
**Example - translations.** Consider the translation generators $P^\mu$ which have the property
\begin{align}
e^{-ia\_\mu P^\mu}x = x+a
\end{align}
The generator of $\rho\_\mathcal F$ corresponding to $P^0$, for instance, is
\begin{align}
(P^0)\_\mathcal F(\phi)(x)
&= i\frac{\partial}{\partial\epsilon}\rho\_\mathcal F(e^{-i\epsilon P^0})(\phi)\bigg|\_{\epsilon = 0} \\
&= i\frac{\partial}{\partial\epsilon}\phi(x + \epsilon e\_0)\bigg|\_{\epsilon = 0} \\
&= i\partial^0\phi(x)
\end{align}
where $e\_0 = (1,0,0,0)$, and similarly for the other $P^\mu$, which gives
\begin{align}
(P^\mu)\_\mathcal F = i\partial^\mu.
\end{align}
**Example - Lorentz boosts.**
If you use this same procedure for Lorentz boost generators, you will find that
\begin{align}
(M^{\mu\nu})\_\mathcal F = i(x^\mu\partial^\nu - x^\nu\partial^\mu) = x^\mu p^\nu - x^\nu p^\mu
\end{align}
**Disclaimer about signs etc.** There are a lot of conventional factors of $i$ and negative signs floating around which I wasn't super careful to keep track of, if you notice an error in this regard, please let me know and I'll fix it.
|
43,242,076 |
I am quite new to MySQL. I have data in more than 2000 text files that I need to import into a table. I have created the table as follow:
```
CREATE TABLE test1
(
Month TINYINT UNSIGNED,
Day TINYINT UNSIGNED,
Year TINYINT UNSIGNED,
Weight FLOAT UNSIGNED,
length FLOAT UNSIGNED,
Site_Number CHAR(3),
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
);
```
All data in my text files are comma separated. Each file contains thousands of rows and each row include month, day, year, weight and length information. The site\_number is the first three numbers of the file name. For example, if the file name is A308102316.txt, the site\_number of all the records imported from this file will be 308. Also, I want the ID to be auto increment.
My question is: how can I achieve what I described above using MySQL command line client as I know nothing about PHP or other. I know how to import one text file into the table, but don't know how to write a loop to read many of them. Also, not know how to get site\_number from the file name.
Thank you for any help that you can provide.
|
2017/04/05
|
[
"https://Stackoverflow.com/questions/43242076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7821588/"
] |
Pattern match is performed linearly as it appears in the sources, so, this line:
```
case Row(t1: Seq[String], t2: Seq[String]) => Some((t1 zip t2).toMap)
```
Which doesn't have any restrictions on the values of t1 and t2 never matter match with the null value.
Effectively, put the null check before and it should work.
|
26,137,413 |
I have an old website, and I would like to add a glyphicons to a page of this site.
I cannot install bootstrap (link bootstrap.js and bootstrap.css to this page) because it will change all styled elements on the page.
Is there a way to add only "glyphicons functionality"?
|
2014/10/01
|
[
"https://Stackoverflow.com/questions/26137413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1049569/"
] |
You can build your bootstrap to components, which you need, on
<http://getbootstrap.com/customize/>
For example for **only glyphicon**, you can check only glyphicon checkbox and download.
Direct url for this setting is
**<http://getbootstrap.com/customize/?id=428c81f3f639eb0564a5>**
Scroll down and download it.
You download only two folders with css for glyphicon (bootstrap.min.css) and fonts files (in all only 170 Kb).
|
50,027,919 |
I can trigger my AWS pipeline from jenkins but I don't want to create buildspec.yaml and instead use the pipeline script which already works for jenkins.
|
2018/04/25
|
[
"https://Stackoverflow.com/questions/50027919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7372933/"
] |
In order to user Codebuild you need to provide the Codebuild project with a buildspec.yaml file along with your source code or incorporate the commands into the actual project.
However, I think you are interested in having the creation of the buildspec.yaml file done within the Jenkins pipeline.
Below is a snippet of a stage within a Jenkinsfile, it creates a build spec file for building docker images and then sends the contents of the workspace to a codebuild project. This uses the plugin for Codebuild.
```
stage('Build - Non Prod'){
String nonProductionBuildSpec = """
version: 0.1
phases:
pre_build:
commands:
- \$(aws ecr get-login --registry-ids <number> --region us-east-1)
build:
commands:
- docker build -t ces-sample-docker .
- docker tag $NAME:$TAG <account-number>.dkr.ecr.us-east-1.amazonaws.com/$NAME:$TAG
post_build:
commands:
- docker push <account-number>.dkr.ecr.us-east-1.amazonaws.com/$NAME:$TAG
""".replace("\t"," ")
writeFile file: 'buildspec.yml', text: nonProductionBuildSpec
//Send checked out files to AWS
awsCodeBuild projectName: "<codebuild-projectname>",region: "us-east-1", sourceControlType: "jenkins"
}
```
I hope this gives you an idea of whats possible.
Good luck!
Patrick
|
22,820,666 |
I have a string like this and I want to convert it to DateTime format(MM/dd/yyyyTHH:mm:ss).
but it fails, Please let me know where I'm wrong.
```
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
string stime = "4/17/2014T12:00:00";
DateTime dt = DateTime.ParseExact(stime, "MM/dd/yyyyTHH:mm:ss", CultureInfo.InvariantCulture);
```
This is the code, how I'm setting this string:
```
string startHH = DropDownList1.SelectedItem.Text;
string startMM = DropDownList2.SelectedItem.Text;
string startSS = DropDownList3.SelectedItem.Text;
string starttime = startHH + ":" + startMM + ":" + startSS;
string stime = StartDateTextBox.Text + "T" + starttime;
```
Getting this exception
```
String was not recognized as a valid DateTime.
```
|
2014/04/02
|
[
"https://Stackoverflow.com/questions/22820666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475314/"
] |
You wrote `MM` in your format string, which means that you need a two digit month. If you want a one digit month, just use `M`.
```
DateTime dt = DateTime.ParseExact(stime, "M/dd/yyyyTHH:mm:ss", CultureInfo.InvariantCulture);
```
The other solution is to change your string to match your format.
```
string stime = "04/17/2014T12:00:00";
DateTime dt = DateTime.ParseExact(stime, "MM/dd/yyyyTHH:mm:ss", CultureInfo.InvariantCulture);
```
The key to this is remembering you're doing [parse *exact*.](http://msdn.microsoft.com/en-us/library/ms131038%28v=vs.110%29.aspx) Therefore, you must exactly match your string with your format.
|
8,256,104 |
I have a sliding section set up as below. I was wondering if I can somehow add `easeIn` and `easeOut` when the slide goes up and down.
```
$('a#slide-up').click(function () {
$('.slide-container').slideUp(400, function(){
$('#slide-toggle').removeClass('active');
});
return false;
});
$('a#slide-toggle').click(function(e) {
e.preventDefault();
var slideToggle = this;
if ($('.slide-container').is(':visible')) {
$('.slide-container').slideUp(400,function() {
$(slideToggle).removeClass('active');
});
}
else {
$('.slide-container').slideDown(400);
$(slideToggle).addClass('active');
}
});
```
|
2011/11/24
|
[
"https://Stackoverflow.com/questions/8256104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/893654/"
] |
You can. Please check the documentation of [slideDown](http://api.jquery.com/slideDown/) at jQuery docs;.
By default jQUery implements only linear and swing easing functions. For additional easing functions you have to user jQUery UI
---
UPDATE:
Acoording to the doc, the second optional argument is a string indicating the name of the easing function.
So,
```
$('.slide-container').slideUp(400, function(){
$('#slide-toggle').removeClass('active');
});
```
will become
```
$('.slide-container').slideUp(400,'linear', function(){
$('#slide-toggle').removeClass('active');
});
```
to use linear easing function.
Similarly , for other easing functions also.
|
41,099 |
I have a tentative understanding of modal logic. Can anyone explain modal logic as it is used in computer science?
|
2015/04/07
|
[
"https://cs.stackexchange.com/questions/41099",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/30383/"
] |
I think you can find many good examples if you search a bit online. Some very-easy-to-find examples are in the following list:
From [Stanford Encyclopedia](http://plato.stanford.edu/entries/logic-modal/)
>
> In computer science, labeled transition systems (LTSs) are commonly used to represent possible computation pathways during execution of a program.
>
>
>
Wikipedia has some examples in its article [modal logic](http://en.wikipedia.org/wiki/Modal_logic):
>
> Versions of temporal logic can be used in computer science to model computer operations and prove theorems about them. In one version, ◇P means "at a future time in the computation it is possible that the computer state will be such that P is true"; □P means "at all future times in the computation P will be true". In another version, ◇P means "at the immediate next state of the computation, P might be true"; □P means "at the immediate next state of the computation, P will be true".
>
>
>
Also, if you go to [Logic in Action](http://www.logicinaction.org/), you will find several examples, e.g.:
>
> [Chapter 6] introduces dynamic logic, a system that was introduced in computer science for reasoning about the behaviour of computer programs, by Vaughan Pratt and others, in the 1970s.
>
>
> In [Chapter 10] it is explained how predicate logic can be used for programming. The chapter gives an introduction to concepts used in automating logical theorem proving. This leads to computational tools underlying the well known logic programming language Prolog, popular in AI an in computational linguistics. The inferential mechanism behind Prolog is called SLD-resolution. This is the reasoning engine for a natural fragment of predicate logic (the so-called Horn-fragment).
>
>
>
|
30,332,197 |
I am working with learning SQL, I have taken the basics course on pluralsight, and now I am using MySQL through Treehouse, with dummy databases they've set up, through the MySQL server. Once my training is complete I will be using SQLServer daily at work.
I ran into a two-part challenge yesterday that I had some trouble with.
The first question in the challenge was:
>
> "We have a 'movies' table with a 'title' and 'genre\_id' column and a
> 'genres' table which has an 'id' and 'name' column. Use an INNER JOIN
> to join the 'movies' and 'genres' tables together only selecting the
> movie 'title' first and the genre 'name' second."
>
>
>
Understanding how to properly set up JOINS has been a little confusing for me, because the concepts seem simple but like in cooking, execution is everything ---and I'm doing it wrong. I *was* able to figure this one out after some trial and error, work, and rewatching the Treehouse explanation a few times; here is how I solved the first question, with a Treehouse-accepted answer:
```
SELECT movies.title, genres.name FROM movies INNER JOIN genres ON movies.genre_id = genres.id;
```
--BUT--
The next question of the challenge I have not been so successful with, and I'm not sure where I'm going wrong. I would really like to get better with JOINS, and picking the brains of all you smartypantses is the best way I can think of to get an explanation for this specific (and I'm sure, pitifully simple for you guys) problem. Thanks for your help, here's where I'm stumped:
>
> "Like before, bring back the movie 'title' and genre 'name' but use
> the correct OUTER JOIN to bring back all movies, regardless of whether
> the 'genre\_id' is set or not."
>
>
>
This is the closest (?) solution that I've come up with, but I'm clearly doing something (maybe a lot) wrong here:
```
SELECT movies.title, genres.name FROM movies LEFT OUTER JOIN genres ON genres.id;
```
I had initially tried this (below) but when it didn't work, I decided to cut out the last portion of the statement, since it's mentioned in the requirement criteria that I need a dataset that doesn't care if genre\_id is set in the movies table or not:
```
SELECT movies.title, genres.name FROM movies LEFT OUTER JOIN genres ON movies.genre_id = genres.id;
```
I know this is **total** noob stuff, but like I said, I'm learning, and the questions I researched on Stack and on the Internet at large were not necessarily geared for the same problem. I am *very* grateful to have your expertise and help to draw on. Thank you for taking the time to read this and help out if you choose to do so!
|
2015/05/19
|
[
"https://Stackoverflow.com/questions/30332197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4611445/"
] |
Remove `float:left` from `.menu` and `.menu a` and just add
```
margin: 0 auto;
```
to `.menu` to make the links centered.
Also, change your `display` from `block` to `inline-block` for `.menu a`
Remember to give a width for `.menu`. I just tried a width of `61%` via Inspect Element and it got right.
**OR**
Add
```
text-align: center;
```
to `.menu`
and change your `display` from `block` to `inline-block` for `.menu a`.
**No need for specifying width for `.menu` in this method.** May be the easiest solution.
|
48,185,675 |
I´ve been searching for a solution to create a dropdownlist in ColumnC (with start from row 2) if there is value in ColumnA same row.
But all I was able to find is how to create one dropdownlist using VBA.
```
Sub DVraschwab()
Dim myList$, i%
myList = ""
For i = 1 To 7
myList = myList & "ListItem" & i & ","
Next i
myList = Mid(myList, 1, Len(myList) - 1)
With Range("A5").Validation
.Delete
.Add _
Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, _
Formula1:=myList
End With
End Sub
```
Is this possible? And how should I begin?
The dropdownlist should contain "Yes" and "No" and No would be standard.
This is code that execute when I have written anythins in A Col:
```
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Me.Range("A:A")) Is Nothing Then Exit Sub
Application.EnableEvents = False 'to prevent endless loop
On Error GoTo Finalize 'to re-enable the events
For Each columnAcell In Target.Cells
columnAcell.Offset(0, 3) = Mid(columnAcell, 2, 3)
If IsEmpty(columnAcell.Value) Then columnAcell.Offset(0, 4).ClearContents
Next
Application.ScreenUpdating = False
Dim w1 As Worksheet, w2 As Worksheet
Dim c As Range, FR As Variant
Set w1 = Workbooks("Excel VBA Test.xlsm").Worksheets("AP_Input")
Set w2 = Workbooks("Excel VBA Test.xlsm").Worksheets("Datakom")
For Each c In w1.Range("D2", w1.Range("D" & Rows.Count).End(xlUp))
FR = Application.Match(c, w2.Columns("A"), 0)
If IsNumeric(FR) Then c.Offset(, 1).Value = w2.Range("B" & FR).Value
Next c
Call Modul1.DVraschwab
If Target.Column = 1 Then
If Target.Value = vbNullString Then
Target.Offset(, 2).Clear
End If
End If
Finalize:
Application.EnableEvents = True
End Sub
```
The module I call is the dropdown you helped me with:
```
Sub DVraschwab()
Dim myList As String, r As Range
myList = "Yes,No"
For Each r In Range("A2", Range("A" & Rows.Count).End(xlUp))
If r.Value <> vbNullString Then
With r.Offset(, 2).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Formula1:=myList
End With
r.Offset(, 2).Value = Split(myList, ",")(1)
End If
Next r
End Sub
```
|
2018/01/10
|
[
"https://Stackoverflow.com/questions/48185675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7888468/"
] |
Do you mean like this? You basically just need a loop added to your code to check column A.
```
Sub DVraschwab()
Dim myList As String, r As Range
myList = "Yes,No"
For Each r In Range("A2", Range("A" & Rows.Count).End(xlUp))
If r.Value <> vbNullString Then
With r.Offset(, 2).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Formula1:=myList
End With
r.Offset(, 2).Value = Split(myList, ",")(1)
End If
Next r
End Sub
'this in the relevant sheet module
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 1 and target.row>1 Then
If Target.Value = vbNullString Then
Target.Offset(, 2).Clear
End If
End If
End Sub
```
|
7,811,268 |
I have recently started going through sound card drivers in Linux[ALSA].
Can a link or reference be suggested where I can get good basics of Audio like :
Sampling rate,bit size etc.
I want to know exactly how samples are stored in Audio files on a computer and reverse of this which is how samples(numbers) are played back.
|
2011/10/18
|
[
"https://Stackoverflow.com/questions/7811268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/993969/"
] |
The [Audacity](http://audacity.sourceforge.net/) [tutorial](http://audacity.sourceforge.net/manual-1.2/tutorial_basics_1.html) is a good place to start. Another [introduction](http://www.pgmusic.com/tutorial_digitalaudio.htm) that covers similar ground. The [PureData](http://puredata.info/) [tutorial at flossmanuals](http://en.flossmanuals.net/pure-data/ch003_what-is-digital-audio/) is also a good starting point. [Wikipedia](http://en.wikipedia.org/wiki/Digital_audio) is a good source once you have the basics down.
Audio is input into a computer via an [analog-to-digital](http://en.wikipedia.org/wiki/Analog-to-digital_converter) converter (ADC). Digital audio is output via a [digital-to-analog](http://en.wikipedia.org/wiki/Digital-to-analog_converter) converter (DAC).
Sample rate is the number of times per second at which the analog signal is measured and stored digitally. You can think of the sample rate as the time resolution of an audio signal. Bit size is the number of bits used to store each sample. You can think of it as analogous to the color depth of an image pixel.
[David Cottle's](http://www.music.utah.edu/faculty/faculty_a-z/david_michael_cottle) [SuperCollider](http://supercollider.sourceforge.net/) book also has a [great introduction](http://supercolliderbook.net/) to digital audio.
|
3,800,925 |
What are some of the better libraries for image generation in Python? If I were to implement a GOTCHA (for example's sake), thereby having to manipulate an image on the pixel level, what would my options be? Ideally I would like to save resulting image as a low-resolution jpeg, but this is mere wishing, I'll settle for any common image format.
Thank you for your attention.
|
2010/09/27
|
[
"https://Stackoverflow.com/questions/3800925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181165/"
] |
The Python Imaging Library (PIL) is the *de facto* image manipulation library on Python. You can find it [here](http://www.pythonware.com/products/pil/), or through **easy\_install** or **pip** if you have them.
Edit: PIL has not been updated in a while, but it has been forked and maintained under the name **[pillow](http://pillow.readthedocs.io/)**. Just install it this way in a shell:
```
pip install Pillow
```
The `import` statements are still the same as PIL (e.g., `from PIL import image`) and is backward compatible.
|
3,013,831 |
I have an existing database design that stores Job Vacancies.
The "Vacancy" table has a number of fixed fields across all clients, such as "Title", "Description", "Salary range".
There is an EAV design for "Custom" fields that the Clients can setup themselves, such as, "Manager Name", "Working Hours". The field names are stored in a "ClientText" table and the data stored in a "VacancyClientText" table with VacancyId, ClientTextId and Value.
Lastly there is a many to many EAV design for custom tagging / categorising the vacancies with things such as Locations/Offices the vacancy is in, a list of skills required. This is stored as a "ClientCategory" table listing the types of tag, "Locations, Skills", a "ClientCategoryItem" table listing the valid values for each Category, e.g., "London,Paris,New York,Rome", "C#,VB,PHP,Python". Finally there is a "VacancyClientCategoryItem" table with VacancyId and ClientCategoryItemId for each of the selected items for the vacancy.
There are no limits to the number of custom fields or custom categories that the client can add.
---
I am now designing a new system that is very similar to the existing system, however, I have the ability to restrict the number of custom fields a Client can have and it's being built from scratch so I have no legacy issues to deal with.
For the Custom Fields my solution is simple, I have 5 additional columns on the Vacancy Table called CustomField1-5. This removes one of the EAV designs.
It is with the tagging / categorising design that I am struggling. If I limit a client to having 5 categories / types of tag. Should I create 5 tables listing the possible values "CustomCategoryItems1-5" and then an additional 5 many to many tables "VacancyCustomCategoryItem1-5"
This would result in 10 tables performing the same storage as the three tables in the existing system.
Also, should (heaven forbid) the requirements change in that I need 6 custom categories rather than 5 then this will result in a lot of code change.
---
Therefore, can anyone suggest any DB Design Patterns that would be more suitable to storing such data. I'm happy to stick with the EAV approach, however, the existing system has come across all the usual performance issues and complex queries associated with such a design.
Any advice / suggestions are much appreciated.
The DBMS system used is SQL Server 2005, however, 2008 is an option if required for any particular pattern.
|
2010/06/10
|
[
"https://Stackoverflow.com/questions/3013831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40655/"
] |
Have you thought about using an XML column? You can enforce all your constraints declaratively through XSL.
Instead of EAV, have a single column with XML data validated by a schema (or a collection of schemas).
|
87,929 |
I'm reading a paper on jet engines that repeatedly mentions the stagnation pressure and temperature. What does this mean? Is it the point where the jet engine stalls in performance/efficiency/thrust, etc?
I'm a bit confused. 99% of the information on stagnation pressure is the static pressure, or the about stagnation point, or pressure where fluid velocity is zero.
|
2021/06/25
|
[
"https://aviation.stackexchange.com/questions/87929",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/44452/"
] |
[](https://i.stack.imgur.com/RtPh1.png)[Image source](https://www.researchgate.net/figure/Smoke-visualisation-and-flow-topology-of-the-airflow-around-a-cylinder_fig7_260045652)
Stagnation pressure is used as a synonym for total pressure. An object in airflow experiences pressure from the flow = dynamic pressure, indeed for incompressible flow proportional to the velocity squared.
In the pic above, on the right hand side, is an indication of the Stagnation Point. This is where the air streaming in does not flow around the cylinder but is stopped by the body contour. The flow stagnates, and all inflowing dynamic air pressure is converted into static pressure at this point.
Which is called the stagnation pressure.
|
25,688,287 |
How can I execute a calculation in python (2.7) and capture the output in the variable 'results'?
**Input:**
```
let calculation = '(3*15)/5'
let formatting = '\\%2d'
let grouping = '0'
exe "python -c \"import math, locale; locale.format(formatting, calculation, grouping)\""
```
and capture the output in a variable `results`
**Output:**
results = '9'
ps:
Is there also a possibility in python to wrap the first part of my calculation, something like the eval() function in vim?
p.e.
```
let command = 'python -c \"import math, locale\"'
exe "eval(command); locale.format(formatting, calculation, grouping)"
```
|
2014/09/05
|
[
"https://Stackoverflow.com/questions/25688287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/662967/"
] |
Hmm… `:let foo = (3*15)/15`.
Anyway, you can capture the output of an external command with `:let foo = system('mycommand')`:
```
:let foo = system("python -c 'print (15*3)/5'")
```
It's up to you to put the string together.
|
59,287,801 |
need help
I have a task count of 250.
I want all these tasks to be done via a fixed no of threads. ex 10
so, I want to feed each thread one task
```
t1 =1
t2=2
.
.
.
```
currently I have written the code in such a way that, among those 10 threads each thread picks one task.
and I will wait till all the 10 threads are done using the `thread.join()`.and then again create 10 threads and feed each thread one task.
### Problem:
Although some of the threads are finished performing the task. I need to still wait for other threads to complete.
I want to maintain the thread count as 10 through . That is if among 10 threads if one thread finished the task, it can pick another task and similarly others.
any solution?
### my Code:
```java
for(int i=0;i<finData.size();i++){
ArrayList<Thread> AllThreads = new ArrayList<>();
if(i+10 <= finData.size()){
p=i+10;
}else{
p=i+10-finData.size();
}
for(int k=i;k<p;k++){
FeeConfigCheck = new Thread(new FeeConfigCheck(finData.get(k)));
AllThreads.add(FeeConfigCheck);
FeeConfigCheck.start();
Thread.sleep(100);
}
for(int h=0;h<AllThreads.size();h++){
AllThreads.get(h).join();
}
if(p<10){
System.out.println("Pointer----------------"+i);
break;
}
i=p;
System.out.println("Pointer----------------"+i);
}
```
|
2019/12/11
|
[
"https://Stackoverflow.com/questions/59287801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12518808/"
] |
You're reinventing the wheel; this is not neccessary. Java already contains functionality to have a fixed number of threads plus a number of tasks, and then having this fixed number of threads process all the tasks: [Executors](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/concurrent/Executors.html)
```
ExecutorService pool = Executors.newFixedThreadPool(10);
for (int k = i; k < p; k++) {
Runnable r = new FooConfigCheck(finData.get(k));
pool.submit(r);
}
pool.shutdown();
while (!pool.awaitTermination(1000, TimeUnit.SECONDS)) ;
```
That's all you have to do here.
See the javadoc of these classes for the various things you can ask it; how many tasks are in the queue is something you can ask, if you need that information.
EDIT: Added a call to shutdown.
|
57,304,522 |
I got an upload file functionality in my application and this is working perfectly fine on `localhost`. However, when will run `firebase deploy` and the application is deployed I got the following error with lack of permissions.
Edit: I can deploy, there's no problem with the CLI, just on deployment it doesn't work as on `localhost`.
Tried:
* This answer: <https://stackoverflow.com/a/50298931/11127383>
* Enabling Blaze plan, thus billing too
* Test on both domains: xxx.web.app and xxx.firebaseapp.com
* Checked Google Cloud Platform Storage, it has exactly the same uploaded files from localhost as the Firebase Cloud Storage
HTML code
```
<mat-form-field>
<!-- Accept only files in the following format: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx. However, this is easy to bypass, Cloud Storage rules has been set up on the back-end side. -->
<ngx-mat-file-input
[accept]="[
'.doc',
'.docx',
'.jpg',
'.jpeg',
'.pdf',
'.png',
'.xls',
'.xlsx'
]"
(change)="uploadFile($event)"
formControlName="fileUploader"
multiple
aria-label="Here you can add additional files about your project, which can be helpeful for us."
placeholder="Additional files"
title="Additional files"
type="file"
>
</ngx-mat-file-input>
<mat-icon matSuffix>folder</mat-icon>
<mat-hint
>Accepted formats: DOC, DOCX, JPG, JPEG, PDF, PNG, XLS and XLSX,
maximum files upload size: 20 MB.
</mat-hint>
<mat-error
*ngIf="contactForm.get('fileUploader')!.hasError('maxContentSize')"
>
This size is too large,
<strong
>maximum acceptable upload size is
{{
contactForm.get('fileUploader')?.getError('maxContentSize')
.maxSize | byteFormat
}}</strong
>
(uploaded size:
{{
contactForm.get('fileUploader')?.getError('maxContentSize')
.actualSize | byteFormat
}}).
</mat-error>
</mat-form-field>
```
TypeScript (in Angular) code
```
/**
* @description Upload additional files to Cloud Firestore and get URL to the files.
* @param {event} - object of sent files.
* @returns {void}
*/
public uploadFile(event: any): void {
// Iterate through all uploaded files.
for (let i = 0; i < event.target.files.length; i++) {
const randomId = Math.random()
.toString(36)
.substring(2); // Create random ID, so the same file names can be uploaded to Cloud Firestore.
const file = event.target.files[i]; // Get each uploaded file.
// Get file reference.
const fileRef: AngularFireStorageReference = this.angularFireStorage.ref(
randomId
);
// Create upload task.
const task: AngularFireUploadTask = this.angularFireStorage.upload(
randomId,
file
);
// Upload file to Cloud Firestore.
task
.snapshotChanges()
.pipe(
finalize(() => {
fileRef.getDownloadURL().subscribe(downloadURL => {
this.angularFirestore
.collection('files')
.add({ downloadURL: downloadURL });
this.downloadURL.push(downloadURL);
});
}),
catchError((error: any) => {
return throwError(error);
})
)
.subscribe();
}
}
```
Storage rules
```
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read; // Required in order to send this as attachment.
// Allow write files Firebase Storage, only if:
// 1) File is no more than 20MB
// 2) Content type is in one of the following formats: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx.
allow write: if request.resource.size <= 20 * 1024 * 1024
&& (request.resource.contentType.matches('application/msword')
|| request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|| request.resource.contentType.matches('image/jpg')
|| request.resource.contentType.matches('image/jpeg')
|| request.resource.contentType.matches('application/pdf')
|| request.resource.contentType.matches('image/png')
|| request.resource.contentType.matches('application/vnd.ms-excel')
|| request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
}
}
}
```
|
2019/08/01
|
[
"https://Stackoverflow.com/questions/57304522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11127383/"
] |
Due to the message you're getting, your issue is related to [IAM roles in Firebase](https://firebase.google.com/docs/projects/iam/roles).
Here a [Quick overview](https://firebase.google.com/docs/projects/iam/overview) of those.
Check the Error message you are getting and make sure that the instance you're deploying or the service account you're using has the needed roles that let them do the action you want to do.
|
5,279,503 |
Looking for some help with my bash script. I am trying to write this shell script to do the following:
1. find files in a dir named:
`server1-date.done`
`server2-date.done`
`server3-date.done`
`...`
`server10-date.done`
2. print to a `listA`
3. find files in a dir (\*.gz) and print to a `listB`
4. if `listA` has a count of `10` (basically found 10 `.done` files), then
proceed with the moving the files in `listB` to its new directory
5. after moving the files from `listB`, then remove the old directory which is similarly named (`server1-date`, `server2-date`, ...) and the .done files.
So far, I have this in the works. I can't get the condition for the `if` section working. I don't think I coded that correctly. Any code suggestions, improvements, etc would be appreciated. Thanks.
```
#Directories
GZDIR=/mydumps/mytest
FINALDIR=/mydumps/mytest/final
FLGDIR=/backup/mytest/flags
export GZDIR FINALDIR FLGDIR
#lists
FLGLIST="/mydumps/mytest/lists/userflgs.lst"
GZLIST="/mydumps/mytest/lists/gzfiles.lst"
export FLGLIST GZLIST
#Find files
find $FLGDIR -name \*.done -print > $FLGLIST
find $GZDIR -name \*.gz -print > $GZLIST
#Get need all (10) flags found before we do the move
FLG_VAL =`cat $FLGLIST | wc -l`
export $FLG_VAL
if [ "$FLG_VAL" = "10" ]; then
for FILE in $GZLIST
do
echo "mv $GZLIST $FINALDIR" 2>&1
for FLAG in $FLGLIST
do
echo "rmdir -f $FLAG" 2>&1
done
done
else
echo "Cannot move file" 2>&1
exit 0
fi
```
|
2011/03/11
|
[
"https://Stackoverflow.com/questions/5279503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/374916/"
] |
I do not know if this will work, but it will fix all the obvious problems:
```
#!/bin/sh
#Directories
GZDIR=/mydumps/mytest
FINALDIR=/mydumps/mytest/final
FLGDIR=/backup/mytest/flags
export GZDIR FINALDIR FLGDIR
#lists
FLGLIST="/mydumps/mytest/lists/userflgs.lst"
GZLIST="/mydumps/mytest/lists/gzfiles.lst"
#Find files
find "$FLGDIR" -name '*.done' -print > "$FLGLIST"
find "$GZDIR" -name '*.gz' -print > "$GZLIST"
#Get need all (10) flags found before we do the move
FLG_VAL=$(wc -l <"$FLGLIST") # Always prefer $( ... ) to backticks.
if [ "$FLG_VAL" -ge 10 ]; then
for FILE in $(cat "$GZLIST")
do
echo "mv $FILE $FINALDIR" 2>&1
done
for FLAG in $(cat "$FLGLIST")
do
echo "rmdir -f $FLAG" 2>&1
done
else
echo "Cannot move file" 2>&1
exit 0
fi
```
|
16,781 |
I am trying to design a filter whose magnitude is the same as that of a given signal. The given signal is wind turbine noise, so it has significant low-frequency content. After designing the filter, I want to filter white Gaussian noise so as to create a model of wind turbine noise. The two signals, that is the original and the filtered noise should sound similar.
I am using arbitrary magnitude filter design in Matlab for that (FIR, Order: 900, Single rate, 1-band, response specified by amplitudes, Sample rate 44100 Hz, Design method: firls). The problem is that, although I design the filter using the values from the original signal's magnitude, the filter magnitude fails to follow the magnitude at higher frequencies. Could you please help me with that?
The idea is that I am using a polynomial curve, to fit the shape of the spectrum of the original sound. Then, I filter the magnitude of the generated noise, by multiplying the extracted polynomial curve with the generated noise magnitude. Finally, after calculating the new magnitude and phase, I get back to the time domain.
```
[x,fs] = audioread('cotton_0115-0145.wav'); % original noise sample
x = x(:,1); % extract one channel
x = x.';
N = length (x);
% fft of original signal
Y = fft(x,N)/N;
fy = (0:N-1)'*fs/N;
% half-bandwidth selection for original signal
mag = abs(Y(1:N/2));
fmag = fy(1:N/2);
% polynomial fitting
degreesOfFreedom=40;
tempMag=20*log10(mag)'; % desired magnitude in dB
tempFmag=fmag;
figure(1)
plot(tempFmag,tempMag,'b');
title('Spectrum of original signal-Polynomial fitting')
xlabel('Frequency (Hz)');
ylabel('20log10(abs(fft(x)))');
axis([tempFmag(1) tempFmag(end) min(tempMag) 0]);
hold on
p = [];
for i=1:4
p=polyfit(tempFmag,tempMag,degreesOfFreedom);
pmag=polyval(p,tempFmag);
plot(tempFmag,pmag,'r');
pause
above=pmag<tempMag;
abovemag=tempMag(above);
abovefmag=tempFmag(above);
tempMag=abovemag;
tempFmag=abovefmag;
end
hold on
legend('signal magnitude','polynomial');
%
loc1 = find(fmag == 0);
loc2 = find(fmag == 22050);
Nmag = length(mag);
M=((Nmag-1)*max(tempFmag))/(tempFmag(end)-tempFmag(1));
freqFinal=tempFmag(1):max(tempFmag)/M:max(tempFmag);
freqFinal=tempFmag(1):max(tempFmag)/length(mag):max(tempFmag);
magnitudesFinal=polyval(p,freqFinal);
figure(2)
plot(fmag,20*log10(mag)');
hold on;
plot(freqFinal,magnitudesFinal,'g');
title('Spectrum of original signal-Choice of polynomial curve')
xlabel('Frequency (Hz)');
ylabel('abs(fft(x))');
axis([freqFinal(1) freqFinal(end) min(magnitudesFinal) max(magnitudesFinal)]);
%%
% noise generation
Nn = N;
noise = wgn(1,Nn,0);
noise = noise/(max(abs(noise)));
Ynoise = fft(noise,Nn)/Nn;
fn = (0:Nn-1)'*fs/Nn;
% polynomial for whole f range
newmagA = 10.^(magnitudesFinal/20);
newmagB = fliplr(newmagA);
newmagB(end+1) = newmagB(end);
newmag = [newmagA newmagB];
%filtering
Ynoisenew = newmag .* Ynoise;
figure(3)
magnoise = 20*log10(abs(Ynoisenew(1:Nn/2)));
fnoise = fn(1:Nn/2);
plot(fnoise, magnoise);
% magnitude and phase of filtered noise
magn = abs(Ynoisenew);
phn = unwrap(angle(Ynoisenew));
% Back to Time domain
sig_new=real(ifft(magn.*exp(1i*phn)));
figure(4)
sig_new = sig_new / max(abs(sig_new));
plot(t, sig_new);
Ysignew = fft(sig_new,Nn)/Nn;
fn = (0:Nn-1)'*fs/Nn;
figure(5); plot(fn(1:Nn/2),20*log10(abs(Ysignew(1:Nn/2))));
```
|
2014/06/10
|
[
"https://dsp.stackexchange.com/questions/16781",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/10166/"
] |
if you are only interested in designing a signal representing the wind turbine noise, you could just generate it from your magnitude. E.g., with your magnitude $A$ over frequency $f$ you can generate a random phase $\phi$ for each frequency and over a time $t$ and then add all together. Here a small code for illustration (I tried to use your varibles. However you need to check orientation etc.):
```
phi = rand(size(fmag))*2*pi;
x = (mag*sin(2*pi*fmag*t+repmat(phi,1,N)));
```
Hope this helps.
|
33,554,536 |
I want to create a string array between From and To input.
like From = 2000 To = 2003
I want to create a string[] as below:
>
>
> ```
> string[] arrayYear = new string[]{"2000","2001","2002","2003"};
>
> ```
>
>
Is there any easy way of building it dynamically for any range of year?
Please suggest me.
|
2015/11/05
|
[
"https://Stackoverflow.com/questions/33554536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1893874/"
] |
You can use `Enumerable.Range`
```
int startYear = 2000, endYear = 2004;
string[] arrayYear = Enumerable.Range(startYear, endYear - startYear + 1).Select(i => i.ToString()).ToArray();
```
|
35,840 |
I am using Cucumber through IntelliJ and am working on fixing a broken test. I was wondering when debugging, is there a way to save the state of the system up to a certain step in the feature file, if they all pass. For example, take this exaggerated example below
```
Given I am a New User
And There is an Event on a certain date
When I log in
And Go to the Events page
And I select the Event
And I go to the Payments Page
And I attempt to pay with credit card
(cont)
```
In the example above, if I am checking why credit card payments were failing in the test, I'd have to rerun the test loads of times to get the system into the state I wanted it in (user, event created). Is there a way to save the state of the system once a step passes? So, therefore, running the test above and it failing on the last step, means that if I run it again it will restore the state of the system based on a snapshot of how it was after the last step and continue to run from the next step. Example...
```
Given I am a New User
(snapshot of the system with a new user is recorded)
And There is an Event on a certain date
(snapshot of the system with a new user and event is recorded)
When I log in
(snapshot of the system with a new user and event is recorded and the user is logged in)
```
I worked in a place that used an in-house test runner and they were able to do it, just wondering if this is a feature that is available?
|
2018/09/28
|
[
"https://sqa.stackexchange.com/questions/35840",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/29912/"
] |
Cucumber executes the step definitions glue that you provide it with, so it can't in any way control the state of your system. If you need to save snapshots of the system after each step, call a function that would do that for you at the end of every step.
|
45,767 |
Every now and then, I find myself reading papers/text talking about how *this* equation is a constraint but *that* equation is an equation of motion which satisfies *this* constraint.
For example, in the Hamiltonian formulation of Maxwell's theory, Gauss' law $\nabla\cdot\mathbf{E}=0$ is a constraint, whereas $\partial\_\mu F^{\mu\nu}=0$ is an equation of motion. But why then isn't $\partial\_\mu j^\mu=0$, the charge-conservation/continuity equation, called an equation of motion. Instead it is just a 'conservation law'.
Maybe first-order differentials aren't allowed to be equations of motion? Then what of the Dirac equation $(i\gamma^\mu\partial\_\mu-m)\psi=0$? This is a first-order differential, isn't it? Or perhaps when there is an $i$, all bets are off...
So, what counts as an equation of motion, and what doesn't?
How can I tell if I am looking at a constraint? or some conservation law?
|
2012/12/03
|
[
"https://physics.stackexchange.com/questions/45767",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/10456/"
] |
In general, a dynamical equation of motion or evolution equation is a (hyperbolic) second order in time differential equation. They determine the evolution of the system.
$\partial\_{\mu}F^{i\mu}$ is a dynamical equation.
However, a constraint is a condition that must be verified at *every* time and, in particular, the initial conditions have to verify the constraints. Since equations of motion are of order two in time, constraints have to be at most order one.
The Gauss law $\partial\_{\mu}F^{0\mu}$ is a constraint because it only involves a first derivative in time in configuration space, i.e., when $\bf E$ it is expressed in function of $A\_0$ and $\bf A$. Furthermore, the gauss law is the generator of gauge transformations. In the quantum theory, only states which are annihilated by the gauss law are physical states.
Both dynamical equations and constraints may be called equations of motion or Euler-Lagrange equations of a given action functional. Or, one may keep the term equation of motion for dynamical equations. It is a matter of semantic. The important distinction is between constraints and evolution equations.
Conservation laws follow mainly from symmetries and from Noether theorem. Often but not always, equations of motion follow from conservation laws. Whether one considerers one more fundamental is a matter of personal taste.
Dirac equation relates several components of a Dirac spinor. Each component verifies the Klein-Gordon equation which is an evolution equation of order two.
|
17,228 |
I'm working with the following op-amps:
LM308AN
LM358P
UA741CP
I want to make a small box that will control the power to any string of christmas lights based off of music that is playing. I would like it to pulse with the base. I want the input to be the signal from the headphone jack of my computer and I want the output to be something that would operate any light that could be plugged into a wall outlet (120VAC?).
|
2011/07/22
|
[
"https://electronics.stackexchange.com/questions/17228",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/5100/"
] |
Sometimes, simply stating what you're trying to accomplish is better than asking the question you *think* you want to ask. This could very well be the case here. So, indulge me as I try to restate your situation and provide some sort of answer.
You have a headphone jack with some music on it, and you want that music to control some lights. You probably want the lights to blink or pulse with the music. Right?
This type of device is called a [Light Organ](http://en.wikipedia.org/wiki/Light_organ). There are many forms of light organs, but I assure you that none of them use an op-amp driving a relay. There are several reasons for this:
1. Relays don't operate well from an audio signal. They really want a signal that stays on or off for a while and doesn't just oscillate like an audio signal does.
2. Relays can't dim a light. They can turn one on or off. Not so good at dimming.
3. Relays would make a lot of noise, chattering away with the music. Not a pleasant sound.
I would recommend that you Google for "Light Organ". When I did, I came up with 65 million pages. Some of them are selling completed units, some have kits, and some have schematics.
I hope that helps!
|
7,809,215 |
I have a project of business objects and a data layer that could potentially be implemented in multiple interfaces (web site, web services, console app, etc).
My question deals with how to properly implement caching in the methods dealing with data retrieval. I'll be using SqlCacheDependency to determine when the cached objects need to be expired, but I'm unsure of the best way of implementing the cache itself:
If the library is being used for a web project, I'd like to use HttpRuntime.Cache; however, I'm guessing that would be an issue for console apps.
What is the best way of implementing caching in your data layer for a .Net project when allowing for multiple types of interfaces like this?
|
2011/10/18
|
[
"https://Stackoverflow.com/questions/7809215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30006/"
] |
You can use "-sync y" on your qsub to cause the qsub to wait until the job(s) are finished.
|
161,751 |
I've created a custom user role and am attempting to change the users role from CUSTOMER to ADVOCATE on purchase of a particular product (using WooCommerce). I'm really close but struggling to get the correctly serialized data into my table:
```
$order = new WC_Order( $order_id );
$items = $order->get_items();
$new_role = 'Array([advocate] => 1)';
$data = serialize( $new_role );
if ( $product_id == '786' ) {
update_user_meta( $order->user_id, 'wp_capabilities', $data );
}
```
The correct table is being populated at the correct time but as
```
s:30:"s:22:"Array([advocate] => 1)";";
```
rather than what I need it to be which is
```
a:1:{s:8:"advocate";b:1;}
```
Where is my serialization tripping up?
|
2014/09/17
|
[
"https://wordpress.stackexchange.com/questions/161751",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45504/"
] |
I think you are not handling the array part correctly.
The right syntax is -
```
$new_role = array("advocate" => 1);
```
The syntax that you have used is shown when you print some array on your screen but it should be written in above format in your PHP code. Currently, you are capturing it as a string and not an array.
|
37,826,786 |
I need to create ordered lists for a specific type of genealogy report called a register. In a register, all children are numbered with lower-case Roman numerals, and those with descendants also get an Arabic numeral, like this:
```
First Generation
1. Joe Smith
2 i. Joe Smith Jr.
ii. Fred Smith
3 iii. Mary Smith
iv. Jane Smith
Second Generation
2. Joe Smith Jr.
i. Oscar Smith
4 ii. Amanda Smith
3. Mary Smith
5 i. Ann Evans
```
You can see my initial attempt on this fiddle: <https://jsfiddle.net/ericstoltz/gpqf0Ltu/>
The problem is that the Arabic numerals need to be consecutive from generation to generation, that is, over separate ordered lists. When you look at the fiddle, you can see the second generation begins again at 1 for Arabic numerals, but it should begin with 2 because that's the number assigned to that person as the child of 1, and the first of 2's children with descendants should be 4 instead of 5. So the counter is continuing on to the second list in some partial way when I need it to be more consistent.
To clarify: this is not just about sequential numbering. Each person with descendants is identified by a unique number, and that number will appear twice: With that person as a child and with that person as a parent.
The generations need to be separated because of the headings and sometimes there is narrative between them.
I feel I am very close and am just overlooking something to get this to work!
UPDATE: SOLVED. See fiddle for how I did this with two counters.
|
2016/06/15
|
[
"https://Stackoverflow.com/questions/37826786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5559646/"
] |
The problem in that query is the semicolon, which is the default query delimiter.
In order to change the delimiter in HeidiSQL, add the DELIMITER client command above the `CREATE PROCEDURE` query:
```
DELIMITER \\
SELECT 1\\
CREATE PROCEDURE ...\\
DELIMITER ;
```
HeidiSQL also has a procedure designer, with no need to set the delimiter:
[](https://i.stack.imgur.com/FCwFm.png)
|
3,151,938 |
I want to create a site using a cms, but I want to use my own look and feel. I want to be able to upload downloadable content such as mp3 files with a flash player. I also want users to sign up and login. I want to be able to track and log downloads and uploads done by users. Any suggestions?
|
2010/06/30
|
[
"https://Stackoverflow.com/questions/3151938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/220007/"
] |
There are dozens of different CMS systems and each works slightly different and is geared for a specific use case. Some of the most popular PHP CMS systems are:
[Drupal](http://drupal.org) - One of my favorites. Very powerful and extensible but a large learning curve and for most projects it can be overkill.
[Joomla](http://www.joomla.org/) - Similar to drupal. Easier to use for sure but a little less powerful. For most projects it can be overkill.
[Wordpress](http://wordpress.org) - The premier PHP blog engine. Designed for blogging but can handle most any site type. Very easy to use but you sacrifice some extensibility.
All of these CMS systems have very popular and well documented theme engines and active development communities. I think a choice of CMS has more to do with how you want to use your site rather than your technical needs because at this point there is a large amount of feature parity ( no flaming on this, I know in some cases this is not true but for most mainstream needs they all offer similar features in third-party modules if not built in). For your specific needs you mentioned any of these will probably work. Download them all and try them out. Why not? They're free.
For a full list of PHP CMS try [Wikipedia](http://en.wikipedia.org/wiki/List_of_content_management_systems#PHP_2)
|
5,476,647 |
I'm running into a problem submitting my application through the Application Loader. I'm receiving the message "This bundle is invalid. Apple is not currently accepting applications built with this version of the SDK."
I've installed Xcode 4.0.1 w/SDK 4.3 ("4A1006", March 24), and I've reinstalled both MonoDevelop and MonoTouch. I've also made sure my build/bundle settings are using SDK 4.3, and I've tried each of the min versions of 4.0, 4.1, 4.2, and 4.3.
Suggestions?
Update: I've uninstalled Xcode 4 (rebooted), installed latest Xcode 3 same w/SDK (rebooted), and reinstalled MonoDevelop & MonoTouch. Still no luck unfortunately. I tried with and without manually specifying DTXcode:0400.
I've been reinstalling MonoTouch by re-running the installer. Is there a way to do a clean uninstall of MT and could that help in this case?
|
2011/03/29
|
[
"https://Stackoverflow.com/questions/5476647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29152/"
] |
Apple changed the keys required in the application manifest in iOS SDK 4.3.1. We've released a new MonoDevelop build to track this.
|
74,640,272 |
I am at the verge of loosing my mind over trying to fix an Email Regex i built:
It is almost perfect for what i need. It works in 99.9% of all cases.
But there is one case which causes a catastrophic backtracking error and i cannot fix my regex for it.
The "Email" causing a catastrophic backtrack error:
`[email protected]@tester.co.ro`
Yes, such emails do occur in the application i need this Regex for.
People enter multiple Emails in one field for some reason. I have no answer for why this occurs.
I need the Help of Wizards of Stack Overflow.
My Email Regex might block or not block some officially valid Emails but that is not the point here.
All i want is to fix the catastrophic backtracking Problem of my Regex. I do not want to change what it blocks or not. It works for what i need it to do.
Here is my Email Regex:
`^[^\W_]+\w*(?:[.-]\w*)*[^\W_]+@[^\W_]+(?:[.-]?\w*[^\W_]+)*(?:\.[^\W_]{2,})$`
How can i make this Regex fail quickly so it doesn't cause a catastrophic backtracking error.
Thank You very much.
|
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3564869/"
] |
You can use
```none
^(?!_)\w+(?:[.-]\w+)*(?<!_)@[^\W_]+(?>[.-]?\w*[^\W_])*\.[^\W_]{2,}$
```
See the [regex demo](https://regex101.com/r/kJdWYO/5).
The main idea is introducing an [atomic group](https://www.regular-expressions.info/atomic.html), `(?>[.-]?\w*[^\W_])*` where backtracking is not allowed into the group pattern, and the re-vamped pattern before `@`: `(?!_)\w+(?:[.-]\w+)*(?<!_)`, that matches one or more word chars (while the first char cannot be a `_`) followed with zero or more sequences of `.` or `-` followed with one or more word chars that cannot end in `_`.
The `+` in `^[^\W_]+` is redundant, the next `\w*` already matches the same chars, so it can be removed. The same idea is behind removing `+` in `[^\W_]@`.
Note that the last non-capturing group is redundant, I removed it.
See the regex graphs:
[](https://i.stack.imgur.com/YgB0z.png)
and from debuggex:
[](https://i.stack.imgur.com/ZjvcB.png)
An ASCII only version:
```none
^(?!_)[A-Za-z0-9_]+(?:[.-][A-Za-z0-9_]+)*(?<!_)@[A-Za-z0-9]+(?>[.-]?[A-Za-z0-9_]*[A-Za-z0-9])*\.[A-Za-z0-9]{2,}$
```
|
13,594,537 |
what does the "overused deferral" warning mean in iced coffeescript? It seems to happen when I throw an uncaught error in the code. How can I let the error bubble up as I need it be an uncaught error for unit testing. For instance, if my getByName method throws an error it bubbles up that iced coffeescript warning rather than bubbling up the exception.
```
await Profile.getByName p.uname, defer(err, existingUser)
return done new errors.DuplicateUserName(), 409 if existingUser isnt null
return done new Error("error in looking up user name " + err), 500 if err
```
|
2012/11/27
|
[
"https://Stackoverflow.com/questions/13594537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/611750/"
] |
This error is generated when a callback generated by `defer` is called more than once. In your case, it could be that `Profile.getByName` is calling its callback twice (or more). This warning almost always indicates an error in my experience.
You can disable this warning if you create a callback from a Rendezvous and explicitly make it a "multi" callback. Otherwise, it only makes sense to have the return from `defer` give you a one-shot callback.
More info here: <https://github.com/maxtaco/coffee-script/blob/iced/iced.md#icedrendezvousidimultidefer-slots>
A small note on terminology: in IcedCoffeeScript, a callback generated by `defer` is known as a "deferral" in error messages and the documentation.
|
107,653 |
In legal texts, at least in Sweden and Germany, it is common to print some parts of the body text in a smaller font. Is there a name for this typographic convention?
Examples:
[](https://i.stack.imgur.com/sLyzz.jpg)
[](https://i.stack.imgur.com/vZnb3.png)
|
2018/04/05
|
[
"https://graphicdesign.stackexchange.com/questions/107653",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/12723/"
] |
I believe it is called an "Inline Citation" or "In-Text Citation"
<https://owl.english.purdue.edu/owl/resource/560/02/>
Here: <http://www.easybib.com/guides/citation-guides/chicago-turabian/notes/> I believe they could be referring to the "same thing" but lacking an actual citation (as in your example) simply as a "note".
**Update:** During some further research I found this document from Harvard: <https://utas.libguides.com/ld.php?content_id=21757697> a solid 48 pages just concerning notes and citations. I stand by my original answer that this is simply an "in text note", or possibly a "parenthetical reference" (also known as Harvard referencing) but the document does provide fascinating (to text nerds!) further reading.
|
22,348,782 |
I'm using Json.Net to DeserializeObject Json data.
This is my Json
```
string datosContratos = {"Total":1,"Contrato":[{"Numero":1818,"CUPS":"ES003L0P","Direccion":"C. O ","TextoCiudad":"MADRID","Tarifa":"2"}]}
```
My classes are:
```
public class Contrato
{
public int Numero;
public String Cups;
public String Direccion;
public String TextoCiudad;
public String Tarifa;
}
public class Contratos
{
public int Total { get; set; }
public List<Contrato> ListaContratos { get; set; }
}
```
when I deseralize:
```
Contratos contratos = JsonConvert.DeserializeObject<Contratos>(datosContratos);
```
And the result is that contratos.Total is correct (in this case 1) but the `ListaContratos` is null although it should be filled with the data. I don't see the problem!!!
|
2014/03/12
|
[
"https://Stackoverflow.com/questions/22348782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/979048/"
] |
Just `IF(@CustomerID IS NULL)` is enough
```
IF(@CustomerID IS NULL)
BEGIN
--insert here..
INSERT INTO [tblCustomerMaster]
([CustomerName]
VALUES
(CustomerName)
SET @CustomerID = Scope_Identity() -- sql server syntax to get the ID after insert..
END
ELSE
BEGIN
-- update perhaps..
END
```
|
22,340,864 |
I am a VHDL coder, and haven't coded much with Verilog. I am going through someone else's code, and I came across this:
```
always@(posedge asix_clk_bufg or negedge pll_asix_locked)
begin
if (~pll_asix_locked)
asix_rst <= 0;
else if (timer[5]) // 355us between asix_clk and asix_rst (min is 200us)
asix_rst <= 1;
end
```
I am not sure if I agree with the above code ! Isn't a possible latch scenario ? I see it is waiting for the pll to lock and then bring the system out of reset, but is this coded correctly?
I don't like to combine sequential and combinatorial code together, but what is the value of "asix\_rst" when timer[5] = 0 ?!?
Thanks,
--Rudy
|
2014/03/12
|
[
"https://Stackoverflow.com/questions/22340864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2002041/"
] |
This is the way to infer a flip-flop with a positive edge clock (asix\_clk\_bufg) an asynchronous active low reset (pll\_asix\_locked) and a clock enable (timer[5]). There is a D input (tied to 1) and a Q output (asix\_rst).
I assume that the PLL starts off not locked so `asix_rst` is 0 until the first clock edge when `timer[5] == 1`. It will then stay high until the PLL loses lock. The reset must be asynchronous since the clock will stop when the PLL loses lock.
I am guessing that the timer[5] bit goes high 5 or 6 clock cycles after the PLL is locked ensuring that there is a stable clock before the rest of the system comes out of reset.
This would be a latch if instead of the clock you had `timer[5]` in the sensitivity list like this:
```
always@(timer[5] or pll_asix_locked)
begin
if (~pll_asix_locked)
asix_rst <= 0;
else if (timer[5]) // 355us between asix_clk and asix_rst (min is 200us)
asix_rst <= 1;
end
```
|
25,291,730 |
I have and 3 images that I need to change like so:
Image 1 > Image 2 > Image 3 > Image 1 and so on in that loop.
**JavaScript**
```
function changeImage() {
if (document.getElementById("imgClickAndChange").src = "Webfiles/SUB15_15A.bmp")
{
document.getElementById("imgClickAndChange").src = "Webfiles/SUB15.bmp";
}
else if (document.getElementById("imgClickAndChange").src = "Webfiles/SUB15.bmp")
{
document.getElementById("imgClickAndChange").src = "Webfiles/SUB15A.bmp";
}
else
{
document.getElementById("imgClickAndChange").src = "Webfiles/SUB15_15A.bmp"
}
}
```
**HTML**
```
<img src="Webfiles/SUB15_15A.bmp" id="imgClickAndChange" onclick="changeImage()" usemap="#SUB15" />
```
Any suggestions are appreciated. Everything else I have tried has not worked.
|
2014/08/13
|
[
"https://Stackoverflow.com/questions/25291730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3854096/"
] |
On *img* click change the *src* attribute of the img tag and using a counter would help more rather checking the previous image source.
HTML :
```
<img src="http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png" id="imgClickAndChange" onclick="changeImage()" usemap="#SUB15" />
```
JS :
```
var counter = 1;
imgClickAndChange.onclick = function(){
if(counter == 0){
document.getElementById("imgClickAndChange").src = "http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png";
counter++;
}
else if(counter == 1){
document.getElementById("imgClickAndChange").src = "http://www.wpclipart.com/education/animal_numbers/animal_number_2.png";
counter++;
}
else if(counter == 2){
document.getElementById("imgClickAndChange").src = "http://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Number_3_in_yellow_rounded_square.svg/512px-Number_3_in_yellow_rounded_square.svg.png";
counter = 0;
}
};
```
[***jsFiddle***](http://jsfiddle.net/codeSpy/6an7kkmm/)
|
63,844,611 |
In most recent django documentation "Overriding from the project’s templates directory"
<https://docs.djangoproject.com/en/3.1/howto/overriding-templates/>
it shows that you can use the following path for templates:
```
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
...
},
]
```
I tried using `[BASE_DIR / 'templates']` but I keep getting the following error:
`TypeError: unsupported operand type(s) for /: 'str' and 'str'`
It all works fine when I change the code to: `[BASE_DIR , 'templates']` or `[os.path.join(BASE_DIR , 'templates')]`, no problem in such case.
Can someone explain what am I missing with the `[BASE_DIR / 'templates']` line?
Thank you.
I'm using Python 3.8 and Django 3.1.
|
2020/09/11
|
[
"https://Stackoverflow.com/questions/63844611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5934625/"
] |
In order to use `BASE_DIR / 'templates'`, you need `BASE_DIR` to be a [`Path()`](https://docs.python.org/3/library/pathlib.html#pathlib.Path).
```
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
```
I suspect that your settings.py was created with an earlier version of Django, and therefore `BASE_DIR` is a string, e.g.
```
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
```
|
3,486,881 |
Group $G$ is abelian and finite. $\langle g\rangle = G$. $p$ is order of $G$ (and $\langle g\rangle$). $p=mn$, $m > 1$, $n > 1$. Why $\langle g^m\rangle < G$ (not $\langle g^m\rangle \le G$)?
|
2019/12/25
|
[
"https://math.stackexchange.com/questions/3486881",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/736839/"
] |
Basic result in theory of cyclic groups: $\langle g\rangle =G\implies |g^m|=\dfrac n{\operatorname {gcd}(n,m)}$, where $n=|G|$.
|
45,724 |
I just made the switch from Windows to Mac, and one thing that's been bothering me is that on a Mac, I can't see multiple Word documents that I have open. On Windows, they all appear in the taskbar (after checking the option to not collapse instances of the same program) and I can quickly switch between them, which is useful for a variety of reasons. On a mac, I can't do that. The best way I've discovered so far is to go into mission control, but then I still have to make two gestures instead of one, and it's hard to see which window is which. What's the best way to do this?
|
2012/03/24
|
[
"https://apple.stackexchange.com/questions/45724",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/20621/"
] |
* [Hyperdock](http://hyperdock.bahoom.com/) will give you window previews of each open window
belonging to an application by hovering over the dock icon, which you
can then click to activate.

* [Witch](http://manytricks.com/witch/) has a popup panel that displays the open
windows belonging to an application and also gives you a preview if
you hover over it.
 
* [Fantasktik](http://dj50.ro/fantasktik/) probably offers the most
similar functionality to the Windows taskbar. However, the original
developer seems to have disappeared and this hasn't been updated in a
while (and therefore probably won't ever be). The new
"owner" claims it works on Lion, so it might be worth a try.

|
26,683,840 |
I am trying to create a ListView inside a ListFragment. My list is customize, so it has been created with an adapter. But the aplication crass and give me this error *your content must have a listview whose id attribute is 'android.r.id.list*
This is the ListFragment class:
```
public static class DummySectionFragment extends ListFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Vector<String> names=new Vector<String>();
names.add("Alex");
names.add("Julia");
setListAdapter(new MyAdapter(getActivity(), names));
return rootView;
}
}
```
This is MyAdapter class:
```
public class MiAdaptador extends BaseAdapter {
private final Activity activ;
private final Vector<String> list;
public MiAdaptador(Activity activ, Vector<String> list) {
super();
this.actividad = activ;
this.list = list;
}
public View getView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = activ.getLayoutInflater();
View view = inflater.inflate(R.layout.adapter_view, null, true);
TextView textView =(TextView)view.findViewById(R.id.titulo);
textView.setText(lista.elementAt(position));
return view;
}
}
```
My fragment\_section\_dummy layout:
```
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name list"
android:gravity="center"
android:layout_margin="10px"
android:textSize="10pt"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false" />
<TextView
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
```
And my adapter\_view layout:
```
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight">
<TextView android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:singleLine="true"
android:text="title"
android:gravity="center"/>
<TextView android:id="@+id/subtitle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Other text"
android:layout_below="@id/title"
android:layout_alignParentBottom="true"
android:gravity="center"/>
</RelativeLayout>
```
How could I solve this problem?
|
2014/10/31
|
[
"https://Stackoverflow.com/questions/26683840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3507510/"
] |
Ignoring the issue of non-linear state machines, I've found the following to work well for my needs on a few projects with simple state machines:
```
# Check if the stage is in or before the supplied stage (stage_to_check).
def in_or_before_stage?(stage_to_check)
if stage_to_check.present? && self.stage.present?
STAGES_IN_ORDER.reverse.lazy.drop_while { |stg| stg != stage_to_check }.include?(self.stage)
else
false
end
end
```
and the other check is sometimes desired as well:
```
# Check if the stage is in or after the supplied stage (stage_to_check).
def in_or_after_stage?(stage_to_check)
if stage_to_check.present? && self.stage.present?
# Get all the stages that are in and after the stage we want to check (stage_to_check),
# and then see if the stage is in that list (well, technically in a lazy enumerable).
STAGES_IN_ORDER.lazy.drop_while { |stg| stg != stage_to_check }.include?(self.stage)
else
false
end
end
```
Where "STAGES\_IN\_ORDER" is just an array with the stages in order from initial to final.
We're just removing items from the list and then checking if our object's current stage is in our resulting list. If we want to know if it's in or before some stage we remove the later stages until we reach our supplied test stage, if we want to know if it's after some given stage we remove items from the front of the list.
I realize you probably don't need this answer anymore, but hopefully it helps someone =]
|
34,051,203 |
I had a question about the return statement that is by itself in the control flow.
```
var rockPaperScissors = function(n) {
var rounds = n;
var results = [];
var weapons = ['rock', 'paper', 'scissors'];
var recurse = function(roundsLeft, played) {
if( roundsLeft === 0) {
results.push(played);
return;
}
for(var i = 0; i<weapons.length; i++) {
var current = weapons[i];
recurse( roundsLeft-1, played.concat(current) );
}
};
recurse(rounds; []);
return results;
}
```
I was wondering why the return statement is not written as:
```
return results.push(played);
```
Is there any benefits? If so, why and when should you write it that way?
|
2015/12/02
|
[
"https://Stackoverflow.com/questions/34051203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4785557/"
] |
You don't need to find the item, you can use `wxMenuBar::IsChecked()`, which will do it for you, directly. And you can either just store the menu bar in `self.menuBar` or retrieve it from the frame using its `GetMenuBar()` method.
|
73,752,793 |
We are using ObjectMapper. When using ObjectMapper with RowMapper, should it be declared inside each mapRow (seen below), or outside of mapRow as a class public member? I assume it should be outside as a public class member per this article. [Should I declare Jackson's ObjectMapper as a static field?](https://stackoverflow.com/questions/3907929/should-i-declare-jacksons-objectmapper-as-a-static-field)
Currently using Spring boot with SQL Server database. Researching thread safety with thousands/millions of sql rows its getting.
```
List<Product> productList = namedParameterJdbcTemplate.query(sqlQuery,
parameters,
new ProductMapper(productRequest));
public class ProductMapper implements RowMapper<Product> {
@Override
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
ObjectMapper objectMapper = new ObjectMapper()
Product product = new Product();
product.setProductId(rs.getLong("ProductId"));
product.setProductType(rs.getString("ProductType"));
product.setLocations(objectMapper.readValue(rs.getString("Locations"), new TypeReference<List<ServiceLocation>>(){}));
} catch (Exception e) {
throw new ServiceException(e);
}
}
```
Note: Please don't ask why we are writing this manual mapper with ObjectMapper, we are doing legacy coding, and architects requested to do this.
|
2022/09/17
|
[
"https://Stackoverflow.com/questions/73752793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15435022/"
] |
An [`ObjectMapper`](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html) instance is not immutable but, as stated in the documentation:
>
> Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY
> read or write calls.
>
>
>
Which means that this code is perfectly thread-safe:
```
public class ProductMapper implements RowMapper<Product> {
private ObjectMapper mapper;
public ProductMapper()
{
objectMapper = new ObjectMapper();
}
@Override
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
Product product = new Product();
product.setLocations(objectMapper.readValue(rs.getString("Locations"), new TypeReference<List<ServiceLocation>>(){}));
return product;
}
}
```
However, the `TypeReference` object is still created for each row, which is not very efficient. A better way is to create
an [`ObjectReader`](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectReader.html)
instance via the [`readerFor()`](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html#readerFor(com.fasterxml.jackson.core.type.TypeReference)) method:
```
public class ProductMapper implements RowMapper<Product> {
private ObjectReader objectReader;
public ProductMapper()
{
ObjectMapper objectMapper = new ObjectMapper();
objectReader = objectMapper.readerFor(new TypeReference<List<ServiceLocation>>(){});
}
@Override
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
Product product = new Product();
product.setLocations(objectReader.readValue(rs.getString("Locations")));
return product;
}
}
```
An `ObjectReader` instance is immutable and thread-safe.
|
19,666,102 |
>
> A certain string-processing language offers a primitive operation which splits a string into two pieces. Since this operation involves copying the original string, it takes n units of time for a string of length n, regardless of the location of the cut. Suppose, now, that you want to break a string into many pieces. The order in which the breaks are made can affect the total running time. For example, if you want to cut a 20-character string at positions 3 and 10, then making the first cut at position 3 incurs a total cost of 20+17=37, while doing position 10 first has a better cost of 20+10=30.
>
>
> Give a dynamic programming algorithm that, given the locations of m cuts in a string of length n, finds the minimum cost of breaking the string into m + 1 pieces.
>
>
>
This problem is from "Algorithms" chapter6 6.9.
Since there is no answer for this problem, This is what I thought.
Define `OPT(i,j,n)` as the minimum cost of breaking the string, `i` for start index, `j` for end index of String and `n` for the remaining number of cut I can use.
Here is what I get:
`OPT(i,j,n) = min {OPT(i,k,w) + OPT(k+1,j,n-w) + j-i} for i<=k<j and 0<=w<=n`
Is it right or not? Please help, thx!
|
2013/10/29
|
[
"https://Stackoverflow.com/questions/19666102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2925372/"
] |
I think your recurrence relation can become more better. Here's what I came up with, define cost(i,j) to be the cost of cutting the string from index i to j. Then,
```
cost(i,j) = min {length of substring + cost(i,k) + cost(k,j) where i < k < j}
```
|
54,794,538 |
I have two dataframes
**df1**
```
+----+-------+
| | Key |
|----+-------|
| 0 | 30 |
| 1 | 31 |
| 2 | 32 |
| 3 | 33 |
| 4 | 34 |
| 5 | 35 |
+----+-------+
```
**df2**
```
+----+-------+--------+
| | Key | Test |
|----+-------+--------|
| 0 | 30 | Test4 |
| 1 | 30 | Test5 |
| 2 | 30 | Test6 |
| 3 | 31 | Test4 |
| 4 | 31 | Test5 |
| 5 | 31 | Test6 |
| 6 | 32 | Test3 |
| 7 | 33 | Test3 |
| 8 | 33 | Test3 |
| 9 | 34 | Test1 |
| 10 | 34 | Test1 |
| 11 | 34 | Test2 |
| 12 | 34 | Test3 |
| 13 | 34 | Test3 |
| 14 | 34 | Test3 |
| 15 | 35 | Test3 |
| 16 | 35 | Test3 |
| 17 | 35 | Test3 |
| 18 | 35 | Test3 |
| 19 | 35 | Test3 |
+----+-------+--------+
```
I want to count how many times each `Test` is listed for each `Key`.
```
+----+-------+-------+-------+-------+-------+-------+-------+
| | Key | Test1 | Test2 | Test3 | Test4 | Test5 | Test6 |
|----+-------|-------|-------|-------|-------|-------|-------|
| 0 | 30 | | | | 1 | 1 | 1 |
| 1 | 31 | | | | 1 | 1 | 1 |
| 2 | 32 | | | 1 | | | |
| 3 | 33 | | | 2 | | | |
| 4 | 34 | 2 | 1 | 3 | | | |
| 5 | 35 | | | 5 | | | |
+----+-------+-------+-------+-------+-------+-------+-------+
```
**What I've tried**
Using join and groupby, I first got the count for each `Key`, regardless of `Test`.
```
result_df = df1.join(df2.groupby('Key').size().rename('Count'), on='Key')
+----+-------+---------+
| | Key | Count |
|----+-------+---------|
| 0 | 30 | 3 |
| 1 | 31 | 3 |
| 2 | 32 | 1 |
| 3 | 33 | 2 |
| 4 | 34 | 6 |
| 5 | 35 | 5 |
+----+-------+---------+
```
I tried to group the `Key` with the `Test`
```
result_df = df1.join(df2.groupby(['Key', 'Test']).size().rename('Count'), on='Key')
```
but this returns an error
`ValueError: len(left_on) must equal the number of levels in the index of "right"`
|
2019/02/20
|
[
"https://Stackoverflow.com/questions/54794538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10540565/"
] |
Check with `crosstab`
```
pd.crosstab(df2.Key,df2.Test).reindex(df1.Key).replace({0:''})
```
|
4,712,335 |
I want to convert a string which contains the date in `yyyyMMdd` format to `mm-dd-yyyy` DateTime format. How do I get it?
|
2011/01/17
|
[
"https://Stackoverflow.com/questions/4712335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578083/"
] |
```
var dateString = "20050802";
var date = myDate = DateTime.ParseExact(dateString,
"yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture);
```
|
75,038 |
I want it to perform good enough as a multimedia machine. Should I get one that is fan cooled or passively cooled? I think I want one with an HDMI port.
What chipset should I look for?
|
2009/11/25
|
[
"https://superuser.com/questions/75038",
"https://superuser.com",
"https://superuser.com/users/-1/"
] |
I agree with an Ion chipset, there's really no competition in the quiet/ITX space. I've got one of [these](http://www.newegg.com/Product/Product.aspx?Item=N82E16813500035&cm_re=zotac-_-13-500-035-_-Product) powering a secondary HTPC for my bedroom. It has a [Celeron 430](http://www.newegg.com/Product/Product.aspx?Item=N82E16819116039) 35W chip in it, and it runs good and quiet. HD playback is no problem, once I got a codec that uses the hardware decoder instead of trying to shove it through the CPU.
My original thought was to go with the Atom 330 version of this board, but what I've seen about it lead me to believe that it would be too sluggish when using the VMC interface. 4 l-cores or not, its still an in-order architecture. If silence is more important to you, there are some Atom Zotac boards that are passively cooled, and have a power brick instead of a normal PSU.
|
2,305 |
Over on Twitter, @kelvinfichter [gave an analysis](https://twitter.com/kelvinfichter/status/1425217046636371969) (included below) of the recent Poly Network hack.
***Without any of the benefits of hindsight, are there reasons why the exploit would have been less likely to occur in Plutus on Cardano?***
>
> Poly has this contract called the `EthCrossChainManager`. It's basically a privileged contract that has the right to trigger messages from another chain. It's a pretty standard thing for cross-chain projects.
>
>
> There's this function `verifyHeaderAndExecuteTx` that anyone can call to execute a cross-chain transaction. Basically it:
>
>
> 1. Verifies that the block header is correct by checking signatures (seems the other chain was a poa sidechain or something) and... then
> 2. Checks that the transaction was included within that block with a Merkle proof. Here's the code, it's pretty simple: [EthCrossChainManager.sol#L127](https://github.com/polynetwork/eth-contracts/blob/d16252b2b857eecf8e558bd3e1f3bb14cff30e9b/contracts/core/cross_chain_manager/logic/EthCrossChainManager.sol#L127)
>
>
> One of the last things the function does is call `_executeCrossChainTx`, which actually makes the call to the target contract. Here's where the critical flaw sits.
>
>
> Poly checks that the target is a contract [EthCrossChainManager.sol#L185](https://github.com/polynetwork/eth-contracts/blob/d16252b2b857eecf8e558bd3e1f3bb14cff30e9b/contracts/core/cross_chain_manager/logic/EthCrossChainManager.sol#L185). But Poly forgot to prevent users from calling a very important target... the `EthCrossChainData` contract: [EthCrossChainData.sol](https://github.com/polynetwork/eth-contracts/blob/master/contracts/core/cross_chain_manager/data/EthCrossChainData.sol).
>
>
> Why is this target so important? It keeps track of the list of public keys that authenticate data coming from the other chain. If you can modify that list, you don't even need to hack private keys. You just set the public keys to match your own private keys. See here for where that list is tracked: [EthCrossChainData.sol#L22](https://github.com/polynetwork/eth-contracts/blob/d16252b2b857eecf8e558bd3e1f3bb14cff30e9b/contracts/core/cross_chain_manager/data/EthCrossChainData.sol#L22).
>
>
> So someone realized that they could send an cross-chain message directly to the `EthCrossChainData` contract.
>
>
> What good does that do them? Well, guess which contracted owned the EthCrossChainData contract... yep. The `EthCrossChainManager`. By sending this cross-chain message, the user could trick the `EthCrossChainManager` into calling the `EthCrossChainData` contract, passing the `onlyOwner` check.
>
>
> Now the user just had to craft the right data to be able to trigger the function that changes the public keys. Link to that function here: [EthCrossChainData.sol#L45](https://github.com/polynetwork/eth-contracts/blob/d16252b2b857eecf8e558bd3e1f3bb14cff30e9b/contracts/core/cross_chain_manager/data/EthCrossChainData.sol#L45).
>
>
> The only remaining challenge was to figure out how to make the `EthCrossChainManager` call the right function. Now comes a little bit of complexity around how Solidity picks which function you're trying to call.
>
>
> The first four bytes of transaction input data is called the "signature hash" or "sighash" for short. It's a short piece of information that tells a Solidity contract what you're trying to do. The sighash of a function is calculated by taking the first four bytes of the hash of "()".
>
>
> For example, the sighash of the ERC20 transfer function is the first four bytes of the hash of `transfer(address,uint256)`. Poly's contract was willing to call *any* contract. However, it would only call the contract function that corresponded to the following sighash: Errr but wait... `_method` here was user input.
>
>
> All the attacker had to do to call the right function was figure out *some* value for `_method` that, when combined with those other values and hashed, had the same leading four bytes as the sighash of our target function.
>
>
> With just a little bit of grinding, you can *easily* find some input that produces the right sighash. You don't need to find a full hash collision, you're only checking the first four bytes.
>
>
> So is this theory correct? Well... here's the actual sighash of the target function:
>
>
>
> ```
> > ethers.utils.id ('putCurEpochConPubKeyBytes(bytes)').slice(0, 10)
> '0x41973cd9'`
>
> ```
>
> And the sighash that the attacker crafted...
>
>
>
> ```
> > ethers.utils.id ('f1121318093(bytes,bytes,uint64)').slice(0, 10)
> '0x41973cd9'
>
> ```
>
> Fantastic. No private key compromise required! Just craft the right data and boom... the contract will just hack itself!
>
>
>
The author then goes on to [give lessons learned](https://twitter.com/kelvinfichter/status/1425220160814784512).
***Do Plutus developers also need to learn from these lessons or are they specific to Solidity?***
>
> One of the biggest design lessons that people need to take away from this is: if you have cross-chain relay contracts like this, MAKE SURE THAT THEY CAN'T BE USED TO CALL SPECIAL CONTRACTS.
>
>
> The `EthCrossDomainManager` shouldn't have owned the `EthCrossDomainData` contract. Separate concerns.
>
>
> If your contract absolutely need to have special privileges like this, make sure that users can't use cross-chain messages to call those special contracts.
>
>
> And just for good measure, here's the function to trigger a cross-chain message: [EthCrossChainManager.sol#L91](https://github.com/polynetwork/eth-contracts/blob/d16252b2b857eecf8e558bd3e1f3bb14cff30e9b/contracts/core/cross_chain_manager/logic/EthCrossChainManager.sol#L91). Nothing here prevents you from sending a message to the `EthCrossChainData` contract.
>
>
>
@kelvinfichter also gives a simplified summary of the attack: <https://twitter.com/kelvinfichter/status/1425290462076747777>
|
2021/08/11
|
[
"https://cardano.stackexchange.com/questions/2305",
"https://cardano.stackexchange.com",
"https://cardano.stackexchange.com/users/1903/"
] |
This one is a bit technical it has to do with looking up and updating the constraints of an already existing transaction (that belongs to the script address). See Case ii) to skip my synopsis.
Just a little synopsis for future readers: The [`Core.hs`](https://github.com/input-output-hk/plutus-pioneer-program/blob/main/code/week06/src/Week06/Oracle/Core.hs) script is an Oracle, that has to update its datum regarding Ada price. The lines in which lookups occur are in the function `updateOracle` that has the purpose of building a transaction and then submitting it. To accomplish this the constraints need to refer to typed script inputs and outputs. In `updateOracle` we dealt with two cases
```
.
.
case m of
Nothing -> do
ledgerTx <- submitTxConstraints (typedOracleValidator oracle) c
.
.
Just (oref, o, _) -> do
let lookups = Constraints.unspentOutputs (Map.singleton oref o) <>
Constraints.typedValidatorLookups (typedOracleValidator oracle) <>
Constraints.otherScript (oracleValidator oracle)
tx = c <> Constraints.mustSpendScriptOutput oref (Redeemer $ PlutusTx.toBuiltinData Update)
ledgerTx <- submitTxConstraintsWith @Oracling lookups tx
.
.
```
* i) Create the Oracle (if it doesn't exists) at the same time of submission and add datum.
* ii) Just update the datum of an existing Oracle
Case i) uses `submitTxConstraints` which takes the constraints as inputs in the form of a script instance (with typed validator hash & the compiled program) and the locked value with the script.
Case ii) on the other hand, uses `submitTxConstraintsWith` which takes the updated constraints as `ScriptLookup` type rather than a script instance. To your question, we need to semigroup:
* `Constraints.typedValidatorLookups` (this gets the previous
parameters of the `ScriptLookup`)
* `Constraints.unspentOutputs` (updates `slTxOutputs` from
`ScriptLookup`, which are the unspent outputs that the script wants to
spend)
* `Constraints.otherScript` (updates `slOtherScripts` from
`ScriptLookup`, which are validators of the script other than our
script)
The reason why `Constraints.typedValidatorLookups` alone is not enough is because we would not be updating anything without semigrouping `ScriptLookup` element by element as defined in [`OffChain.hs`](https://github.com/input-output-hk/plutus/blob/master/plutus-ledger/src/Ledger/Constraints/OffChain.hs))
|
72,528,078 |
I have a csv file that looks like:
```
,,,,,,,,
,,,,a,b,c,d,e
,,,"01.01.2022, 00:00 - 01:00",82.7,57.98,0.0,0.0,0.0
,,,"01.01.2022, 01:00 - 02:00",87.6,50.05,15.0,25.570000000000004,383.55000000000007
,,,"01.01.2022, 02:00 - 03:00",87.6,41.33,0.0,0.0,0.0
```
And I want to import headers first and then the data, and finally insert headers to the names of the table with data
```
file <- "path"
pnl <- read.csv(file, dec = ",") #, skip = 1, header = TRUE)
headers <- read.csv(file, skip = 1, header = F, nrows = 1, as.is = T)
df <- read.csv(file, skip = 2, header = F, as.is = T)
#or this
#df <- read.csv(file, skip = 2, header = F, nrow = 1,dec = ".",sep=",", quote = "\"")
colnames(df) <- headers
```
When importing headers I have multiple columns with the headers entries. However, when importing table all entries are put inside one column, the same as in csv file (should be multiple columns). How can I solve it with read.csv() function?
|
2022/06/07
|
[
"https://Stackoverflow.com/questions/72528078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15184843/"
] |
like this?
```
data.table::fread(',,,,,,,,
,,,,a,b,c,d,e
,,,"01.01.2022, 00:00 - 01:00",82.7,57.98,0.0,0.0,0.0
,,,"01.01.2022, 01:00 - 02:00",87.6,50.05,15.0,25.570000000000004,383.55000000000007
,,,"01.01.2022, 02:00 - 03:00",87.6,41.33,0.0,0.0,0.0',
skip = 1)
V1 V2 V3 V4 a b c d e
1: NA NA NA 01.01.2022, 00:00 - 01:00 82.7 57.98 0 0.00 0.00
2: NA NA NA 01.01.2022, 01:00 - 02:00 87.6 50.05 15 25.57 383.55
3: NA NA NA 01.01.2022, 02:00 - 03:00 87.6 41.33 0 0.00 0.00
```
|
3,349,400 |
I have a question, which might also fit on stackoverflow, but due to I think I made some mistake in my mathematical considerations I think math.stackexchange is more proper for my question.
Currently I'm writing a (python) program, where a small part of it deals with matrix logarithms. Due to I'm looking for a mistake, I could locate the error in the program part, which does the matrix logarithm. While looking where exactly the error might be, I got quite unsure whether my notion about matrix logarithm is correct.
For testing purposes I calculate the matrix logarithm by using scipy.linalg.logm() and some matrices, which are derived from random matrices. To ensure, that the input has full rank, I add $\delta \cdot \mathbf{1}$ for some little $\delta > 0$.
Although I insert a real matrix $M$, most of the time $logm(M)$ is complex valued. The complex values don't seem to be numerical artefacts, since their magnitude is the same as the magnitude of the real values.
My question now is, whether it can be correct, that real matrices have complex logarithms?
On the one hand I know, that logm uses approximations, since not all matrices are can be diagonalized. According to the sourcecode logm uses techniques from Nicholas J. Higham's "Functions of Matrices: Theory and Computation", so (beside the fact, that scipy is tested quite well) I think the algorithm works correctly.
On the other hand both ways of calculating matrix logarithm I know about (diagonalizing and power series, which both of course don't work in all cases) give real logarithms for real matrices. So, since complex logarithms for real matrices don't occur in this cases, I cannot imagine whether such a result might be correct.
Does anyone have some argument which can confirm or deny my concerns?
Or do I have to look for the problem in the program code, as my cosiderations are correct?
Thanks in advance!
|
2019/09/09
|
[
"https://math.stackexchange.com/questions/3349400",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/432130/"
] |
Well, a quick search revealed the following answer (from [Wikipedia](https://en.wikipedia.org/wiki/Logarithm_of_a_matrix)):
>
> The answer is more involved in the real setting. **A real matrix has a real logarithm if and only if it is invertible and each Jordan block belonging to a negative eigenvalue occurs an even number of times.** If an invertible real matrix does not satisfy the condition with the Jordan blocks, then it has only non-real logarithms. This can already be seen in the scalar case: no branch of the logarithm can be real at -1. The existence of real matrix logarithms of real 2×2 matrices is considered in a later section.
>
>
>
You should check if in your case you verify the property underlined above.
|
66,025,267 |
On Qt Creator `Tools`>`Options`>`Build & Run`>`Default Build Properties` the `Default build directory`
has the value defined in terms of variables
```
../%{JS: Util.asciify("_build-%{CurrentProject:Name}-%{CurrentKit:FileSystemName}-%{CurrentBuild:Name}")}
```
which result in something like
```
_build-Project1-Desktop_Qt_5_15_2_MSVC2019_64bit-Debug
```
1. From where those variables (CurrentProject:Name, CurrentKit:FileSystemName and CurrentBuild:Name) come from?
2. I would like to generate something different (shorter), perhaps like
`_x86-debug` or `_x86d` or `_x64-debug` or `_x64d`
which variables should I look for?
|
2021/02/03
|
[
"https://Stackoverflow.com/questions/66025267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5082463/"
] |
This worked for me.
```
:host ::ng-deep .multiselect-dropdown .dropdown-btn {
padding: 6px 24px 6px 12px !important;
}
```
|
29,413,180 |
I have a multiple select option that display the result in a div container, when click on ctrl+"orange""apple""banana" the result display: "orange, apple, banana" in one line, but i want to display each result in a new single line with a link that goes to different page like this:
Orange - "goes to a link"
Apple - "goes to a link"
Banana - "goes to a link"
Here are my codes below:
```
<script src="jquery-mobile/jquery-1.8.3.min.js" type="text/javascript">
</script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option> </select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; "> <span id="yourfruit"> </span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#select-custom-19').change(function() {
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
$('#yourfruit').text($(this).val());
});
});
</script>
```
your help will be highly appreciated.
Thanks
|
2015/04/02
|
[
"https://Stackoverflow.com/questions/29413180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742303/"
] |
You can try adding `<br/>` element after every selected option. I have used `<label>` element but you can add link or any other element you want
```
$(document).ready( function ()
{
$('#select-custom-19').change(function(){
$('#yourfruit').empty();
var values = $(this).val();
for(var i=0; i < values.length ; i++)
{
$('#yourfruit').append('<lable>'+values[i]+'</label><br/>');
}
});
});
```
**[JSFiddle Demo](http://jsfiddle.net/yqjwa93d/5/)**
|
85,177 |
im quite new in music theory and i really dont understand what he is doing here.
is he changing the key after every chord?
he talks about c minor being the root note. after that he switches to c# which would be off the key?
what kind of chord progession is this? does it have a name? i have a really hard time figuring out what is happening here :( it sounds so good tho!
thanks for helping!
|
2019/05/24
|
[
"https://music.stackexchange.com/questions/85177",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/59146/"
] |
He is doing this:
`Cm Db => Fm Gb => Bbm Cb => Ebm Fb => ...`
What I hear is a continuous modulation up in perfect fourths. The chords `Cm Db Fm` can be heard in the key of F minor. The F minor chord is then re-interpreted as the Vm chord of the next key (Bbm) etc. So what you have is
```
key
Fm: Cm Db Fm
Bbm: Fm Gb Bbm
Ebm: Bbm Cb Ebm
...
```
|
72,889,130 |
I am currently doing the US Medical Insurance Cost Portfolio Project through Code Academy and am having trouble combining two lists into a single dictionary. I created two new lists (`smoking_status` and `insurance_costs`) in hope of investigating how insurance costs differ between smokers and non-smokers. When I try to zip these two lists together, however, the new dictionary only has two components. It should have well over a thousand. Where did I go wrong? Below is my code and output. It is worth nothing that the output seen is the last two data points in my original csv file.
```
import csv
insurance_db =
with open('insurance.csv',newline='') as insurance_csv:
insurance_reader = csv.DictReader(insurance_csv)
for row in insurance_reader:
insurance_db.append(row)
smoking_status = []
for person in insurance_db:
smoking_status.append(person.get('smoker'))
insurance_costs = []
for person in insurance_db:
insurance_costs.append(person.get('charges'))
smoker_dictionary = {key:value for key,value in zip(smoking_status,insurance_costs)}
print(smoker_dictionary)
```
Output:
```none
{'yes': '29141.3603', 'no': '2007.945'}
```
|
2022/07/06
|
[
"https://Stackoverflow.com/questions/72889130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19497618/"
] |
>
> Is there a way to update Progressbar from another thread
>
>
>
Short answer: No. A control can only be updated on the thread on which it was originally created.
What you can do is to display the `ProgressBar` in another window that runs on another thread and then close this window when the `RichTextBox` on the original thread has been updated.
|
26,480,683 |
I used code for sum cells of `datagridview1` like below
```
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
int sum = 0;
for (i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value != null)
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value.ToString());
label1.Text = Convert.ToString(sum);
}
}
}
```
but i want my `cell[0].value` sum is shown in `label1` is ok like below,but if i can use multiplied by any numbers in other cells like below image the answer should be = `60`
see below details how its come
>
> 5+4 = 9 \* 2 = 18
>
>
> (18+2) \* 3 = 60
>
>
>

|
2014/10/21
|
[
"https://Stackoverflow.com/questions/26480683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4085654/"
] |
Try this solution:
```
int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
//for 1st column
if (dataGridView1.Rows[i].Cells[0].Value != null && !String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[0].Value.ToString()))
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value.ToString());
//for 2nd column
if (dataGridView1.Rows[i].Cells[1].Value != null && !String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[1].Value.ToString()))
sum *= Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value.ToString());
//for 3rd column
if (dataGridView1.Rows[i].Cells[2].Value != null && !String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[2].Value.ToString()))
sum *= Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value.ToString());
}
label1.Text = Convert.ToString(sum);
```
Assign `sum` to `label1` after all calculations. Its useless to do it in every iteration.
|
49,646,601 |
So I've literally copy-pasted the code from <https://codepen.io/hellokatili/pen/rVvMZb> (HTML in a template, CSS in styles.css and JS using this plugin <https://wordpress.org/plugins/header-and-footer-scripts/>)
I added the JS script within tags.
Here is the above code from codepen (after converting from HAML to HTML and SCSS to CSS).
HTML:
```
> <div class="content">
<script type="text/javascript"> </script>
<div class="slider single-item">
> <div class="quote-container">
> <div class="portrait octogon">
> <img src="http://www.tuacahntech.com/uploads/6/1/7/9/6179841/6166205_orig.jpg"/>
> </div>
> <div class="quote">
> <blockquote>
> <p>Meditation shabby chic master cleanse banh mi Godard. Asymmetrical Wes Anderson Intelligentsia you probably haven't heard of
> them.</p>
> <cite>
> <span>Kristi McSweeney</span>
> <br/>
> Thundercats twee
> <br/>
> Austin selvage beard
> </cite>
> </blockquote>
> </div>
> </div>
> <div class="quote-container">
> <div class="portrait octogon">
> <img src="http://static1.squarespace.com/static/51579fb2e4b0fc0d9469ff97/56cc83dfe707ebc39cf3269f/56d0b59e27d4bde4665fded3/1457365822199/"/>
> </div>
> <div class="quote">
> <blockquote>
> <p>Bespoke occupy cred seitan. Austin street art freegan Truffaut leggings aesthetic, salvia chia Brooklyn flexitarian.
> Single-origin coffee before they sold out health goth, cornhole irony
> keffiyeh Austin taxidermy mlkshk blog trust fund banh mi you probably
> haven't heard of them.</p>
> <cite>
> <span>Dina Anderson</span>
> <br/>
> Blue Bottle keffiyeh
> <br/>
> Sartorial locavore Schlitz ennui
> </cite>
> </blockquote>
> </div>
> </div> </div> </div> <svg> <defs>
> <clipPath clipPathUnits="objectBoundingBox" id="octogon">
> <polygon points="0.50001 0.00000, 0.61887 0.06700, 0.75011 0.06721, 0.81942 0.18444, 0.93300 0.25001, 0.93441 0.38641, 1.00000 0.49999, 0.93300 0.61887, 0.93300 0.75002, 0.81556 0.81944, 0.74999 0.93302, 0.61357 0.93444, 0.50001 1.00000, 0.38118 0.93302, 0.24998 0.93302, 0.18056 0.81556, 0.06700 0.74899, 0.06559 0.61359, 0.00000 0.49999, 0.06700 0.38111, 0.06700 0.25001, 0.18440 0.18058, 0.25043 0.06700, 0.38641 0.06559, 0.50001 0.00000"></polygon>
> </clipPath> </defs> </svg>
```
CSS:
```
html {
height: 100%;
}
body {
background: linear-gradient(130deg, #1abc9c, #d1f2eb);
background-size: 400% 400%;
-webkit-animation: gradient 16s ease infinite;
-moz-animation: gradient 16s ease infinite;
animation: gradient 16s ease infinite;
}
.content {
margin: auto;
padding: 20px;
width: 80%;
max-width: 1200px;
min-width: 300px;
}
.slick-slider {
margin: 30px auto 50px;
}
.slick-prev, .slick-next {
color: white;
opacity: 1;
height: 40px;
width: 40px;
margin-top: -20px;
}
.slick-prev path, .slick-next path {
fill: rgba(255, 255, 255, 0.4);
}
.slick-prev:hover path, .slick-next:hover path {
fill: #fff;
}
.slick-prev {
left: -35px;
}
.slick-next {
right: -35px;
}
.slick-prev:before, .slick-next:before {
content: none;
}
.slick-dots li button:before {
color: rgba(255, 255, 255, 0.4);
opacity: 1;
font-size: 8px;
}
.slick-dots li.slick-active button:before {
color: #fff;
}
.quote-container {
min-height: 200px;
color: #666;
font-size: 36px;
margin: 0 20px;
position: relative;
}
.quote-container:hover {
cursor: grab;
}
.quote-container .portrait {
position: absolute;
top: 0;
bottom: 0;
margin: auto;
height: 140px;
width: 140px;
overflow: hidden;
}
.quote-container .portrait img {
display: block;
height: auto;
width: 100%;
}
.quote-container .quote {
position: relative;
z-index: 600;
padding: 40px 0 40px 180px;
margin: 0;
font-size: 20px;
font-style: italic;
line-height: 1.4 !important;
font-family: Calibri;
color: white;
}
.quote-container .quote p {
position: relative;
margin-bottom: 20px;
}
.quote-container .quote p:first-child:before {
content: '\201C';
color: rgba(255, 255, 255, 0.44);
font-size: 7.5em;
font-weight: 700;
opacity: 1;
position: absolute;
top: -0.4em;
left: -0.2em;
text-shadow: none;
z-index: -10;
}
.quote-container .quote cite {
display: block;
font-size: 14px;
}
.quote-container .quote cite span {
font-size: 16px;
font-style: normal;
letter-spacing: 1px;
text-transform: uppercase;
}
.dragging .quote-container {
cursor: grabbing;
}
.octogon {
-webkit-clip-path: polygon(50% 0%, 38.11% 6.7%, 24.99% 6.72%, 18.06% 18.44%, 6.7% 25%, 6.56% 38.64%, 0% 50%, 6.7% 61.89%, 6.7% 75%, 18.44% 81.94%, 25% 93.3%, 38.64% 93.44%, 50% 100%, 61.88% 93.3%, 75% 93.3%, 81.94% 81.56%, 93.3% 74.9%, 93.44% 61.36%, 100% 50%, 93.3% 38.11%, 93.3% 25%, 81.56% 18.06%, 74.96% 6.7%, 61.36% 6.56%, 50% 0%);
clip-path: url(#octogon);
height: 140px;
width: 140px;
}
@-webkit-keyframes gradient {
0% {
background-position: 5% 0%;
}
50% {
background-position: 96% 100%;
}
100% {
background-position: 5% 0%;
}
}
@-moz-keyframes gradient {
0% {
background-position: 5% 0%;
}
50% {
background-position: 96% 100%;
}
100% {
background-position: 5% 0%;
}
}
@keyframes gradient {
0% {
background-position: 5% 0%;
}
50% {
background-position: 96% 100%;
}
100% {
background-position: 5% 0%;
}
}
```
JS:
```
var prevButton = '<button type="button" data-role="none" class="slick-prev" aria-label="prev"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" version="1.1"><path fill="#FFFFFF" d="M 16,16.46 11.415,11.875 16,7.29 14.585,5.875 l -6,6 6,6 z" /></svg></button>',
nextButton = '<button type="button" data-role="none" class="slick-next" aria-label="next"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="#FFFFFF" d="M8.585 16.46l4.585-4.585-4.585-4.585 1.415-1.415 6 6-6 6z"></path></svg></button>';
$('.single-item').slick({
infinite: true,
dots: true,
autoplay: true,
autoplaySpeed: 4000,
speed: 1000,
cssEase: 'ease-in-out',
prevArrow: prevButton,
nextArrow: nextButton
});
$('.quote-container').mousedown(function(){
$('.single-item').addClass('dragging');
});
$('.quote-container').mouseup(function(){
$('.single-item').removeClass('dragging');
});
```
The HTML and CSS part work fine but the JS isn't functioning. I'm using a different JS script on the same WP site and it works just fine. Is there anything I'm missing?
|
2018/04/04
|
[
"https://Stackoverflow.com/questions/49646601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1889865/"
] |
You can also try the code by writing inside **jquery** ready :
```
(function($){
'use strict';
var prevButton = '<button type="button" data-role="none" class="slick-prev" aria-label="prev"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" version="1.1"><path fill="#FFFFFF" d="M 16,16.46 11.415,11.875 16,7.29 14.585,5.875 l -6,6 6,6 z" /></svg></button>',
nextButton = '<button type="button" data-role="none" class="slick-next" aria-label="next"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="#FFFFFF" d="M8.585 16.46l4.585-4.585-4.585-4.585 1.415-1.415 6 6-6 6z"></path></svg></button>';
$('.single-item').slick({
infinite: true,
dots: true,
autoplay: true,
autoplaySpeed: 4000,
speed: 1000,
cssEase: 'ease-in-out',
prevArrow: prevButton,
nextArrow: nextButton
});
$('.quote-container').mousedown(function(){
$('.single-item').addClass('dragging');
});
$('.quote-container').mouseup(function(){
$('.single-item').removeClass('dragging');
});
})(jQuery);
```
Hope this will work.
|
32,933,106 |
**My onClick() method:**
```
public void onClick(View v) {
String Adm = ((Button)v).getText().toString();
EditText t1 = (EditText) findViewById(R.id.editText);
EditText t2 = (EditText) findViewById(R.id.editText2);
if (Adm.equals("Administrator")){
t1.setVisibility(View.VISIBLE);
t2.setVisibility(View.VISIBLE);
}
}
```
**My layout.xml:**
```
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Administrator"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:visibility="invisible" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editText"
android:layout_below="@+id/button2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView"
android:visibility="invisible" />
```
So basically I have 2 Buttons and what I want to do is call ClickEvent to change the visibility of the EditText fields. I'm new to this so I'm trying my best but still something is missing.
Relevant code above.
|
2015/10/04
|
[
"https://Stackoverflow.com/questions/32933106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3360710/"
] |
If I understand correctly the directory structure of your project, you have the routes directory next to the models directory, right?
if this is the case, you need to change the require in routes/index.js to use ../, so it will get to the right location:
```
var User = require('../models/User');
```
|
53,111,297 |
My function is given a 'to\_find\_value' then I have 2 lists which are the same in length and index values. Once I find the index value in list 1 that 'to\_find\_value' is in, I want to take that index of list 2 and return the value found at list 2.
Ex:
```
function_name('tree', ['bush', 'tree', 'shrub'], ['red', 'green', 'yellow'])
'green'
```
So in the above function I was given tree, and I found it at index 1 in list 1 so then I go to index 1 in list 2 and return the value at that index
This is what I have started so far but I am unsure how to format an 'unknown' index:
```
for plant in plant_data:
if plant in list1:
list1[?] == list2[?]
return list2[?}
```
\*The '?' represents the part I'm unsure about
|
2018/11/02
|
[
"https://Stackoverflow.com/questions/53111297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10438529/"
] |
Something like:
```
def f(a,b,c):
return c[b.index(a)]
```
Then call it like:
```
print(f('tree', ['bush', 'tree', 'shrub'], ['red', 'green', 'yellow']))
```
Output is:
```
green
```
|
19,166,342 |
I am using a list view in which I have an xml referencing drawable/list as follows:
```
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
//For the borders
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="0dp" />
</shape>
</item>
//For the background color of cells
<item android:top="1px"
android:left="0dp"
android:right="0dp"
android:bottom="1px">
<shape android:shape="rectangle">
<solid android:color="#262626" />
<corners android:radius="0dp" />
</shape>
</item>
</layer-list>
```
The above code is basically used to define the borders and the background color of cells. However, I want to be able to use line for the borders instead of rectangle so that the bottom border of one rectangle doesnt leave a 1 dp gap between the top border of another rectangle below it.
Please refer the image below:

As you can see from the image, the rectangular bottom border below BOK.L is a little off showing a gap between the top rectangular border of GOOG.OQ Is there a way to fix this such that both the borders either overlap on top of each other and no such double line gap appears or is there a way I can define a line shape such that it is defined above and below all the cells in the pic without a gap?
Any clue?
Thanks!
Justin
The xml file referencing the same (drawable/list) is as follows :
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/list"
android:padding="4dp"
>
<TextView
android:id="@+id/symbol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:paddingLeft="8dp"
android:textColor="@color/search_autosuggest_header_text"
foo:customFont="Roboto-Bold.ttf"
android:singleLine="true"
android:layout_toLeftOf="@+id/last_container"
android:ellipsize="end"
android:gravity="left"
android:textSize="14sp"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
foo:customFont="Roboto-Regular.ttf"
android:layout_alignParentLeft="true"
android:layout_below="@id/symbol"
android:layout_toLeftOf="@+id/last_container"
android:paddingBottom="4dp"
android:textColor="@color/search_autosuggest_item_subtitle"
android:singleLine="true"
android:ellipsize="end"
android:textSize="11sp" />
<FrameLayout
android:id="@+id/last_container"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/net_change_container" >
<TextView
android:id="@+id/last_back"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/last"
style="@style/TextView.ListsTextView"
android:layout_width="87dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/net_change_container"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_toLeftOf="@+id/percent_change_container" >
<TextView
android:id="@+id/net_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/net_change"
style="@style/TextView.ListsTextView"
android:layout_width="80dp"
android:textSize="12sp"
android:layout_height="wrap_content" />
</FrameLayout>
<FrameLayout
android:id="@+id/percent_change_container"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="1dp" >
<TextView
android:id="@+id/percent_change_back"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="14sp"
foo:customFont="Roboto-Regular.ttf"
android:layout_height="wrap_content"
android:padding="3dp" />
<TextView
android:id="@+id/percent_change"
style="@style/TextView.ListsTextView"
android:layout_width="65dp"
android:textSize="12sp"
android:layout_height="wrap_content"/>
</FrameLayout>
</RelativeLayout>
```
Also,@jboi with with your fix the screen that I get is:

|
2013/10/03
|
[
"https://Stackoverflow.com/questions/19166342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I dont think you would like to use Regex for this. You may try simply like this:-
```
<a id="myLink" href="http://www.google.com">Google</a>
var anchor = document.getElementById("myLink");
alert(anchor.getAttribute("href")); // Extract link
alert(anchor.innerHTML); // Extract Text
```
[Sample DEMO](http://jsfiddle.net/Ms7bc/3/)
**EDIT:-**(As rightly commented by Patrick Evans)
```
var str = "<a href=www.google.com>Google</a>";
var str1 = document.createElement('str1');
str1.innerHTML = str;
alert(str1.textContent);
alert( str1.innerText);
```
[Sample DEMO](http://jsfiddle.net/ScacH/3/)
|
31,355 |
In my world human(oid)s are not born anymore, they are grown in pods which mirror the conditions of a natural womb.
Children are educated before birth and are "born" as fully mature adults with a standard education ready to join society.
How long would this process take? I assume that artificial growth could be much quicker than a natural 18-20 year period. Could a human be grown in a year? A decade?
|
2015/12/12
|
[
"https://worldbuilding.stackexchange.com/questions/31355",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/18/"
] |
A year? No. Babies already require 9 months in the womb to get to where they get. You're limited because many processes in growth require chemical processes that simply take time. Humans simply aren't cars to be manufactured.
A decade? Now its getting interesting. It is reasonable to assume that a human could grow faster in a "perfect" environment with genes to leverage that perfect environment. Its entierly possible we could reach "fully grown" in a decade. However, the womb would probably have to be adjusted. Many thing a human body needs require things that challenge their motion (so they can learn which muscles are doing what). The humans would be gloriously clumsy unless they got Physical Education as part of their standard education in the womb.
A standard education in the womb you say? That education process might be very daunting indeed. You may be able to physically produce a human in a decade, but you may find it hard to properly educate them that fast.
|
23,775,272 |
I'm new to Modals, I have a Form and when the user clicks submit, It will show a Modal confirming if the user wants to submit, the modal also contains the user input from the form fields. I searched all over the internet but can't find the right one on my needs. And all I see is that they tag the click event to open modal on a a link. i have a input type submit. Can you give examples or ideas? Thanks! Here's my sample form.
```
<form role="form" id="formfield" action="inc/Controller/OperatorController.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm();">
<input type="hidden" name="action" value="add_form" />
<div class="form-group">
<label>Last Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter Last Name" name="lastname" id="lastname">
</div>
<div class="form-group">
<label>First Name</label><span class="label label-danger">*required</span>
<input class="form-control" placeholder="Enter First Name" name="firstname" id="firstname">
</div>
<input type="submit" name="btn" value="Submit" id="submitBtn" class="btn btn-default" data-confirm="Are you sure you want to delete?"/>
<input type="button" name="btn" value="Reset" onclick="window.location='fillup.php'" class="btn btn-default" data-modal-type="confirm"/>
</form>
```
|
2014/05/21
|
[
"https://Stackoverflow.com/questions/23775272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3651491/"
] |
So if I get it right, on click of a button, you want to open up a modal that lists the values entered by the users followed by submitting it.
For this, you first change your `input type="submit"` to `input type="button"` and add `data-toggle="modal" data-target="#confirm-submit"` so that the modal gets triggered when you click on it:
```
<input type="button" name="btn" value="Submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-default" />
```
Next, the modal dialog:
```
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div>
<div class="modal-body">
Are you sure you want to submit the following details?
<!-- We display the details entered by the user here -->
<table class="table">
<tr>
<th>Last Name</th>
<td id="lname"></td>
</tr>
<tr>
<th>First Name</th>
<td id="fname"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a href="#" id="submit" class="btn btn-success success">Submit</a>
</div>
</div>
</div>
</div>
```
Lastly, a little bit of jQuery:
```
$('#submitBtn').click(function() {
/* when the button in the form, display the entered values in the modal */
$('#lname').text($('#lastname').val());
$('#fname').text($('#firstname').val());
});
$('#submit').click(function(){
/* when the submit button in the modal is clicked, submit the form */
alert('submitting');
$('#formfield').submit();
});
```
You haven't specified what the function `validateForm()` does, but based on this you should restrict your form from being submitted. Or you can run that function on the form's button `#submitBtn` click and then load the modal after the validations have been checked.
**[DEMO](http://jsfiddle.net/0gct8qd8/)**
|
22,168,437 |
We have a Java project that we wish to distribute to users. It does not use any Java features beyond Java 1.5, so we wish it to run on Java 1.5 and above.
At this point, you might rightfully note that Java 1.6 is the oldest available currently, so why target Java 1.5? However, that does not change the generic nature of the question of cross-compiling for older versions.
So, the way one usually starts cross-compilation attempts is by specifying `-source 1.5` and `-target 1.5` options to `javac`, at which point one gets a famous warning about `-bootclasspath` not being set:
```
$ javac -source 1.5 -target 1.5 Test.java
warning: [options] bootstrap class path not set in conjunction with -source 1.5
1 warning
```
Now, according to [Oracle blog post](https://blogs.oracle.com/darcy/entry/bootclasspath_older_source), as well as [official documentation](http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/javac.html#crosscomp-example), the correct practice for cross-compilation is to:
>
> To use javac from JDK N to cross-compiler to an older platform version, the correct practice is to:
>
>
> * Use the older -source setting.
> * Set the bootclasspath to compile against the rt.jar (or equivalent) for the older platform.
>
>
> If the second step is not taken, javac will dutifully use the old language rules combined with new libraries, which can result in class files that do not work on the older platform since references to non-existent methods can get included.
>
>
>
For instance, quoting official documentation:
```
% javac -source 1.6 -target 1.6 -bootclasspath jdk1.6.0/lib/rt.jar \
-extdirs "" OldCode.java
```
This is great and has been answered many times before both on Stack Overflow and the rest of the Internet.
However, none of the resources we have found seem to indicate where to actually find the `rt.jar` for older versions of Java. As an example, JDK 1.7 does not ship with `rt.jar` except its own:
```
$ find jdk-1.7.0_45 -name rt.jar
jdk-1.7.0_45/jre/lib/rt.jar
```
That makes one think that in order to obtain `rt.jar` for Java 1.6, for instance, one needs to download JDK 1.6. But then two questions arise:
1. if we download JDK 1.6, we might as well use that for compilation instead of JDK 1.7;
2. if we wish to cross-compile for Java 1.5, then JDK 1.5 is no longer available for download.
So, how do we actually specify `-bootclasspath` option to use this cross-compilation feature?
|
2014/03/04
|
[
"https://Stackoverflow.com/questions/22168437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1307749/"
] |
The rt.jar is included with the JRE. You will be able to perform the cross compilation if you have, say, JDK 1.6 and JRE 1.5.
Using your JDK 1.6:
```
$ javac -source 1.5 -target 1.5 -bootclasspath jre1.5.0/lib/rt.jar Test.java
```
The advantage here is that the JRE can be as little as 1/3 the size of a full JDK. You can often remove old JDK versions without removing old JRE versions.
If you need to get hold of an old JRE, they can be found following links on the Java Archive page <http://www.oracle.com/technetwork/java/javase/archive-139210.html>
|
38,470,462 |
I have the following:
```
public class Car{
public Car()
{//some stuff
}
private Car [] carmodels ;
public Car [] getCarModel() {
return this.carmodels;
}
public void setcarModel(Car [] carmodels ) {
this.carmodels = carmodels;
}
```
Now on my test class, I have something like this
```
public void main (String [] args)
{
Car car1= new Car();
car.setcarModel(new Car[5]);//here i create an array of Car
for(int i =0;i<5;i++)
{
// how can i created 5 cars and set them based on index i
// car.setCarModel[new Car()]????
}
}
```
How can do that? I could use a temp array of type Car which I can pass to my Setter just after the loop. But is there a better way?
|
2016/07/20
|
[
"https://Stackoverflow.com/questions/38470462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3841581/"
] |
If you insist on not using a temp value in the for loop you could use an [ArrayList](https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html) instead of an array for the carmodels.
than add a method
```
public void addCar(Car toadd)
{
carmodels.add(toadd);
}
```
than in your foor loop just call
```
for(int i =0;i<5;i++)
{
car.addCar(new Car());
}
```
Im assuming the size can vary and that a fixed size array is not sufficient.
|
10,424,848 |
I have installed all the necessary files from android site, but when I run my emulator it just displays "ANDROID" and nothing else. I am using Intel Dual core (2.20GHz), ASUS motherboard and 3gb of RAM. Whats the prob I couldnt understand.. Even one of my friend using Intel Dual core(1.80GHz) with 1gb of RAM running smoothly then whats my problem.
|
2012/05/03
|
[
"https://Stackoverflow.com/questions/10424848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1349138/"
] |
The emulator is slow becasue it is, of all things, emulating a completely different architecture (arm), and if it's the first time you've started it it has to create the memory file toi emulate the SD card you told it was there.
My bet would be that you simply didn't wait long enough for it to boot up.
You can save yourself some time by checking the option to save snapshots and start from them (it'll save you start time after the first time at least). Another emulator speed-up is to open your run configuration for whatever app you are going to run, click on the "Target" tab, and check the box to "Disable Boot Animation".
|
8,324,359 |
I am a beginner in Java programming. Using JavaMail API, I wrote a program to send emails. Now I need to create a front end and connect those. I use only Notepad to write programs, I don't use any IDE. How to create front end easily and connect to my program?
My program is:
```java
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import java.util.*;
public class Mailer {
public void Mailer() throws Exception {
String usrname;
String pwd;
Scanner in = new Scanner(System.in);
System.out.println("\nEnter the gmail user name :");
usrname = in.next();
System.out.println("\nEnter the Password :");
pwd = in.next();
String HOST_NAME = "smtp.gmail.com";
int HOST_PORT = 465;
Properties props = new Properties();
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", HOST_NAME);
props.put("mail.smtps.auth", "true");
Session mailSession = Session.getDefaultInstance(props);
Transport transport = mailSession.getTransport();
String toadd;
System.out.println("\nEnter the Recipient Address:");
toadd = in.next();
MimeMessage message = new MimeMessage(mailSession);
System.out.println("\nEnter the Subject:");
String sub = in.nextLine();
message.setSubject(sub);
System.out.println("\nEnter the message body:");
String body = in.nextLine();
message.setContent(body, "text/plain");
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toadd));
transport.connect(HOST_NAME, HOST_PORT, usrname, pwd);
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
System.out.println("Mail Sent successfully!!!!");
System.exit(0);
}
public static void main(String[] args) throws Exception {
System.out.println("*******************Welcome to Mailer*************************");
Mailer mail = new Mailer();
mail.Mailer();
}
}
```
|
2011/11/30
|
[
"https://Stackoverflow.com/questions/8324359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073084/"
] |
1. Factor out a method which takes parameters and do the email sending.
No system.out and system.in allowed in this method.
2. For a test, you can drive this method with your existing code parts
which reads parameters from console.
3. Make a GUI form which contains all input fields and probably some
button. Your code will start something like this: JFrame f = new
JFrame(); f.add(new JLabel("to")); ... f.setVisible(true); You have
to learn a lot about component layouts. This code can be in the 'main' method for simplicity.
4. Wire your frontend with the backend: create an actionListener method
on the button which collects parameters from the input fields (getText()) and
invokes the email sender method.
That's all. :)
|
1,644,694 |
$$a^2+ab+b^2\ge 3(a+b-1)$$
$a,b$ are real numbers
using $AM\ge GM$
I proved that
$$a^2+b^2+ab\ge 3ab$$
$$(a^2+b^2+ab)/3\ge 3ab$$
how do I prove that $$3ab\ge 3(a+b-1)$$
if I'm able to prove the above inequality then i'll be done
|
2016/02/07
|
[
"https://math.stackexchange.com/questions/1644694",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/300970/"
] |
**Hint**: Let $a=x+1$ and $b=y+1$ (in the original inequality).
|
55,577,262 |
Using `@WebMvcTest` will auto-configure all web layer beans by looking for a `@SpringBootConfiguration` class (such as `@SpringBootApplication`).
If the configuration class is in a different package and can't be found by scanning, can I provide it directly to `@WebMvcTest`?
|
2019/04/08
|
[
"https://Stackoverflow.com/questions/55577262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9773274/"
] |
The following will point to the correct `@SpringBootApplication` class:
```
@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(controllers = {MyController.class})
@ContextConfiguration(classes={MySpringBootApplicationClass.class})
public class MyControllerTest {
//...
}
```
|
10,537,897 |
How can I override spring messages like 'Bad Credentials'?
I've configured my servlet context file with following beans
```
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="WEB-INF/messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
```
I'm able to use `<spring:message>` tag to display messages from my custom file . In the same file I've redefined all messages that are mapped to 'Bad Credentials' in spring-security-core.jar (messages.properties file) but they are not used. I still see 'Bad Credentials' message.
How can I override these spring messages?
|
2012/05/10
|
[
"https://Stackoverflow.com/questions/10537897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547750/"
] |
It turns out that these beans should be defined in general application context and not in myservlet-servlet.xml file. Once I moved the definitions from servlet context it started to work as expected.
|
54,908,164 |
jQuery newbie. My goal is to loop through each article and append the img to the div with the class body. The problem is its taking every image and appending to the div with the class body. Thanks!
My Script
```
jQuery('article .date').each(function() {
jQuery(this).closest('article').find('img').after(this);
});
```
Markup
```
<article>
<div class="date">Feb 22, 2019</div>
<div class="body">
<img src="imagone.png">
Some random text
</div>
</article>
<article>
<div class="date">Feb 23, 2019</div>
<div class="body">
<img src="imagtwo.png">
Some random text
</div>
</article>
<article>
<div class="date">Feb 24, 2019</div>
<div class="body">
<img src="imagthree.png">
Some random text
</div>
</article>
```
Desired markup
```
<article>
<div class="date">Feb 22, 2019</div><img src="imagone.png">
<div class="body">
Some random text
</div>
</article>
<article>
<div class="date">Feb 23, 2019</div><img src="imagtwo.png">
<div class="body">
Some random text
</div>
</article>
<article>
<div class="date">Feb 24, 2019</div><img src="imagthree.png">
<div class="body">
Some random text
</div>
</article>
```
|
2019/02/27
|
[
"https://Stackoverflow.com/questions/54908164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10529685/"
] |
You could slice a given array and take only five elements for getting an average.
```js
function standardDeviation(array) {
const arrAvg = tempArray => tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
return array.map((_, i, a) => arrAvg(a.slice(i, i + 5)));
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(standardDeviation(arr));
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.