Search is not available for this dataset
qid
int64
1
74.7M
question
stringlengths
1
70k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
0
60.5k
6,073,935
I have installed the Java 3D API on PC via the exe installer, which simply created a new directory with `j3dcore.jar`, `vecmath.jar`, `j3dutils.jar` in a lib sub-directory and `j3dcore-ogl.dll` in a bin sub-directory. Netbeans had no issues and my code compiled and executed smoothly, however once I built my project and tried to run it from the command prompt I got an `UnsatisfiedLinkError` saying that `no j3dcore-ogl in java.library.path`. Google came to the rescue and gave me 3 viable solutions: * by copying the dll file into my JRE's bin directory * by adding the path of the dll file to the library path (`java -Djava.library.path=dllpath`) * load the dll in the program with `System.load()` (I couldn't get this one to work, actually) My question is: Is there an elegant solution to this problem, that I missed? It seems tedious that for each different PC someone would like to use this program on, he'd have to either copy the dll or add it to the library path before it can run. (Side question: How come Netbeans didn't have a problem with the dll?)
2011/05/20
[ "https://Stackoverflow.com/questions/6073935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/639422/" ]
> > Making my Java program easily distributable > > > If you mean 'easy for the end user' look to [Java Web Start](https://stackoverflow.com/tags/java-web-start/info). --- A passer-by asks: > > Can you package the dll dependencies with Web Start? > > > Yes, but much, much better. You can package the natives for each platform in separate Jars, and supply them only to the platform that uses that native, even so far as partitioning the download between 32 & 64 bit versions of the natives. JWS puts the natives on the run-time class-path of the application, ready for loading in code. This all happens automatically for the end user, they click a link, approve the trust dialog(s) when asked, and the application installs - possibly with desktop integration, and appears on screen like magic. JWS apps. that use natives need to be distributed as `all-permissions` security level, because the JVM cannot guarantee the actions of anything that 'goes native'.
If you put the dlls in the same directory than you Jar, does it work? If yes, you could consider distributing it like this.
6,073,935
I have installed the Java 3D API on PC via the exe installer, which simply created a new directory with `j3dcore.jar`, `vecmath.jar`, `j3dutils.jar` in a lib sub-directory and `j3dcore-ogl.dll` in a bin sub-directory. Netbeans had no issues and my code compiled and executed smoothly, however once I built my project and tried to run it from the command prompt I got an `UnsatisfiedLinkError` saying that `no j3dcore-ogl in java.library.path`. Google came to the rescue and gave me 3 viable solutions: * by copying the dll file into my JRE's bin directory * by adding the path of the dll file to the library path (`java -Djava.library.path=dllpath`) * load the dll in the program with `System.load()` (I couldn't get this one to work, actually) My question is: Is there an elegant solution to this problem, that I missed? It seems tedious that for each different PC someone would like to use this program on, he'd have to either copy the dll or add it to the library path before it can run. (Side question: How come Netbeans didn't have a problem with the dll?)
2011/05/20
[ "https://Stackoverflow.com/questions/6073935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/639422/" ]
*Edit - After re-reading your question, your issue sounds different. However I'm able to get my running like so, by just dropping all dll files in the same directory as the .bat file starting the java process:* *java -classpath ./YourJar.jar;./lib/j3dcore.jar;./lib/vecmath.jar;./lib/j3dutils.jar package.MainClass* *And that works on multiple user's PCs, so I know simply dropping it in the working directory works.* I believe it depends on the version of Java being used - 64 bit or 32 bit. The correct dll file (of the same name) needs to be in the working directory. I think I was getting a similar problem when the wrong dll was being used, and it's not OS-dependent (if your 64 bit OS has 32-bit Java installed, you'd need the 32 bit j3dcore-ogl.dll file). So the question is, which version of Java are you using *(when running outside of your IDE)*, and which version of the dll are you putting (if any) in the working directory? I don't need any dll files in my path settings to get this working on other's PCs, and did not use System.load(), and did NOT copy files into my user's JRE/bin directory - so I know this is possible without the 3 options you mention.
If you put the dlls in the same directory than you Jar, does it work? If yes, you could consider distributing it like this.
6,073,935
I have installed the Java 3D API on PC via the exe installer, which simply created a new directory with `j3dcore.jar`, `vecmath.jar`, `j3dutils.jar` in a lib sub-directory and `j3dcore-ogl.dll` in a bin sub-directory. Netbeans had no issues and my code compiled and executed smoothly, however once I built my project and tried to run it from the command prompt I got an `UnsatisfiedLinkError` saying that `no j3dcore-ogl in java.library.path`. Google came to the rescue and gave me 3 viable solutions: * by copying the dll file into my JRE's bin directory * by adding the path of the dll file to the library path (`java -Djava.library.path=dllpath`) * load the dll in the program with `System.load()` (I couldn't get this one to work, actually) My question is: Is there an elegant solution to this problem, that I missed? It seems tedious that for each different PC someone would like to use this program on, he'd have to either copy the dll or add it to the library path before it can run. (Side question: How come Netbeans didn't have a problem with the dll?)
2011/05/20
[ "https://Stackoverflow.com/questions/6073935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/639422/" ]
> > Making my Java program easily distributable > > > If you mean 'easy for the end user' look to [Java Web Start](https://stackoverflow.com/tags/java-web-start/info). --- A passer-by asks: > > Can you package the dll dependencies with Web Start? > > > Yes, but much, much better. You can package the natives for each platform in separate Jars, and supply them only to the platform that uses that native, even so far as partitioning the download between 32 & 64 bit versions of the natives. JWS puts the natives on the run-time class-path of the application, ready for loading in code. This all happens automatically for the end user, they click a link, approve the trust dialog(s) when asked, and the application installs - possibly with desktop integration, and appears on screen like magic. JWS apps. that use natives need to be distributed as `all-permissions` security level, because the JVM cannot guarantee the actions of anything that 'goes native'.
I guess DLL are searched in all folders in %PATH% on windows. (LD\_LIBRARY\_PATH for UNIX flavors) Could you try by adding the path to dll to %path% variable? It appears that you are trying package a product with many jars as dependencies. You may benefit from [One-Jar](http://one-jar.sourceforge.net/index.php?page=details&file=native). It claims to have native dll support.
6,073,935
I have installed the Java 3D API on PC via the exe installer, which simply created a new directory with `j3dcore.jar`, `vecmath.jar`, `j3dutils.jar` in a lib sub-directory and `j3dcore-ogl.dll` in a bin sub-directory. Netbeans had no issues and my code compiled and executed smoothly, however once I built my project and tried to run it from the command prompt I got an `UnsatisfiedLinkError` saying that `no j3dcore-ogl in java.library.path`. Google came to the rescue and gave me 3 viable solutions: * by copying the dll file into my JRE's bin directory * by adding the path of the dll file to the library path (`java -Djava.library.path=dllpath`) * load the dll in the program with `System.load()` (I couldn't get this one to work, actually) My question is: Is there an elegant solution to this problem, that I missed? It seems tedious that for each different PC someone would like to use this program on, he'd have to either copy the dll or add it to the library path before it can run. (Side question: How come Netbeans didn't have a problem with the dll?)
2011/05/20
[ "https://Stackoverflow.com/questions/6073935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/639422/" ]
*Edit - After re-reading your question, your issue sounds different. However I'm able to get my running like so, by just dropping all dll files in the same directory as the .bat file starting the java process:* *java -classpath ./YourJar.jar;./lib/j3dcore.jar;./lib/vecmath.jar;./lib/j3dutils.jar package.MainClass* *And that works on multiple user's PCs, so I know simply dropping it in the working directory works.* I believe it depends on the version of Java being used - 64 bit or 32 bit. The correct dll file (of the same name) needs to be in the working directory. I think I was getting a similar problem when the wrong dll was being used, and it's not OS-dependent (if your 64 bit OS has 32-bit Java installed, you'd need the 32 bit j3dcore-ogl.dll file). So the question is, which version of Java are you using *(when running outside of your IDE)*, and which version of the dll are you putting (if any) in the working directory? I don't need any dll files in my path settings to get this working on other's PCs, and did not use System.load(), and did NOT copy files into my user's JRE/bin directory - so I know this is possible without the 3 options you mention.
I guess DLL are searched in all folders in %PATH% on windows. (LD\_LIBRARY\_PATH for UNIX flavors) Could you try by adding the path to dll to %path% variable? It appears that you are trying package a product with many jars as dependencies. You may benefit from [One-Jar](http://one-jar.sourceforge.net/index.php?page=details&file=native). It claims to have native dll support.
44,608,964
``` pt=new Date(2019,11,12,8,2,3) console.log(pt.getFullYear()," ",pt.getMonth()); ``` gives result `2019 " " 11` ``` console.log(pt.getFullYear()+" "+pt.getMonth()); ``` gives the result as `2019 11` What is the difference between using, and + in this example?
2017/06/17
[ "https://Stackoverflow.com/questions/44608964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3967709/" ]
The first of these gives three separate arguments to console.log, while the second appends the three together, then passes that as a single argument to console.log.
With the (,) you're with the console.log you're requesting to show a separate group of items as string, making a kind of array. When you put the (+) symbol you are adding the strings, and in this case the " " is just adding a space between the first and the second string. It is called concatenation.
44,608,964
``` pt=new Date(2019,11,12,8,2,3) console.log(pt.getFullYear()," ",pt.getMonth()); ``` gives result `2019 " " 11` ``` console.log(pt.getFullYear()+" "+pt.getMonth()); ``` gives the result as `2019 11` What is the difference between using, and + in this example?
2017/06/17
[ "https://Stackoverflow.com/questions/44608964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3967709/" ]
The first of these gives three separate arguments to console.log, while the second appends the three together, then passes that as a single argument to console.log.
console.log is part of the Console API and is accesible in various browsers. You can find its full documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Console/log). It states that console log has the following parameters: ``` obj1 ... objN ``` > > A list of JavaScript objects to output. The string representations of > each of these objects are appended together in the order listed and > output. > > > So, when you concatenate the parameters you pass only one object to the function and when you pass multiple parameters `console.log` will do the concatenation for you.
44,608,964
``` pt=new Date(2019,11,12,8,2,3) console.log(pt.getFullYear()," ",pt.getMonth()); ``` gives result `2019 " " 11` ``` console.log(pt.getFullYear()+" "+pt.getMonth()); ``` gives the result as `2019 11` What is the difference between using, and + in this example?
2017/06/17
[ "https://Stackoverflow.com/questions/44608964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3967709/" ]
``` console.log(pt.getFullYear()," ",pt.getMonth()); ``` The above example passes three separate arguments to console.log. What it outputs depends on how `console.log` is implemented. It has changed over time and is little bit different between browsers. When invoked with arguments like in the example, it has access to the variables and can display them with some magic depending on type, for example if they are arrays or objects. In your example it is displayed as: ``` 2019 " " 11 ``` where the numbers are in blue text, indicating that it was a variable of type number, and the empty string is shown in red, indicating that is was a string. Compare this to the following example, where it all is converted to a string before being passed to `console.log` in one argument: ``` console.log(pt.getFullYear()+" "+pt.getMonth()); ``` where it is displayed as ``` 2017 5 ``` with black text, indicating that it was passed as a string in the first parameter. The first parameter to `console.log` can be used as a format string, like `printf` in c and other languages. For example ``` console.log( "%d %d", pt.getFullYear(), pt.getMonth() ); ``` where %d is a place holder for a number. The output is in black text and gives the exact same output as your second example. ``` console.log("%d %d", pt.getFullYear(),pt.getMonth(), pt.getDate()); ``` In the example above, the year and month will be shown in black text, but the date will be in blue. This is because the format string only have two placeholders, but there are three arguments. `console.log` show the extra arguments, using the magic. Documentation: * [Standard](https://console.spec.whatwg.org/) * [Google Chrome](https://developers.google.com/web/tools/chrome-devtools/console/console-reference). * [Mozilla Firefox](https://developer.mozilla.org/en-US/docs/Web/API/Console) * [Microsoft Edge](https://msdn.microsoft.com/library/hh772169.aspx) * [Apple Safari](https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html) * [Opera](http://www.opera.com/dragonfly/documentation/console/)
With the (,) you're with the console.log you're requesting to show a separate group of items as string, making a kind of array. When you put the (+) symbol you are adding the strings, and in this case the " " is just adding a space between the first and the second string. It is called concatenation.
44,608,964
``` pt=new Date(2019,11,12,8,2,3) console.log(pt.getFullYear()," ",pt.getMonth()); ``` gives result `2019 " " 11` ``` console.log(pt.getFullYear()+" "+pt.getMonth()); ``` gives the result as `2019 11` What is the difference between using, and + in this example?
2017/06/17
[ "https://Stackoverflow.com/questions/44608964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3967709/" ]
``` console.log(pt.getFullYear()," ",pt.getMonth()); ``` The above example passes three separate arguments to console.log. What it outputs depends on how `console.log` is implemented. It has changed over time and is little bit different between browsers. When invoked with arguments like in the example, it has access to the variables and can display them with some magic depending on type, for example if they are arrays or objects. In your example it is displayed as: ``` 2019 " " 11 ``` where the numbers are in blue text, indicating that it was a variable of type number, and the empty string is shown in red, indicating that is was a string. Compare this to the following example, where it all is converted to a string before being passed to `console.log` in one argument: ``` console.log(pt.getFullYear()+" "+pt.getMonth()); ``` where it is displayed as ``` 2017 5 ``` with black text, indicating that it was passed as a string in the first parameter. The first parameter to `console.log` can be used as a format string, like `printf` in c and other languages. For example ``` console.log( "%d %d", pt.getFullYear(), pt.getMonth() ); ``` where %d is a place holder for a number. The output is in black text and gives the exact same output as your second example. ``` console.log("%d %d", pt.getFullYear(),pt.getMonth(), pt.getDate()); ``` In the example above, the year and month will be shown in black text, but the date will be in blue. This is because the format string only have two placeholders, but there are three arguments. `console.log` show the extra arguments, using the magic. Documentation: * [Standard](https://console.spec.whatwg.org/) * [Google Chrome](https://developers.google.com/web/tools/chrome-devtools/console/console-reference). * [Mozilla Firefox](https://developer.mozilla.org/en-US/docs/Web/API/Console) * [Microsoft Edge](https://msdn.microsoft.com/library/hh772169.aspx) * [Apple Safari](https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html) * [Opera](http://www.opera.com/dragonfly/documentation/console/)
console.log is part of the Console API and is accesible in various browsers. You can find its full documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Console/log). It states that console log has the following parameters: ``` obj1 ... objN ``` > > A list of JavaScript objects to output. The string representations of > each of these objects are appended together in the order listed and > output. > > > So, when you concatenate the parameters you pass only one object to the function and when you pass multiple parameters `console.log` will do the concatenation for you.
343,937
I need to take some online tests for school. This website tells me I need Flash Player 11.3.0 or higher. As far as I can see that is not yet avaible for Linux. I use Ubuntu 12.04 LTS and Chromium. Is there a way I can work around it? Greetz. Rob.
2013/09/10
[ "https://askubuntu.com/questions/343937", "https://askubuntu.com", "https://askubuntu.com/users/191781/" ]
The best way to get Flash Player 11.2+ is to use Google Chrome in Ubuntu. There is no other way to get it, because a higher version has not been released for Ubuntu. [Download Google Chrome From Here](https://www.google.com/intl/en/chrome/browser/) Select your OS version x86 or x64 and download it to any path. Then you can open it with the Ubuntu Software Center to install. You can also install by executing command: ``` sudo dpkg -i <googlechromefile.deb> ``` Hope it helps you somewhat!!
sudo apt-get install wine Download Firefox for Windows Visit Youtube and install the addon that pops up. You now have the latest version of Flash!
40,155,466
we got homework to make convertor of weights where the fields are updated while typing the number (no need to click "calculate" or anything). one of the students offered the code below. the code works: when putting a number in field 1, field 2 changes while typing. what i dont understand is how does that work? in the `onKey` method, no value is given to `View` `int` and `keyEvent` so how does the listener "knows" on which view to and what keys to listen to or what event to activate ? ``` public class Screen extends Activity { double weight = 2.20462; EditText kgEdit, lbsEdit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); kgEdit = (EditText) findViewById(R.id.kgEdit); lbsEdit = (EditText) findViewById(R.id.lbsEdit); kgEdit.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { String kg = kgEdit.getText().toString(); if (kg.isEmpty()) { lbsEdit.setText(""); } else { double num = Double.valueOf(kgEdit.getText().toString()) * weight; lbsEdit.setText(num + ""); } return false; } }); lbsEdit.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { String lbs = lbsEdit.getText().toString(); if (lbs.isEmpty()) { kgEdit.setText(""); } else { double num = Double.valueOf(lbsEdit.getText().toString()) / weight; kgEdit.setText(num + ""); } return false; } }); } ``` }
2016/10/20
[ "https://Stackoverflow.com/questions/40155466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932394/" ]
I'm going to focus on just 1 of the text fields to answer this. Look at this first line: `kgEdit = (EditText) findViewById(R.id.kgEdit);` All this does is get a reference to the `EditText` for entering kg. Now that there is a reference, we can call methods on that object. Next, we have this: ``` kgEdit.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { // ... } } ``` What the above does is the following. Take our reference to the `EditText` for kilograms that we retrieved in our first line. The method `setOnKeyListener` does the following (from [here](https://developer.android.com/reference/android/view/View.html#setOnKeyListener(android.view.View.OnKeyListener))): "Register a callback to be invoked when a hardware key is pressed in this view." What this means is that you've now told the view that you want to be informed every time the user presses a key while this EditText has the focus. You make this call to the Android API and in the background Android handles everything you're asking. It will call the method with the `View view`, `int keyCode` and `KeyEvent event`. You give it a method that then handles those inputs. So nowhere in your code do you need to call the method, Android calls it in the background where you'll never have to see or worry about it. Now, because you called the method on `kgEdit`, that means the following code will ONLY be called when `kgEdit` is focused and keys are typed, so there's no confusion with the other `EditText`. It gets its own method call later, just below. Here's the rest of the code inside the `setOnKeyListener`: ``` String kg = kgEdit.getText().toString(); if (kg.isEmpty()) { lbsEdit.setText(""); } else { double num = Double.valueOf(kgEdit.getText().toString()) * weight; lbsEdit.setText(num + ""); } return false; ``` What this does is get the current text in `kgEdit`, which has already been updated with the key the user pressed. And it just checks if the text is empty, and if so remove the text in `lbsEdit`. If it's not empty, then get the text, convert it to a number, convert the number from kg to lbs and update `lbsEdit`
You have to use addTextChangedListener like this- ``` EditText editText = (EditText) findViewById(R.id.editText1); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { //do here your calculation String data = s.toString(); } }); ```
19,074,447
I have to go into a table to retrieve a parameter, then go back into the same table to retrieve data based on the parameter. ``` <cfquery name = "selnm" datasource = "Moxart"> select SelName from AuxXref where Fieldname = <cfqueryparam value = "#orig#"> </cfquery> <cfset selname = selnm.SelName> <cfquery name = "fld" datasource = "Moxart"> select Fieldname, DBname from AuxXref where SelName = <cfqueryparam value = "#selname#"> </cfquery> ``` Can this be done in a single query?
2013/09/29
[ "https://Stackoverflow.com/questions/19074447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1497281/" ]
You can do this in one query like so: ``` <cfquery name = "fld" datasource = "Moxart"> select Fieldname, DBname, SelName from AuxXref where SelName = <cfqueryparam value = "#orig#"> AND FieldName = <cfqueryparam value = "#orig#"> </cfquery> ```
Something like this might satisfy your requirements. ``` select fieldname, DBname from AuxXref where selname in (select distinct selname from auxXref where fieldname = <cfqueryparam value = "#orig#"> ) and fieldname <> <cfqueryparam value = "#orig#"> ``` If the subquery returns more than one row, and you only want one, then you'll have to specify which one you want.
115,794
**Rules** 1. Place some pentominoes into an 8 x 8 grid. They do not touch each other. They can touch only diagonally (with corner). 2. Pentominoes cannot repeat in the grid. Rotations and reflections of a pentomino are considered the same shape. 3. Grid is 8 x 8.
2022/04/17
[ "https://puzzling.stackexchange.com/questions/115794", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/79520/" ]
With integer programming, I managed to place > > 8 pieces, proved to be optimal > > > like this. > > $$\begin{array}{cccccccc} 3&3&3&3& &5&5&5\\ 3& & & & &5& &5\\ &4&4&4&4& &A&\\ 6& & &4& &A&A&A\\ 6&6&6& &8& &A&\\ & &6& &8&8& &B\\ 2&2& &8&8& &B&B\\2&2&2& & &B&B&\\ \end{array}$$ > > > Here is my formulation. I happened to solve a similar model to solve a puzzle called One puzzle a day. Let $B$ be the set of cells in the 8x8 board, and $P$ be the set of all kinds of pieces (rotating and flipping count difference here), so I have $|P|=63$, then we need to choose a subset of $P$ and place them only by translation. Let binary variable $x\_{pb}$ indicate whether the piece $p$ is placed on the cell $b$ (some predefined reference point on the piece being on $b$). Let the set $P\_i\subset P$ represent all flipped and rotated version of a same pentomino, and binary variable $y\_i$ indicates whether the pentomino $i$ is placed on the board, so we have $$ y\_i = \sum\_{p\in P\_i} \sum\_{b\in B} x\_{pb} $$ and the objective is to maximize $\sum\_i y\_i$. Putting the reference point on some cells make the tile out of the board, let that set be $F\_p$, we have $$ x\_{pb} = 0 \quad\forall b \in F\_p. $$ Now the main part. Actually in every cell $b$, we could find all possible $(p,b')$ that will cover the cell $b$, say the set is $Covered(b)$. By constraining $\sum\_{Covered(b)} x\_{pb'} \leq 1$, we could prevent overlap. To prevent neighboring, I build sets $Edge(b) = \{(p, b')\}$ similarly, which means if putting $p$ in $b'$, the cell $b$ will be on the edge of that piece. Then we need some constraints like $$ \alpha \sum\_{(p,b')\in Covered(b)} x\_{pb'} + \beta \sum\_{(p,b') \in Edge(b)} x\_{pb'} \leq \delta $$ The parameters $\alpha, \beta, \delta >0$should satisfy that $\alpha \leq \delta$, $4\beta \leq \delta$, $\alpha + \beta > \delta$, $2\alpha > \delta$, meaning that "one cover is allowed", "four edges on the same cell is allowed", "one cover and one edge is not allowed" (that is when two pieces are next to each other) and "no overlap". I chose $\alpha=\delta=1, \beta=0.25$ (actually any $\beta > 0$ works...). That is all constraints we need.
I can manage > > seven pentominoes, in a few different ways: > > > > [![seven pentominoes](https://i.stack.imgur.com/FPIEH.png)](https://i.stack.imgur.com/FPIEH.png) [![seven again](https://i.stack.imgur.com/rVcqQ.png)](https://i.stack.imgur.com/rVcqQ.png) > > > There is an obvious upper bound of > > twelve (the total number of distinct pentominoes, and $12\times5$ is still less than the number of squares on the board), > > > but this is nowhere near achievable given the restriction that pentominoes are not allowed to touch each other orthogonally. This means that > > every placed pentomino creates at least 4 squares around it that no other pentomino can occupy. *At least* 4, in the best possible scenario where the pentomino is placed in a corner - usually more. (I think 4 is only achievable with the P-pentomino in the corner and 5 is only achievable with the symmetric L-pentomino in the corner, otherwise it's more.) > > > Because of this, I'm pretty sure the number I managed above is optimal and it's not possible to place more.
115,794
**Rules** 1. Place some pentominoes into an 8 x 8 grid. They do not touch each other. They can touch only diagonally (with corner). 2. Pentominoes cannot repeat in the grid. Rotations and reflections of a pentomino are considered the same shape. 3. Grid is 8 x 8.
2022/04/17
[ "https://puzzling.stackexchange.com/questions/115794", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/79520/" ]
I solved this completely by hand. > > ![solution with 8 pentominos](https://i.stack.imgur.com/0ksZz.png) > > > Here is a clean proof of its optimality. No computer is needed. Mere pencil and paper suffice. Expand each pentomino by adding little right-angled isosceles triangles with area 1/4 as follows: 1. For each (unit) cell with edge $A$ along its perimeter, add a little triangle with hypotenuse $A$ beside that cell. 2. For each pair of adjacent cells with adjacent edges $A,B$ along its perimeter, add a little triangle beside both the triangles that had been added beside those cells at $A,B$. 3. For the V-pentomino, add 2 more little triangles to completely fill in the region between the two arms of the "V". Here is an example (with added triangles yellow in step 1 and green in step 2):   ![F-pentomino with 12 triangles added in step 1 and 2 triangles added in step 2](https://i.stack.imgur.com/4Yh3T.png) Observe that the number of little triangles added is at least the perimeter, regardless of the pentomino. The perimeter is at least 12 except for the P-pentomino, but the P-pentomino has 4 little triangles added in step 2. Except the X-pentomino, every other pentomino has at least 2 little triangles added in step 2. Thus the expanded X-pentomino has area $5+12/4 = 8$, and the expanded P,F,W-pentominos have area $5+14/4 = 8.5$, and every other pentomino has area at least $5+16/4 = 9$. It is easy to see that, for any solution to the puzzle, the expanded pentominos will still not overlap. So if there are 9 distinct pentominos, then their total area is at least $8 + 8.5×3 + 9×5 = 78.5$. Now expand the 8×8 board as well in the same manner, which adds 15 little triangles to each side. The expanded board has area $8×8 + 15 = 79$, but at least one of the added triangles next to each side of the board will not be covered, so the actual covered area is at most 78. Hence 9 distinct pentominos cannot fit. --- In fact, we can show that 9 pentominos cannot fit even if each pentomino can be used 4 times! To see why, observe that each pentomino can only cover 6 units of the board perimeter, after which there is a gap of at least 1 unit before the next pentomino along the board perimeter. Let T be the expanded board area. Due to the gaps, not all of T can be covered by the pentominos. First, each isolated gap 'reduces' T by 1 unit. Two adjacent gaps 'reduces' T by at least 1.5 units (attained at the board corner). In general, $(k+1)$ adjacent gaps 'reduces' T by at least $(k+1)/2$ units. Thus the average reduction is at least 1/7 per board perimeter. Thus the gaps 'reduces' T by at least $\lceil32×1/7\rceil = 5$, so the covered expanded board area is at most $8×8 + 15 − 5 = 74$. But 9 pentominos (even with quadrupled pentominos) would have total area at least $8×4 + 8.5×5 = 74.5$. I presume that these bounds can be improved to show that 9 pentominos regardless of how many repeats cannot fit, but I did not bother to squeeze this last bit. --- An equivalent counting method is to count the cell edges instead of area. Each pentomino already has 15 or 16 cell edges, and between each pair of adjacent cells along its perimeter we can add 1/2 edge sticking out, because that goes at most halfway to any other pentomino. In total we would get at least 17 edges per pentomino except 16 for the X-pentomino, which corresponds to 8.5 area for each pentomino except 8 for the X-pentomino. The slight advantage of this counting is that it is easier to see where we are making losses. For instance, every untouched corner incurs a loss of at least 1 edge (i.e. 1/2×2), and this applies at the boundary as well, so we automatically know that we want to minimize the number of untouched corners. Also, every empty 2×2 square in the board incurs a loss of at least 2 edges, twice as bad as an untouched corner. I initially did not mention this approach because the area equivalent is a bit easier to understand. However, I have decided to add it in, because it is much easier to *write a program* that uses this for a branch-and-bound search that counts the total edges *plus the (necessary) losses* so far. This makes it easy to prune most branches of the search. We even get a reasonable heuristic for branch-ordering, namely to first try placing the next pentomino to minimize the total edges+loss so far.
I can manage > > seven pentominoes, in a few different ways: > > > > [![seven pentominoes](https://i.stack.imgur.com/FPIEH.png)](https://i.stack.imgur.com/FPIEH.png) [![seven again](https://i.stack.imgur.com/rVcqQ.png)](https://i.stack.imgur.com/rVcqQ.png) > > > There is an obvious upper bound of > > twelve (the total number of distinct pentominoes, and $12\times5$ is still less than the number of squares on the board), > > > but this is nowhere near achievable given the restriction that pentominoes are not allowed to touch each other orthogonally. This means that > > every placed pentomino creates at least 4 squares around it that no other pentomino can occupy. *At least* 4, in the best possible scenario where the pentomino is placed in a corner - usually more. (I think 4 is only achievable with the P-pentomino in the corner and 5 is only achievable with the symmetric L-pentomino in the corner, otherwise it's more.) > > > Because of this, I'm pretty sure the number I managed above is optimal and it's not possible to place more.
44,410,809
I'm looking for changing the **TextView** Sizes automatically. And I found the solution as well. Here is the official [Doc](https://developer.android.com/preview/features/autosizing-textview.html) for Auto sizing textviews. But Still I'm not able to resolve it. When i paste autoSizeTextType its showing error in xml file. Here is the my xml code and gradle code snippets myactivity.xml ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" android:orientation="vertical"> <include layout="@layout/toolbar" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" app:autoSizeTextType="uniform"/> </LinearLayout> ``` Gradle snippet ``` dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:support-v4:25.2.0'//Added support library compile 'com.android.support:appcompat-v7:25.2.0' compile 'com.android.support:design:25.2.0' testCompile 'junit:junit:4.12' } ```
2017/06/07
[ "https://Stackoverflow.com/questions/44410809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3824298/" ]
As stated in the [docs](https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html#setting-textview-autosize): > > The Support Library 26.0 provides full support to the autosizing TextView feature on devices running Android versions prior to Android 8.0 (API level 26). The library provides support to Android 4.0 (API level 14) and higher. **The android.support.v4.widget package contains the TextViewCompat** class to access features in a backward-compatible fashion. > > > You need to replace `TextView` with `AppCompatTextView` and upgrade your support lib to v26.0.0 in order to use that feature. ``` compile 'com.android.support:support-v4:26.0.0' ``` Don't forget to upgrade your `buildToolsVersion` to `26.0.0` and `compileSdkVersion` to `26` as well.
This API is available only from API level 26.
44,410,809
I'm looking for changing the **TextView** Sizes automatically. And I found the solution as well. Here is the official [Doc](https://developer.android.com/preview/features/autosizing-textview.html) for Auto sizing textviews. But Still I'm not able to resolve it. When i paste autoSizeTextType its showing error in xml file. Here is the my xml code and gradle code snippets myactivity.xml ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" android:orientation="vertical"> <include layout="@layout/toolbar" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" app:autoSizeTextType="uniform"/> </LinearLayout> ``` Gradle snippet ``` dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:support-v4:25.2.0'//Added support library compile 'com.android.support:appcompat-v7:25.2.0' compile 'com.android.support:design:25.2.0' testCompile 'junit:junit:4.12' } ```
2017/06/07
[ "https://Stackoverflow.com/questions/44410809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3824298/" ]
Use AppCompatTextView and supportLibrary 26.0.1 ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.AppCompatTextView android:layout_width="match_parent" android:layout_height="200dp" app:autoSizeTextType="uniform" /> </LinearLayout> ```
This API is available only from API level 26.
44,410,809
I'm looking for changing the **TextView** Sizes automatically. And I found the solution as well. Here is the official [Doc](https://developer.android.com/preview/features/autosizing-textview.html) for Auto sizing textviews. But Still I'm not able to resolve it. When i paste autoSizeTextType its showing error in xml file. Here is the my xml code and gradle code snippets myactivity.xml ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" android:orientation="vertical"> <include layout="@layout/toolbar" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" app:autoSizeTextType="uniform"/> </LinearLayout> ``` Gradle snippet ``` dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:support-v4:25.2.0'//Added support library compile 'com.android.support:appcompat-v7:25.2.0' compile 'com.android.support:design:25.2.0' testCompile 'junit:junit:4.12' } ```
2017/06/07
[ "https://Stackoverflow.com/questions/44410809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3824298/" ]
As stated in the [docs](https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html#setting-textview-autosize): > > The Support Library 26.0 provides full support to the autosizing TextView feature on devices running Android versions prior to Android 8.0 (API level 26). The library provides support to Android 4.0 (API level 14) and higher. **The android.support.v4.widget package contains the TextViewCompat** class to access features in a backward-compatible fashion. > > > You need to replace `TextView` with `AppCompatTextView` and upgrade your support lib to v26.0.0 in order to use that feature. ``` compile 'com.android.support:support-v4:26.0.0' ``` Don't forget to upgrade your `buildToolsVersion` to `26.0.0` and `compileSdkVersion` to `26` as well.
Use AppCompatTextView and supportLibrary 26.0.1 ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.AppCompatTextView android:layout_width="match_parent" android:layout_height="200dp" app:autoSizeTextType="uniform" /> </LinearLayout> ```
2,829,287
For example, User adds this "iamsmelly.com". And if I add an href to this, the link would be www.mywebsite.com/iamsmelly.com Is there a way to make it absolute if its not prepended by an http:// ? Or should I revert to jQuery for this?
2010/05/13
[ "https://Stackoverflow.com/questions/2829287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93311/" ]
Probably a good place to handle this is in a `before_save` on your model. I'm not aware of a predefined helper (though `auto_link` comes somewhat close) but a relatively simple regexp should do the job: ``` class User < ActiveRecord::Base before_save :check_links def check_links self.link = "http://" + self.link unless self.link.match /^(https?|ftp):\/\// end end ```
I've looked for something similar before with no luck. I made a helper method like so: ``` def ensure_absolute(str_link) (str_link.include?("http://") || str_link.include?("https://")) ? str_link : ("http://"+str_link) end ```
16,114,993
I have a `<div id="content">`. I want to load the content from <http://vietduc24h.com> into my `div`: ``` <html> <head> <script type="text/javascript"> $(document).ready(function() { $("#content").attr("src","http://vietduc24h.com"); }) </script> </head> <body> <div id="content"></div> </body> </html ``` I don't want to use an iframe. How can I do this?
2013/04/19
[ "https://Stackoverflow.com/questions/16114993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2300976/" ]
You need to think about CORS in this aspect. The code you need to have is: ``` <script type="text/javascript"> $(document).ready(function() { $("#content").load("http://vietduc24h.com"); }) </script> ``` When your domain is not inside `vietduc24h.com`, you might get some security exception. In order to avoid that, you can host a local proxy here. In PHP, we do this way (`url.php`): ``` <?php $url = file_get_contents(urlencode($_GET["url"])); echo $url; ?> ``` And in the script, you need to modify this way: ``` <script type="text/javascript"> $(document).ready(function() { $("#content").load("proxy.php?url=http://vietduc24h.com"); }) </script> ```
Try this code with the jQuery `Load` function: ``` $('#content').load('http://vietduc24h.com', function() { alert('Load was performed.'); }); ``` If you encounter in security issues because of the Cross-Origin-Resource-Sharing policy than you have to use a proxy in your server code.
16,114,993
I have a `<div id="content">`. I want to load the content from <http://vietduc24h.com> into my `div`: ``` <html> <head> <script type="text/javascript"> $(document).ready(function() { $("#content").attr("src","http://vietduc24h.com"); }) </script> </head> <body> <div id="content"></div> </body> </html ``` I don't want to use an iframe. How can I do this?
2013/04/19
[ "https://Stackoverflow.com/questions/16114993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2300976/" ]
Try this code with the jQuery `Load` function: ``` $('#content').load('http://vietduc24h.com', function() { alert('Load was performed.'); }); ``` If you encounter in security issues because of the Cross-Origin-Resource-Sharing policy than you have to use a proxy in your server code.
Try this: ``` $("#content").html('<object data="http://vietduc24h.com">'); ``` Taken from [this answer](https://stackoverflow.com/a/9964050/646668).
16,114,993
I have a `<div id="content">`. I want to load the content from <http://vietduc24h.com> into my `div`: ``` <html> <head> <script type="text/javascript"> $(document).ready(function() { $("#content").attr("src","http://vietduc24h.com"); }) </script> </head> <body> <div id="content"></div> </body> </html ``` I don't want to use an iframe. How can I do this?
2013/04/19
[ "https://Stackoverflow.com/questions/16114993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2300976/" ]
You need to think about CORS in this aspect. The code you need to have is: ``` <script type="text/javascript"> $(document).ready(function() { $("#content").load("http://vietduc24h.com"); }) </script> ``` When your domain is not inside `vietduc24h.com`, you might get some security exception. In order to avoid that, you can host a local proxy here. In PHP, we do this way (`url.php`): ``` <?php $url = file_get_contents(urlencode($_GET["url"])); echo $url; ?> ``` And in the script, you need to modify this way: ``` <script type="text/javascript"> $(document).ready(function() { $("#content").load("proxy.php?url=http://vietduc24h.com"); }) </script> ```
Try this: ``` $("#content").html('<object data="http://vietduc24h.com">'); ``` Taken from [this answer](https://stackoverflow.com/a/9964050/646668).
7,262,136
![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png) can we change text in this lightbox want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue"
2011/08/31
[ "https://Stackoverflow.com/questions/7262136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922283/" ]
It is always safe! (Math agrees with me.) The result of a mod operation is always less than the divisor. Since the result of a mod operation is essentially the remainder after performing integer division, you will never have a remainder larger than the divisor. I suspect the reason for having the operation return a `long` is because the divisor gets expanded to a `long` before the operation takes place. This makes a `long` result possible. (*note* even though the variable is expanded in memory, its value will not change. An expanded `int` will never be larger than an `int` can hold.)
As Marc B alluded to, Java will promote `b` to a `long` before actually doing the `%` operation. This promotion applies to all the arithmetic operations, even `<<` and `>>` I believe. In other words, if you have a binary operation and the two arguments don't have the same type, the smaller one will be promoted so that both sides will have the same type.
7,262,136
![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png) can we change text in this lightbox want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue"
2011/08/31
[ "https://Stackoverflow.com/questions/7262136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922283/" ]
For most (if not all) arithmetic operations, Java will assume you want the maximum defined precision. Imagine if you did this: ``` long a = ...; int b = ...; long c = a % b + Integer.MAX_VALUE; ``` If Java automatically down-casted `a % b` to an `int`, then the above code would cause an `int` overflow rather than setting `c` to a perfectly reasonable `long` value. This is the same reason that performing operations with a `double` and an `int` will produce a `double`. It's much safer to up-cast the least-accurate value to a more accurate one. Then if the programmer knows more than the compiler and wants to down-cast, he can do it explicitly. Update ------ Also, after thinking more about this, I'm guessing most CPU architectures don't have operations that combine 32-bit and 64-bit values. So the 32-bit value would need to be promoted to a 64-bit value just to use it as an argument to the CPU's mod operation, and the result of that operation would be a 64-bit value natively. A down-cast to an `int` would add an operation, which has performance implications. Combining that fact with the idea that you might actually want to keep a `long` value for other operations (as I mention above), it really wouldn't make sense to force the result into an `int` unless the developer explicitly wants it to be one.
It is always safe! (Math agrees with me.) The result of a mod operation is always less than the divisor. Since the result of a mod operation is essentially the remainder after performing integer division, you will never have a remainder larger than the divisor. I suspect the reason for having the operation return a `long` is because the divisor gets expanded to a `long` before the operation takes place. This makes a `long` result possible. (*note* even though the variable is expanded in memory, its value will not change. An expanded `int` will never be larger than an `int` can hold.)
7,262,136
![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png) can we change text in this lightbox want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue"
2011/08/31
[ "https://Stackoverflow.com/questions/7262136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922283/" ]
It is always safe! (Math agrees with me.) The result of a mod operation is always less than the divisor. Since the result of a mod operation is essentially the remainder after performing integer division, you will never have a remainder larger than the divisor. I suspect the reason for having the operation return a `long` is because the divisor gets expanded to a `long` before the operation takes place. This makes a `long` result possible. (*note* even though the variable is expanded in memory, its value will not change. An expanded `int` will never be larger than an `int` can hold.)
> > does any one know why Java has a longer type for % than needed? > > > I don't know for sure. Maybe to make it work exactly the same way as the other multiplicative operators: `*` and `\`. In the [JLS](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17) `The type of a multiplicative expression is the promoted type of its operands.` Adding an exception to `long % int` would be confusing.
7,262,136
![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png) can we change text in this lightbox want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue"
2011/08/31
[ "https://Stackoverflow.com/questions/7262136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922283/" ]
It is always safe! (Math agrees with me.) The result of a mod operation is always less than the divisor. Since the result of a mod operation is essentially the remainder after performing integer division, you will never have a remainder larger than the divisor. I suspect the reason for having the operation return a `long` is because the divisor gets expanded to a `long` before the operation takes place. This makes a `long` result possible. (*note* even though the variable is expanded in memory, its value will not change. An expanded `int` will never be larger than an `int` can hold.)
This is a late party chime-in but the reason is pretty simple: The bytecode operands do need explicit casts (`L2I`) and longs need 2 stack positions compared to 1 for int, char, short, byte [casting from byte to int doesn't need a bytecode instruction]. After the mod operation the result takes 2 positions on the top of stack. *edit:* Also, I forgot to mention Java doesn't have division/remainder of 64b/32b. There are only 64->64bit operations, i.e. `LDIV` and `LREM`.
7,262,136
![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png) can we change text in this lightbox want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue"
2011/08/31
[ "https://Stackoverflow.com/questions/7262136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922283/" ]
For most (if not all) arithmetic operations, Java will assume you want the maximum defined precision. Imagine if you did this: ``` long a = ...; int b = ...; long c = a % b + Integer.MAX_VALUE; ``` If Java automatically down-casted `a % b` to an `int`, then the above code would cause an `int` overflow rather than setting `c` to a perfectly reasonable `long` value. This is the same reason that performing operations with a `double` and an `int` will produce a `double`. It's much safer to up-cast the least-accurate value to a more accurate one. Then if the programmer knows more than the compiler and wants to down-cast, he can do it explicitly. Update ------ Also, after thinking more about this, I'm guessing most CPU architectures don't have operations that combine 32-bit and 64-bit values. So the 32-bit value would need to be promoted to a 64-bit value just to use it as an argument to the CPU's mod operation, and the result of that operation would be a 64-bit value natively. A down-cast to an `int` would add an operation, which has performance implications. Combining that fact with the idea that you might actually want to keep a `long` value for other operations (as I mention above), it really wouldn't make sense to force the result into an `int` unless the developer explicitly wants it to be one.
As Marc B alluded to, Java will promote `b` to a `long` before actually doing the `%` operation. This promotion applies to all the arithmetic operations, even `<<` and `>>` I believe. In other words, if you have a binary operation and the two arguments don't have the same type, the smaller one will be promoted so that both sides will have the same type.
7,262,136
![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png) can we change text in this lightbox want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue"
2011/08/31
[ "https://Stackoverflow.com/questions/7262136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922283/" ]
As Marc B alluded to, Java will promote `b` to a `long` before actually doing the `%` operation. This promotion applies to all the arithmetic operations, even `<<` and `>>` I believe. In other words, if you have a binary operation and the two arguments don't have the same type, the smaller one will be promoted so that both sides will have the same type.
> > does any one know why Java has a longer type for % than needed? > > > I don't know for sure. Maybe to make it work exactly the same way as the other multiplicative operators: `*` and `\`. In the [JLS](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17) `The type of a multiplicative expression is the promoted type of its operands.` Adding an exception to `long % int` would be confusing.
7,262,136
![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png) can we change text in this lightbox want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue"
2011/08/31
[ "https://Stackoverflow.com/questions/7262136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922283/" ]
For most (if not all) arithmetic operations, Java will assume you want the maximum defined precision. Imagine if you did this: ``` long a = ...; int b = ...; long c = a % b + Integer.MAX_VALUE; ``` If Java automatically down-casted `a % b` to an `int`, then the above code would cause an `int` overflow rather than setting `c` to a perfectly reasonable `long` value. This is the same reason that performing operations with a `double` and an `int` will produce a `double`. It's much safer to up-cast the least-accurate value to a more accurate one. Then if the programmer knows more than the compiler and wants to down-cast, he can do it explicitly. Update ------ Also, after thinking more about this, I'm guessing most CPU architectures don't have operations that combine 32-bit and 64-bit values. So the 32-bit value would need to be promoted to a 64-bit value just to use it as an argument to the CPU's mod operation, and the result of that operation would be a 64-bit value natively. A down-cast to an `int` would add an operation, which has performance implications. Combining that fact with the idea that you might actually want to keep a `long` value for other operations (as I mention above), it really wouldn't make sense to force the result into an `int` unless the developer explicitly wants it to be one.
> > does any one know why Java has a longer type for % than needed? > > > I don't know for sure. Maybe to make it work exactly the same way as the other multiplicative operators: `*` and `\`. In the [JLS](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17) `The type of a multiplicative expression is the promoted type of its operands.` Adding an exception to `long % int` would be confusing.
7,262,136
![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png) can we change text in this lightbox want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue"
2011/08/31
[ "https://Stackoverflow.com/questions/7262136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922283/" ]
For most (if not all) arithmetic operations, Java will assume you want the maximum defined precision. Imagine if you did this: ``` long a = ...; int b = ...; long c = a % b + Integer.MAX_VALUE; ``` If Java automatically down-casted `a % b` to an `int`, then the above code would cause an `int` overflow rather than setting `c` to a perfectly reasonable `long` value. This is the same reason that performing operations with a `double` and an `int` will produce a `double`. It's much safer to up-cast the least-accurate value to a more accurate one. Then if the programmer knows more than the compiler and wants to down-cast, he can do it explicitly. Update ------ Also, after thinking more about this, I'm guessing most CPU architectures don't have operations that combine 32-bit and 64-bit values. So the 32-bit value would need to be promoted to a 64-bit value just to use it as an argument to the CPU's mod operation, and the result of that operation would be a 64-bit value natively. A down-cast to an `int` would add an operation, which has performance implications. Combining that fact with the idea that you might actually want to keep a `long` value for other operations (as I mention above), it really wouldn't make sense to force the result into an `int` unless the developer explicitly wants it to be one.
This is a late party chime-in but the reason is pretty simple: The bytecode operands do need explicit casts (`L2I`) and longs need 2 stack positions compared to 1 for int, char, short, byte [casting from byte to int doesn't need a bytecode instruction]. After the mod operation the result takes 2 positions on the top of stack. *edit:* Also, I forgot to mention Java doesn't have division/remainder of 64b/32b. There are only 64->64bit operations, i.e. `LDIV` and `LREM`.
7,262,136
![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png) can we change text in this lightbox want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue"
2011/08/31
[ "https://Stackoverflow.com/questions/7262136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922283/" ]
This is a late party chime-in but the reason is pretty simple: The bytecode operands do need explicit casts (`L2I`) and longs need 2 stack positions compared to 1 for int, char, short, byte [casting from byte to int doesn't need a bytecode instruction]. After the mod operation the result takes 2 positions on the top of stack. *edit:* Also, I forgot to mention Java doesn't have division/remainder of 64b/32b. There are only 64->64bit operations, i.e. `LDIV` and `LREM`.
> > does any one know why Java has a longer type for % than needed? > > > I don't know for sure. Maybe to make it work exactly the same way as the other multiplicative operators: `*` and `\`. In the [JLS](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17) `The type of a multiplicative expression is the promoted type of its operands.` Adding an exception to `long % int` would be confusing.
45,507,197
This is about converting the enumeration values to a string array. I have an enumeration: ``` enum Weather { RAINY, SUNNY, STORMY } ``` And I want to convert this to a string array with minimal effort and no loops with Java 8+. This is the best I came up with: ``` Arrays.stream(Weather.values()).map(Enum::toString).toArray(String[]::new) ``` Any other and similarly or more convenient ways to do the same thing?
2017/08/04
[ "https://Stackoverflow.com/questions/45507197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2735286/" ]
Original post ============= Yes, that's a good Java 8 way, but... The `toString` can be overridden, so you'd better go with `Weather::name` which returns the name of an enum constant (exactly as declared in the enum declaration) and can't be changed: ``` Stream.of(Weather.values()).map(Weather::name).toArray(String[]::new); ``` --- A bit of generics ================= I wrote a helper class to deal with any enum in a generic way: ``` class EnumUtils { public static <T extends Enum<T>> String[] getStringValues(Class<T> enumClass) { return getStringValuesWithStringExtractor(enumClass, Enum::name); } public static <T extends Enum<T>> String[] getStringValuesWithStringExtractor( Class<T> enumClass, Function<? super T, String> extractor ) { return of(enumClass.getEnumConstants()).map(extractor).toArray(String[]::new); } } ``` Here is a demonstration: ``` enum Weather { RAINY, SUNNY, STORMY; @Override public String toString() { return String.valueOf(hashCode()); } public static void main(String[] args) { System.out.println(Arrays.toString(EnumUtils.getStringValues(Weather.class))); System.out.println(Arrays.toString(EnumUtils.getStringValuesWithStringExtractor(Weather.class, Weather::toString))); } } ``` And the output: ``` [RAINY, SUNNY, STORMY] [359023572, 305808283, 2111991224] ```
If you're frequently converting enum values to any kind of array you can as well precompute it values as static field: ``` enum Weather { RAINY, SUNNY, STORMY; public static final String[] STRINGS = Arrays.stream(Weather.values()) .map(Enum::name) .collect(Collectors.toList()) .toArray(new String[0]); } ``` And use it just like that `Weather.STRINGS;`.
26,351
I was studying for icing and a tailplane stall. I have looked up some internet pages and instrument flying handbook, and found the procedure below. 1. raise flaps to the previous setting. (To reduce down wash from the main wing so that reducing negative angle of attack of the tail and break the stall) 2. apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?) 3. do not increase airspeed unless it is necessary to avoid a wing stall. (Why shouldn't we increase airspeed?) So now I'm trying to understand the reason why should a pilot do such actions. Can you help me out?
2016/03/23
[ "https://aviation.stackexchange.com/questions/26351", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/6831/" ]
Lets start with the very basic concepts.... In most aircraft, the Centre of Gravity (cg) is somewhat forward of the wing or mainplane Centre of Pressure. The exact distance between the cg and the Centre of pressure will depend on aircraft loading, configuration, thrust setting and drag. However, cg forward of the Centre of Pressure produces a nose-down pitching moment. The horizontal stabilizer, or tailplane, then provides a downward force to overcome this normal, nose-down, pitching moment. The tailplane behaves as an ‘upside down’ wing and operates with negative Angle of Attack (AOA) as shown in Figure 1 ***Positive and Negative Angle of Attack*** ![enter image description here](https://i.stack.imgur.com/60asc.jpg) Figure 1 - Positive and Negative Angle of Attack If the horizontal stabiliser becomes contaminated with ice, airflow separation from the surface can prevent it from providing sufficient downward force or negative lift to balance the aircraft and a nose-down pitch upset can occur. When compared to an aircraft's mainplane, the horizontal stabiliser normally has a thinner aerofoil with a sharper leading edge. Differences in the ice collection efficiency or catch rate between the two surfaces means ice accumulates faster on the horizontal stabiliser and may form before any ice is present on the aircraft's mainplane. Tailplane stall can occur at relatively high speeds, well above the normal 1G stall speed of the mainplane. Typically, tailplane stall induced by icing is most likely to occur near the flap limit speed when the flaps are extended to the landing position, especially when extension is combined with a nose down pitching manoeuvre, airspeed change, power change or flight through turbulence. Aircraft stall warning systems provide warnings based on an uncontaminated mainplane stall so during a tailplane stall induced upset there will be NO artificial stall warning indications, such as a stick shaker, warning horn or the mainplane or flap buffeting normally associated with a mainplane stall. **Tailplane Stall Aerodynamics** 1. The horizontal stabiliser, or tailplane, of an aircraft is an aerofoil that provides a downward force to overcome the aircraft's normal nose-down pitching moment. The further forward the Centre of Gravity is from the Center of Pressure, the greater the nose down moment and, thus, the greater the amount of down-force that must be generated by the tailplane. This, in turn, requires a greater negative tailplane angle of attack (AOA). angle of attack (AOA). [As shown in Figure 1, The tailplane is effectively an upside down aerofoil so an increase in negative tailplane AOA occurs with UP elevator movement or when the aircraft is pitching nose down.] 2. Accumulation of ice on the tailplane will result in disruption of the normal airflow around that surface and will reduce the critical (or stalling) negative AOA of the horizontal stabiliser. 3. Ice can accumulate on the tailplane before it begins to accumulate on the mainplane or other parts of the aircraft. 4. Flaps extension usually moves the mainplane Centre of Pressure aft, lengthening the arm between the Centre of Pressure and the cg and increasing the mainplane nose down moment. More down force is required from the tailplane to counter this moment, necessitating a higher negative tailplane AOA. 5. Flap extension, especially near the maximum extension speed, increases the negative tailplane AOA due to the increase in downwash, as shown in Figure 2 6. Increasing the power setting on a propeller driven aircraft may, depending on aircraft configuration and flap settings, increase the downwash and negative tailplane AOA. 7. When the critical negative AOA of the horizontal stabiliser is exceeded causing it to stall. 8. Tailplane stall drastically reduces the downward force it produces, creating a rapid aircraft nose-down pitching moment. **Effect of mainplane flap on downwash** ![enter image description here](https://i.stack.imgur.com/xHo2B.jpg) Figure 2 - Effect of mainplane flap on downwash On aircraft with reversible (unpowered) elevator, tailplane airflow changes caused by ice accretion may lead to an aerodynamic overbalance driving the elevator trailing edge down and pitching the aircraft nose down. This can occur separately from or in combination with the nose down pitching moment caused by tailplane stall. The yoke may be snatched forward out of the pilot’s hands and the control force required for the pilot to return the elevator to neutral or to a nose-up deflection can be significant and potentially greater than the pilot can exert. **now match with your recovery actions** 1. You have no doubt with your 1st point. 2. The second point: You have to resist the nose down elevator movement. Once the tailplane is already stalled then you have to assume the elevator has already gone in down position to make your ac nose down. So you have to apply nose up elevator pressure. 3. You should not increase the airspeed cause it might make the situation worse. Cause in dive with increased airspeed is always difficult to maintain the aircraft control. And you might end up with overstressing the elevator which is not good at all in such condition.
There was a NASA report on the [NASA/FAA Tailplane Icing Program Overview](http://ntrs.nasa.gov/search.jsp?R=19990019485&hterms=19990019485&qs=Ntk%3DDocument-ID%26Ntt%3D19990019485%26N%3D0), which covers the points raised by you. It lists certain actions that can be done to recover from a tail plane stall: > > When the full tail stall was experienced during the power transition, the stall recovery procedure was: > > > • Reduce thrust (may be airplane specific) > > > • Pull back on yoke/ increase $\alpha$ > > > • Raise flaps > > > * Raise flaps to previous setting This is done mainly to undo the changes that caused the stall in the first place (reducing thrust is also done for this reason). The report says, > > The major lesson learned to recover from a tail stall was to undo what was > just done to cause the event. > > > * Apply nose up elevator pressure Basically you are pulling back on the yoke to increase the tail download so that the aircraft nose-down pitching moment is countered. From the report: > > Pulling back on the yoke increased the camber of the tailplane, which provided enough tail download to counteract the nose-down pitching moment and increase the $\alpha\_{tail}$ > > > This sounds counterintutive as the conventional tail produces force in the direction opposite to the main wing. The report notes: > > It was noted that this tail stall recovery procedure is opposite of the recovery from a wing stall. The reason for the difference is the location of the flow separation. In a wing stall, the flow separates from the upper surface of the wing, therefore reattachment is made by decreasing the wing $\alpha$. In a tail stall event, the flow separates from the lower surface of the tail and requires a positive increase in tail to reattach the flow. > > > * Do not increase airspeed unless it is necessary to avoid a wing stall The aircraft is already at a nose down attitude. Increasing speed will further excabarate the situation, which may put the corrective action beyond the capability of the tailplane.
26,351
I was studying for icing and a tailplane stall. I have looked up some internet pages and instrument flying handbook, and found the procedure below. 1. raise flaps to the previous setting. (To reduce down wash from the main wing so that reducing negative angle of attack of the tail and break the stall) 2. apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?) 3. do not increase airspeed unless it is necessary to avoid a wing stall. (Why shouldn't we increase airspeed?) So now I'm trying to understand the reason why should a pilot do such actions. Can you help me out?
2016/03/23
[ "https://aviation.stackexchange.com/questions/26351", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/6831/" ]
Lets start with the very basic concepts.... In most aircraft, the Centre of Gravity (cg) is somewhat forward of the wing or mainplane Centre of Pressure. The exact distance between the cg and the Centre of pressure will depend on aircraft loading, configuration, thrust setting and drag. However, cg forward of the Centre of Pressure produces a nose-down pitching moment. The horizontal stabilizer, or tailplane, then provides a downward force to overcome this normal, nose-down, pitching moment. The tailplane behaves as an ‘upside down’ wing and operates with negative Angle of Attack (AOA) as shown in Figure 1 ***Positive and Negative Angle of Attack*** ![enter image description here](https://i.stack.imgur.com/60asc.jpg) Figure 1 - Positive and Negative Angle of Attack If the horizontal stabiliser becomes contaminated with ice, airflow separation from the surface can prevent it from providing sufficient downward force or negative lift to balance the aircraft and a nose-down pitch upset can occur. When compared to an aircraft's mainplane, the horizontal stabiliser normally has a thinner aerofoil with a sharper leading edge. Differences in the ice collection efficiency or catch rate between the two surfaces means ice accumulates faster on the horizontal stabiliser and may form before any ice is present on the aircraft's mainplane. Tailplane stall can occur at relatively high speeds, well above the normal 1G stall speed of the mainplane. Typically, tailplane stall induced by icing is most likely to occur near the flap limit speed when the flaps are extended to the landing position, especially when extension is combined with a nose down pitching manoeuvre, airspeed change, power change or flight through turbulence. Aircraft stall warning systems provide warnings based on an uncontaminated mainplane stall so during a tailplane stall induced upset there will be NO artificial stall warning indications, such as a stick shaker, warning horn or the mainplane or flap buffeting normally associated with a mainplane stall. **Tailplane Stall Aerodynamics** 1. The horizontal stabiliser, or tailplane, of an aircraft is an aerofoil that provides a downward force to overcome the aircraft's normal nose-down pitching moment. The further forward the Centre of Gravity is from the Center of Pressure, the greater the nose down moment and, thus, the greater the amount of down-force that must be generated by the tailplane. This, in turn, requires a greater negative tailplane angle of attack (AOA). angle of attack (AOA). [As shown in Figure 1, The tailplane is effectively an upside down aerofoil so an increase in negative tailplane AOA occurs with UP elevator movement or when the aircraft is pitching nose down.] 2. Accumulation of ice on the tailplane will result in disruption of the normal airflow around that surface and will reduce the critical (or stalling) negative AOA of the horizontal stabiliser. 3. Ice can accumulate on the tailplane before it begins to accumulate on the mainplane or other parts of the aircraft. 4. Flaps extension usually moves the mainplane Centre of Pressure aft, lengthening the arm between the Centre of Pressure and the cg and increasing the mainplane nose down moment. More down force is required from the tailplane to counter this moment, necessitating a higher negative tailplane AOA. 5. Flap extension, especially near the maximum extension speed, increases the negative tailplane AOA due to the increase in downwash, as shown in Figure 2 6. Increasing the power setting on a propeller driven aircraft may, depending on aircraft configuration and flap settings, increase the downwash and negative tailplane AOA. 7. When the critical negative AOA of the horizontal stabiliser is exceeded causing it to stall. 8. Tailplane stall drastically reduces the downward force it produces, creating a rapid aircraft nose-down pitching moment. **Effect of mainplane flap on downwash** ![enter image description here](https://i.stack.imgur.com/xHo2B.jpg) Figure 2 - Effect of mainplane flap on downwash On aircraft with reversible (unpowered) elevator, tailplane airflow changes caused by ice accretion may lead to an aerodynamic overbalance driving the elevator trailing edge down and pitching the aircraft nose down. This can occur separately from or in combination with the nose down pitching moment caused by tailplane stall. The yoke may be snatched forward out of the pilot’s hands and the control force required for the pilot to return the elevator to neutral or to a nose-up deflection can be significant and potentially greater than the pilot can exert. **now match with your recovery actions** 1. You have no doubt with your 1st point. 2. The second point: You have to resist the nose down elevator movement. Once the tailplane is already stalled then you have to assume the elevator has already gone in down position to make your ac nose down. So you have to apply nose up elevator pressure. 3. You should not increase the airspeed cause it might make the situation worse. Cause in dive with increased airspeed is always difficult to maintain the aircraft control. And you might end up with overstressing the elevator which is not good at all in such condition.
For those recommended actions to be effective, two preconditions have been quietly assumed: 1. The tail surface produces downward lift and 2. The wing has positive camber. Both can be assumed to be correct in almost any case. Now let’s look at the three recommendations in detail: > > raise flaps to the previous setting. > > > Flaps increase camber and shift the center of pressure backwards. In order to balance the aircraft with the same center of gravity location, the tail needs to produce [more downward force](https://aviation.stackexchange.com/questions/13855/why-cant-planes-use-only-flaps-in-the-tail-section-instead-of-stabilizers/13861#13861) with lowered flaps. Retracting flaps will unload the horizontal tail and reduce the stall condition. > > apply nose up elevator pressure. > > > This [adds tail camber](https://aviation.stackexchange.com/questions/44338/is-it-correct-to-say-the-up-elevator-position-decreases-the-camber-of-the-eleva) and helps to produce the same downward force at a less negative local angle of attack of the stabilizer. The induced angle of attack of the added tail camber will increase the local angle of attack at the stabilizer. This can only help momentarily, though, because it will make the aircraft pitch up and lose speed - unless you have a movable stabilizer which is used for trim. Re-trim with the new elevator setting and the change becomes permanent. > > do not increase airspeed unless it is necessary to avoid a wing stall. > > > When the main wing has positive camber, a lower wing angle of attack [shifts its center of pressure backwards](https://aviation.stackexchange.com/questions/47306/does-static-longitudinal-stability-require-download-on-the-tail/47308#47308). Therefore, the tail load and lift coefficient are lowest at low speed, and flying slowly will unload the tail. With rear center of gravity, tail load normally can even become slightly positive at low speed. So in all cases the recommendations help to unload the tail and reduce the condition that let the iced tail stall.
26,351
I was studying for icing and a tailplane stall. I have looked up some internet pages and instrument flying handbook, and found the procedure below. 1. raise flaps to the previous setting. (To reduce down wash from the main wing so that reducing negative angle of attack of the tail and break the stall) 2. apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?) 3. do not increase airspeed unless it is necessary to avoid a wing stall. (Why shouldn't we increase airspeed?) So now I'm trying to understand the reason why should a pilot do such actions. Can you help me out?
2016/03/23
[ "https://aviation.stackexchange.com/questions/26351", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/6831/" ]
Lets start with the very basic concepts.... In most aircraft, the Centre of Gravity (cg) is somewhat forward of the wing or mainplane Centre of Pressure. The exact distance between the cg and the Centre of pressure will depend on aircraft loading, configuration, thrust setting and drag. However, cg forward of the Centre of Pressure produces a nose-down pitching moment. The horizontal stabilizer, or tailplane, then provides a downward force to overcome this normal, nose-down, pitching moment. The tailplane behaves as an ‘upside down’ wing and operates with negative Angle of Attack (AOA) as shown in Figure 1 ***Positive and Negative Angle of Attack*** ![enter image description here](https://i.stack.imgur.com/60asc.jpg) Figure 1 - Positive and Negative Angle of Attack If the horizontal stabiliser becomes contaminated with ice, airflow separation from the surface can prevent it from providing sufficient downward force or negative lift to balance the aircraft and a nose-down pitch upset can occur. When compared to an aircraft's mainplane, the horizontal stabiliser normally has a thinner aerofoil with a sharper leading edge. Differences in the ice collection efficiency or catch rate between the two surfaces means ice accumulates faster on the horizontal stabiliser and may form before any ice is present on the aircraft's mainplane. Tailplane stall can occur at relatively high speeds, well above the normal 1G stall speed of the mainplane. Typically, tailplane stall induced by icing is most likely to occur near the flap limit speed when the flaps are extended to the landing position, especially when extension is combined with a nose down pitching manoeuvre, airspeed change, power change or flight through turbulence. Aircraft stall warning systems provide warnings based on an uncontaminated mainplane stall so during a tailplane stall induced upset there will be NO artificial stall warning indications, such as a stick shaker, warning horn or the mainplane or flap buffeting normally associated with a mainplane stall. **Tailplane Stall Aerodynamics** 1. The horizontal stabiliser, or tailplane, of an aircraft is an aerofoil that provides a downward force to overcome the aircraft's normal nose-down pitching moment. The further forward the Centre of Gravity is from the Center of Pressure, the greater the nose down moment and, thus, the greater the amount of down-force that must be generated by the tailplane. This, in turn, requires a greater negative tailplane angle of attack (AOA). angle of attack (AOA). [As shown in Figure 1, The tailplane is effectively an upside down aerofoil so an increase in negative tailplane AOA occurs with UP elevator movement or when the aircraft is pitching nose down.] 2. Accumulation of ice on the tailplane will result in disruption of the normal airflow around that surface and will reduce the critical (or stalling) negative AOA of the horizontal stabiliser. 3. Ice can accumulate on the tailplane before it begins to accumulate on the mainplane or other parts of the aircraft. 4. Flaps extension usually moves the mainplane Centre of Pressure aft, lengthening the arm between the Centre of Pressure and the cg and increasing the mainplane nose down moment. More down force is required from the tailplane to counter this moment, necessitating a higher negative tailplane AOA. 5. Flap extension, especially near the maximum extension speed, increases the negative tailplane AOA due to the increase in downwash, as shown in Figure 2 6. Increasing the power setting on a propeller driven aircraft may, depending on aircraft configuration and flap settings, increase the downwash and negative tailplane AOA. 7. When the critical negative AOA of the horizontal stabiliser is exceeded causing it to stall. 8. Tailplane stall drastically reduces the downward force it produces, creating a rapid aircraft nose-down pitching moment. **Effect of mainplane flap on downwash** ![enter image description here](https://i.stack.imgur.com/xHo2B.jpg) Figure 2 - Effect of mainplane flap on downwash On aircraft with reversible (unpowered) elevator, tailplane airflow changes caused by ice accretion may lead to an aerodynamic overbalance driving the elevator trailing edge down and pitching the aircraft nose down. This can occur separately from or in combination with the nose down pitching moment caused by tailplane stall. The yoke may be snatched forward out of the pilot’s hands and the control force required for the pilot to return the elevator to neutral or to a nose-up deflection can be significant and potentially greater than the pilot can exert. **now match with your recovery actions** 1. You have no doubt with your 1st point. 2. The second point: You have to resist the nose down elevator movement. Once the tailplane is already stalled then you have to assume the elevator has already gone in down position to make your ac nose down. So you have to apply nose up elevator pressure. 3. You should not increase the airspeed cause it might make the situation worse. Cause in dive with increased airspeed is always difficult to maintain the aircraft control. And you might end up with overstressing the elevator which is not good at all in such condition.
I have a theory on applying the backstick on a tail stall induced while lowering the flaps. OP’s comment: > > apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?) > > > If the tail stalls, then the nose pitches forward. The center of rotation is about somewhere near the wing and CG, well forward of the tail. So the tail instantly sees a step increase in AOA, to well beyond the stall AOA. Probably really high AOA. The aircraft develops inertia in pitch too. At this point, you are doing triage while you lower the flaps and undo what you did. While you’re not getting much lift (downward) from the tail, it is resisting the forward pitch with drag. Letting the stick or yoke come forward would dump this pitch resisting force, and the aircraft would go right over its nose before the flaps could raise. There’s my theory.
26,351
I was studying for icing and a tailplane stall. I have looked up some internet pages and instrument flying handbook, and found the procedure below. 1. raise flaps to the previous setting. (To reduce down wash from the main wing so that reducing negative angle of attack of the tail and break the stall) 2. apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?) 3. do not increase airspeed unless it is necessary to avoid a wing stall. (Why shouldn't we increase airspeed?) So now I'm trying to understand the reason why should a pilot do such actions. Can you help me out?
2016/03/23
[ "https://aviation.stackexchange.com/questions/26351", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/6831/" ]
There was a NASA report on the [NASA/FAA Tailplane Icing Program Overview](http://ntrs.nasa.gov/search.jsp?R=19990019485&hterms=19990019485&qs=Ntk%3DDocument-ID%26Ntt%3D19990019485%26N%3D0), which covers the points raised by you. It lists certain actions that can be done to recover from a tail plane stall: > > When the full tail stall was experienced during the power transition, the stall recovery procedure was: > > > • Reduce thrust (may be airplane specific) > > > • Pull back on yoke/ increase $\alpha$ > > > • Raise flaps > > > * Raise flaps to previous setting This is done mainly to undo the changes that caused the stall in the first place (reducing thrust is also done for this reason). The report says, > > The major lesson learned to recover from a tail stall was to undo what was > just done to cause the event. > > > * Apply nose up elevator pressure Basically you are pulling back on the yoke to increase the tail download so that the aircraft nose-down pitching moment is countered. From the report: > > Pulling back on the yoke increased the camber of the tailplane, which provided enough tail download to counteract the nose-down pitching moment and increase the $\alpha\_{tail}$ > > > This sounds counterintutive as the conventional tail produces force in the direction opposite to the main wing. The report notes: > > It was noted that this tail stall recovery procedure is opposite of the recovery from a wing stall. The reason for the difference is the location of the flow separation. In a wing stall, the flow separates from the upper surface of the wing, therefore reattachment is made by decreasing the wing $\alpha$. In a tail stall event, the flow separates from the lower surface of the tail and requires a positive increase in tail to reattach the flow. > > > * Do not increase airspeed unless it is necessary to avoid a wing stall The aircraft is already at a nose down attitude. Increasing speed will further excabarate the situation, which may put the corrective action beyond the capability of the tailplane.
For those recommended actions to be effective, two preconditions have been quietly assumed: 1. The tail surface produces downward lift and 2. The wing has positive camber. Both can be assumed to be correct in almost any case. Now let’s look at the three recommendations in detail: > > raise flaps to the previous setting. > > > Flaps increase camber and shift the center of pressure backwards. In order to balance the aircraft with the same center of gravity location, the tail needs to produce [more downward force](https://aviation.stackexchange.com/questions/13855/why-cant-planes-use-only-flaps-in-the-tail-section-instead-of-stabilizers/13861#13861) with lowered flaps. Retracting flaps will unload the horizontal tail and reduce the stall condition. > > apply nose up elevator pressure. > > > This [adds tail camber](https://aviation.stackexchange.com/questions/44338/is-it-correct-to-say-the-up-elevator-position-decreases-the-camber-of-the-eleva) and helps to produce the same downward force at a less negative local angle of attack of the stabilizer. The induced angle of attack of the added tail camber will increase the local angle of attack at the stabilizer. This can only help momentarily, though, because it will make the aircraft pitch up and lose speed - unless you have a movable stabilizer which is used for trim. Re-trim with the new elevator setting and the change becomes permanent. > > do not increase airspeed unless it is necessary to avoid a wing stall. > > > When the main wing has positive camber, a lower wing angle of attack [shifts its center of pressure backwards](https://aviation.stackexchange.com/questions/47306/does-static-longitudinal-stability-require-download-on-the-tail/47308#47308). Therefore, the tail load and lift coefficient are lowest at low speed, and flying slowly will unload the tail. With rear center of gravity, tail load normally can even become slightly positive at low speed. So in all cases the recommendations help to unload the tail and reduce the condition that let the iced tail stall.
26,351
I was studying for icing and a tailplane stall. I have looked up some internet pages and instrument flying handbook, and found the procedure below. 1. raise flaps to the previous setting. (To reduce down wash from the main wing so that reducing negative angle of attack of the tail and break the stall) 2. apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?) 3. do not increase airspeed unless it is necessary to avoid a wing stall. (Why shouldn't we increase airspeed?) So now I'm trying to understand the reason why should a pilot do such actions. Can you help me out?
2016/03/23
[ "https://aviation.stackexchange.com/questions/26351", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/6831/" ]
There was a NASA report on the [NASA/FAA Tailplane Icing Program Overview](http://ntrs.nasa.gov/search.jsp?R=19990019485&hterms=19990019485&qs=Ntk%3DDocument-ID%26Ntt%3D19990019485%26N%3D0), which covers the points raised by you. It lists certain actions that can be done to recover from a tail plane stall: > > When the full tail stall was experienced during the power transition, the stall recovery procedure was: > > > • Reduce thrust (may be airplane specific) > > > • Pull back on yoke/ increase $\alpha$ > > > • Raise flaps > > > * Raise flaps to previous setting This is done mainly to undo the changes that caused the stall in the first place (reducing thrust is also done for this reason). The report says, > > The major lesson learned to recover from a tail stall was to undo what was > just done to cause the event. > > > * Apply nose up elevator pressure Basically you are pulling back on the yoke to increase the tail download so that the aircraft nose-down pitching moment is countered. From the report: > > Pulling back on the yoke increased the camber of the tailplane, which provided enough tail download to counteract the nose-down pitching moment and increase the $\alpha\_{tail}$ > > > This sounds counterintutive as the conventional tail produces force in the direction opposite to the main wing. The report notes: > > It was noted that this tail stall recovery procedure is opposite of the recovery from a wing stall. The reason for the difference is the location of the flow separation. In a wing stall, the flow separates from the upper surface of the wing, therefore reattachment is made by decreasing the wing $\alpha$. In a tail stall event, the flow separates from the lower surface of the tail and requires a positive increase in tail to reattach the flow. > > > * Do not increase airspeed unless it is necessary to avoid a wing stall The aircraft is already at a nose down attitude. Increasing speed will further excabarate the situation, which may put the corrective action beyond the capability of the tailplane.
I have a theory on applying the backstick on a tail stall induced while lowering the flaps. OP’s comment: > > apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?) > > > If the tail stalls, then the nose pitches forward. The center of rotation is about somewhere near the wing and CG, well forward of the tail. So the tail instantly sees a step increase in AOA, to well beyond the stall AOA. Probably really high AOA. The aircraft develops inertia in pitch too. At this point, you are doing triage while you lower the flaps and undo what you did. While you’re not getting much lift (downward) from the tail, it is resisting the forward pitch with drag. Letting the stick or yoke come forward would dump this pitch resisting force, and the aircraft would go right over its nose before the flaps could raise. There’s my theory.
2,093,466
I understand that division by zero isn't allowed, but we merely just multiplied $f(x) = 1$ by $\frac{x-1}{x-1}$ to get $f(x) = \frac{x-1}{x-1}$ and $a\cdot 1 = 1\cdot a = a$ so they're the **same function** but with **different domain** how is this possible? *Or in other words* why don't we simplify $f(x) = \frac{x-1}{x-1}$ to $f(x) = 1$ before plotting the points. Is it just defined this way or is there a particular reason ? **Note:** my book says the domain of $f(x) = 1$ is $\mathbb{R}$ and the domain of $f(x) = \frac{x-1}{x-1}$ is $\mathbb{R}$ except $1$.
2017/01/11
[ "https://math.stackexchange.com/questions/2093466", "https://math.stackexchange.com", "https://math.stackexchange.com/users/406041/" ]
They are the same *almost everywhere*. But clearly one of them does not exist for $x=1$ (since "$\tfrac{0}{0}$" is undefined), while the other one is simply $1$ at $x=1$. > > I understand that division by zero isn't allowed, but we merely just multiplied f(x) = 1 by (x-1)/(x-1) > > > You can multiply by any fraction $\tfrac{a}{a}$; but not when $a=0$ because the fraction you want to multiply with, isn't even defined then. So multiplying by $\tfrac{x-1}{x-1}$ is fine, but only valid for $x \ne 1$. > > why don't we simplify f(x) = (x-1)/(x-1) to f(x) = 1 before plotting the points. > Is it just defined this way or is there a particular reason ? > > > You can simplify, but recall that simplifying is actually dividing numerator and denominator by the same number: you can simplify $\tfrac{ka}{kb}$ to $\tfrac{a}{b}$ by dividing by $k$. But also then: this only works for $k \ne 0$ since you can't divide by $0$. So "simplifying" $\tfrac{x-1}{x-1}$ to $1$ is fine, for $x-1 \ne 0$ so for $x \ne 1$. --- > > **Note:** my book says the domain of $f(x) = 1$ is $\mathbb{R}$ and the domain of > $f(x) = \frac{x-1}{x-1}$ is $\mathbb{R}$ except $1$. > > > Technically, the domain is a part of the function: it should be given (as well as the codomain). It is very common though that when unspecified, in the context of real-valued functions of a real variable, we assume the 'maximal domain' is intended (and $\mathbb{R}$ is taken as codomain). Then look at: $$f : \mathbb{R} \to \mathbb{R} : x \mapsto f(x) = 1$$ and $$g : \mathbb{R} \setminus \left\{ 1 \right\} \to \mathbb{R} : x \mapsto g(x) = \frac{x-1}{x-1}$$ The functions $f$ and $g$ are different, but $f(x) = g(x)=1$ for all $x$ except when $x=1$, where $g$ is undefined.
**Question**: What is a function? **Answer**: Maybe simply said it is a map (receipe), $f(x)$, that projects some elements, $x$, contained in a specifically defined set, Domain $D$, into another set, Range $R$. **Discussion**: Hence when defining a function one must define the Domain as well as the functional form. Otherwise the function is not defined. **Conclusion**: If two funtions have the same domain and the same receipe then they are the same "maps" otherwise they are not.
2,093,466
I understand that division by zero isn't allowed, but we merely just multiplied $f(x) = 1$ by $\frac{x-1}{x-1}$ to get $f(x) = \frac{x-1}{x-1}$ and $a\cdot 1 = 1\cdot a = a$ so they're the **same function** but with **different domain** how is this possible? *Or in other words* why don't we simplify $f(x) = \frac{x-1}{x-1}$ to $f(x) = 1$ before plotting the points. Is it just defined this way or is there a particular reason ? **Note:** my book says the domain of $f(x) = 1$ is $\mathbb{R}$ and the domain of $f(x) = \frac{x-1}{x-1}$ is $\mathbb{R}$ except $1$.
2017/01/11
[ "https://math.stackexchange.com/questions/2093466", "https://math.stackexchange.com", "https://math.stackexchange.com/users/406041/" ]
They are the same *almost everywhere*. But clearly one of them does not exist for $x=1$ (since "$\tfrac{0}{0}$" is undefined), while the other one is simply $1$ at $x=1$. > > I understand that division by zero isn't allowed, but we merely just multiplied f(x) = 1 by (x-1)/(x-1) > > > You can multiply by any fraction $\tfrac{a}{a}$; but not when $a=0$ because the fraction you want to multiply with, isn't even defined then. So multiplying by $\tfrac{x-1}{x-1}$ is fine, but only valid for $x \ne 1$. > > why don't we simplify f(x) = (x-1)/(x-1) to f(x) = 1 before plotting the points. > Is it just defined this way or is there a particular reason ? > > > You can simplify, but recall that simplifying is actually dividing numerator and denominator by the same number: you can simplify $\tfrac{ka}{kb}$ to $\tfrac{a}{b}$ by dividing by $k$. But also then: this only works for $k \ne 0$ since you can't divide by $0$. So "simplifying" $\tfrac{x-1}{x-1}$ to $1$ is fine, for $x-1 \ne 0$ so for $x \ne 1$. --- > > **Note:** my book says the domain of $f(x) = 1$ is $\mathbb{R}$ and the domain of > $f(x) = \frac{x-1}{x-1}$ is $\mathbb{R}$ except $1$. > > > Technically, the domain is a part of the function: it should be given (as well as the codomain). It is very common though that when unspecified, in the context of real-valued functions of a real variable, we assume the 'maximal domain' is intended (and $\mathbb{R}$ is taken as codomain). Then look at: $$f : \mathbb{R} \to \mathbb{R} : x \mapsto f(x) = 1$$ and $$g : \mathbb{R} \setminus \left\{ 1 \right\} \to \mathbb{R} : x \mapsto g(x) = \frac{x-1}{x-1}$$ The functions $f$ and $g$ are different, but $f(x) = g(x)=1$ for all $x$ except when $x=1$, where $g$ is undefined.
$f(x)=(x-1)/(x-1)$ does not have a value when $x=1$, different thing happens to $f(x)=1$
2,093,466
I understand that division by zero isn't allowed, but we merely just multiplied $f(x) = 1$ by $\frac{x-1}{x-1}$ to get $f(x) = \frac{x-1}{x-1}$ and $a\cdot 1 = 1\cdot a = a$ so they're the **same function** but with **different domain** how is this possible? *Or in other words* why don't we simplify $f(x) = \frac{x-1}{x-1}$ to $f(x) = 1$ before plotting the points. Is it just defined this way or is there a particular reason ? **Note:** my book says the domain of $f(x) = 1$ is $\mathbb{R}$ and the domain of $f(x) = \frac{x-1}{x-1}$ is $\mathbb{R}$ except $1$.
2017/01/11
[ "https://math.stackexchange.com/questions/2093466", "https://math.stackexchange.com", "https://math.stackexchange.com/users/406041/" ]
**Question**: What is a function? **Answer**: Maybe simply said it is a map (receipe), $f(x)$, that projects some elements, $x$, contained in a specifically defined set, Domain $D$, into another set, Range $R$. **Discussion**: Hence when defining a function one must define the Domain as well as the functional form. Otherwise the function is not defined. **Conclusion**: If two funtions have the same domain and the same receipe then they are the same "maps" otherwise they are not.
$f(x)=(x-1)/(x-1)$ does not have a value when $x=1$, different thing happens to $f(x)=1$
59,133,760
I have following HTML code ``` <div class="compatible-product ng-star-inserted"> <adapt-checkbox2 class="checkbox ng-valid ng-star-inserted ng-dirty ng-touched" ng-reflect-model="false"> <label class="checkbox__label" for= "adapt-checkbox-453-input"> <input class="checkbox__input" type="checkbox" id="adapt-checkbox-453-input" tabindex="0" aria-label="" aria-checked="false"> <span class="checkbox__item"> <span class="sr-only" ng-reflect-ng-class="[object Object]"></span> </span> </label> </adapt-checkbox2> <span class="compatible-product-name" style="">Product - ABC</span> </div> <div class="compatible-product ng-star-inserted"> <adapt-checkbox2 class="checkbox ng-untouched ng-pristine ng-valid ng-star-inserted"> <label class="checkbox__label" for="adapt-checkbox-454-input"> <input class="checkbox__input" type="checkbox" id="adapt-checkbox-454-input" tabindex="0" aria-label="" aria-checked="false"> <span class="checkbox__item"> <span class="sr-only" ng-reflect-ng-class="[object Object]"></span> </span> </label> </adapt-checkbox2> <span class="compatible-product-name" style="">Product - XYZ</span> </div> ``` [Please check screenshot here](https://i.stack.imgur.com/0iOkd.png) From which 1) First I need to select/click on "adapt-checkbox2" who is left to Span "Product - ABC" So I have written code as follows ``` WebElement selectCompatibleProduct1 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - ABC']"))); selectCompatibleProduct1.click(); ``` **Which is working fine. Its selecting the correct check-box.** 2) But Whenever I tried to select 2nd check-box its not working. Its again clicking/selecting 1st checkbox. Code for 2nd checkbox is:- ``` WebElement selectCompatibleProduct2 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - XYZ']"))); selectCompatibleProduct2.click(); ``` Selenium Version is:- 4.0.0-alpha-3 Please can someone help me on this? Thanks in advance.
2019/12/02
[ "https://Stackoverflow.com/questions/59133760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3189243/" ]
Basically, you are getting an **Array of Object** and you want to access the last element of the array, you can **get last array position by** `array.length - 1`, and access the gfs value. if you want to **check whether gfs value is array** not then you can **check by** `typeof gfs` ```js var data= [ { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'base', pos: 0, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'node', pos: 1, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'node', pos: 2, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'boomerang', pos: 3, gfs: ['a','b','c'] } ] // You can access like this console.log(data[data.length-1].gfs) ```
You can access the array value by `index` so you can use loop to access it by index or you can directly access it using `index` number. Check out these docs. It will help out to better understand [Loops\_and\_iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration) [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) [Property accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) ```js let data = [ { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'base', pos: 0, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'node', pos: 1, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'node', pos: 2, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'boomerang', pos: 3, gfs: [1, 2, 4, 5] } ]; // by looping for(let i = 0; i < data.length; i++) { // iterate on data, for(initilize, condition, increment) let item = data[i]; // access item from data by bracket notation property accessors, pass index number i let gfsList = item['gfs'] // grab the gfs object from item by bracket notation property accessors if(Array.isArray(gfsList)) { // check if gfs is array or not for(let j = 0; j < gfsList.length; j++) { //gfs is array so we can iterate again on each item of it let gfsItem = gfsList[j]; console.log(gfsItem); } } } // direct access console.log(data[data.length - 1]['gfs']) ```
59,133,760
I have following HTML code ``` <div class="compatible-product ng-star-inserted"> <adapt-checkbox2 class="checkbox ng-valid ng-star-inserted ng-dirty ng-touched" ng-reflect-model="false"> <label class="checkbox__label" for= "adapt-checkbox-453-input"> <input class="checkbox__input" type="checkbox" id="adapt-checkbox-453-input" tabindex="0" aria-label="" aria-checked="false"> <span class="checkbox__item"> <span class="sr-only" ng-reflect-ng-class="[object Object]"></span> </span> </label> </adapt-checkbox2> <span class="compatible-product-name" style="">Product - ABC</span> </div> <div class="compatible-product ng-star-inserted"> <adapt-checkbox2 class="checkbox ng-untouched ng-pristine ng-valid ng-star-inserted"> <label class="checkbox__label" for="adapt-checkbox-454-input"> <input class="checkbox__input" type="checkbox" id="adapt-checkbox-454-input" tabindex="0" aria-label="" aria-checked="false"> <span class="checkbox__item"> <span class="sr-only" ng-reflect-ng-class="[object Object]"></span> </span> </label> </adapt-checkbox2> <span class="compatible-product-name" style="">Product - XYZ</span> </div> ``` [Please check screenshot here](https://i.stack.imgur.com/0iOkd.png) From which 1) First I need to select/click on "adapt-checkbox2" who is left to Span "Product - ABC" So I have written code as follows ``` WebElement selectCompatibleProduct1 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - ABC']"))); selectCompatibleProduct1.click(); ``` **Which is working fine. Its selecting the correct check-box.** 2) But Whenever I tried to select 2nd check-box its not working. Its again clicking/selecting 1st checkbox. Code for 2nd checkbox is:- ``` WebElement selectCompatibleProduct2 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - XYZ']"))); selectCompatibleProduct2.click(); ``` Selenium Version is:- 4.0.0-alpha-3 Please can someone help me on this? Thanks in advance.
2019/12/02
[ "https://Stackoverflow.com/questions/59133760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3189243/" ]
Basically, you are getting an **Array of Object** and you want to access the last element of the array, you can **get last array position by** `array.length - 1`, and access the gfs value. if you want to **check whether gfs value is array** not then you can **check by** `typeof gfs` ```js var data= [ { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'base', pos: 0, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'node', pos: 1, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'node', pos: 2, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'boomerang', pos: 3, gfs: ['a','b','c'] } ] // You can access like this console.log(data[data.length-1].gfs) ```
JSON.parse() gives JavaScript object. Here it is the Array object, so you can access it by looping the array or specifying the array index directly. ``` var data = [ { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'base', pos: 0, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'node', pos: 1, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'node', pos: 2, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'boomerang', pos: 3, gfs: [Array] } ] data.forEach(data => { console.log(data.gfs); //Print the gfs value of every object in the array }) ```
59,133,760
I have following HTML code ``` <div class="compatible-product ng-star-inserted"> <adapt-checkbox2 class="checkbox ng-valid ng-star-inserted ng-dirty ng-touched" ng-reflect-model="false"> <label class="checkbox__label" for= "adapt-checkbox-453-input"> <input class="checkbox__input" type="checkbox" id="adapt-checkbox-453-input" tabindex="0" aria-label="" aria-checked="false"> <span class="checkbox__item"> <span class="sr-only" ng-reflect-ng-class="[object Object]"></span> </span> </label> </adapt-checkbox2> <span class="compatible-product-name" style="">Product - ABC</span> </div> <div class="compatible-product ng-star-inserted"> <adapt-checkbox2 class="checkbox ng-untouched ng-pristine ng-valid ng-star-inserted"> <label class="checkbox__label" for="adapt-checkbox-454-input"> <input class="checkbox__input" type="checkbox" id="adapt-checkbox-454-input" tabindex="0" aria-label="" aria-checked="false"> <span class="checkbox__item"> <span class="sr-only" ng-reflect-ng-class="[object Object]"></span> </span> </label> </adapt-checkbox2> <span class="compatible-product-name" style="">Product - XYZ</span> </div> ``` [Please check screenshot here](https://i.stack.imgur.com/0iOkd.png) From which 1) First I need to select/click on "adapt-checkbox2" who is left to Span "Product - ABC" So I have written code as follows ``` WebElement selectCompatibleProduct1 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - ABC']"))); selectCompatibleProduct1.click(); ``` **Which is working fine. Its selecting the correct check-box.** 2) But Whenever I tried to select 2nd check-box its not working. Its again clicking/selecting 1st checkbox. Code for 2nd checkbox is:- ``` WebElement selectCompatibleProduct2 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - XYZ']"))); selectCompatibleProduct2.click(); ``` Selenium Version is:- 4.0.0-alpha-3 Please can someone help me on this? Thanks in advance.
2019/12/02
[ "https://Stackoverflow.com/questions/59133760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3189243/" ]
Basically, you are getting an **Array of Object** and you want to access the last element of the array, you can **get last array position by** `array.length - 1`, and access the gfs value. if you want to **check whether gfs value is array** not then you can **check by** `typeof gfs` ```js var data= [ { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'base', pos: 0, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'node', pos: 1, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'node', pos: 2, gfs: null }, { url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4', typ: 'boomerang', pos: 3, gfs: ['a','b','c'] } ] // You can access like this console.log(data[data.length-1].gfs) ```
Accessed it by using `console.log(obj.data[3].gfs)` I didn't take into account that the data key stored inside data inside obj(which I assigned)/
299,700
I was following [this tutorial](https://www.youtube.com/watch?v=lrvLnhm6Rqw&list=PLpVC00PAQQxHi-llE9Z8-Q747NYWpsq6t&index=32) on Drupal module development. It talks about database query joins in module development. The tutorial is made for Drupal 8 and I'm using Drupal 9. Then I made this (look at the join part): ``` protected function load () { $select = Database::getConnection()->select('rsvplist', 'r'); $select.join('users_field_data', 'u', 'r.uid = u.uid'); $select->join('node_field_data', 'n', 'r.nid = n.nid'); $select->addField('u', 'name'); $select->addField('n', 'title'); $select->addField('r', 'mail'); $entries = $select->execute()->fetchAll(\PDO::FETCH_ASSOC); return $entries; } ``` But get this error: ``` warning: join() expects at most 2 parameters, 3 given in Drupal\rsvplist\Controller\ReportController->load() (line 24 of /var/www/htdocs/drupal-modules/modules/custom/rsvplist/src/Controller/ReportController.php) #0 /var/www/htdocs/drupal-modules/core/includes/bootstrap.inc(305): _drupal_error_handler_real(2, 'join() expects ...', '/var/www/htdocs...', 24) #1 [internal function]: _drupal_error_handler(2, 'join() expects ...', '/var/www/htdocs...', 24, Array) #2 /var/www/htdocs/drupal-modules/modules/custom/rsvplist/src/Controller/ReportController.php(24): join('users_field_dat...', 'u', 'r.uid = u.uid') #3 /var/www/htdocs/drupal-modules/modules/custom/rsvplist/src/Controller/ReportController.php(52): Drupal\rsvplist\Controller\ReportController->load() #4 [internal function]: Drupal\rsvplist\Controller\ReportController->report() #5 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call_user_func_array(Array, Array) #6 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/Render/Renderer.php(573): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() #7 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure)) #8 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) #9 /var/www/htdocs/drupal-modules/vendor/symfony/http-kernel/HttpKernel.php(158): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() #10 /var/www/htdocs/drupal-modules/vendor/symfony/http-kernel/HttpKernel.php(80): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1) #11 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #12 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #13 /var/www/htdocs/drupal-modules/core/modules/page_cache/src/StackMiddleware/PageCache.php(106): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #14 /var/www/htdocs/drupal-modules/core/modules/page_cache/src/StackMiddleware/PageCache.php(85): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true) #15 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #16 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(52): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #17 /var/www/htdocs/drupal-modules/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #18 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/DrupalKernel.php(706): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #19 /var/www/htdocs/drupal-modules/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request)) #20 {main} ``` Drupal 9's join don't accepts the third argument: ``` 'r.uid = u.uid' ``` A made some research but I was not able to find an equivalent example about how to use join this way in Drupap 9 documentation and other sources. How can I add joins to a query in Drupal 9?
2021/01/25
[ "https://drupal.stackexchange.com/questions/299700", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/102226/" ]
In PHP: * `.` is the string concatenation operator, not the one to call an object method * [`join()`](https://www.php.net/manual/en/function.join.php) is an alias for the [`implode()`](https://www.php.net/manual/en/function.implode.php) function, which effectively requires 2 arguments, not 3 This means that `$select.join('users_field_data', 'u', 'r.uid = u.uid')` (which PHP reads as `$select . join('users_field_data', 'u', 'r.uid = u.uid')`) is: * Converting the value contained in `$select` to a string * Concatenating that string with the string returned by `implode()` The arguments accepted by [`implode()`](https://www.php.net/manual/en/function.implode.php) has been changed in the latest PHP versions, but the function has never accepted three arguments, and the first two arguments has never been two strings. This explains the error you are getting. In Drupal 9, if `$select` is an object implementing [`SelectInterface`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21SelectInterface.php/interface/SelectInterface/9.0.x), [`$select->join()`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Select.php/function/Select%3A%3Ajoin/9.0.x) is an available method. ```php public function join($table, $alias = NULL, $condition = NULL, $arguments = []) { return $this->addJoin('INNER', $table, $alias, $condition, $arguments); } ``` Instead of `$select->join()`, you could call `$select->addJoin()`. The first method doesn't require to specify the first or the last argument of `$select->addJoin()`, and it's the normally called method. As side note, instead of using `$select` on database tables used for entity data, it's generally preferable to use the class returned from [`Drupal::entityQuery()`](https://api.drupal.org/api/drupal/core%21lib%21Drupal.php/function/Drupal%3A%3AentityQuery/9.0.x).
Solution: In Drupal 9, I needed to replace joins so it works: ``` //$select.join('users_field_data', 'u', 'r.uid = u.uid'); $select->addJoin('inner','users_field_data','u','r.uid = u.uid'); //$select->join('node_field_data', 'n', 'r.nid = n.nid'); $select->addJoin('inner','node_field_data','n','r.nid = n.nid'); ```
74,243,879
I want to use UTC dates in my Node.js backend app, however, I need to be able to set time (hours and minutes) in a local/user-specified timezone. I am looking for a solution in either pure JS or using `dayjs`. I am not looking for a solution in `moment`. It seemed like using `dayjs` I could solve this problem quite easily, however, I could not find a way to accomplish this. I can use UTC timezone by using [`dayjs.utc()`](https://day.js.org/docs/en/plugin/utc) or using [`dayjs.tz(someDate, 'Etc/UTC')`](https://day.js.org/docs/en/timezone/timezone). When using `dayjs.utc()`, I cannot use/specify other timezones for *anything*, therefore I could not find a way to tell `dayjs` I want to set hours/minutes in a particular (non-UTC) timezone. When using `dayjs.tz()`, I still cannot define a timezone of time I want to set to a particular date. ### Example in plain JS My locale timezone is `Europe/Slovakia` (CEST = UTC+02 with DST, CET = UTC+1 without DST), however, I want this to work with any timezone. ```js // Expected outcome // old: 2022-10-29T10:00:00.000Z // new time: 10h 15m CEST // new: 2022-10-29T08:15:00.000Z // Plain JS const now = new Date('2022-10-29T10:00:00.000Z') const hours = 10 const minutes = 15 now.setHours(10) now.setMinutes(15) // As my default timezone is `Europe/Bratislava`, it seems to work as expected console.log(now) // Output: 2022-10-29T08:15:00.000Z // However, it won't work with timezones other than my local timezone ``` ### (Nearly) a solution ***Update: I posted a working function in [this answer](https://stackoverflow.com/a/74245936/3408342).*** The following functions seems to work for most test cases, however, it fails for 6 4 cases known to me (any help is greatly appreciated): * [DST to ST] `now` in DST before double hour, `newDate` in ST during double hour; * [DST to ST] `now` in DST during double hour, `newDate` in ST during double hour; * [DST to ST] `now` in ST during double hour, `newDate` in DST during double hour; * [DST to ST] `now` in ST after double hour, `newDate` in DST during double hour; * [ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour; * [ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour. I think the only missing piece is to find a way to check if a particular date in a non-UTC timezone falls into double hour. By *double hour* I mean a situation caused by changint DST to ST, i.e. setting our clock back an hour (e.g. at 3am to 2am → double hour is between `02:00:00.000` and `02:59:59.999`, which occur both in DST and ST). ```js /** * Set time provided in a timezone * * @param {Date} [dto.date = new Date()] Date object to work with * @param {number} [dto.time.h = 0] Hour to set * @param {number} [dto.time.m = 0] Minute to set * @param {number} [dto.time.s = 0] Second to set * @param {number} [dto.time.ms = 0] Millisecond to set * @param {string} [dto.timezone = 'Europe/Bratislava'] Timezone of `dto.time` * * @return {Date} Date object */ function setLocalTime(dto = { date: new Date(), // TODO: Rename the property to `{h, m, s, ms}`. time: {h: 0, m: 0, ms: 0, s: 0}, timezone: 'Europe/Bratislava' }) { const defaultTime = {h: 0, m: 0, ms: 0, s: 0} const defaultTimeKeys = Object.keys(defaultTime) // src: https://stackoverflow.com/a/44118363/3408342 if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) { throw new Error('`Intl` API is not available or it does not contain a list of timezone identifiers in this environment') } if (!(dto.date instanceof Date)) { throw Error('`date` must be a `Date` object.') } try { Intl.DateTimeFormat(undefined, {timeZone: dto.timezone}) } catch (e) { throw Error('`timezone` must be a valid IANA timezone.') } if ( typeof dto.time !== 'undefined' && typeof dto.time !== 'object' && dto.time instanceof Object && Object.keys(dto.time).every(v => defaultTimeKeys.indexOf(v) !== -1) ) { throw Error('`time` must be an object of `{h: number, m: number, s: number, ms: number}` format, where numbers should be valid time values.') } dto.time = Object.assign({}, defaultTime, dto.time) const getTimezoneOffsetHours = ({date, localisedDate, returnNumber, timezone}) => { let offsetString if (localisedDate) { offsetString = localisedDate.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0] } else { offsetString = new Intl .DateTimeFormat('en-GB', {timeZone: timezone, timeZoneName: 'longOffset'}) .formatToParts(date) .find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0] } return returnNumber ? offsetString.split(':').reduce((a, c) => /^[+-]/.test(c) ? +c * 60 : a + +c, 0) : offsetString } const pad = (n, len) => `00${n}`.slice(-len) let [datePart, offset] = dto.date.toLocaleDateString('sv', { timeZone: dto.timezone, timeZoneName: 'longOffset' }).split(/ GMT|\//) offset = offset.replace(String.fromCharCode(8722), '-') const newDateWithoutOffset = `${datePart}T${pad(dto.time.h || 0, 2)}:${pad(dto.time.m || 0, 2)}:${pad(dto.time.s || 0, 2)}.${pad(dto.time.ms || 0, 3)}` let newDate = new Date(`${newDateWithoutOffset}${offset}`) const newDateTimezoneOffsetHours = getTimezoneOffsetHours({date: newDate, timezone: dto.timezone}) // Check if timezones of `dto.date` and `newDate` match; if not, use the new timezone to re-create `newDate` newDate = newDateTimezoneOffsetHours === offset ? newDate : new Date(`${newDateWithoutOffset}${newDateTimezoneOffsetHours}`) if (dto.time.h !== +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(newDate)?.[0].value) { newDate = new Date('') } return newDate } const timezoneIana = 'Europe/Bratislava' const tests = [ { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-29T23:56:12.006Z'), testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST before double hour', time: {h: 1, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+02:00', now: new Date('2022-10-29T23:56:12.006Z'), testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST during double hour', time: {h: 2, m: 55} }, // FIXME { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-29T23:56:12.006Z'), testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST during double hour', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-29T23:56:12.006Z'), testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST after double hour', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-30T00:56:12.006Z'), testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST before double hour', time: {h: 1, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+02:00', now: new Date('2022-10-30T00:56:12.006Z'), testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST during double hour', time: {h: 2, m: 55} }, // FIXME { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T00:56:12.006Z'), testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST during double hour', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-30T00:56:12.006Z'), testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST after double hour', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-30T01:56:12.006Z'), testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST before double hour', time: {h: 1, m: 55} }, // FIXME { expString: '30/10/2022, 02:55:00 GMT+02:00', now: new Date('2022-10-30T01:56:12.006Z'), testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST during double hour', time: {h: 2, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T01:56:12.006Z'), testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-30T01:56:12.006Z'), testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST after double hour', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-30T02:56:12.006Z'), testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST before double hour', time: {h: 1, m: 55} }, // FIXME { expString: '30/10/2022, 02:55:00 GMT+02:00', now: new Date('2022-10-30T02:56:12.006Z'), testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST during double hour', time: {h: 2, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T02:56:12.006Z'), testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-30T02:56:12.006Z'), testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST after double hour', time: {h: 3, m: 55} }, { expString: '26/03/2023, 01:55:00 GMT+01:00', now: new Date('2023-03-26T00:56:12.006Z'), testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST before skipped hour', time: {h: 1, m: 55} }, // FIXME { expString: 'Invalid Date', now: new Date('2023-03-26T00:56:12.006Z'), testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour', time: {h: 2, m: 55} }, { expString: '26/03/2023, 03:55:00 GMT+02:00', now: new Date('2023-03-26T00:56:12.006Z'), testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in DST after skipped hour', time: {h: 3, m: 55} }, { expString: '26/03/2023, 01:55:00 GMT+01:00', now: new Date('2023-03-26T01:56:12.006Z'), testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST before skipped hour', time: {h: 1, m: 55} }, // FIXME { expString: 'Invalid Date', now: new Date('2023-03-26T01:56:12.006Z'), testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour', time: {h: 2, m: 55} }, { expString: '26/03/2023, 03:55:00 GMT+02:00', now: new Date('2023-03-26T01:56:12.006Z'), testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in DST after skipped hour', time: {h: 3, m: 55} } // TODO: Add a test of a date in DST and ST on a day on which there is no timezone change (two tests in total, one for DST and another for ST). ] const results = tests.map(t => { const newDate = setLocalTime({date: t.now, time: t.time, timezone: timezoneIana}) const newDateString = newDate.toLocaleString('en-GB', {timeZone: timezoneIana, timeZoneName: 'longOffset'}) const testResult = newDateString === t.expString if (testResult) { console.log(testResult, `: ${t.testName} : ${newDateString}`) } else { console.log(testResult, `: ${t.testName} : ${newDateString} :`, {newDate, newDateString, test: t}) } return testResult }).reduce((a, c, i) => { if (c) { a.passed++ } else { a.failed++ a.failedTestIds.push(i) } return a }, {failed: 0, failedTestIds: [], passed: 0}) console.log(results) ```
2022/10/29
[ "https://Stackoverflow.com/questions/74243879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3408342/" ]
I created the following function that sets the time in a local timezone, for example, if you have `Date` object and you want to change its time (but not date in a particular timezone, regardless of the UTC date of that time), you provide this function with that `Date` object, the required time, timezone and optionally whether you prefer using the new timezone (see below). I had to add `preferNewTimezone` parameter because off so-called *double hours* (hours in a non-UTC timezone that occur twice because of setting the clock back by an hour), as those failed to output the date (including timezone offset) I expected. I don’t say it is fast nor perfect, however, it works. :) I have created 52 tests of this function in `Europe/Bratislava` timezone. They all pass. I presume it’ll work for any timezone. If not and you find an issue or have an improvement/optimisation, I want to hear about it. ```js /** * Set time provided in a timezone * * @param {Date} [dto.date = new Date()] Date object to work with * @param {boolean} [dto.preferNewTimezone = false] Whether to prefer new timezone for double hours * @param {number} [dto.time.h = 0] Hour to set * @param {number} [dto.time.m = 0] Minute to set * @param {number} [dto.time.s = 0] Second to set * @param {number} [dto.time.ms = 0] Millisecond to set * @param {string} [dto.timezone = 'Europe/Bratislava'] Timezone of `dto.time` * * @return {Date} Date object */ function setLocalTime(dto = { date: new Date(), preferNewTimezone: false, time: {h: 0, m: 0, ms: 0, s: 0}, timezone: 'Europe/Bratislava' }) { const defaultTime = {h: 0, m: 0, ms: 0, s: 0} const defaultTimeKeys = Object.keys(defaultTime) // src: https://stackoverflow.com/a/44118363/3408342 if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) { throw new Error('`Intl` API is not available or it does not contain a list of timezone identifiers in this environment') } if (!(dto.date instanceof Date)) { throw Error('`date` must be a `Date` object.') } try { Intl.DateTimeFormat(undefined, {timeZone: dto.timezone}) } catch (e) { throw Error('`timezone` must be a valid IANA timezone.') } if ( typeof dto.time !== 'undefined' && typeof dto.time !== 'object' && dto.time instanceof Object && Object.keys(dto.time).every(v => defaultTimeKeys.includes(v)) ) { throw Error('`time` must be an object of `{h: number, m: number, s: number, ms: number}` format, where numbers should be valid time values.') } dto.time = Object.assign({}, defaultTime, dto.time) /** * Whether a date falls in double hour in a particular timezone * * @param {Date} dto.date Date * @param {string} dto.timezone IANA timezone * @return {boolean} `true` if the specified Date falls in double hour in a particular timezone, `false` otherwise */ const isInDoubleHour = (dto = {date: new Date(), timezone: 'Europe/Bratislava'}) => { // Get hour in `dto.timezone` of timezones an hour before and after `dto.date` const hourBeforeHour = +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(new Date(new Date(dto.date).setUTCHours(dto.date.getUTCHours() - 1)))?.[0].value const hourDateHour = +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(dto.date)?.[0].value const hourAfterHour = +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(new Date(new Date(dto.date).setUTCHours(dto.date.getUTCHours() + 1)))?.[0].value return hourBeforeHour === hourDateHour || hourAfterHour === hourDateHour } const getTimezoneOffsetHours = ({date, localisedDate, returnNumber, timezone}) => { let offsetString if (localisedDate) { offsetString = localisedDate.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0] } else { offsetString = new Intl .DateTimeFormat('en-GB', {timeZone: timezone, timeZoneName: 'longOffset'}) .formatToParts(date) .find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0] } return returnNumber ? offsetString.split(':').reduce((a, c) => /^[+-]/.test(c) ? +c * 60 : a + +c, 0) : offsetString } /** * Pad a number with zeros from left to a required length * * @param {number} n Number * @param {number} len Length * @return {string} Padded number */ const pad = (n, len) => `00${n}`.slice(-len) let [datePart, offset] = dto.date.toLocaleDateString('sv', { timeZone: dto.timezone, timeZoneName: 'longOffset' }).split(/ GMT|\//) offset = offset.replace(String.fromCharCode(8722), '-') const newDateWithoutOffset = `${datePart}T${pad(dto.time.h || 0, 2)}:${pad(dto.time.m || 0, 2)}:${pad(dto.time.s || 0, 2)}.${pad(dto.time.ms || 0, 3)}` let newDate = new Date(`${newDateWithoutOffset}${offset}`) const newDateTimezoneOffsetHours = getTimezoneOffsetHours({date: newDate, timezone: dto.timezone}) // Check if timezones of `dto.date` and `newDate` match; if not, use the new timezone to re-create `newDate` newDate = newDateTimezoneOffsetHours === offset ? newDate : new Date(`${newDateWithoutOffset}${newDateTimezoneOffsetHours}`) // Invalidate the date in `newDate` when the hour defined by user is not the same as the hour of `newDate` formatted in the user-defined timezone if (dto.time.h !== +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(newDate)?.[0].value) { newDate = new Date('') } // Check if the user prefers using the new timezone when `newDate` is in double hour newDate = dto.preferNewTimezone && !isNaN(newDate) && isInDoubleHour({date: newDate, timezone: dto.timezone}) ? new Date(`${newDateWithoutOffset}${getTimezoneOffsetHours({date: new Date(new Date(newDate).setUTCHours(dto.date.getUTCHours() + 1)), timezone: dto.timezone})}`) : newDate return newDate } const timezoneIana = 'Europe/Bratislava' const tests = [ { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-29T23:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST before double hour [don\'t prefer new timezone]', time: {h: 1, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+02:00', now: new Date('2022-10-29T23:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST during double hour [don\'t prefer new timezone]', time: {h: 2, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+02:00', now: new Date('2022-10-29T23:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST during double hour [don\'t prefer new timezone]', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-29T23:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST after double hour [don\'t prefer new timezone]', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-30T00:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST before double hour [don\'t prefer new timezone]', time: {h: 1, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+02:00', now: new Date('2022-10-30T00:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST during double hour [don\'t prefer new timezone]', time: {h: 2, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+02:00', now: new Date('2022-10-30T00:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST during double hour [don\'t prefer new timezone]', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-30T00:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST after double hour [don\'t prefer new timezone]', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-30T01:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST before double hour [don\'t prefer new timezone]', time: {h: 1, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T01:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour [don\'t prefer new timezone]', time: {h: 2, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T01:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour [don\'t prefer new timezone]', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-30T01:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST after double hour [don\'t prefer new timezone]', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-30T02:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST before double hour [don\'t prefer new timezone]', time: {h: 1, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T02:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour [don\'t prefer new timezone]', time: {h: 2, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T02:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour [don\'t prefer new timezone]', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-30T02:56:12.006Z'), preferNewTimezone: false, testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST after double hour [don\'t prefer new timezone]', time: {h: 3, m: 55} }, { expString: '26/03/2023, 01:55:00 GMT+01:00', now: new Date('2023-03-26T00:56:12.006Z'), preferNewTimezone: false, testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST before skipped hour [don\'t prefer new timezone]', time: {h: 1, m: 55} }, { expString: 'Invalid Date', now: new Date('2023-03-26T00:56:12.006Z'), preferNewTimezone: false, testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour [don\'t prefer new timezone]', time: {h: 2, m: 55} }, { expString: '26/03/2023, 03:55:00 GMT+02:00', now: new Date('2023-03-26T00:56:12.006Z'), preferNewTimezone: false, testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in DST after skipped hour [don\'t prefer new timezone]', time: {h: 3, m: 55} }, { expString: '26/03/2023, 01:55:00 GMT+01:00', now: new Date('2023-03-26T01:56:12.006Z'), preferNewTimezone: false, testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST before skipped hour [don\'t prefer new timezone]', time: {h: 1, m: 55} }, { expString: 'Invalid Date', now: new Date('2023-03-26T01:56:12.006Z'), preferNewTimezone: false, testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour [don\'t prefer new timezone]', time: {h: 2, m: 55} }, { expString: '26/03/2023, 03:55:00 GMT+02:00', now: new Date('2023-03-26T01:56:12.006Z'), preferNewTimezone: false, testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in DST after skipped hour [don\'t prefer new timezone]', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-29T23:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST before double hour [prefer new timezone] ', time: {h: 1, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-29T23:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST during double hour [prefer new timezone] ', time: {h: 2, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-29T23:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST during double hour [prefer new timezone] ', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-29T23:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST after double hour [prefer new timezone] ', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-30T00:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST before double hour [prefer new timezone] ', time: {h: 1, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T00:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST during double hour [prefer new timezone] ', time: {h: 2, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T00:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST during double hour [prefer new timezone] ', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-30T00:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST after double hour [prefer new timezone] ', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-30T01:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST before double hour [prefer new timezone] ', time: {h: 1, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T01:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour [prefer new timezone] ', time: {h: 2, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T01:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour [prefer new timezone] ', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-30T01:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST after double hour [prefer new timezone] ', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-30T02:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST before double hour [prefer new timezone] ', time: {h: 1, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T02:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour [prefer new timezone] ', time: {h: 2, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T02:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour [prefer new timezone] ', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-30T02:56:12.006Z'), preferNewTimezone: true, testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST after double hour [prefer new timezone] ', time: {h: 3, m: 55} }, { expString: '26/03/2023, 01:55:00 GMT+01:00', now: new Date('2023-03-26T00:56:12.006Z'), preferNewTimezone: true, testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST before skipped hour [prefer new timezone] ', time: {h: 1, m: 55} }, { expString: 'Invalid Date', now: new Date('2023-03-26T00:56:12.006Z'), preferNewTimezone: true, testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour [prefer new timezone] ', time: {h: 2, m: 55} }, { expString: '26/03/2023, 03:55:00 GMT+02:00', now: new Date('2023-03-26T00:56:12.006Z'), preferNewTimezone: true, testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in DST after skipped hour [prefer new timezone] ', time: {h: 3, m: 55} }, { expString: '26/03/2023, 01:55:00 GMT+01:00', now: new Date('2023-03-26T01:56:12.006Z'), preferNewTimezone: true, testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST before skipped hour [prefer new timezone] ', time: {h: 1, m: 55} }, { expString: 'Invalid Date', now: new Date('2023-03-26T01:56:12.006Z'), preferNewTimezone: true, testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour [prefer new timezone] ', time: {h: 2, m: 55} }, { expString: '26/03/2023, 03:55:00 GMT+02:00', now: new Date('2023-03-26T01:56:12.006Z'), preferNewTimezone: true, testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in DST after skipped hour [prefer new timezone] ', time: {h: 3, m: 55} }, { expString: '01/01/2023, 03:55:00 GMT+01:00', now: new Date('2023-01-01T10:00:00.000Z'), preferNewTimezone: true, testName: '[ST] `now` in ST, `newDate` in ST before `now` [prefer new timezone] ', time: {h: 3, m: 55} }, { expString: '01/01/2023, 12:00:00 GMT+01:00', now: new Date('2023-01-01T10:00:00.000Z'), preferNewTimezone: true, testName: '[ST] `now` in ST, `newDate` in ST after `now` [prefer new timezone] ', time: {h: 12} }, { expString: '01/07/2023, 03:55:00 GMT+02:00', now: new Date('2023-07-01T10:00:00.000Z'), preferNewTimezone: true, testName: '[ST] `now` in DST, `newDate` in DST before `now` [prefer new timezone] ', time: {h: 3, m: 55} }, { expString: '01/07/2023, 12:00:00 GMT+02:00', now: new Date('2023-07-01T10:00:00.000Z'), preferNewTimezone: true, testName: '[ST] `now` in DST, `newDate` in DST after `now` [prefer new timezone] ', time: {h: 12} }, { expString: '01/01/2023, 03:55:00 GMT+01:00', now: new Date('2023-01-01T10:00:00.000Z'), preferNewTimezone: false, testName: '[ST] `now` in ST, `newDate` in ST before `now` [don\'t prefer new timezone]', time: {h: 3, m: 55} }, { expString: '01/01/2023, 12:00:00 GMT+01:00', now: new Date('2023-01-01T10:00:00.000Z'), preferNewTimezone: false, testName: '[ST] `now` in ST, `newDate` in ST after `now` [don\'t prefer new timezone]', time: {h: 12} }, { expString: '01/07/2023, 03:55:00 GMT+02:00', now: new Date('2023-07-01T10:00:00.000Z'), preferNewTimezone: false, testName: '[ST] `now` in DST, `newDate` in DST before `now` [don\'t prefer new timezone]', time: {h: 3, m: 55} }, { expString: '01/07/2023, 12:00:00 GMT+02:00', now: new Date('2023-07-01T10:00:00.000Z'), preferNewTimezone: false, testName: '[ST] `now` in DST, `newDate` in DST after `now` [don\'t prefer new timezone]', time: {h: 12} } ] const results = tests.map(t => { const newDate = setLocalTime({date: t.now, preferNewTimezone: t.preferNewTimezone, time: t.time, timezone: timezoneIana}) const newDateString = newDate.toLocaleString('en-GB', {timeZone: timezoneIana, timeZoneName: 'longOffset'}) const testResult = newDateString === t.expString if (testResult) { console.log(testResult, `: ${t.testName} : ${newDateString}`) } else { console.log(testResult, `: ${t.testName} : ${newDateString} :`, {newDate, newDateString, test: t}) } return testResult }).reduce((a, c, i) => { if (c) { a.passed++ } else { a.failed++ a.failedTestIds.push(i) } return a }, {failed: 0, failedTestIds: [], passed: 0}) console.log(results) ```
In JavaScript the `Date` objects usually expect time definitions in the local (browser) time and store it in UTC time. You can explicitly set a time in the UTC timezone with the `.setUTC<time part>()` methods. You can set the time `hours` for the timezone GMT+2 by using the `.setUTCHours()` function with an argument of `hours-2`. ```js const d=new Date(),hours=10,minutes=40; d.setUTCHours(hours-2);d.setUTCMinutes(minutes); console.log("GMT/UTC:",d); // UTC time ("Z") console.log("New York:",d.toLocaleString("en-US",{timeZone:"America/New_York"})); // local time US console.log("Berlin:",d.toLocaleString("de-DE",{timeZone:"Europe/Berlin"})); // local time Germany (GMT+2) ``` The method `.setUTCMinutes()` and `setMinutes()` will in most cases achieve the same result. One notable exception is the time zone "Asia/Kolkata" which will apply a 30 minutes offset.
74,243,879
I want to use UTC dates in my Node.js backend app, however, I need to be able to set time (hours and minutes) in a local/user-specified timezone. I am looking for a solution in either pure JS or using `dayjs`. I am not looking for a solution in `moment`. It seemed like using `dayjs` I could solve this problem quite easily, however, I could not find a way to accomplish this. I can use UTC timezone by using [`dayjs.utc()`](https://day.js.org/docs/en/plugin/utc) or using [`dayjs.tz(someDate, 'Etc/UTC')`](https://day.js.org/docs/en/timezone/timezone). When using `dayjs.utc()`, I cannot use/specify other timezones for *anything*, therefore I could not find a way to tell `dayjs` I want to set hours/minutes in a particular (non-UTC) timezone. When using `dayjs.tz()`, I still cannot define a timezone of time I want to set to a particular date. ### Example in plain JS My locale timezone is `Europe/Slovakia` (CEST = UTC+02 with DST, CET = UTC+1 without DST), however, I want this to work with any timezone. ```js // Expected outcome // old: 2022-10-29T10:00:00.000Z // new time: 10h 15m CEST // new: 2022-10-29T08:15:00.000Z // Plain JS const now = new Date('2022-10-29T10:00:00.000Z') const hours = 10 const minutes = 15 now.setHours(10) now.setMinutes(15) // As my default timezone is `Europe/Bratislava`, it seems to work as expected console.log(now) // Output: 2022-10-29T08:15:00.000Z // However, it won't work with timezones other than my local timezone ``` ### (Nearly) a solution ***Update: I posted a working function in [this answer](https://stackoverflow.com/a/74245936/3408342).*** The following functions seems to work for most test cases, however, it fails for 6 4 cases known to me (any help is greatly appreciated): * [DST to ST] `now` in DST before double hour, `newDate` in ST during double hour; * [DST to ST] `now` in DST during double hour, `newDate` in ST during double hour; * [DST to ST] `now` in ST during double hour, `newDate` in DST during double hour; * [DST to ST] `now` in ST after double hour, `newDate` in DST during double hour; * [ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour; * [ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour. I think the only missing piece is to find a way to check if a particular date in a non-UTC timezone falls into double hour. By *double hour* I mean a situation caused by changint DST to ST, i.e. setting our clock back an hour (e.g. at 3am to 2am → double hour is between `02:00:00.000` and `02:59:59.999`, which occur both in DST and ST). ```js /** * Set time provided in a timezone * * @param {Date} [dto.date = new Date()] Date object to work with * @param {number} [dto.time.h = 0] Hour to set * @param {number} [dto.time.m = 0] Minute to set * @param {number} [dto.time.s = 0] Second to set * @param {number} [dto.time.ms = 0] Millisecond to set * @param {string} [dto.timezone = 'Europe/Bratislava'] Timezone of `dto.time` * * @return {Date} Date object */ function setLocalTime(dto = { date: new Date(), // TODO: Rename the property to `{h, m, s, ms}`. time: {h: 0, m: 0, ms: 0, s: 0}, timezone: 'Europe/Bratislava' }) { const defaultTime = {h: 0, m: 0, ms: 0, s: 0} const defaultTimeKeys = Object.keys(defaultTime) // src: https://stackoverflow.com/a/44118363/3408342 if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) { throw new Error('`Intl` API is not available or it does not contain a list of timezone identifiers in this environment') } if (!(dto.date instanceof Date)) { throw Error('`date` must be a `Date` object.') } try { Intl.DateTimeFormat(undefined, {timeZone: dto.timezone}) } catch (e) { throw Error('`timezone` must be a valid IANA timezone.') } if ( typeof dto.time !== 'undefined' && typeof dto.time !== 'object' && dto.time instanceof Object && Object.keys(dto.time).every(v => defaultTimeKeys.indexOf(v) !== -1) ) { throw Error('`time` must be an object of `{h: number, m: number, s: number, ms: number}` format, where numbers should be valid time values.') } dto.time = Object.assign({}, defaultTime, dto.time) const getTimezoneOffsetHours = ({date, localisedDate, returnNumber, timezone}) => { let offsetString if (localisedDate) { offsetString = localisedDate.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0] } else { offsetString = new Intl .DateTimeFormat('en-GB', {timeZone: timezone, timeZoneName: 'longOffset'}) .formatToParts(date) .find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0] } return returnNumber ? offsetString.split(':').reduce((a, c) => /^[+-]/.test(c) ? +c * 60 : a + +c, 0) : offsetString } const pad = (n, len) => `00${n}`.slice(-len) let [datePart, offset] = dto.date.toLocaleDateString('sv', { timeZone: dto.timezone, timeZoneName: 'longOffset' }).split(/ GMT|\//) offset = offset.replace(String.fromCharCode(8722), '-') const newDateWithoutOffset = `${datePart}T${pad(dto.time.h || 0, 2)}:${pad(dto.time.m || 0, 2)}:${pad(dto.time.s || 0, 2)}.${pad(dto.time.ms || 0, 3)}` let newDate = new Date(`${newDateWithoutOffset}${offset}`) const newDateTimezoneOffsetHours = getTimezoneOffsetHours({date: newDate, timezone: dto.timezone}) // Check if timezones of `dto.date` and `newDate` match; if not, use the new timezone to re-create `newDate` newDate = newDateTimezoneOffsetHours === offset ? newDate : new Date(`${newDateWithoutOffset}${newDateTimezoneOffsetHours}`) if (dto.time.h !== +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(newDate)?.[0].value) { newDate = new Date('') } return newDate } const timezoneIana = 'Europe/Bratislava' const tests = [ { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-29T23:56:12.006Z'), testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST before double hour', time: {h: 1, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+02:00', now: new Date('2022-10-29T23:56:12.006Z'), testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST during double hour', time: {h: 2, m: 55} }, // FIXME { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-29T23:56:12.006Z'), testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST during double hour', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-29T23:56:12.006Z'), testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST after double hour', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-30T00:56:12.006Z'), testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST before double hour', time: {h: 1, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+02:00', now: new Date('2022-10-30T00:56:12.006Z'), testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST during double hour', time: {h: 2, m: 55} }, // FIXME { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T00:56:12.006Z'), testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST during double hour', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-30T00:56:12.006Z'), testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST after double hour', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-30T01:56:12.006Z'), testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST before double hour', time: {h: 1, m: 55} }, // FIXME { expString: '30/10/2022, 02:55:00 GMT+02:00', now: new Date('2022-10-30T01:56:12.006Z'), testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST during double hour', time: {h: 2, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T01:56:12.006Z'), testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-30T01:56:12.006Z'), testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST after double hour', time: {h: 3, m: 55} }, { expString: '30/10/2022, 01:55:00 GMT+02:00', now: new Date('2022-10-30T02:56:12.006Z'), testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST before double hour', time: {h: 1, m: 55} }, // FIXME { expString: '30/10/2022, 02:55:00 GMT+02:00', now: new Date('2022-10-30T02:56:12.006Z'), testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST during double hour', time: {h: 2, m: 55} }, { expString: '30/10/2022, 02:55:00 GMT+01:00', now: new Date('2022-10-30T02:56:12.006Z'), testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour', time: {h: 2, m: 55} }, { expString: '30/10/2022, 03:55:00 GMT+01:00', now: new Date('2022-10-30T02:56:12.006Z'), testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST after double hour', time: {h: 3, m: 55} }, { expString: '26/03/2023, 01:55:00 GMT+01:00', now: new Date('2023-03-26T00:56:12.006Z'), testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST before skipped hour', time: {h: 1, m: 55} }, // FIXME { expString: 'Invalid Date', now: new Date('2023-03-26T00:56:12.006Z'), testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour', time: {h: 2, m: 55} }, { expString: '26/03/2023, 03:55:00 GMT+02:00', now: new Date('2023-03-26T00:56:12.006Z'), testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in DST after skipped hour', time: {h: 3, m: 55} }, { expString: '26/03/2023, 01:55:00 GMT+01:00', now: new Date('2023-03-26T01:56:12.006Z'), testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST before skipped hour', time: {h: 1, m: 55} }, // FIXME { expString: 'Invalid Date', now: new Date('2023-03-26T01:56:12.006Z'), testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour', time: {h: 2, m: 55} }, { expString: '26/03/2023, 03:55:00 GMT+02:00', now: new Date('2023-03-26T01:56:12.006Z'), testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in DST after skipped hour', time: {h: 3, m: 55} } // TODO: Add a test of a date in DST and ST on a day on which there is no timezone change (two tests in total, one for DST and another for ST). ] const results = tests.map(t => { const newDate = setLocalTime({date: t.now, time: t.time, timezone: timezoneIana}) const newDateString = newDate.toLocaleString('en-GB', {timeZone: timezoneIana, timeZoneName: 'longOffset'}) const testResult = newDateString === t.expString if (testResult) { console.log(testResult, `: ${t.testName} : ${newDateString}`) } else { console.log(testResult, `: ${t.testName} : ${newDateString} :`, {newDate, newDateString, test: t}) } return testResult }).reduce((a, c, i) => { if (c) { a.passed++ } else { a.failed++ a.failedTestIds.push(i) } return a }, {failed: 0, failedTestIds: [], passed: 0}) console.log(results) ```
2022/10/29
[ "https://Stackoverflow.com/questions/74243879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3408342/" ]
The following follows your method of getting the date and offset in the target timezone then using it with the time parts to generate a timestamp that is parsed by the built–in parser. It doesn't fix the issue of the initial date and the result crossing an offset (likely DST), it's just a bit less code. You really should use a suitable library. E.g. ```js function setLocalTime( date = new Date(), time = {h: 0, m: 0, s: 0, ms: 0}, tz = 'Europe/Bratislava') { let {h, m, s, ms} = time; let z = (n,len) => ('00'+n).slice(-len); let [datePart, offset] = date.toLocaleDateString('sv', { timeZone:tz, timeZoneName:'longOffset' }).split(' GMT'); let timestamp = `${datePart}T` + `${z(h||0,2)}:${z(m||0,2)}:${z(s||0,2)}.${z(ms||0,3)}` + `${offset.replace(String.fromCharCode(8722),'-')}`; return new Date(timestamp); } let tz, d; tz = 'Europe/Bratislava'; d = setLocalTime(new Date(), {h: 15, m: 30, s: 0, ms: 0}, tz); console.log('UTC: ' + d.toISOString()); console.log(tz + ': ' + d.toLocaleString('en-gb',{timeZone: tz, timeZoneName: 'long'})); tz = 'America/New_York'; d = setLocalTime(new Date(), {h: 15, m: 30, s: 0, ms: 0}, tz); console.log('UTC: '+ d.toISOString()); console.log(tz + ': ' + d.toLocaleString('en-gb',{timeZone: tz, timeZoneName: 'long'})); ``` In Safari, "−" character (charCode 8722) in a negative offset isn't parsed correctly so it's replaced with a hyphen. Also, `timeZoneName:'longOffset'` may not be that widely supported yet.
In JavaScript the `Date` objects usually expect time definitions in the local (browser) time and store it in UTC time. You can explicitly set a time in the UTC timezone with the `.setUTC<time part>()` methods. You can set the time `hours` for the timezone GMT+2 by using the `.setUTCHours()` function with an argument of `hours-2`. ```js const d=new Date(),hours=10,minutes=40; d.setUTCHours(hours-2);d.setUTCMinutes(minutes); console.log("GMT/UTC:",d); // UTC time ("Z") console.log("New York:",d.toLocaleString("en-US",{timeZone:"America/New_York"})); // local time US console.log("Berlin:",d.toLocaleString("de-DE",{timeZone:"Europe/Berlin"})); // local time Germany (GMT+2) ``` The method `.setUTCMinutes()` and `setMinutes()` will in most cases achieve the same result. One notable exception is the time zone "Asia/Kolkata" which will apply a 30 minutes offset.
199,880
Is there any way to show a calculated field when I'm filling out a new item for a list? For example: If I select "Blue" in field1, and "Bird" in field2, then, on the same page where I am filling in information, I can see field3(Calculated field) show a value of "Blue Jay" Currently, the calculated field doesn't show until I add a new item. It would be even better if the update was in real time, though I don't expect that.
2016/11/17
[ "https://sharepoint.stackexchange.com/questions/199880", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/61825/" ]
**As a short answer** : unfortunately , No, the calculated field is calculated after the item added or updated If you are using Enterprise Edition of SharePoint then try editing list form with InfoPath and insert field which will do the calculation for you. Make that field read-only and then publish the form. In InfoPath , You can * Add a Textbox as `field3` in your form * At `field2` add new a `Action rule` and at **run these action select** `set a fields value` * At **Field** Value select Field3 * At **Value** concatenate your `field1` and `field2` [![enter image description here](https://i.stack.imgur.com/SN6jP.gif)](https://i.stack.imgur.com/SN6jP.gif)
Calculated columns don't work that way, they are visible on the display form only or in views and only recalculate when items are edited. If you want that type of preview feature, you'll have to incorporate custom javascript on your forms.
77,133
There seems to be a lot of software to control (or emulate) mouse input through the keyboard, but what about the opposite? Basically I'm looking for a way to emulate up/down/left/right clicks with mouse movement, at a fast rate (i.e. lots of very short and quick right clicks while I move the mouse to the right) If I have to learn some scripting language to do it, ok, but I don't know if it would even be possible. Note: This is meant to work on fullscreen, and having a way to turn it on/off with an F# key would be awesome! Thanks for your time :)
2009/11/30
[ "https://superuser.com/questions/77133", "https://superuser.com", "https://superuser.com/users/19668/" ]
OK, hopefully supplying a *useful* answer this time, instead of the inverse of the actual answer you wanted... How about an AutoHotkey script for [mouse gestures](http://www.autohotkey.com/docs/scripts/MouseGestures.htm)? You haven't indicated what sort of control you require, so perhaps a set of gestures is adequate. If, however, you're looking to essentially replace the whole keyboard with one mouse, well, this may not be the answer you need. Or, good luck memorizing all those gestures. :-D --- As is so often the case, [AutoHotkey](http://www.autohotkey.com) is your tool. I won't bore you with extensive review or details, as Google (and even SuperUser) are loaded with info about it. EDIT: In fact, here's a [ready-made script](http://www.autohotkey.com/docs/scripts/NumpadMouse.htm) that'll enable you to use your numeric keypad as a mouse, with several customizations.
If you want something where you can type with your mouse, then I suggest you take a look at [Dasher](http://www.inference.phy.cam.ac.uk/dasher/). That is, if I take your question title as the question. As I really don't quite understand your question.
77,133
There seems to be a lot of software to control (or emulate) mouse input through the keyboard, but what about the opposite? Basically I'm looking for a way to emulate up/down/left/right clicks with mouse movement, at a fast rate (i.e. lots of very short and quick right clicks while I move the mouse to the right) If I have to learn some scripting language to do it, ok, but I don't know if it would even be possible. Note: This is meant to work on fullscreen, and having a way to turn it on/off with an F# key would be awesome! Thanks for your time :)
2009/11/30
[ "https://superuser.com/questions/77133", "https://superuser.com", "https://superuser.com/users/19668/" ]
If you're on Windows, what about the On-Screen Keyboard? It's found under **All Programs -> Accessories -> Accessibility** on XP (similar for Vista+) ![alt text](https://i.stack.imgur.com/nPFOE.png)
If you want something where you can type with your mouse, then I suggest you take a look at [Dasher](http://www.inference.phy.cam.ac.uk/dasher/). That is, if I take your question title as the question. As I really don't quite understand your question.
77,133
There seems to be a lot of software to control (or emulate) mouse input through the keyboard, but what about the opposite? Basically I'm looking for a way to emulate up/down/left/right clicks with mouse movement, at a fast rate (i.e. lots of very short and quick right clicks while I move the mouse to the right) If I have to learn some scripting language to do it, ok, but I don't know if it would even be possible. Note: This is meant to work on fullscreen, and having a way to turn it on/off with an F# key would be awesome! Thanks for your time :)
2009/11/30
[ "https://superuser.com/questions/77133", "https://superuser.com", "https://superuser.com/users/19668/" ]
OK, hopefully supplying a *useful* answer this time, instead of the inverse of the actual answer you wanted... How about an AutoHotkey script for [mouse gestures](http://www.autohotkey.com/docs/scripts/MouseGestures.htm)? You haven't indicated what sort of control you require, so perhaps a set of gestures is adequate. If, however, you're looking to essentially replace the whole keyboard with one mouse, well, this may not be the answer you need. Or, good luck memorizing all those gestures. :-D --- As is so often the case, [AutoHotkey](http://www.autohotkey.com) is your tool. I won't bore you with extensive review or details, as Google (and even SuperUser) are loaded with info about it. EDIT: In fact, here's a [ready-made script](http://www.autohotkey.com/docs/scripts/NumpadMouse.htm) that'll enable you to use your numeric keypad as a mouse, with several customizations.
If you're on Windows, what about the On-Screen Keyboard? It's found under **All Programs -> Accessories -> Accessibility** on XP (similar for Vista+) ![alt text](https://i.stack.imgur.com/nPFOE.png)
95,407
I was playing some math games intended for children, in Japanese, and the subject was 引き算. The isolated question came up "14は10といくつ?" In the context of 引き算 it makes sense that the answer turned out to be 4, but I don't understand the question structurally. How does it imply "If you take 10 away from 14, what's left?" Is this to be understood only in the context? Assuming the と is conditional, my rough translation is "As for 14... if (you take away) 10... how much(left)?" with everything in parenthesis being only implied. Is this correct? Are the は and と particles doing what I think?
2022/07/15
[ "https://japanese.stackexchange.com/questions/95407", "https://japanese.stackexchange.com", "https://japanese.stackexchange.com/users/41549/" ]
> > Is this to be understood only in the context? Assuming the と is conditional > > > The と is not conditional, and you can tell that from the word followed by the と. **The conditional と should follow 活用語の終止形/the terminal form of a conjugatable word**, such as verb, i/na-adjective, auxiliary, eg 「話す」「寒い」「静かだ」「〇〇だ」「~ない」. It *cannot* follow a 体言(unconjugatable word). > > Eg. > > **食べると**太ってしまう > > **明るいと**眠れない > > **静かだと**勉強がはかどる > > 佐藤さんが**いないと**困る > > > When と is attached to a 体言 (unconjugatable word) as in your example where と is attached to 「10」, it should be the case particle (格助詞). The case particle と can attach to words of various part-of-speech (because of its quotative usage). It can be used for saying "~ and ~" (enumeration), "with (someone)", (same/different) as/from..." (comparison), "(saying) that..."(quotation), etc., as you probably know. > > Eg. > > **13と**14 -- "~ and ~" ← と follows 体言 > > **リンゴとバナナと**ヨーグルト -- "~ and ~" ← と follows 体言 > > **妹と**一緒に勉強する -- "with (someone)" ← と follows 体言 > > **山田さんと**同じクラス -- "(same) as ~" ← と follows 体言 > > いや**だと**言う -- "(say) that..." ← と can follow various words > > > And as you can see, と in the sense "~ and ~" would make the most sense in your example. --- > > "14**は**10**と**いくつ?" > > > I'd say the は is the topic marker, or the thematic は (主題の「は」). > > *lit.* **As for** 14, 10 **and** how many (is it)? > > >
I think it is an odd way to ask, but the structure is: * 14 は 10 と いくつ * 14 = 10 + ? so that it is essentially a subtraction. Grammatically, は is the subject marker and と is *and* (In words, *14 is 10 and how many?*)
57,779,158
I am using material-ui for my project and I have a need to get the selected text (not the value) and do some parsing. I can't seem to find a way to do this. Here is what my component looks like: ``` <TextField select margin="dense" label="Name" variant="outlined" className={classes.textField} value={values.nameId} onChange={handleChange('nameId')} > {names.map(row => ( <MenuItem key={row.Id} value={row.Id}>{row.Name}</MenuItem> ))} </TextField> ``` handler looks like this: ``` const handleChange = name => event => { setValues({ ...values, [name]: event.target.value }); }; ``` Obviously event.target.value gets my selected value, but I want to also get the selected innerText of the selected index. Any ideas?
2019/09/03
[ "https://Stackoverflow.com/questions/57779158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8484824/" ]
This regex match should get you what you're looking for ```js let regex = /1-[0-9]{3}-[0-9]{3}-[0-9]{4}/ ```
Try ``` let candidateValue = getMeSomeValue(); const isValid = (candidateValue || "").match( /^1-[0-9]{3}-[0-9]{4}$/ ); ``` Add `\s` following the `^` and before the `$` if you want to play nice and ignore leading/trailing whitespace.
195,501
Is it coherent to suggest that it is possible to iterate, one-by-one, through every single item in an infinite set? Some have suggested that it is possible to iterate (or count) completely through an infinite set with no start (or lower bound), making infinite regress a genuinely possible reality. Mathematically, is this possible? I don't know much about math proofs, so the more basic (with the least symbols) you can keep your answer, the more likely I will understand and appreciate it. Thank you very much! ADDENDUM When I write an infinite loop into my computer code, the code begins to execute and will never complete it's looping (unless it crashes or I stop it). I am wondering if it is mathematically possible, adding one to another, to ever arrive at the completion of an infinite set, like the set of negative integers, or will it continue permanently?
2012/09/14
[ "https://math.stackexchange.com/questions/195501", "https://math.stackexchange.com", "https://math.stackexchange.com/users/40191/" ]
We may count through the integers by listing them $0,1,-1,2,-2,\dots$. This is an infinite set without a lower bound. In general, if you have a bijection $f:\mathbb{N} \to X$ where $X$ is an infinite set, then you can "iterate" through them by listing $f(1),f(2),f(3), \dots$.
Here is a way to iterate... To me, it is like mixing math and computers. You can find the ideas described in much more detail in [Generatingfunctionology by Wilf](http://www.math.upenn.edu/~wilf/gfology2.pdf). Knowing Calculus is very helpful for this. Let me explain. We would like to iterate through infinity and stop. To do this, we will use a function that is like a set. It is called a "generating function". You can find a description in more advanced English [here](http://en.wikipedia.org/wiki/Generating_function). The idea is that we use numbers (integers) to give order to the set. (This makes it a sequence). We start with the number 0 (like people often do with computers) and give it a value from the set. Suppose we give it the value 53. Then we say this as a generating function by saying $f(x)$, our function of $x$, is equal to $53 x^0$: $$f(x) = 53x^0$$ It is like a power series, if you are familiar with calculus. We raise $x$ to the 0th power, and then multiply it by 53. If we want to add a second number, say 42, we use $x$ to the first power: $$f(x) = 53 x^0 + 42 x^1$$ The idea is that the powers of $x$ let us order the numbers. This also helps us seperate the numbers. If we add the numbers 8, 71, and 32, can you guess how to write this? The answer is: $$f(x) = 53x^0 + 42x^1 + 8x^2 + 71x^3 + 32x^4$$ I hope this idea is clear. Now we want to create an infinite series. To do this, many people study [power series](http://en.wikipedia.org/wiki/Power_series). Many Calculus books study these. For example, a common one is: $$f(x) = 1x^0 + 1x^1 + 1x^2 + 1x^3 + \dots$$ This is an like an infinite set of ones. It can be written as: $$\frac{1}{1-x} = 1x^0 + 1x^1 + 1x^2 + 1x^3 + \dots$$ This means that the fraction on the left side is the same as the right side of the equals sign. They are a function. The type of function is again a generating function. The series of ones was given as: $$\frac{1}{1-x} = 1x^0 + 1x^1 + 1x^2 + 1x^3 + \dots$$ Set $x$ to some value, and you will have iterated through an infinite amount of values. The result may be somewhat suprising, so I'll leave it up to you to pick a value. Remember that you can't divide by zero, so you'll have to be careful to avoid that. The study of Calculus and, in particular, limits helps provide a solution to that problem.
69,581,492
I have string column in my `df` table, like this below: ``` d = {'col1': ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3']} df = pd.DataFrame(data=d) df ``` [![enter image description here](https://i.stack.imgur.com/X2WXJ.png)](https://i.stack.imgur.com/X2WXJ.png) I would like to convert this column, so that all values ​​contain two decimal places, but **without changing the type of this column to numeric type**. Expected output - a string column with values: [![enter image description here](https://i.stack.imgur.com/3Aefa.png)](https://i.stack.imgur.com/3Aefa.png) I am a little new to Python, I tried padding 0 [How to pad a numeric string with zeros to the right in Python?](https://stackoverflow.com/questions/40999973/how-to-pad-a-numeric-string-with-zeros-to-the-right-in-python/46021306) depending on the length of the value in the column, but it actually didn't work. Do you have idea how to handle it?
2021/10/15
[ "https://Stackoverflow.com/questions/69581492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16734748/" ]
Like this: ``` df['col1'] = df['col1'].astype(float).map('{:,.2f}'.format).astype(str) ``` If you have '' in this column you better replace them before to '0'.
This one will work no matter how many columns are in your dictionary. Try this: ```py d = {'col1': ['1.2', '3.4', '1.99', '0.14', '2.9' '', '2.3']} for x in d: for y in range(0,len(d[x])): d[x][y]=d[x][y].ljust(4,"0") print(d) ```
69,581,492
I have string column in my `df` table, like this below: ``` d = {'col1': ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3']} df = pd.DataFrame(data=d) df ``` [![enter image description here](https://i.stack.imgur.com/X2WXJ.png)](https://i.stack.imgur.com/X2WXJ.png) I would like to convert this column, so that all values ​​contain two decimal places, but **without changing the type of this column to numeric type**. Expected output - a string column with values: [![enter image description here](https://i.stack.imgur.com/3Aefa.png)](https://i.stack.imgur.com/3Aefa.png) I am a little new to Python, I tried padding 0 [How to pad a numeric string with zeros to the right in Python?](https://stackoverflow.com/questions/40999973/how-to-pad-a-numeric-string-with-zeros-to-the-right-in-python/46021306) depending on the length of the value in the column, but it actually didn't work. Do you have idea how to handle it?
2021/10/15
[ "https://Stackoverflow.com/questions/69581492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16734748/" ]
Use [`str.ljust`](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.ljust.html): ``` df['col1'] = df['col1'].str.ljust(4, '0') ``` output: ``` col1 0 1.20 1 3.40 2 1.99 3 0.14 4 2.90 5 2.30 ``` To leave empty rows intact: ``` df['col1'] = df['col1'].mask(df['col1'].astype(bool), df['col1'].str.ljust(4, '0')) ``` output: ``` col1 0 1.20 1 3.40 2 1.99 3 0.14 4 2.90 5 6 2.30 ``` NB. to get the max string length: `df['col1'].str.len().max()` -> `4`
Like this: ``` df['col1'] = df['col1'].astype(float).map('{:,.2f}'.format).astype(str) ``` If you have '' in this column you better replace them before to '0'.
69,581,492
I have string column in my `df` table, like this below: ``` d = {'col1': ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3']} df = pd.DataFrame(data=d) df ``` [![enter image description here](https://i.stack.imgur.com/X2WXJ.png)](https://i.stack.imgur.com/X2WXJ.png) I would like to convert this column, so that all values ​​contain two decimal places, but **without changing the type of this column to numeric type**. Expected output - a string column with values: [![enter image description here](https://i.stack.imgur.com/3Aefa.png)](https://i.stack.imgur.com/3Aefa.png) I am a little new to Python, I tried padding 0 [How to pad a numeric string with zeros to the right in Python?](https://stackoverflow.com/questions/40999973/how-to-pad-a-numeric-string-with-zeros-to-the-right-in-python/46021306) depending on the length of the value in the column, but it actually didn't work. Do you have idea how to handle it?
2021/10/15
[ "https://Stackoverflow.com/questions/69581492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16734748/" ]
Like this: ``` df['col1'] = df['col1'].astype(float).map('{:,.2f}'.format).astype(str) ``` If you have '' in this column you better replace them before to '0'.
You can easily use the `round` or `format` function. In your specific case, using `format`, you can write something like this: ``` d = ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3'] for i in range(len(d)): if d[i] == '': d[i] = '0' d[i] = "{:.2f}".format(float(d[i])) print ('col1', d) ``` output: ``` 'col1', ['1.20', '3.40', '1.99', '0.14', '2.90', '0.00', '2.30'] ```
69,581,492
I have string column in my `df` table, like this below: ``` d = {'col1': ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3']} df = pd.DataFrame(data=d) df ``` [![enter image description here](https://i.stack.imgur.com/X2WXJ.png)](https://i.stack.imgur.com/X2WXJ.png) I would like to convert this column, so that all values ​​contain two decimal places, but **without changing the type of this column to numeric type**. Expected output - a string column with values: [![enter image description here](https://i.stack.imgur.com/3Aefa.png)](https://i.stack.imgur.com/3Aefa.png) I am a little new to Python, I tried padding 0 [How to pad a numeric string with zeros to the right in Python?](https://stackoverflow.com/questions/40999973/how-to-pad-a-numeric-string-with-zeros-to-the-right-in-python/46021306) depending on the length of the value in the column, but it actually didn't work. Do you have idea how to handle it?
2021/10/15
[ "https://Stackoverflow.com/questions/69581492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16734748/" ]
Use [`str.ljust`](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.ljust.html): ``` df['col1'] = df['col1'].str.ljust(4, '0') ``` output: ``` col1 0 1.20 1 3.40 2 1.99 3 0.14 4 2.90 5 2.30 ``` To leave empty rows intact: ``` df['col1'] = df['col1'].mask(df['col1'].astype(bool), df['col1'].str.ljust(4, '0')) ``` output: ``` col1 0 1.20 1 3.40 2 1.99 3 0.14 4 2.90 5 6 2.30 ``` NB. to get the max string length: `df['col1'].str.len().max()` -> `4`
This one will work no matter how many columns are in your dictionary. Try this: ```py d = {'col1': ['1.2', '3.4', '1.99', '0.14', '2.9' '', '2.3']} for x in d: for y in range(0,len(d[x])): d[x][y]=d[x][y].ljust(4,"0") print(d) ```
69,581,492
I have string column in my `df` table, like this below: ``` d = {'col1': ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3']} df = pd.DataFrame(data=d) df ``` [![enter image description here](https://i.stack.imgur.com/X2WXJ.png)](https://i.stack.imgur.com/X2WXJ.png) I would like to convert this column, so that all values ​​contain two decimal places, but **without changing the type of this column to numeric type**. Expected output - a string column with values: [![enter image description here](https://i.stack.imgur.com/3Aefa.png)](https://i.stack.imgur.com/3Aefa.png) I am a little new to Python, I tried padding 0 [How to pad a numeric string with zeros to the right in Python?](https://stackoverflow.com/questions/40999973/how-to-pad-a-numeric-string-with-zeros-to-the-right-in-python/46021306) depending on the length of the value in the column, but it actually didn't work. Do you have idea how to handle it?
2021/10/15
[ "https://Stackoverflow.com/questions/69581492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16734748/" ]
Use [`str.ljust`](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.ljust.html): ``` df['col1'] = df['col1'].str.ljust(4, '0') ``` output: ``` col1 0 1.20 1 3.40 2 1.99 3 0.14 4 2.90 5 2.30 ``` To leave empty rows intact: ``` df['col1'] = df['col1'].mask(df['col1'].astype(bool), df['col1'].str.ljust(4, '0')) ``` output: ``` col1 0 1.20 1 3.40 2 1.99 3 0.14 4 2.90 5 6 2.30 ``` NB. to get the max string length: `df['col1'].str.len().max()` -> `4`
You can easily use the `round` or `format` function. In your specific case, using `format`, you can write something like this: ``` d = ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3'] for i in range(len(d)): if d[i] == '': d[i] = '0' d[i] = "{:.2f}".format(float(d[i])) print ('col1', d) ``` output: ``` 'col1', ['1.20', '3.40', '1.99', '0.14', '2.90', '0.00', '2.30'] ```
2,435,039
Sorry the title's so convoluted... I must've tried for ten minutes to get a good, descriptive title! Basically, here's the scenario. Let's say a user can pick fifty different hat colors and styles to put on an avatar. The avatar can move his head around, so we'd need the same types of movements in the symbol for when that happens. Additionally, it gets which hat should be on the 'avatar' from a database. The problem is that we can't just make 50 different frames with a different hat on each. And each hat symbol will have the same movements, it'll just be different styles, colors and sizes. So how can I make one variable that is the HAT, that way we can just put the appropriate hat symbol into the variable and always be able to call Hat.gotoAndplay('tip\_hat') or any other generic functions.... Does that make sense? Hope that's not too confusing. Sorry, I'm not great at the visual Flash stuff, but it's gotta be done! Thanks!
2010/03/12
[ "https://Stackoverflow.com/questions/2435039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48957/" ]
[debu's suggestion](https://stackoverflow.com/questions/2435039/best-way-to-be-able-to-pick-multiple-colors-designs-of-symbols-dynamically-from-f/2435101#2435101) about a hat container makes sense in order to separate out control of the hat movement. You could take this further by separating out different aspects of the appearance of each hat (not just the colours, but also style, pattern, size, orientation etc) - this would allow you produce a wide variety of different hats from just a few parameters. So for example 6 styles x 4 patterns x 8 colours = 192 different hats (without having to draw each one!) [![parametric hats diagram](https://i.stack.imgur.com/dHyh6.jpg)](https://i.stack.imgur.com/dHyh6.jpg) (source: [webfactional.com](http://roi.webfactional.com/img/so/hats.jpg))
You could do that a number of ways; firstly you could have each different hat as a different symbol in the Flash Library (if you're using the IDE), and then in their properties tick to 'Export for Actionscript', and choose some appropriate name. It'll tell you that there's no definition for the class path, and one will be created automatically (or something), but that's no problem as you don't need to create a class file for these objects - they're simply MovieClip extensions with some specific data in them. So if you do that with each hat, let's say you name them Hat\_1, Hat\_2, etc; then you need to create a 'hat' object inside your avatar's head object. Whenever the hat is changed, you call a new instance of that specific hat object, and put it on the stage: ``` //when user chooses a hat, however this is done: var newHat:Hat_1 = new Hat_1(); avatarBody.avatarHead.hat.addChild(newHat); ``` Then that hat symbol gets added to the hat object of your avatar, and will move with the head object as you'd expect. You can change up the hat on the fly, by simply calling a different hat type and removing the previous one. Alternatively you could do it by loading in the hat symbols from external images, and storing them in variables for when they need to be added to the avatar object. You'd do this using XML; if you don't know how that's done, I can explain.
26,678,924
I'm writing a Linux device driver using kernel 3.13.0 and I'm confused as to why I'm getting this warning. ``` warning: initialization from incompatible pointer type [enabled by default] .read = read_proc, ^ warning: (near initialization for ‘proc_fops.read’) [enabled by default] ``` As far as I can tell my file\_operations setup for the proc functions are identical to the device functions. I can read/write to /dev/MyDevice with no issue and there are no warnings. The proc write function does not throw a warning, only the read. What did I do wrong? ``` /*****************************************************************************/ //DEVICE OPERATIONS /*****************************************************************************/ static ssize_t dev_read(struct file *pfil, char __user *pBuf, size_t len, loff_t *p_off) { //Not relevant to this question } static ssize_t dev_write(struct file *pfil, const char __user *pBuf, size_t len, loff_t *p_off) { //Not relevant to this question } static struct file_operations dev_fops = { //None of these cause a warning but the code is identical the proc code below .owner = THIS_MODULE, .read = dev_read, .write = dev_write }; /*****************************************************************************/ //PROCESS OPERATIONS /*****************************************************************************/ static int read_proc(struct file *pfil, char __user *pBuf, size_t len, loff_t *p_off) { //Not relevant to this question } static ssize_t write_proc(struct file *pfil, const char __user *pBuf, size_t len, loff_t *p_off) { //Not relevant to this question } struct file_operations proc_fops = { .owner = THIS_MODULE, .write = write_proc, .read = read_proc, //This line causes the warning. }; ``` EDIT: So the answer is that I'm an idiot for not seeing the "int" versus "ssize\_t". Thank you everyone! Both Codenheim and Andrew Medico had the correct answer at roughly the same time but I chose Medico's because it's more pedantic and obvious for future visitors.
2014/10/31
[ "https://Stackoverflow.com/questions/26678924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289746/" ]
The return type of your `read_proc` function (which throws the warning) does not match the the function that compiles cleanly. ``` static ssize_t dev_read(struct file *pfil, char __user *pBuf, size_t len, loff_t *p_off) ``` vs. ``` static int read_proc(struct file *pfil, char __user *pBuf, size_t len, loff_t *p_off) ``` `ssize_t` and `int` may be different sizes. Your function's return type should be `ssize_t`.
The function pointer expects a function with return type of `ssize_t` but you've given it one of `int` You need a `ssize_t` there, not an `int`.
26,678,924
I'm writing a Linux device driver using kernel 3.13.0 and I'm confused as to why I'm getting this warning. ``` warning: initialization from incompatible pointer type [enabled by default] .read = read_proc, ^ warning: (near initialization for ‘proc_fops.read’) [enabled by default] ``` As far as I can tell my file\_operations setup for the proc functions are identical to the device functions. I can read/write to /dev/MyDevice with no issue and there are no warnings. The proc write function does not throw a warning, only the read. What did I do wrong? ``` /*****************************************************************************/ //DEVICE OPERATIONS /*****************************************************************************/ static ssize_t dev_read(struct file *pfil, char __user *pBuf, size_t len, loff_t *p_off) { //Not relevant to this question } static ssize_t dev_write(struct file *pfil, const char __user *pBuf, size_t len, loff_t *p_off) { //Not relevant to this question } static struct file_operations dev_fops = { //None of these cause a warning but the code is identical the proc code below .owner = THIS_MODULE, .read = dev_read, .write = dev_write }; /*****************************************************************************/ //PROCESS OPERATIONS /*****************************************************************************/ static int read_proc(struct file *pfil, char __user *pBuf, size_t len, loff_t *p_off) { //Not relevant to this question } static ssize_t write_proc(struct file *pfil, const char __user *pBuf, size_t len, loff_t *p_off) { //Not relevant to this question } struct file_operations proc_fops = { .owner = THIS_MODULE, .write = write_proc, .read = read_proc, //This line causes the warning. }; ``` EDIT: So the answer is that I'm an idiot for not seeing the "int" versus "ssize\_t". Thank you everyone! Both Codenheim and Andrew Medico had the correct answer at roughly the same time but I chose Medico's because it's more pedantic and obvious for future visitors.
2014/10/31
[ "https://Stackoverflow.com/questions/26678924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289746/" ]
While working with file operations just follow rules according to this structure ``` struct file_operations { struct module *owner; loff_t (*llseek) (struct file *, loff_t, int); ssize_t (*read) (struct file *, char __user *, size_t, loff_t *); ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *); ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t); ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t); ssize_t (*read_iter) (struct kiocb *, struct iov_iter *); ssize_t (*write_iter) (struct kiocb *, struct iov_iter *); int (*iterate) (struct file *, struct dir_context *); unsigned int (*poll) (struct file *, struct poll_table_struct *); long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long); long (*compat_ioctl) (struct file *, unsigned int, unsigned long); int (*mmap) (struct file *, struct vm_area_struct *); int (*open) (struct inode *, struct file *); int (*flush) (struct file *); int (*release) (struct inode *, struct file *); int (*fsync) (struct file *, loff_t, loff_t, int datasync); int (*aio_fsync) (struct kiocb *, int datasync); int (*fasync) (int, struct file *, int); int (*lock) (struct file *, int, struct file_lock *); ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int); unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long); int (*check_flags)(int); int (*flock) (struct file *, int, struct file_lock *); ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, size_t, unsigned int); ssize_t (*splice_read)(struct file *, struct pipe_inode_info *, size_t, unsigned int); int (*setlease)(struct file *, long arg, struct file_lock **); long (*fallocate)(struct file *, int mode, loff_t offset, loff_t len); int (*show_fdinfo)(struct seq_file *m, struct file *f); }; ``` You can find this structure in Kernel Documentation Documentation/filesystems/vfs.txt or you can find it using tag vim -t file\_operations from Kernel Source or you can look at header file /include/linux/fs.h. Just Your mistake is return type you used static int instead of using ssize\_t.
The function pointer expects a function with return type of `ssize_t` but you've given it one of `int` You need a `ssize_t` there, not an `int`.
26,678,924
I'm writing a Linux device driver using kernel 3.13.0 and I'm confused as to why I'm getting this warning. ``` warning: initialization from incompatible pointer type [enabled by default] .read = read_proc, ^ warning: (near initialization for ‘proc_fops.read’) [enabled by default] ``` As far as I can tell my file\_operations setup for the proc functions are identical to the device functions. I can read/write to /dev/MyDevice with no issue and there are no warnings. The proc write function does not throw a warning, only the read. What did I do wrong? ``` /*****************************************************************************/ //DEVICE OPERATIONS /*****************************************************************************/ static ssize_t dev_read(struct file *pfil, char __user *pBuf, size_t len, loff_t *p_off) { //Not relevant to this question } static ssize_t dev_write(struct file *pfil, const char __user *pBuf, size_t len, loff_t *p_off) { //Not relevant to this question } static struct file_operations dev_fops = { //None of these cause a warning but the code is identical the proc code below .owner = THIS_MODULE, .read = dev_read, .write = dev_write }; /*****************************************************************************/ //PROCESS OPERATIONS /*****************************************************************************/ static int read_proc(struct file *pfil, char __user *pBuf, size_t len, loff_t *p_off) { //Not relevant to this question } static ssize_t write_proc(struct file *pfil, const char __user *pBuf, size_t len, loff_t *p_off) { //Not relevant to this question } struct file_operations proc_fops = { .owner = THIS_MODULE, .write = write_proc, .read = read_proc, //This line causes the warning. }; ``` EDIT: So the answer is that I'm an idiot for not seeing the "int" versus "ssize\_t". Thank you everyone! Both Codenheim and Andrew Medico had the correct answer at roughly the same time but I chose Medico's because it's more pedantic and obvious for future visitors.
2014/10/31
[ "https://Stackoverflow.com/questions/26678924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289746/" ]
The return type of your `read_proc` function (which throws the warning) does not match the the function that compiles cleanly. ``` static ssize_t dev_read(struct file *pfil, char __user *pBuf, size_t len, loff_t *p_off) ``` vs. ``` static int read_proc(struct file *pfil, char __user *pBuf, size_t len, loff_t *p_off) ``` `ssize_t` and `int` may be different sizes. Your function's return type should be `ssize_t`.
While working with file operations just follow rules according to this structure ``` struct file_operations { struct module *owner; loff_t (*llseek) (struct file *, loff_t, int); ssize_t (*read) (struct file *, char __user *, size_t, loff_t *); ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *); ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t); ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t); ssize_t (*read_iter) (struct kiocb *, struct iov_iter *); ssize_t (*write_iter) (struct kiocb *, struct iov_iter *); int (*iterate) (struct file *, struct dir_context *); unsigned int (*poll) (struct file *, struct poll_table_struct *); long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long); long (*compat_ioctl) (struct file *, unsigned int, unsigned long); int (*mmap) (struct file *, struct vm_area_struct *); int (*open) (struct inode *, struct file *); int (*flush) (struct file *); int (*release) (struct inode *, struct file *); int (*fsync) (struct file *, loff_t, loff_t, int datasync); int (*aio_fsync) (struct kiocb *, int datasync); int (*fasync) (int, struct file *, int); int (*lock) (struct file *, int, struct file_lock *); ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int); unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long); int (*check_flags)(int); int (*flock) (struct file *, int, struct file_lock *); ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, size_t, unsigned int); ssize_t (*splice_read)(struct file *, struct pipe_inode_info *, size_t, unsigned int); int (*setlease)(struct file *, long arg, struct file_lock **); long (*fallocate)(struct file *, int mode, loff_t offset, loff_t len); int (*show_fdinfo)(struct seq_file *m, struct file *f); }; ``` You can find this structure in Kernel Documentation Documentation/filesystems/vfs.txt or you can find it using tag vim -t file\_operations from Kernel Source or you can look at header file /include/linux/fs.h. Just Your mistake is return type you used static int instead of using ssize\_t.
8,499
I am writing an application, running on a server, where multiple users access data from a database which is AES encrypted with a master secret. The master secret itself is initially randomly generated, and then AES encrypted with a user-secret to yield a 'user-hash'. The master secret is never stored, but the user-hash is stored in a database. When a user enters his user-secret, the user-hash is decrypted to temporarily (on the fly) yield the master-secret which is used to decrypt the data. The data is then send to the user. If a user is deleted, the user-hash is deleted. He may have saved decrypted data, but cannot decrypt further data. The question is: How safe is the master-secret in this constellation? If the database is compromised, an attacker has access to the user-hash and the encrypted data. If the attacker was a user, he may also have decrypted data. Will he then be able to break the master-secret?
2013/05/30
[ "https://crypto.stackexchange.com/questions/8499", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/7065/" ]
If a user has a copy of both the encrypted and decrypted data, he is in a position to perform at least a [known-plaintext attack](http://en.wikipedia.org/wiki/Known-plaintext_attack). If users can submit arbitrary plaintexts for encryption, they can conduct a [chosen-plaintext attack](http://en.wikipedia.org/wiki/Chosen-plaintext_attack), which is stronger. In a chosen-plaintext attack, the attacker can submit any number of plaintexts and can retrieve the corresponding ciphertext. All reasonable encryption algorithms are resistant to chosen-plaintext attacks, and AES is considered a reasonable encryption algorithm. Someone in possession of some (plaintext, ciphertext) pairs cannot encrypt or decrypt other messages (except sometimes messages derived from the known messages if a bad mode is used). In particular, no matter how many known plaintexts and ciphertexts the attacker is, he has no method to obtain the key that is better than brute force (trying all possible $2^{128}$ keys). Do note that deleting the private secret does not delete the master secret. The master secret can still be recovered from backup copies of the private secret that weren't deleted, from other users' private secret, or from extant copies of the master secret.
Your master secret is **never** secure, at least not as you have described it. As a user, I know my private secret. When I use your application, my private secret decrypts the master secret right there in the application. With modest technical skills, I can examine the memory of the process or machine and read the master secret in plaintext any time I wish. I can retain that master secret forever, and the administrator will never know. To solve this, I expect you are relying on the master secret being secured on a different platform than the one the users are logged into. Your problem has now expanded and shifted to securely communicating the users' secrets to the secure platform. To accomplish that, you need an authentication mechanism. Once you have solved that, there becomes less need for the double encryption as you have defined it - simply authenticate user access to the platform, and revoke it as needed. The platform can own the master secret if on-disk encryption is desired. The user never has to access it directly. A different approach is that you can allow users to encrypt data locally (using public key cryptography to encrypt a random AES key) but they can never decrypt it themselves. That job is performed only on the server.
2,055,713
In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics. My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics? Some subjects I would like reference in particular, otherwise state any book you consider a classic, are: 1) Analysis 2) Abstract algebra 3) Linear Algebra 4) Number theory 5) Combinatorics and Graph theory, etc.
2016/12/12
[ "https://math.stackexchange.com/questions/2055713", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
1. Feller's first volume for Probability Theory. 2. Arnold's ODE for differential equations. 3. Cartan's Elementary Theory of Analytic Functions of One or Several Complex Variables for Complex Analysis
It's a bit more advanced than the topics you asked about, but Milnor's *Morse Theory* and Milnor and Stasheff's *Characteristic Classes* are astoundingly good. (There's a pattern here: Milnor's *Lectures on the h-Cobordism Theorem* is pretty good too!) At a somewhat lower level, I find Spivak's *Calculus* (which many might argue is an introductory analysis book) pretty darned wonderful.
2,055,713
In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics. My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics? Some subjects I would like reference in particular, otherwise state any book you consider a classic, are: 1) Analysis 2) Abstract algebra 3) Linear Algebra 4) Number theory 5) Combinatorics and Graph theory, etc.
2016/12/12
[ "https://math.stackexchange.com/questions/2055713", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
I don’t agree with Bell on this point: one may well learn better and more easily from a book that is *not* generally considered a classic. For example, most people have never even heard of John Greever’s modified Moore method textbook *Theory and Examples of Point-Set Topology*, but for me it was the ideal introduction to the field. That said, I can nevertheless name a few examples. For someone of my generation I.N. Herstein’s *Topics in Algebra* is a classic introduction to abstract algebra. The first volume of William J. LeVeque’s two-volume *Topics in Number Theory* is a classic at the higher end of the undergraduate level; Underwood Dudley’s *Elementary Number Theory* is a classic at the lower end.
It's a bit more advanced than the topics you asked about, but Milnor's *Morse Theory* and Milnor and Stasheff's *Characteristic Classes* are astoundingly good. (There's a pattern here: Milnor's *Lectures on the h-Cobordism Theorem* is pretty good too!) At a somewhat lower level, I find Spivak's *Calculus* (which many might argue is an introductory analysis book) pretty darned wonderful.
2,055,713
In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics. My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics? Some subjects I would like reference in particular, otherwise state any book you consider a classic, are: 1) Analysis 2) Abstract algebra 3) Linear Algebra 4) Number theory 5) Combinatorics and Graph theory, etc.
2016/12/12
[ "https://math.stackexchange.com/questions/2055713", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
1. Feller's first volume for Probability Theory. 2. Arnold's ODE for differential equations. 3. Cartan's Elementary Theory of Analytic Functions of One or Several Complex Variables for Complex Analysis
The Mathematical Association of America (MAA) has got a rich collection of classic books under Doclani Mathematical Expositions. I would suggest you following: $1$. Mathematical Gems Series ($3$ Volumes) By Ross Honsburger. $2$. Linear Algebra problem book By Paul R Halmos. $3$. Euler: Master of us all By William Dunham. Some other texts: $1$ Introduction to Commutative Algebra by Atiyah and MacDonald. $2$ A book of abstract algebra by Pinter.
2,055,713
In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics. My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics? Some subjects I would like reference in particular, otherwise state any book you consider a classic, are: 1) Analysis 2) Abstract algebra 3) Linear Algebra 4) Number theory 5) Combinatorics and Graph theory, etc.
2016/12/12
[ "https://math.stackexchange.com/questions/2055713", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
I don’t agree with Bell on this point: one may well learn better and more easily from a book that is *not* generally considered a classic. For example, most people have never even heard of John Greever’s modified Moore method textbook *Theory and Examples of Point-Set Topology*, but for me it was the ideal introduction to the field. That said, I can nevertheless name a few examples. For someone of my generation I.N. Herstein’s *Topics in Algebra* is a classic introduction to abstract algebra. The first volume of William J. LeVeque’s two-volume *Topics in Number Theory* is a classic at the higher end of the undergraduate level; Underwood Dudley’s *Elementary Number Theory* is a classic at the lower end.
The Mathematical Association of America (MAA) has got a rich collection of classic books under Doclani Mathematical Expositions. I would suggest you following: $1$. Mathematical Gems Series ($3$ Volumes) By Ross Honsburger. $2$. Linear Algebra problem book By Paul R Halmos. $3$. Euler: Master of us all By William Dunham. Some other texts: $1$ Introduction to Commutative Algebra by Atiyah and MacDonald. $2$ A book of abstract algebra by Pinter.
2,055,713
In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics. My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics? Some subjects I would like reference in particular, otherwise state any book you consider a classic, are: 1) Analysis 2) Abstract algebra 3) Linear Algebra 4) Number theory 5) Combinatorics and Graph theory, etc.
2016/12/12
[ "https://math.stackexchange.com/questions/2055713", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
1. Feller's first volume for Probability Theory. 2. Arnold's ODE for differential equations. 3. Cartan's Elementary Theory of Analytic Functions of One or Several Complex Variables for Complex Analysis
In the early '70s, I used two teaching books that I consider ''classic'': *Foundations of modern analysis* of J. Dieudonné (at least in Europe). *Algebra* of S. Mac Lane and G. Birkoff At a different level, I think that an ''evergreen'' is: *Methods of Mathematical physics* of R. Courant and D. Hilbert.
2,055,713
In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics. My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics? Some subjects I would like reference in particular, otherwise state any book you consider a classic, are: 1) Analysis 2) Abstract algebra 3) Linear Algebra 4) Number theory 5) Combinatorics and Graph theory, etc.
2016/12/12
[ "https://math.stackexchange.com/questions/2055713", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
I don’t agree with Bell on this point: one may well learn better and more easily from a book that is *not* generally considered a classic. For example, most people have never even heard of John Greever’s modified Moore method textbook *Theory and Examples of Point-Set Topology*, but for me it was the ideal introduction to the field. That said, I can nevertheless name a few examples. For someone of my generation I.N. Herstein’s *Topics in Algebra* is a classic introduction to abstract algebra. The first volume of William J. LeVeque’s two-volume *Topics in Number Theory* is a classic at the higher end of the undergraduate level; Underwood Dudley’s *Elementary Number Theory* is a classic at the lower end.
1. Feller's first volume for Probability Theory. 2. Arnold's ODE for differential equations. 3. Cartan's Elementary Theory of Analytic Functions of One or Several Complex Variables for Complex Analysis
2,055,713
In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics. My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics? Some subjects I would like reference in particular, otherwise state any book you consider a classic, are: 1) Analysis 2) Abstract algebra 3) Linear Algebra 4) Number theory 5) Combinatorics and Graph theory, etc.
2016/12/12
[ "https://math.stackexchange.com/questions/2055713", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
I don’t agree with Bell on this point: one may well learn better and more easily from a book that is *not* generally considered a classic. For example, most people have never even heard of John Greever’s modified Moore method textbook *Theory and Examples of Point-Set Topology*, but for me it was the ideal introduction to the field. That said, I can nevertheless name a few examples. For someone of my generation I.N. Herstein’s *Topics in Algebra* is a classic introduction to abstract algebra. The first volume of William J. LeVeque’s two-volume *Topics in Number Theory* is a classic at the higher end of the undergraduate level; Underwood Dudley’s *Elementary Number Theory* is a classic at the lower end.
In the early '70s, I used two teaching books that I consider ''classic'': *Foundations of modern analysis* of J. Dieudonné (at least in Europe). *Algebra* of S. Mac Lane and G. Birkoff At a different level, I think that an ''evergreen'' is: *Methods of Mathematical physics* of R. Courant and D. Hilbert.
36,447,958
I'm using the [jQuery Validate Plugin](http://jqueryvalidation.org/validate) and I want to be able to hide the error messages next to my inputs and have a main error message at the bottom, I have this working kind of but the error messages are showing next to my input fields. (Obviously I would clean up the styling if i was using it). As you can see at the bottom it is telling me there are 4 errors see details below.. I want this to stay but not the error messages and styling above? [![enter image description here](https://i.stack.imgur.com/taT8w.png)](https://i.stack.imgur.com/taT8w.png) ``` $( ".form-group-rules" ).validate({ rules: { rule_name: { required: true }, rule_desc: { required: false }, rule_type: { required: true }, vali_type: { required: true }, tran_type: { required: true }, vali_fields: { required: true }, acct_sel: { required: true } }, messages: { rule_name: "Please enter a rule name", rule_type: "Please select a rule type", vali_fields: "Please select a validation field", tran_type: "Please select at least 1 transaction type", vali_type: "Please select a valiation type", acct_sel: "Please select at least 1 account" }, showErrors: function(errorMap, errorList) { $(".error-container").html("Your form contains " + this.numberOfInvalids() + " errors, see details below."); this.defaultShowErrors(); } }); ```
2016/04/06
[ "https://Stackoverflow.com/questions/36447958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4532646/" ]
May be use the Validator method ``` errorPlacement: function(error,element) { return true; } ``` It will not append the error to the inputs.
You can hide the error messages with CSS: ``` span.error { display: none; } ```
36,447,958
I'm using the [jQuery Validate Plugin](http://jqueryvalidation.org/validate) and I want to be able to hide the error messages next to my inputs and have a main error message at the bottom, I have this working kind of but the error messages are showing next to my input fields. (Obviously I would clean up the styling if i was using it). As you can see at the bottom it is telling me there are 4 errors see details below.. I want this to stay but not the error messages and styling above? [![enter image description here](https://i.stack.imgur.com/taT8w.png)](https://i.stack.imgur.com/taT8w.png) ``` $( ".form-group-rules" ).validate({ rules: { rule_name: { required: true }, rule_desc: { required: false }, rule_type: { required: true }, vali_type: { required: true }, tran_type: { required: true }, vali_fields: { required: true }, acct_sel: { required: true } }, messages: { rule_name: "Please enter a rule name", rule_type: "Please select a rule type", vali_fields: "Please select a validation field", tran_type: "Please select at least 1 transaction type", vali_type: "Please select a valiation type", acct_sel: "Please select at least 1 account" }, showErrors: function(errorMap, errorList) { $(".error-container").html("Your form contains " + this.numberOfInvalids() + " errors, see details below."); this.defaultShowErrors(); } }); ```
2016/04/06
[ "https://Stackoverflow.com/questions/36447958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4532646/" ]
May be use the Validator method ``` errorPlacement: function(error,element) { return true; } ``` It will not append the error to the inputs.
Normally, `showErrors` will automatically suppress the default messages next to each input element. You're creating your own issue because **`.defaultShowErrors()` is the method for putting back the default messages**. Simply remove `this.defaultShowErrors()`... ``` showErrors: function(errorMap, errorList) { $(".error-container").html("Your form contains " + this.numberOfInvalids() + " errors, see details below."); this.defaultShowErrors(); // <- REMOVE THIS LINE } ``` **DEMO: <http://jsfiddle.net/jmdnxedq/>**
9,994,676
I have checked out many pages but most of the tutorials and script return an error code with this type of JSON output. So how would I be able to extract the data from this JSON in Java?: ``` [ { "user":{"id":"1","username":"user1"}, "item_name":"item1", "custom_field":"custom1" }, { "user":{"id":"2","username":"user2"}, "item_name":"item2", "custom_field":"custom2" }, { "user":{"id":"3","username":"user3"}, "item_name":"item3", "custom_field":"custom3" } ] ```
2012/04/03
[ "https://Stackoverflow.com/questions/9994676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310575/" ]
If you want to use Gson, then first you declare classes for holding each element and sub elements: ``` public class MyUser { public String id; public String username; } public class MyElement { public MyUser user; public String item_name; public String custom_field; } ``` Then you declare an array of the outermost element (because in your case the JSON object is a JSON array), and assign it: ``` MyElement[] data = gson.fromJson (myJSONString, MyElement[].class); ``` Then you simply access the elements of `data`. The important thing to remember is that the names and types of the attributes you declare should match the ones in the JSON string. e.g. "id", "item\_name" etc.
If your trying to serialize/deserialize json in Java I would recommend using Jackson. <http://jackson.codehaus.org/> Once you have Jackson downloaded you can deserialize the json strings to an object which matches the objects in JSON. Jackson provides annotations that can be attached to your class which make deserialization pretty simple.
9,994,676
I have checked out many pages but most of the tutorials and script return an error code with this type of JSON output. So how would I be able to extract the data from this JSON in Java?: ``` [ { "user":{"id":"1","username":"user1"}, "item_name":"item1", "custom_field":"custom1" }, { "user":{"id":"2","username":"user2"}, "item_name":"item2", "custom_field":"custom2" }, { "user":{"id":"3","username":"user3"}, "item_name":"item3", "custom_field":"custom3" } ] ```
2012/04/03
[ "https://Stackoverflow.com/questions/9994676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310575/" ]
If you want to use Gson, then first you declare classes for holding each element and sub elements: ``` public class MyUser { public String id; public String username; } public class MyElement { public MyUser user; public String item_name; public String custom_field; } ``` Then you declare an array of the outermost element (because in your case the JSON object is a JSON array), and assign it: ``` MyElement[] data = gson.fromJson (myJSONString, MyElement[].class); ``` Then you simply access the elements of `data`. The important thing to remember is that the names and types of the attributes you declare should match the ones in the JSON string. e.g. "id", "item\_name" etc.
You could try JSON Simple <http://code.google.com/p/json-simple/> Example: ``` JSONParser jsonParser = new JSONParser(); JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonDataString); for (int i = 0; i < jsonArray.size(); i++) { JSONObject obj = (JSONObject) jsonArray.get(i); //Access data with obj.get("item_name") } ``` Just be careful to check for nulls/be careful with casting and such.
10,839
I am reading Novuum Lumen Chemicum with the help of Waite’s English translation. (<https://www.sacred-texts.com/alc/hm2/hm204.htm>) The following passage I cannot understand clearly. It seems that Waite had skipped this.(org.: Musaeum Hermeticum, Frankfurt, 1677, p.545 – page number misprinted as 454) > > Nos dum illam quaerimus alia invenimus: & nisi ita usitata esset procreatio humana, & natura in eo suum jus teneret, jam vix non deviaremus. > > > The sentences before and after this one: > > Si hoc revivisceret ipse Philosophorum pater Hermes, & subtilis ingenii Geber, cum profundissimo RAYMUNDO LULLIO, non pro Philosophis, sed potius pro discipulis a nostris Chemistis haberentur: Nescirent tot hodie usitatas destilationes, tot circulationes, tot calcinationes, & tot alia innumerabilia alia Artistarum opera, quae ex illorum scriptis hujus saeculi homines invenerunt & excogitarunt. Unicum tantum nobis deest, ut id sciamus quod ipsi fecerunt, lapidem videlicet Philosophorum seu Tincturam Physicam. Nos dum illam quaerimus alia invenimus: & nisi ita usitata esset procreatio humana, & natura in eo suum jus teneret, jam vix non deviaremus. Sed, ut revertar ad propositum, promisi in hoc primo tractatu Naturam explicare; ne nos a simplici via vera, vana deflectat imaginatio. > > > I would appreciate any help.
2019/05/24
[ "https://latin.stackexchange.com/questions/10839", "https://latin.stackexchange.com", "https://latin.stackexchange.com/users/2954/" ]
To supplement, I've located [a different published (i.e. professional) English translation](https://archive.org/details/alchymytakenouto00sedz): that of a Dr John French, published in 1674. Here's what he has to say [for this section](https://archive.org/details/alchymytakenouto00sedz/page/2): > > If *Hermes* himfelf, the Father of Philosophers, should now be alive, and subtil-witted *Geber*, together with most profound *Raimundus Lullius*, they would not be accounted by our Chymists for Philosophers, but rather for Scholars: They would be ignorant of those so many Distillations, so many Circulations, so many Calcinations, and so many other innumerable Operations of Artists now adays used, which men of this age devised, and found out of their Writings. There is one only thing wanting to us, that is, to know that which they effected, *viz.* the Philosophers Stone, or Physical Tincture **we whilst we seek that, find out other things: and unless the Procreation of Man were so usual as it is, and Nature did in that thing still observe her own Law, and Rules we should scarce not but err.** But to return to what I intended; I promised in this first Treatise to explain Nature, lest every idle fancy should turn us aside from the true and plain way. > > > (Errors as in the original.) I'm afraid I'm not sure what "unless the Procreation of Man were so usual as it is" is supposed to mean: it's a very literal translation of the Latin, but doesn't really seem to make a lot of sense.
Here's my translation of that whole section: > > *Si hoc revivisceret ipse Philosophorum pater Hermes,* > > If Hermes himself, father of philosophers, were to come back to life, > > > *& subtilis ingenii Geber,* > > and subtle-witted Jabir, > > > *cum profundissimo RAYMUNDO LULLIO,* > > along with the most profound RAYMUND LULLY, > > > *non pro Philosophis, sed potius pro discipulis a nostris Chemistis haberentur:* > > our Chemists would take them not for Philosophers, but rather for students: > > > *Nescirent tot hodie usitatas destilationes, tot circulationes, tot calcinationes,* > > those [ancients] wouldn't recognize all the distillations we use today, all the circulations, all the calcinations, > > > *& tot alia innumerabilia alia Artistarum opera,* > > and all the myriad other works of our Artists, > > > *quae ex illorum scriptis hujus saeculi homines invenerunt & excogitarunt.* > > which the people of this century have discovered and derived from their [the old alchemists'] writings. > > > *Unicum tantum nobis deest, ut id sciamus quod ipsi fecerunt,* > > We're missing only one single important thing, that would let us understand what those [alchemists] created: > > > *lapidem videlicet Philosophorum seu Tincturam Physicam.* > > namely, the Philosopher's Stone aka the Elixir of Life. > > > *Nos dum illam quaerimus alia invenimus:* > > While we seek the Elixir, we find other things: > > > *& nisi ita usitata esset procreatio humana,* > > and so unless human creations were useful to the same extent (?), > > > *& natura in eo suum jus teneret,* > > and nature kept following its own law where the Stone was concerned, > > > *jam vix non deviaremus.* > > then we could hardly **not** go astray. > > > *Sed, ut revertar ad propositum,* > > But, to return to the original point, > > > *promisi in hoc primo tractatu Naturam explicare;* > > I promised in this first chapter to explain Nature; > > > *ne nos a simplici via vera, vana deflectat imaginatio.* > > we must not let empty imaginings turn us away from the simple, true path. > > > The sentence you've highlighted is basically the author saying that modern alchemists have strayed from the path, which is why they can't make the Philosopher's Stone any more: and it's understandable that they've strayed, because the laws of Nature stop applying where the Stone is concerned, and Nature is so much more interesting to study than the Stone. (I'm also not quite sure what *tinctura physica* is supposed to mean; I translated it tentatively as "Elixir of Life" here, since it's linked to the Philosopher's Stone, and [asked a new question about it](https://latin.stackexchange.com/q/10841/406).)
72,026,622
I have an array of objects: ``` this.array = [{name: null}, {name: null}, {name: null}] ``` and array of reservend names: ``` this.reserved = ["name2", "name3"] ``` I loop through array and try to set uniques name (not included inside `reserved` array) ``` for (let i = 0; i < array.length; i++) { this.setDefaultName(array[i], 1); } private setDefaultName(obj, index){ if (!this.reserved.includes(`name${index}`)) { obj.name = `name${index}`; this.reserved.push(`name${index}`); } else { return this.setDefaultName(obj, index + 1); } } ``` After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5". Could anyone help me?
2022/04/27
[ "https://Stackoverflow.com/questions/72026622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16078729/" ]
**Update:** In the meantime, GitLab have released a new version of their Docker Machine fork which upgrades the default AMI to Ubuntu 20.04. That means that upgrading Docker Machine to the latest version released by GitLab will fix the issue without changing your runner configuration. The latest release can be found [here](https://gitlab-docker-machine-downloads.s3.amazonaws.com/main/index.html). **Original Workaround/fix:** Explicitly specify the AMI in your runner configuration and do not rely on the default one anymore, i.e. add something like `"amazonec2-ami=ami-02584c1c9d05efa69"` to your `MachineOptions`: ``` MachineOptions = [ "amazonec2-access-key=xxx", "amazonec2-secret-key=xxx", "amazonec2-region=eu-central-1", "amazonec2-vpc-id=vpc-xxx", "amazonec2-subnet-id=subnet-xxx", "amazonec2-use-private-address=true", "amazonec2-tags=runner-manager-name,gitlab-aws-autoscaler,gitlab,true,gitlab-runner-autoscale,true", "amazonec2-security-group=ci-runners", "amazonec2-instance-type=m5.large", "amazonec2-ami=ami-02584c1c9d05efa69", # Ubuntu 20.04 for amd64 in eu-central-1 "amazonec2-request-spot-instance=true", "amazonec2-spot-price=0.045" ] ``` You can get a list of Ubuntu AMI IDs [here](https://cloud-images.ubuntu.com/locator/ec2/). Be sure to select one that fits your AWS region and instance architecture and [is supported by Docker](https://docs.docker.com/engine/install/ubuntu/#os-requirements). **Explanation:** The default AMI that GitLab Runner / the Docker Machine EC2 driver use is Ubuntu 16.04. The install script for Docker, which is available on <https://get.docker.com/> and which Docker Machine relies on, seems to have stopped supporting Ubuntu 16.04 recently. Thus, the installation of Docker fails on the EC2 instance spawned by Docker Machine and the job cannot run. See also [this](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/69) GitLab issue. [Azure](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/71) and [GCP](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/70) suffer from similar problems.
I had the same issue since yesterday. It could be related to GitLab releasing 15.0 with breaking changes (going `live on GitLab.com sometime between April 23 – May 22`) * <https://about.gitlab.com/blog/2022/04/18/gitlab-releases-15-breaking-changes/> * but there is no mention of missing `AMI` field to add to field `MachineOptions` Adding field `AMI` solved the issue on my side.
72,026,622
I have an array of objects: ``` this.array = [{name: null}, {name: null}, {name: null}] ``` and array of reservend names: ``` this.reserved = ["name2", "name3"] ``` I loop through array and try to set uniques name (not included inside `reserved` array) ``` for (let i = 0; i < array.length; i++) { this.setDefaultName(array[i], 1); } private setDefaultName(obj, index){ if (!this.reserved.includes(`name${index}`)) { obj.name = `name${index}`; this.reserved.push(`name${index}`); } else { return this.setDefaultName(obj, index + 1); } } ``` After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5". Could anyone help me?
2022/04/27
[ "https://Stackoverflow.com/questions/72026622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16078729/" ]
**Update:** In the meantime, GitLab have released a new version of their Docker Machine fork which upgrades the default AMI to Ubuntu 20.04. That means that upgrading Docker Machine to the latest version released by GitLab will fix the issue without changing your runner configuration. The latest release can be found [here](https://gitlab-docker-machine-downloads.s3.amazonaws.com/main/index.html). **Original Workaround/fix:** Explicitly specify the AMI in your runner configuration and do not rely on the default one anymore, i.e. add something like `"amazonec2-ami=ami-02584c1c9d05efa69"` to your `MachineOptions`: ``` MachineOptions = [ "amazonec2-access-key=xxx", "amazonec2-secret-key=xxx", "amazonec2-region=eu-central-1", "amazonec2-vpc-id=vpc-xxx", "amazonec2-subnet-id=subnet-xxx", "amazonec2-use-private-address=true", "amazonec2-tags=runner-manager-name,gitlab-aws-autoscaler,gitlab,true,gitlab-runner-autoscale,true", "amazonec2-security-group=ci-runners", "amazonec2-instance-type=m5.large", "amazonec2-ami=ami-02584c1c9d05efa69", # Ubuntu 20.04 for amd64 in eu-central-1 "amazonec2-request-spot-instance=true", "amazonec2-spot-price=0.045" ] ``` You can get a list of Ubuntu AMI IDs [here](https://cloud-images.ubuntu.com/locator/ec2/). Be sure to select one that fits your AWS region and instance architecture and [is supported by Docker](https://docs.docker.com/engine/install/ubuntu/#os-requirements). **Explanation:** The default AMI that GitLab Runner / the Docker Machine EC2 driver use is Ubuntu 16.04. The install script for Docker, which is available on <https://get.docker.com/> and which Docker Machine relies on, seems to have stopped supporting Ubuntu 16.04 recently. Thus, the installation of Docker fails on the EC2 instance spawned by Docker Machine and the job cannot run. See also [this](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/69) GitLab issue. [Azure](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/71) and [GCP](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/70) suffer from similar problems.
Make sure to select an ami for Ubuntu and not Debian and that your aws account is subscribed to it What I did 1. subscribe in aws marketplace to a Ubuntu Amazon Image (Ubuntu 20.04 LTS - Focal) 2. select launch instance, choose the region, and copy the ami shown
72,026,622
I have an array of objects: ``` this.array = [{name: null}, {name: null}, {name: null}] ``` and array of reservend names: ``` this.reserved = ["name2", "name3"] ``` I loop through array and try to set uniques name (not included inside `reserved` array) ``` for (let i = 0; i < array.length; i++) { this.setDefaultName(array[i], 1); } private setDefaultName(obj, index){ if (!this.reserved.includes(`name${index}`)) { obj.name = `name${index}`; this.reserved.push(`name${index}`); } else { return this.setDefaultName(obj, index + 1); } } ``` After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5". Could anyone help me?
2022/04/27
[ "https://Stackoverflow.com/questions/72026622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16078729/" ]
**Update:** In the meantime, GitLab have released a new version of their Docker Machine fork which upgrades the default AMI to Ubuntu 20.04. That means that upgrading Docker Machine to the latest version released by GitLab will fix the issue without changing your runner configuration. The latest release can be found [here](https://gitlab-docker-machine-downloads.s3.amazonaws.com/main/index.html). **Original Workaround/fix:** Explicitly specify the AMI in your runner configuration and do not rely on the default one anymore, i.e. add something like `"amazonec2-ami=ami-02584c1c9d05efa69"` to your `MachineOptions`: ``` MachineOptions = [ "amazonec2-access-key=xxx", "amazonec2-secret-key=xxx", "amazonec2-region=eu-central-1", "amazonec2-vpc-id=vpc-xxx", "amazonec2-subnet-id=subnet-xxx", "amazonec2-use-private-address=true", "amazonec2-tags=runner-manager-name,gitlab-aws-autoscaler,gitlab,true,gitlab-runner-autoscale,true", "amazonec2-security-group=ci-runners", "amazonec2-instance-type=m5.large", "amazonec2-ami=ami-02584c1c9d05efa69", # Ubuntu 20.04 for amd64 in eu-central-1 "amazonec2-request-spot-instance=true", "amazonec2-spot-price=0.045" ] ``` You can get a list of Ubuntu AMI IDs [here](https://cloud-images.ubuntu.com/locator/ec2/). Be sure to select one that fits your AWS region and instance architecture and [is supported by Docker](https://docs.docker.com/engine/install/ubuntu/#os-requirements). **Explanation:** The default AMI that GitLab Runner / the Docker Machine EC2 driver use is Ubuntu 16.04. The install script for Docker, which is available on <https://get.docker.com/> and which Docker Machine relies on, seems to have stopped supporting Ubuntu 16.04 recently. Thus, the installation of Docker fails on the EC2 instance spawned by Docker Machine and the job cannot run. See also [this](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/69) GitLab issue. [Azure](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/71) and [GCP](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/70) suffer from similar problems.
As Moritz pointed out: Adding: ``` MachineOptions = [ "amazonec2-ami=ami-02584c1c9d05efa69", ] ``` solves the issue.
72,026,622
I have an array of objects: ``` this.array = [{name: null}, {name: null}, {name: null}] ``` and array of reservend names: ``` this.reserved = ["name2", "name3"] ``` I loop through array and try to set uniques name (not included inside `reserved` array) ``` for (let i = 0; i < array.length; i++) { this.setDefaultName(array[i], 1); } private setDefaultName(obj, index){ if (!this.reserved.includes(`name${index}`)) { obj.name = `name${index}`; this.reserved.push(`name${index}`); } else { return this.setDefaultName(obj, index + 1); } } ``` After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5". Could anyone help me?
2022/04/27
[ "https://Stackoverflow.com/questions/72026622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16078729/" ]
**Update:** In the meantime, GitLab have released a new version of their Docker Machine fork which upgrades the default AMI to Ubuntu 20.04. That means that upgrading Docker Machine to the latest version released by GitLab will fix the issue without changing your runner configuration. The latest release can be found [here](https://gitlab-docker-machine-downloads.s3.amazonaws.com/main/index.html). **Original Workaround/fix:** Explicitly specify the AMI in your runner configuration and do not rely on the default one anymore, i.e. add something like `"amazonec2-ami=ami-02584c1c9d05efa69"` to your `MachineOptions`: ``` MachineOptions = [ "amazonec2-access-key=xxx", "amazonec2-secret-key=xxx", "amazonec2-region=eu-central-1", "amazonec2-vpc-id=vpc-xxx", "amazonec2-subnet-id=subnet-xxx", "amazonec2-use-private-address=true", "amazonec2-tags=runner-manager-name,gitlab-aws-autoscaler,gitlab,true,gitlab-runner-autoscale,true", "amazonec2-security-group=ci-runners", "amazonec2-instance-type=m5.large", "amazonec2-ami=ami-02584c1c9d05efa69", # Ubuntu 20.04 for amd64 in eu-central-1 "amazonec2-request-spot-instance=true", "amazonec2-spot-price=0.045" ] ``` You can get a list of Ubuntu AMI IDs [here](https://cloud-images.ubuntu.com/locator/ec2/). Be sure to select one that fits your AWS region and instance architecture and [is supported by Docker](https://docs.docker.com/engine/install/ubuntu/#os-requirements). **Explanation:** The default AMI that GitLab Runner / the Docker Machine EC2 driver use is Ubuntu 16.04. The install script for Docker, which is available on <https://get.docker.com/> and which Docker Machine relies on, seems to have stopped supporting Ubuntu 16.04 recently. Thus, the installation of Docker fails on the EC2 instance spawned by Docker Machine and the job cannot run. See also [this](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/69) GitLab issue. [Azure](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/71) and [GCP](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/70) suffer from similar problems.
Just wanted to add as well, go [here](https://cloud-images.ubuntu.com/locator/ec2/) for the ubuntu that corresponds with your region. Amis are region specific
72,026,622
I have an array of objects: ``` this.array = [{name: null}, {name: null}, {name: null}] ``` and array of reservend names: ``` this.reserved = ["name2", "name3"] ``` I loop through array and try to set uniques name (not included inside `reserved` array) ``` for (let i = 0; i < array.length; i++) { this.setDefaultName(array[i], 1); } private setDefaultName(obj, index){ if (!this.reserved.includes(`name${index}`)) { obj.name = `name${index}`; this.reserved.push(`name${index}`); } else { return this.setDefaultName(obj, index + 1); } } ``` After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5". Could anyone help me?
2022/04/27
[ "https://Stackoverflow.com/questions/72026622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16078729/" ]
**Update:** In the meantime, GitLab have released a new version of their Docker Machine fork which upgrades the default AMI to Ubuntu 20.04. That means that upgrading Docker Machine to the latest version released by GitLab will fix the issue without changing your runner configuration. The latest release can be found [here](https://gitlab-docker-machine-downloads.s3.amazonaws.com/main/index.html). **Original Workaround/fix:** Explicitly specify the AMI in your runner configuration and do not rely on the default one anymore, i.e. add something like `"amazonec2-ami=ami-02584c1c9d05efa69"` to your `MachineOptions`: ``` MachineOptions = [ "amazonec2-access-key=xxx", "amazonec2-secret-key=xxx", "amazonec2-region=eu-central-1", "amazonec2-vpc-id=vpc-xxx", "amazonec2-subnet-id=subnet-xxx", "amazonec2-use-private-address=true", "amazonec2-tags=runner-manager-name,gitlab-aws-autoscaler,gitlab,true,gitlab-runner-autoscale,true", "amazonec2-security-group=ci-runners", "amazonec2-instance-type=m5.large", "amazonec2-ami=ami-02584c1c9d05efa69", # Ubuntu 20.04 for amd64 in eu-central-1 "amazonec2-request-spot-instance=true", "amazonec2-spot-price=0.045" ] ``` You can get a list of Ubuntu AMI IDs [here](https://cloud-images.ubuntu.com/locator/ec2/). Be sure to select one that fits your AWS region and instance architecture and [is supported by Docker](https://docs.docker.com/engine/install/ubuntu/#os-requirements). **Explanation:** The default AMI that GitLab Runner / the Docker Machine EC2 driver use is Ubuntu 16.04. The install script for Docker, which is available on <https://get.docker.com/> and which Docker Machine relies on, seems to have stopped supporting Ubuntu 16.04 recently. Thus, the installation of Docker fails on the EC2 instance spawned by Docker Machine and the job cannot run. See also [this](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/69) GitLab issue. [Azure](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/71) and [GCP](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/70) suffer from similar problems.
Using the new AMI worked for a bit but after sometime the /etc/gitlab-runner/config.toml reverted back to old configuration. All the changes made is gone and reset automatically. Anyone have any idea why the config.toml file revert back and how to prevent it ?
72,026,622
I have an array of objects: ``` this.array = [{name: null}, {name: null}, {name: null}] ``` and array of reservend names: ``` this.reserved = ["name2", "name3"] ``` I loop through array and try to set uniques name (not included inside `reserved` array) ``` for (let i = 0; i < array.length; i++) { this.setDefaultName(array[i], 1); } private setDefaultName(obj, index){ if (!this.reserved.includes(`name${index}`)) { obj.name = `name${index}`; this.reserved.push(`name${index}`); } else { return this.setDefaultName(obj, index + 1); } } ``` After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5". Could anyone help me?
2022/04/27
[ "https://Stackoverflow.com/questions/72026622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16078729/" ]
Make sure to select an ami for Ubuntu and not Debian and that your aws account is subscribed to it What I did 1. subscribe in aws marketplace to a Ubuntu Amazon Image (Ubuntu 20.04 LTS - Focal) 2. select launch instance, choose the region, and copy the ami shown
I had the same issue since yesterday. It could be related to GitLab releasing 15.0 with breaking changes (going `live on GitLab.com sometime between April 23 – May 22`) * <https://about.gitlab.com/blog/2022/04/18/gitlab-releases-15-breaking-changes/> * but there is no mention of missing `AMI` field to add to field `MachineOptions` Adding field `AMI` solved the issue on my side.
72,026,622
I have an array of objects: ``` this.array = [{name: null}, {name: null}, {name: null}] ``` and array of reservend names: ``` this.reserved = ["name2", "name3"] ``` I loop through array and try to set uniques name (not included inside `reserved` array) ``` for (let i = 0; i < array.length; i++) { this.setDefaultName(array[i], 1); } private setDefaultName(obj, index){ if (!this.reserved.includes(`name${index}`)) { obj.name = `name${index}`; this.reserved.push(`name${index}`); } else { return this.setDefaultName(obj, index + 1); } } ``` After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5". Could anyone help me?
2022/04/27
[ "https://Stackoverflow.com/questions/72026622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16078729/" ]
Make sure to select an ami for Ubuntu and not Debian and that your aws account is subscribed to it What I did 1. subscribe in aws marketplace to a Ubuntu Amazon Image (Ubuntu 20.04 LTS - Focal) 2. select launch instance, choose the region, and copy the ami shown
As Moritz pointed out: Adding: ``` MachineOptions = [ "amazonec2-ami=ami-02584c1c9d05efa69", ] ``` solves the issue.
72,026,622
I have an array of objects: ``` this.array = [{name: null}, {name: null}, {name: null}] ``` and array of reservend names: ``` this.reserved = ["name2", "name3"] ``` I loop through array and try to set uniques name (not included inside `reserved` array) ``` for (let i = 0; i < array.length; i++) { this.setDefaultName(array[i], 1); } private setDefaultName(obj, index){ if (!this.reserved.includes(`name${index}`)) { obj.name = `name${index}`; this.reserved.push(`name${index}`); } else { return this.setDefaultName(obj, index + 1); } } ``` After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5". Could anyone help me?
2022/04/27
[ "https://Stackoverflow.com/questions/72026622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16078729/" ]
Make sure to select an ami for Ubuntu and not Debian and that your aws account is subscribed to it What I did 1. subscribe in aws marketplace to a Ubuntu Amazon Image (Ubuntu 20.04 LTS - Focal) 2. select launch instance, choose the region, and copy the ami shown
Just wanted to add as well, go [here](https://cloud-images.ubuntu.com/locator/ec2/) for the ubuntu that corresponds with your region. Amis are region specific
72,026,622
I have an array of objects: ``` this.array = [{name: null}, {name: null}, {name: null}] ``` and array of reservend names: ``` this.reserved = ["name2", "name3"] ``` I loop through array and try to set uniques name (not included inside `reserved` array) ``` for (let i = 0; i < array.length; i++) { this.setDefaultName(array[i], 1); } private setDefaultName(obj, index){ if (!this.reserved.includes(`name${index}`)) { obj.name = `name${index}`; this.reserved.push(`name${index}`); } else { return this.setDefaultName(obj, index + 1); } } ``` After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5". Could anyone help me?
2022/04/27
[ "https://Stackoverflow.com/questions/72026622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16078729/" ]
Make sure to select an ami for Ubuntu and not Debian and that your aws account is subscribed to it What I did 1. subscribe in aws marketplace to a Ubuntu Amazon Image (Ubuntu 20.04 LTS - Focal) 2. select launch instance, choose the region, and copy the ami shown
Using the new AMI worked for a bit but after sometime the /etc/gitlab-runner/config.toml reverted back to old configuration. All the changes made is gone and reset automatically. Anyone have any idea why the config.toml file revert back and how to prevent it ?
32,251,446
I am developing an Android application and I have trouvble making javascript work. Here is my main activity code : ``` protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "create LocalDialogActivity"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_local_dialog); webView = (WebView)findViewById(R.id.local_dialog_webview); webView.setWebChromeClient(new WebChromeClient()); webView.getSettings().setUseWideViewPort(true); webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setSupportZoom(true); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setDisplayZoomControls(false); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); } } private class WebAppInterface { @JavascriptInterface public void validate() { //do some action... } @JavascriptInterface public void cancel() { //do some actions... } } ``` here is my html code : ``` <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="../css/style.css"> <script src="../js/myjavascript.js"></script> </head> <body> <section id="header"> </section> <section id="buttons"> <button class="button" id="no" onclick="cancel()">cancel</button> <button class="button" id="yes" onclick="validate()">validate</button> </section> <footer id="footer"> </footer> </body> </html> ``` When I click on my buttons, the functions validate() and cancel() doesn't work. here is my javascript code : ``` function validate() { Interface.validate(); } function cancel() { Interface.cancel(); } ``` Interface is my javascriptInterface in my Android code. Any ideas would be welcome.
2015/08/27
[ "https://Stackoverflow.com/questions/32251446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3664585/" ]
Just add ``` webView.getSettings().setDomStorageEnabled(true); ```
From my usage of Android webview, check if you are at "default" zoom level. For instance, if you zoom in/out and then press a button, you cannot press it, but instead pan the zoom at the position you clicked. If that is not your issue, attemp the following: Check if the script is being read correctly. Do this by adding the `cancel()/validate()` functions to the header of the HTML... Check if the document is being fully loaded. Do this by adding something like `functcion initialize(){alert("loaded");}` at `window.onload = initialize();` If it is still failling, then post your Manifest, and any logcat should an error happen, as well as the reference to the webview (the full class where the webview is used, or at least all variables that are used with it).
49,336,275
Prestashop 1.6 has some strange functions. One of them is: ``` \themes\my_theme\js\autoload\15-jquery.uniform-modified.js ``` Which add span to radio, input button. For example: ``` <div class="checker" id="uniform-cgv"> <span class="checked"> <input name="cgv" id="cgv" value="1" type="checkbox"> </span> </div> ``` If this span has class checked then checkbox is checked. the problem is when quest user want buy products without create a account. The user need to provide some information about his self. In the end click on "save" button ``` <button type="submit" name="submitGuestAccount" id="submitGuestAccount" class="btn btn-default button button-medium"><span>Zapisz<i class="icon-chevron-right right"></i></span></button> ``` When I click this button the html is change to: ``` <p class="checkbox"> <input name="cgv" id="cgv" value="1" checked="checked" type="checkbox"> </p> ``` the question is. How can I call function which add span to input field after click on this button. For now I have something like this: ``` $('#submitGuestAccount').click(function () { }); ``` Below I past all content from: [view-source:https://dev.suszek.info/themes/default-bootstrap/js/autoload/15-jquery.uniform-modified.js](https://dev.suszek.info/themes/default-bootstrap/js/autoload/15-jquery.uniform-modified.js) Thanks for any help.
2018/03/17
[ "https://Stackoverflow.com/questions/49336275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9368657/" ]
If you want to get the same checkbox like with uniform you just need to invoke method bindUniform() after your button was handled. I assume that you get an answer after form handling with an ajax response, so you need to add `if (typeof bindUniform !=='undefined') { bindUniform(); }` after you get response and DOM was done.
@Alexander Grosul Thanks again. To fix this issues You need to add this code to any js file. ``` $("select.form-control,input[type='radio'],input[type='checkbox']").uniform(); ```
12,023,986
Today I noticed that new MVC projects in VS 2012 are using [WebMatrix.WebData.WebSecurity](http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity%28v=vs.99%29.aspx) to handle membership related tasks. I went to msdn to a quick look at the documentation and was surprised. Lot's of good stuff in there and it will definitely save me a lot of time in future projects. But one thing got my attention: It doesn't have a function to "Remove Accounts". Is there a particular reason for that? Should I use the underlying membership provider to remove accounts (and other things such as unlock accounts)?
2012/08/19
[ "https://Stackoverflow.com/questions/12023986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061342/" ]
Found the answer at MSDN: <http://msdn.microsoft.com/en-us/library/webmatrix.webdata.simplemembershipprovider%28v=vs.111%29> > > In ASP.NET Web Pages sites, you can access the functionality of the SimpleMembershipProvider class by using the Membership property of a web page. You do not (in fact, cannot) initialize a new instance of the SimpleMembershipProvider class... > > >
`((SimpleMembershipProvider)Membership.Provider).DeleteAccount("UserName");` //This will remove entry from **[webpages\_Membership]** table `Roles.RemoveUserFromRole("UserName", "RoleName");` // This will remove from **[webpages\_UsersInRoles]** table `((SimpleMembershipProvider)Membership.Provider).DeleteUser("UserName", true);` // This will remove from **userprofile** table
12,023,986
Today I noticed that new MVC projects in VS 2012 are using [WebMatrix.WebData.WebSecurity](http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity%28v=vs.99%29.aspx) to handle membership related tasks. I went to msdn to a quick look at the documentation and was surprised. Lot's of good stuff in there and it will definitely save me a lot of time in future projects. But one thing got my attention: It doesn't have a function to "Remove Accounts". Is there a particular reason for that? Should I use the underlying membership provider to remove accounts (and other things such as unlock accounts)?
2012/08/19
[ "https://Stackoverflow.com/questions/12023986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061342/" ]
``` ((SimpleMembershipProvider)Membership.Provider).DeleteAccount("username"); ((SimpleMembershipProvider)Membership.Provider).DeleteUser("username", true); ```
`((SimpleMembershipProvider)Membership.Provider).DeleteAccount("UserName");` //This will remove entry from **[webpages\_Membership]** table `Roles.RemoveUserFromRole("UserName", "RoleName");` // This will remove from **[webpages\_UsersInRoles]** table `((SimpleMembershipProvider)Membership.Provider).DeleteUser("UserName", true);` // This will remove from **userprofile** table
60,655,194
everyone! I am trying to render the exchange rates from a server to my page. Here is my React code: ``` import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component { constructor() { super(); this.state = { exRates: [] }; } getCurrencyRatesFromDB = () => { fetch('https://api.exchangeratesapi.io/latest') .then((response) => { console.log('then 1', response); return response.json(); }).then((data) => { console.log('then 2', data); this.setState({ exRates: data.rates }); }); } render() { console.log('render started'); return ( <div> console.log('return started'), <button type="button" className="btn" onClick={() => { this.getCurrencyRatesFromDB(); }} > Load rates </button> <p>{this.state}</p> </div> ) } } ReactDOM.render(<App />, document.getElementById('root')); ``` How do I modify the 'render' part to see the rates in a column like it is on the server? Thank very much to you in advance!
2020/03/12
[ "https://Stackoverflow.com/questions/60655194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11894807/" ]
1. You must not had an empty line beetween `@app.route("/profile/<name>")` and `def profile(name):` 2. You have to set the html file in a folder called templates. 3. You have to set the templates folder and run.py in the same folder
You can try this below by adding the type string in your @app.route : ``` @app.route("/profile/<string:name>") def profile(name): return render_template("test.html", name=name) ```
60,655,194
everyone! I am trying to render the exchange rates from a server to my page. Here is my React code: ``` import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component { constructor() { super(); this.state = { exRates: [] }; } getCurrencyRatesFromDB = () => { fetch('https://api.exchangeratesapi.io/latest') .then((response) => { console.log('then 1', response); return response.json(); }).then((data) => { console.log('then 2', data); this.setState({ exRates: data.rates }); }); } render() { console.log('render started'); return ( <div> console.log('return started'), <button type="button" className="btn" onClick={() => { this.getCurrencyRatesFromDB(); }} > Load rates </button> <p>{this.state}</p> </div> ) } } ReactDOM.render(<App />, document.getElementById('root')); ``` How do I modify the 'render' part to see the rates in a column like it is on the server? Thank very much to you in advance!
2020/03/12
[ "https://Stackoverflow.com/questions/60655194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11894807/" ]
Whenever we receive 500 internal server error on a Python wsgi application we can log it using 'logging' First import `from logging import FileHandler,WARNING` then after `app = Flask(__name__, template_folder = 'template')` add ``` file_handler = FileHandler('errorlog.txt') file_handler.setLevel(WARNING) ``` Then you can run the application and when you receive a 500 Internal server error, cat/nano your errortext.txt file to read it, which will show you what the error was caused by.
You can try this below by adding the type string in your @app.route : ``` @app.route("/profile/<string:name>") def profile(name): return render_template("test.html", name=name) ```
35,285,191
I am executing a stored procedure but it is failing at some point, Current error code is not helping me to find where and exactly what the error is I wanted to know where it is exactly failing so wanted to print line by line output while executing. for eg : ``` create or replace -- decaring required variable PROCEDURE "PROC_DATA_TABLE_DETAILS" IS FOR TABLEDETAILS IN (SELECT * FROM user_tables ) LOOP dbms_output.put_line (TABLENAME); select NUM_ROWS INTO COUNTRECORDS from all_tables where owner not like 'SYS%'and TABLE_NAME = TABLEDETAILS.TABLE_NAME; FOR FIELDSDETAILS IN (SELECT * FROM USER_TAB_COLUMNS WHERE TABLE_NAME = TABLENAME) LOOP FIELDNAME :=FIELDSDETAILS.COLUMN_NAME; dbms_output.put_line (FIELDNAME ); execute immediate 'SELECT NVL(count(*),0) FROM ' ||TABLENAME || ' WHERE '|| FIELDNAME || ' is not null ' into TEMPNONBLANK; END LOOP; INSERT INTO DATA_TABLE_DETAILS VALUES (TABLEDETAILS.TABLE_NAME,COUNTFIELDS) END LOOP; END PROC_DATA_TABLE_DETAILS; ```
2016/02/09
[ "https://Stackoverflow.com/questions/35285191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1767969/" ]
Your code will look like this; additionally you can write a procedure with autonomous transactions to log all error or logs. you will also get online code for this functionality. [http://log4plsql.sourceforge.net/](http://logs) ``` create or replace procedure proc_data_table_details is tablename varchar2(30); countrecords number; fieldname varchar2(30); tempnonblank number; begin for tabledetails in (select * from user_tables where rownum < 3) loop tablename := tabledetails.table_name; dbms_output.put_line(tabledetails.table_name); select num_rows into countrecords from all_tables where owner not like 'SYS%' and table_name = tablename; for fieldsdetails in (select * from user_tab_columns where table_name = tablename) loop fieldname := fieldsdetails.column_name; dbms_output.put_line(fieldname); execute immediate 'SELECT NVL(count(*),0) FROM ' || tablename || ' WHERE ' || fieldname || ' is not null ' into tempnonblank; dbms_output.put_line('TABLENAME :' || tablename || ' column name :' || fieldname || ' count :' || tempnonblank); end loop; end loop; end proc_data_table_details; ```
Try to break the code to few segements. That way you will narrow down your search field. Becoz what you are trying to do is take an analytical decision about when to print. Alternatively, if u want to print after every value assignment, you can parse the PL/SQL code as long to a variable and then loop over it until next ':=' isn't found. And then within the Loop, find the next position of ';' and substring thr. Append dbms\_output.print\_line(preceeding\_part\_of\_assignment) and then append again the remaining string. Instead you can just use debug.
29,908,287
I need help with my program. I declared a one-dimensional array of 6 and I want to show random values between 1-6 in a text box My question is how do I show values in my array in textbox1.text? Here is my code: ``` Public Sub ClickMyFirstClassButton() If FirstClass.Checked = True Then 'This piece of code declares an array Dim Seats As Integer() 'This is a One Dimensional Array ReDim Seats(6) TextBox1.Text = (String.Format("First Class is checked. The number of seats are : ", (Seats))) 'ElseIf FirstClass.AutoCheck = True Then 'MessageBox.Show("FirstClass is Auto checked") End If End Sub ``` I messed around with my program and this is what I did. Public Sub ClickMyFirstClassButton() ``` If FirstClass.Checked = True Then 'Dim Seats As Integer() = {1, 2, 3, 4, 5, 6} Dim Seats(0 To 6) As Integer Seats(0) = 1 Seats(1) = 2 Seats(2) = 3 Seats(3) = 4 Seats(4) = 5 Seats(5) = 6 TextBox1.Text = (String.Format("First Class is checked. Your seat is : {0}", Seats(RandomNumber(Seats)))) MessageBox.Show(String.Format("First Class is checked. Your seat is : {0}", Seats(RandomNumber(Seats)))) 'ElseIf FirstClass.AutoCheck Then 'MessageBox.Show("FirstClass is Auto checked") End If End Sub ```
2015/04/28
[ "https://Stackoverflow.com/questions/29908287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4601982/" ]
As suggested by @eryksun, this solves the issue: ``` p = subprocess.Popen('clip.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True) p.communicate('hello \n world') p.wait() ```
I suspect it's because you're using `shell=True`, refactor your code to not use it. But I would suggest abandoning this approach alltogether and use [pyperclip](https://pypi.python.org/pypi/pyperclip/) for the clipboard support. It's cross-platform and freely available.
11,881,490
In a C# enumeration, are there any negative side effects of using a negative number? I am modelling response codes and one of the codes in negative. This compiles but I want to know if there are any negative side effects to this. ``` public enum ResponseCodes { InvalidServerUserPasswordCombo = -1, // etc. } ```
2012/08/09
[ "https://Stackoverflow.com/questions/11881490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64226/" ]
> > negative side effects of using a negative number > > > Clearly, with any underlying signed type, any bitwise operations are going to get "interesting" very quickly. But using an enum as a collection of related constants can quite happily use negative values.
There's no negative side effects, however, keep in mind that an enum gets initialized to zero in this instance: ``` class YourClass { public ResponseCodes ResponseCode { get; set; } } ``` Providing just negative one will have an undesired impact for any users of the class (unless they initialize it.
11,881,490
In a C# enumeration, are there any negative side effects of using a negative number? I am modelling response codes and one of the codes in negative. This compiles but I want to know if there are any negative side effects to this. ``` public enum ResponseCodes { InvalidServerUserPasswordCombo = -1, // etc. } ```
2012/08/09
[ "https://Stackoverflow.com/questions/11881490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64226/" ]
> > negative side effects of using a negative number > > > Clearly, with any underlying signed type, any bitwise operations are going to get "interesting" very quickly. But using an enum as a collection of related constants can quite happily use negative values.
No, the enum is a value with an integer type and this can be any value from -2,147,483,648 to 2,147,483,647! :)
11,881,490
In a C# enumeration, are there any negative side effects of using a negative number? I am modelling response codes and one of the codes in negative. This compiles but I want to know if there are any negative side effects to this. ``` public enum ResponseCodes { InvalidServerUserPasswordCombo = -1, // etc. } ```
2012/08/09
[ "https://Stackoverflow.com/questions/11881490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64226/" ]
> > negative side effects of using a negative number > > > Clearly, with any underlying signed type, any bitwise operations are going to get "interesting" very quickly. But using an enum as a collection of related constants can quite happily use negative values.
This answer is 7 years late but I haven't seen the point made anywhere else. There is a minor negative side effect when using negative numbers for enums. If you want to cast a negative number to an enum you'll need to ensure the number is in brackets to avoid a compile error, e.g.: ``` class YourClass { ResponseCodes rc = (ResponseCodes)(-1); } ```
11,881,490
In a C# enumeration, are there any negative side effects of using a negative number? I am modelling response codes and one of the codes in negative. This compiles but I want to know if there are any negative side effects to this. ``` public enum ResponseCodes { InvalidServerUserPasswordCombo = -1, // etc. } ```
2012/08/09
[ "https://Stackoverflow.com/questions/11881490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64226/" ]
There's no negative side effects, however, keep in mind that an enum gets initialized to zero in this instance: ``` class YourClass { public ResponseCodes ResponseCode { get; set; } } ``` Providing just negative one will have an undesired impact for any users of the class (unless they initialize it.
No, the enum is a value with an integer type and this can be any value from -2,147,483,648 to 2,147,483,647! :)
11,881,490
In a C# enumeration, are there any negative side effects of using a negative number? I am modelling response codes and one of the codes in negative. This compiles but I want to know if there are any negative side effects to this. ``` public enum ResponseCodes { InvalidServerUserPasswordCombo = -1, // etc. } ```
2012/08/09
[ "https://Stackoverflow.com/questions/11881490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64226/" ]
There's no negative side effects, however, keep in mind that an enum gets initialized to zero in this instance: ``` class YourClass { public ResponseCodes ResponseCode { get; set; } } ``` Providing just negative one will have an undesired impact for any users of the class (unless they initialize it.
This answer is 7 years late but I haven't seen the point made anywhere else. There is a minor negative side effect when using negative numbers for enums. If you want to cast a negative number to an enum you'll need to ensure the number is in brackets to avoid a compile error, e.g.: ``` class YourClass { ResponseCodes rc = (ResponseCodes)(-1); } ```
261,384
I am trying to install additional drivers on Ubuntu 12.04. The application is returning an error. In the log file I can see various NVIDIA module failed to load. However, my PC do not have NVIDIA graphics card. Its Intel card, then why is Ubuntu searching for NVIDIA card? I have installed Ubuntu 12.04 and additional drivers before without any error. Though this is the first time I am using Windows installer version. I don't know if its related to that.
2013/02/26
[ "https://askubuntu.com/questions/261384", "https://askubuntu.com", "https://askubuntu.com/users/135680/" ]
**Yes**, but you will need Ubuntu 12.10. 1. Download Steam from Ubuntu Software Center 2. Start it up, you will be asked to log in with your Steam account. If you don't have one you can choose the create account option. 3. Go to the Store tab 4. Enter Don't Starve in the search bar in the top-right and click Don't Starve 5. Scroll a bit down and click the green button to buy the game 6. Pay with credit card or PayPal. It costs €14 7. The game will be downloaded and installed 8. **Play :-D**
**Install from Chrome Webstore and play via Google Chrome** Yes you can, altough Linux isn't officially supported according to the game's website ([system requirements](http://www.dontstarvegame.com/blog/system-requirements)), but the game is available in the *Chrome Webstore* for all platforms: [Chrome Web Store - Don't Starve](https://chrome.google.com/webstore/detail/dont-starve/hiledapehlkhdehbhppgmekfalnlfajc) **Note**: does not work on the Ubuntu builds of Chromium, because Native Client (NaCl) is disabled ([bug](https://bugs.launchpad.net/ubuntu/+source/chromium-browser/+bug/882942)). 1. Open the above Chrome Webstore link in `Google Chrome`. 2. Click ***Add to Chrome***. 3. You will be prompted to log in with a Google account - log in or create one and log in. 4. Answer ***Add*** to the confirmation question when asked. Once installed, you can launch it from Chrome's *new tab page*. If it does not work, there might be an issue with your graphics card, its drivers and the WebGL support in Chrome. Tested on: Chrome 30.0.1599.66, Ubuntu 12.10 64-bit, Intel HD4000 Graphics (xserver-xorg-video-intel: 2:2.21.9-0ubuntu0~raring).
3,195,720
I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ? This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows). Thanks in advance !
2010/07/07
[ "https://Stackoverflow.com/questions/3195720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277128/" ]
Writing to a file is not possible, you'd have to write a server-side script and make a request to that script. Reading is possible if you use an iframe with the text file's location as source, and reading the iframe contents.
Javascript in browsers doesn't allow you to write local files, for **security reasons**. This **may change with time**, but as for now you have to **deal with it**.
3,195,720
I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ? This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows). Thanks in advance !
2010/07/07
[ "https://Stackoverflow.com/questions/3195720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277128/" ]
Writing to a file is not possible, you'd have to write a server-side script and make a request to that script. Reading is possible if you use an iframe with the text file's location as source, and reading the iframe contents.
Only with a server side javascript interpreter, but that isn't the typical environment you run javascript in.
3,195,720
I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ? This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows). Thanks in advance !
2010/07/07
[ "https://Stackoverflow.com/questions/3195720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277128/" ]
Writing to a file is not possible, you'd have to write a server-side script and make a request to that script. Reading is possible if you use an iframe with the text file's location as source, and reading the iframe contents.
What about cookies? It is accessible via javascript, it is on your client and it is a plain text file. Only issue is the size of it (4k max if I remember well). What you can do as well is use your browser localStorage / userData / globalStorage (depending on your browser version). It acts like cookies (new webStorage / HTML5 specs) but can handle bigger amounts of data. Then, using some add ons (firebug on firefox for instance) you can easily read / copy / past the value and do whatever you have to do with it!
3,195,720
I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ? This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows). Thanks in advance !
2010/07/07
[ "https://Stackoverflow.com/questions/3195720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277128/" ]
**It *is* possible to read/write to a local file via JavaScript**: take a look at [TiddlyWIki](http://www.tiddlywiki.com/). *(Caveat: only works for local documents.)* I have actually written a [Single Page Application](http://softwareas.com/towards-a-single-page-application-framework) (SPA) using [twFile](http://jquery.tiddlywiki.org/twFile.html), a part of the TiddlyWiki codebase: 1. Works in different browsers: (IE, Firefox, Chrome) 2. This code is a little old now. TiddlyWiki abandoned the jQuery plugin design a while ago. (Look at the [current TiddlyWiki filesystem.js](http://dev.tiddlywiki.org/browser/Trunk/core/js/FileSystem.js) for more a more recent implementation. It's not isolated for you like the twFile plug-in, though). 3. Although written as a jQuery plug-in, I've studied the code and it is almost completely decoupled from jQuery. **Update:** I have uploaded a [proof-of-concept](http://coolcases.com/jeopardy/) that accesses a local file via JavaScript. * Modifying this application to write to a file is trivial. * I have not tried to get this to work as a file served from a web server, but it should be possible since there are [server-side implementations of TiddlyWiki](http://tiddlywiki.org/wiki/Can_I_use_TiddlyWiki_as_a_multi-user/collaborative/server_based_wiki%3F)<>. **Update:** So it looks like the server side implementations of TiddlyWiki use a server "adapter" to modify a file stored on the server, similar to [Peter's description](https://stackoverflow.com/questions/3195720/write-a-file-with-prototype-or-plain-javascript/3195752#3195752). The pure JavaScript method will probably not work if the page is served from a web server due to cross-domain security limitations.
Javascript in browsers doesn't allow you to write local files, for **security reasons**. This **may change with time**, but as for now you have to **deal with it**.