qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
110,860 | Based on what I have read on this site and heard from a rav, the majority of what most people currently do during burial is minhag rather than halacha.
Is there a written or online compilation of halachot and minhagim (Ashkenaz, Sephardi, or others) explaining both the procedures as well as the reasons for what is commonly done during burial. Among the things I've seen:
* Carrying the coffin a few feet while reciting something (I don't know what); stopping, and repeating this process several times until they reach the grave.
* Positioning the coffin so that the head faces a certain direction
* How much must be manually shovelled and what can be done by machine?
There are likely many other rules and customs in addition to the above. I'd like to find a single source that explains most or all of these.
**Note / Update**
I pretty much know the main rules of mourning and burial. I am specifically interested in sources that explain the reasons for various items done at burial, not merely a list of what to do. Per, @DoubleAa's suggestion, please specify which sections of your source explains what is done during just the burial, not the rest of mourning period. If the source does not provide any reason for anything, then this is not what I am seeking. | 2020/01/14 | [
"https://judaism.stackexchange.com/questions/110860",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/5275/"
] | If you are somewhat language limited and prefer English, you should consider **[Mourning in Halacha](https://www.artscroll.com/Products/MOUH.html)** by Rabbi Chaim Binyamin Goldberg.
It is quite comprehensive and heavily footnoted.
The subject of burial is covered primarily in chapters 9 and 10 with some related information in chapter 12.
Concerning your first bullet point, this practice is called *Ma’amadot* (Halts) and is addressed in 10:15, pp. 132-133.
I’m not sure what you are referring to in bullet point 2.
Bullet point 3 is addressed generally in 10:17 saying that:
1: Actual practice should follow the custom of the local Chevrah Kaddisha being used.
2: All those attending the burial should place at least some dirt to participate in the actual covering.
and
3: The details of how to handle the shovel or other tool for the burial.
I saw nothing in the text addressing what percentage must be done manually with a shovel versus allowing the grave diggers to finish the fill in with a backhoe. But from personal experience, this varies according to civil, legal requirements from one locale to the next. The owners of the particular cemetery or the grave diggers will let you know.
For what it’s worth, a generous gratuity to the (non-Jewish) grave diggers will often eliminate whatever obstacles you might encounter to allow one of the Jews present for the burial to drop the shovel of the backhoe. | [The Laws of Mourning by Rabbi Shmuel Tendler](https://www.israelbookshop.com/the-laws-of-mourning-step-by-step-guide-for-the-mourner-by-rabbi-sm-tendler.html)
is a concise book of laws ranging from last hours of life to the yahrzeit.
Product Description from [Amazon](https://rads.stackoverflow.com/amzn/click/com/096707052X):
>
> The Laws of Mourning is a compilation of mourning laws intended to set
> down in front of the mourner the basic fundamental halachos that
> he/she must be made aware of from immediately prior to the time of
> death through the extended mourning period.
>
>
>
The first four chapters discuss the items you are looking for.
Chapter 1 - Last Hours
Chapter 2 - Death until funeral
Chapter 3 - At the Chapel
Chapter 4 - At the Cemetery |
58,770,630 | I'm trying to implement a quite basic validation for a form field/select. Validation schema:
```
vehicleProvider: Yup.object() // This is an object which is null by default
.required('formvalidation.required.message')
.nullable(),
reserveVehicle: Yup.number().when('vehicleProvider', { // This is a number which is null by default
is: provider => provider?.hasReserve,
then: Yup.number()
.required('formvalidation.required.message')
.nullable(),
otherwise: Yup.number().notRequired()
}),
```
What I want to do: Only require/validate `reserveVehicle` if `provider.hasReserve` is `true`. Otherwise, don't require the number.
I get this error:
>
> "reserveVehicle must be a `number` type, but the final value was: `NaN` (cast from the value `NaN`)."
>
>
>
This makes sense (kind of) because, well `null` is Not a number. But as I'm trying to tell it that it shouldn't be required, in my opinion it shouldn't try to evaluate it.
Did I miss any key concepts of `Yup`? | 2019/11/08 | [
"https://Stackoverflow.com/questions/58770630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5243272/"
] | You should use **typeError**
Here is an example from my code:
```
amount: Yup.number()
.typeError('Amount must be a number')
.required("Please provide plan cost.")
.min(0, "Too little")
.max(5000, 'Very costly!')
``` | You can use:
```
amount: yup.number().typeError("")
```
This will omit the validation message, but you should be **careful** when doing this. |
71,991,800 | I need show Splash Screen(image: background\_light\_SC.png) when user open my application and flutter load my application. I use this [package](https://pub.dev/packages/flutter_native_splash), and all work good. But if I start my application in android 12, I see white background with my icon app in Splash Screen.
**pubspec.yaml**
```
flutter_native_splash:
background_image: "assets/images/background_light_SC.png"
android: true
android12: true
ios: true
```
Whats wrong? In all android up to Android 12, everything works well. | 2022/04/24 | [
"https://Stackoverflow.com/questions/71991800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18906338/"
] | As mentioned in @Dani3le\_ answer "Note that a background image is not supported". its means you can only play with the launch screen icon and background color, not with the background image...
another hack is used in old school way to show the splash screen after the launch screen for 3 sec ... but you gonna end up with 2 splash screens for android 12. | As specified into the [package](https://pub.dev/packages/flutter_native_splash):
>
> **Android 12 Support**
> ----------------------
>
>
> Android 12 has a [new method](https://developer.android.com/about/versions/12/features/splash-screen) of adding splash
> screens, which consists of a window background, icon, and the icon
> background. Note that a background image is not supported.
>
>
> The package provides Android 12 support while maintaining the legacy
> splash screen for previous versions of Android.
>
>
> PLEASE NOTE: The splash screen may not appear when you launch the app
> from Android Studio. However, it should appear when you launch by
> clicking on the launch icon in Android.
>
>
>
You also need to edit your `pubspec.yaml` following example. I don't think it's sufficent to add `android12:true`
```
android_12:
# The image parameter sets the splash screen icon image. If this parameter is not specified,
# the app's launcher icon will be used instead.
# Please note that the splash screen will be clipped to a circle on the center of the screen.
# App icon with an icon background: This should be 960×960 pixels, and fit within a circle
# 640 pixels in diameter.
# App icon without an icon background: This should be 1152×1152 pixels, and fit within a circle
# 768 pixels in diameter.
#image: assets/android12splash.png
# App icon background color.
#icon_background_color: "#111111"
# The image_dark parameter and icon_background_color_dark set the image and icon background
# color when the device is in dark mode. If they are not specified, the app will use the
# parameters from above.
#image_dark: assets/android12splash-invert.png
#icon_background_color_dark: "#eeeeee"
``` |
57,624,065 | I want to define a custom bash function, which gets an argument as a part of a dir path.
I'm new to bash scripts. The codes provided online are somehow confusing for me or don't work properly.
---
For example, the expected bash script looks like:
```sh
function my_copy() {
sudo cp ~/workspace/{$1} ~/tmp/{$2}
}
```
If I type `my_copy a b`,
then I expect the function executes `sudo cp ~/workspace/a ~/tmp/b`
in the terminal.
---
Thanks in advance. | 2019/08/23 | [
"https://Stackoverflow.com/questions/57624065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7149195/"
] | If you have the below function in say `copy.sh` file and if you [source](http://www.theunixschool.com/2012/04/what-is-sourcing-file.html) it ( `source copy.sh` or `. copy.sh`) then the function call `my_copy` will work as expected.
`$1` and `$2` are [positional parameters](https://www.gnu.org/software/bash/manual/html_node/Positional-Parameters.html).
i.e. when you call `my_copy a b`, `$1` will have the first command line argument as its value which is `a` in your case and `$2` which is second command line argument, will have the value `b`. The function will work as expected.
Also you have a **logical error** in the function, you have given `{$1}` instead of `${1}`. It will expand to `{a}` instead of `a` in your function and it will throw an **error** that says `cp: cannot stat '~/workspace/{a}': No such file or directory` when you run it.
Additionally, if the number of positional parameters are greater than 10, only then it is required to use `{}` in between otherwise you can avoid it. eg: `${11}` instead of `$11`.
```
function my_copy() {
sudo cp ~/workspace/$1 ~/tmp/$2
}
```
So above function will execute the statement `sudo cp ~/workspace/a ~/tmp/b` as expected.
To understand the concept, you can try `echo $1`, `echo ${1}`, `echo {$1}`, `echo {$2}`, `echo ${2}` and `echo $2` inside the script to see the resulting values. [For more special $ sign shell variables](https://stackoverflow.com/questions/5163144/what-are-the-special-dollar-sign-shell-variables) | There is a syntax error in your code. You don't call a variable like `{$foo}`. If `1=a` and `2=b` then you execute
`sudo cp ~/workspace/{$1} ~/tmp/{$2}`
BASH is going to replace `$1` with `a` and `$2` with `b`, so, BASH is going to execute
`sudo cp ~/workspace/{a} ~/tmp/{b}`
That means tha `cp` is going to fail because there is no file with a name like `{a}`
There is some ways to call a variable
`echo $foo`
`echo ${foo}`
`echo "$foo"`
`echo "${foo}"`
Otherwise, your code looks good, should work.
Take a look a this links [first](https://stackoverflow.com/questions/18135451/what-is-the-difference-between-var-var-and-var-in-the-bash-shell) and [second](https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells), it's really important to quoting your variables. If you want more information about BASH or can't sleep at night try with the [Official Manual](https://www.gnu.org/software/bash/manual/), it have everything you must know about BASH and it's a good somniferous too ;)
PS: I know $1, $2, etc are positional parameters, I called it variables because you treat it as a variable, and my anwser can be applied for both. |
17,508,481 | I am looking to have a script to output a large amount of sequential numbers (One million at a time) from a number that is 17 char's long. (EG 12345678912345678)
I essentially want it to work like this site (<http://sequencegenerator.com>) but use MY CPU and not his. His site locks up when I tell it to do a million and I tend to generate many millions at a time.
I found this script from online, but I don't know any VisualBasic so I am unsure how to make it work for me.
```
Set WSHShell = Wscript.CreateObject("WScript.Shell")
Set FSO = Wscript.CreateObject("Scripting.FileSystemObject")
Set EnvVar = wshShell.Environment("Process")
tBestand= EnvVar("USERPROFILE") & "\Desktop\HexNumbers.txt"
Set Bestand = fso.createtextfile(tBestand,1)
For x = 1486262272 To 1486461337
Bestand.WriteLine(hex(x))
Next
Bestand.close
WScript.quit
``` | 2013/07/07 | [
"https://Stackoverflow.com/questions/17508481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2009282/"
] | To avoid all problems with the reliable range of VBScript's Double/Currency numbers, split your start number (string) into a stable/never changing prefix and a Long number tail that gets incremented:
```
Option Explicit
Dim sStart : sStart = "12345678901234567"
Dim nCount : nCount = 20
Dim sPfx : sPfx = Left(sStart, 10)
Dim nStart : nStart = CLng(Mid(sStart, 11))
Dim n
For n = 1 To nCount
WScript.Echo sPfx, nStart, sPfx & nStart
nStart = nStart + 1
Next
```
output:
```
1234567890 1234567 12345678901234567
1234567890 1234568 12345678901234568
1234567890 1234569 12345678901234569
1234567890 1234570 12345678901234570
1234567890 1234571 12345678901234571
1234567890 1234572 12345678901234572
1234567890 1234573 12345678901234573
1234567890 1234574 12345678901234574
1234567890 1234575 12345678901234575
1234567890 1234576 12345678901234576
1234567890 1234577 12345678901234577
1234567890 1234578 12345678901234578
1234567890 1234579 12345678901234579
1234567890 1234580 12345678901234580
1234567890 1234581 12345678901234581
1234567890 1234582 12345678901234582
1234567890 1234583 12345678901234583
1234567890 1234584 12345678901234584
1234567890 1234585 12345678901234585
1234567890 1234586 12345678901234586
``` | Ekkehard.Horner's script with some slight modifications. Working as I wanted. Thanks!
```
Option Explicit
Dim sStart : sStart = "1234567891234567"
Dim nCount : nCount = 1000000
Dim sPfx : sPfx = Left(sStart, 10)
Dim nStart : nStart = CLng(Mid(sStart, 11))
Dim n
For n = 1 To nCount
Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")
Dim objLog
set objLog = Fs.OpenTextFile("Numbers.txt", 8, true, 0)
objLog.WriteLine sPfx & nStart
objLog.close
nStart = nStart + 1
Next
``` |
9,252,392 | This prepared statement seems like valid SQL to me.
```
PreparedStatement dropTable = cnx.prepareStatement(
"DROP TABLE IF EXISTS ?");
dropTable.setString(1, "features");
dropTable.execute();
```
But when I run this, I get the error:
>
> Exception in thread "main"
> com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
> error in your SQL syntax; check the manual that corresponds to your
> MySQL server version for the right syntax to use near ''features'' at
> line 1 at
> sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
> at
> sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
> at
> sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
> at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
> at com.mysql.jdbc.Util.handleNewInstance(Util.java:406) at
> com.mysql.jdbc.Util.getInstance(Util.java:381) at
> com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1031) at
> com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at
> com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558) at
> com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490) at
> com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959) at
> com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109) at
> com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2648) at
> com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
> at
> com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1356)
> at doriangray.db.TestSetup.main(TestSetup.java:62)
>
>
>
Does anyone see the problem here? I'm stumped. | 2012/02/12 | [
"https://Stackoverflow.com/questions/9252392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61104/"
] | I think your code prepares this statement:
```
DROP TABLE IF EXISTS 'features'
```
while you want:
```
DROP TABLE IF EXISTS features
``` | PreparedStatements are used for making database compile the query (make the execution plan) once, so executing the same query with different parameters happens faster.
In short in a PreparedStatement you can not have a wildcard for database objects. Including table name, column name, different where clauses and .... |
599,281 | My computer randomly restarts. Is it more likely my motherboard or processor? So, I know which one to return or replace first.
* Windows 7 SP1 64-bit
* Motherboard: Asus P8Z68-V/GEN3
* CPU: Intel i7
**Times it restarts**
* randomly during use in Windows 7
* during boot
* while in BIOS
* before BIOS
* basically randomly as soon as I press the power button
---
**Attempted solutions or diagnostics**
* I have taken the computer down to the bare minimum of hardware
components to see if it fixed the problem; CPU, mobo, PSU, 1 memory
stick, 1 HDD. The problem still persisted.
* I swapped all the memory sticks and problem still persisted.
* I did a memory check on the memory and they seem fine.
* Nothing is overheating.
* I tried replacing the PSU with another one that works and it still
persisted.
* Nothing, besides the notice that the system did not shutdown
properly, is showing up in the hardware or application logs in
Windows.
* I have reseated everything.
* I have taken everything out of the computer and cleaned it completely
out and still having the issue.
* I have moved the computer to a different outlet in my house and the
problem still persists.
* I have tried a second working CPU and it still does not work.
* Checked for blown caps.
* Swapped out all cables with known working cables.
* Sent Motherboard for repairs and they repaired it and sent it back and it is still not working
---
**New Verdict @ 12 August 2013**
I sent the motherboard for repairs to ASUS a few weeks ago. They said something was wrong with it and repaired it and sent it back. However, it is still randomly restarting.
I did some more part swapping over the weekend and discovered the problem is still the motherboard. I am going to talk to ASUS again today and see what they can do about replacing the motherboard. Will update this post when the problem is resolved.
---
**UPDATE @ 28 August 2013**
Got the replacement motherboard last night and everything is working fine so far. It has not restarted for 12+ hours. Will be letting it run for the next couple days to see if it restarts. Typically it would have restarted numerous times within the 12 hours. So far so good. =) If it does not restart today or this evening i will create an answer and close this question.
---
**UPDATE @ 29 August 2013**
Still no restarts with the replacement motherboard. Declaring it fixed. | 2013/05/23 | [
"https://superuser.com/questions/599281",
"https://superuser.com",
"https://superuser.com/users/59178/"
] | Your options are:
* Remove all but 1 stick of ram
* Disable sound card, network card, and any other devices in the bios
* Remove any other PCI devices (video card, sound card, cd rom ect..)
Once you have done that, and the issue continues:
* **Remove the motherboard from the case. It could be grounding out on a motherboard stand off.**
* Borrow a compatible CPU
If you have swapped every part, and removed the motherboard from the case, then the only other options are:
* Bad power cable
* Bad motherboard
Just because it came back from RMA, doesn't mean they fixed it.
---
Lastly Verify the following:
If you have a modular power supply, make absolutely sure you use the cables that were provided with it. Modular cables do not have the same pinouts between manufactures.
Double check that you are using the cables in the right places. I've seen 8 pin power connectors intended for video cards, that fit inside the 4 pin cpu power header. (They are not the same pinout)
I've seen counterfeit cpu's which are over clocked and are extremely unreliable. (very unlikely)
Check for blown capacitors. Also unlikely since the board just came back from RMA | Disconnect the power button and reset button and see if that fixes it. Start your computer by shorting the power pins with a screwdriver or something without the buttons attached. If it doesn't have the problem any more, focus on the buttons. Based on your description, it is highly likely your power or reset button is mechanically failing.
If you really want to know if it is your case/buttons, put it all in a new case and see if it still does it.
CPU and MB issues would be crashes and BSOD's. |
53,852,484 | I am Using angular Material design and i used Textarea but the height is not change is fixed i tried so many ways but not working i like want
However, it is always the same size. Even Change css Also but its just changing height and i can say its not working
***Any idea on how to change the size of the textarea?***
```
<mat-form-field appearance="outline" class="example-full-width">
<mat-label>Discription</mat-label>
<textarea matInput></textarea>
</mat-form-field>
```
***Even I Tried This But same issue am getting***
```
<mat-form-field>
<mat-label>Description</mat-label>
<textarea matInput formControlName="description" matTextareaAutosize matAutosizeMinRows=1 matAutosizeMaxRows=5></textarea>
</mat-form-field>
```
This Output i am getting form code
[](https://i.stack.imgur.com/qjYTE.png)
**Expected Output**
[](https://i.stack.imgur.com/h5PKl.png) | 2018/12/19 | [
"https://Stackoverflow.com/questions/53852484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8636516/"
] | You need to add:
```
matAutosizeMinRows=5 matAutosizeMaxRows=20
```
This will set a minimum number of rows and the maximum number of rows which control the height also.
If you tried the above, as you edited the question, and you are getting a different results. Then probably another CSS overrides the `textarea` height. Check with your developer tool to find out other CSS attached to the `textarea`. | set `line-height` style for `textarea`.
e.g:
```
<mat-form-field >
<textarea matInput placeholder="Description" style="line-height: 20px !important"></textarea>
</mat-form-field>
``` |
63,731,443 | **Summary:**
In the most recent (Sept. 2020) version of 64-bit cygwin, the symlinks in the `/bin/` and `/lib` directories have puzzling features, and seem to differ from any of the various other documented symlinks. The questions are:
1. why are they hidden from CMD.EXE, but visible elsewhere, unlike
other symlink types
2. is it possible to create symlinks with identical features? if so, how?
**TL;DR**
See @matzeri's answer: the SYSTEM attribute is set on `/bin/awk`, making it invisible to CMD.EXE sessions.
The symlinks below `/bin` and `/lib` seem to be one of the two types of "default cygwin symlinks" described here:
>
> The default symlinks created by Cygwin are either special reparse
> points shared with WSL on Windows 10, or plain files containing a
> magic cookie followed by the path to which the link points. The
> reparse point is used on NTFS, the plain file on almost any other
> filesystem.
> see [symbolic links](https://cygwin.com/cygwin-ug-net/using.html#pathnames-symlinks)
>
>
>
However, all of the symlinks below `/bin` have the SYSTEM attribute set, and most of the symlinks below `/lib` don't. I don't know how was I able to create a symlink with a magic cookie on NTFS.
**Below is the long version of the question**
There are multiple types of symlinks under cygwin. Other questions explain their history, describe their differences, and show how to create them, etc. For example:
[check the difference of symlink type in cygwin](https://stackoverflow.com/questions/24222591/check-the-difference-of-symlink-type-in-cygwin)
Here's a discussion of some of the history and problems with symlinks on windows:
[Symlinks on the mounted Windows directories are not compatible with native](https://github.com/microsoft/WSL/issues/353)
As described, there are shortcuts, junction points, and symlinks, all of which are visible from a CMD.EXE session, as demonstrated.
However, under my 64-bit cygwin installation, there is another type that I can't find any explanation for. A number of them appear below `/bin`, `/lib`, and perhaps other places. The main characteristic that distinguishes them from the other 3 is that they aren't visible from a CMD.EXE session.
Here's one example:
If I attempt to list 'awk' via CMD.EXE from the /bin directory, the file seems to not exist:
```sh
$ cd /bin
$ cmd.exe /c dir awk
Volume in drive C is opt
Volume Serial Number is D0C8-EA58
Directory of C:\cygwin64\bin
File Not Found
```
Here's what it looks to to `ls`:
```sh
$ ls -l awk
lrwxrwxrwx 1 philwalk None 8 May 14 12:26 awk -> gawk.exe
```
But most symlinks, in my experience, ARE visible from a CMD.EXE session. Let's create a symlink for testing:
```sh
$ CYGWIN=winsymlinks:nativestrict # make sure we don't create an old-style symlink
$ ln -s `which ls.exe` ls-link
$ cmd.exe /c dir ls-link
Volume in drive C is opt
Volume Serial Number is D0C8-EA58
Directory of C:\opt\ue
2020-09-03 13:12 <SYMLINK> ls-link [C:\cygwin64\bin\ls.exe]
1 File(s) 0 bytes
0 Dir(s) 295,290,556,416 bytes free
```
This shows that CMD.EXE can see this type of symlink.
It appears that all symlinks can be dereferenced like this:
```
$ cygpath -w `which awk`
C:\cygwin64\bin\gawk.exe
```
So can a windows-based program dereference them? Can it see them at all? Because they aren't visible to CMD.EXE, I would have guessed that they aren't visible to any other windows (i.e., non-cygwin) program.
Here's a scala script, `deref.sc`, that will test these questions:
```scala
#!/usr/bin/env scala
import java.nio.file._
for( posixPath <- args ){
val cyg = cygpath(posixPath)
val windows = Paths.get(posixPath)
val exists = Files.exists(windows)
printf("file path [%s]\n",posixPath )
printf("cygpath [%s]\n",cyg)
printf("windows [%s]\n",windows)
if( exists ){
printf("exists [%s] # visible to jvm-based programs\n",exists)
} else {
printf("exists [%s] # NOT visible to jvm-based programs\n",exists)
}
val realpath = if( exists ){
if( Files.isSymbolicLink(windows) ){
Files.readSymbolicLink(windows)
} else {
windows.toRealPath()
}
}
printf("real windows [%s]\n",realpath)
printf("\n")
}
def cygpath(posixPath:String) = {
import scala.sys.process._
Seq("cygpath.exe","-m",posixPath).lazyLines_!.mkString("")
}
```
Here's the output from deref.sc as applied to /bin/awk and to ./ls-link.
(we have to pass the windows-visible version of /bin/awk)
```sh
$ deref.sc ls-link
cygpath [ls-link]
windows [.\ls-link]
exists [true] # visible to jvm-based programs
real windows [C:\cygwin64\bin\ls.exe]
$ cd /bin
$ deref.sc awk
file path [awk]
cygpath [C:/cygwin64/bin/gawk.exe]
windows [awk]
exists [true] # visible to jvm-based programs
real windows [C:\cygwin64\bin\awk]
```
So this shows that, although some windows programs (such as CMD.EXE) cannot see c:/cygwin64/bin/awk, others (such as jvm-based programs) can!
My original question was based on the mistaken assumption that windows programs are not able to see these new symlinks, and since that isn't correct, the residual question is:
What are these new symlinks, and how are they created? Are they really different, or is this perhaps a side-effect of permissions? Running CMD.EXE as administrator seems to make no difference.
I verified that `c:/cygwin64/bin/awk` is also visible from a WSL session, although that's not so surprising given that the jvm can see them.
UPDATE: it seems that, although `/bin/awk` is visible to our program, it isn't considered to be a symbolic link by `java.nio.file.Files.isSymbolicLink()`. Its contents consist of the string `"!<symlink>gawk.exe"`, so it seems to be an early cygwin implementation of symlinks, before windows provided native symlinks.
It's unremarkable except for being invisible from CMD.EXE. | 2020/09/03 | [
"https://Stackoverflow.com/questions/63731443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666886/"
] | Inside the map function, put them all in an array and then sort them. Then you can return a new object in the map with the order you wish.
```js
let arr = [
{ length: 5.6, width: 5.1, height: 5.3 },
{ length: 7.7, width: 6.4, height: 6.5 },
{ length: 2.7, width: 6.3, height: 9.5 }
];
let res = arr.map(({length, width, height}) => {
let temp = [length, width, height].sort((a, b) => b - a);
return {
length: temp[0],
width: temp[1],
height: temp[2]
}
});
console.log(res);
```
**EDIT:**
>
> thank you this worked perfectly once i have my new array how would I get the largest length and largest width from the entire array?
>
>
>
Expand the code snippet below to see the answer to your secondary question:
```js
let arr = [
{ length: 5.6, width: 5.1, height: 5.3 },
{ length: 7.7, width: 6.4, height: 6.5 },
{ length: 2.7, width: 6.3, height: 9.5 }
];
console.log('max length = ', Math.max(...arr.map(a => a.length)));
console.log('max width = ', Math.max(...arr.map(a => a.width)));
console.log('max height = ', Math.max(...arr.map(a => a.height)));
console.log('min length = ', Math.min(...arr.map(a => a.length)));
console.log('min width = ', Math.min(...arr.map(a => a.width)));
console.log('min height = ', Math.min(...arr.map(a => a.height)));
``` | If the properties of the objects within the array are always `length`, `width` and `height` then yes, you can achieve this with the `map` function:
```js
const arr = [
{ length: 5.6, width: 5.1, height: 5.3 },
{ length: 7.7, width: 6.4, height: 6.5 }
]
const result = arr.map(obj => {
const max = Math.max(obj.length, obj.width, obj.height)
const min = Math.min(obj.length, obj.width, obj.height)
// This calculation will leave us with the remainder of the 3
const mid = obj.length + obj.width + obj.height - max - min
return {
length: max,
width: mid,
height: min
}
})
console.log(result);
```
**Edit**: I prefer @Rahul Bhobe's cleaner approach to this: <https://stackoverflow.com/a/63731483/3011431>. Again, the solution works perfectly if the object will always only contain `length`, `width` and `height` |
14,129,773 | I am new to use the AJAX tool kit in ASP.NET
I have a masked edit extender for start date. How can I specify minimum date value on this?
Currently this is accepting 11/11/1111.
```
<asp:MaskedEditExtender runat="server"
ID="meeStartDate"
Mask="99/99/9999"
MaskType="Date"
TargetControlID="txtStartDate" />
```
I appreciate your support! | 2013/01/02 | [
"https://Stackoverflow.com/questions/14129773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/529866/"
] | Try this :
```
MaximumValue="01/01/2099" MinimumValue="01/01/2000"
``` | You can try this
```
this._minDate = DateTime.Now.Date;
this._maxDate = DateTime.Now.Date.AddDays(120);
``` |
162,804 | My girlfriend left a job on good terms to work for a different company. Apparently the payroll manager (one person department, it’s a company of <100 employees) forgot to take her off the payroll because she’s still getting paid her old salary. Does she have a legal obligation to pay the money back or inform them of the error in any way?
Before you go calling her an awful person, the company stopped paying her bonuses without notice and for no declared reason, and she tried to ask about them and they blew her off. In the end she was “owed” about $3k (depending on how you qualify “owed” in terms of monthly and quarterly bonuses).
As of today they’ve paid her about $4k extra. Anyone have any legal expertise in this matter? If they put money in her account because of an employee’s incompetence, is that her responsibility? The company is in Missouri if that makes a difference. | 2020/08/15 | [
"https://workplace.stackexchange.com/questions/162804",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/109782/"
] | I would suggest checking the pay stubs or whatever system tracks work hours. If she doesn't have access to any of that, contact the company for clarification of the situation. Communicating through email may be helpful to get their answer in writing in case things escalate to the point of needing a lawyer.
If the payments are cashing out accrued vacation time this may actually be the correct payout from the company. If the payments are for work weeks after she left then there may be a problem/mistake.
Whatever you do, **do not** spend the money until you know it's properly accounted for and not an accident. If the money was paid through direct deposit, it is possible the company will reverse accidental payments through direct deposit as well. You do not want a shock from a sudden massive withdrawal. | Her employer has a legal right to reclaim the overpayment; see for example [this Nolo article](https://www.nolo.com/legal-encyclopedia/can-employer-deduct-previous-overpayment-paycheck.html). Since she's no longer employed there it's probably a bit harder for them to actually take that money back (though if it was direct deposit, in some states they can simply pull it back directly from her account, so be careful!)
Given that they likely have years to reclaim the payment, even if you don't care about the morality of not reporting it, you're best off reporting it simply so that you don't end up with them taking back $4k or whatever in a year or two when you perhaps don't have it available and end up in money trouble because of it. |
12,365,958 | While uploading multiple image at a time i want to show progress bar which show the progress bar in statusbar notification area with the info 1/5 and 2/5 and so on. where 1 is no of image uploaded and 5 is total no of image to be uploaded.
here i am able show progress bar in notification area. can any one suggest me, how to calculate no of image uploaded(finished) to show in progress bar (like 1/5)update. thanks in advance.
For making more clear
i have a asyntask which upload a single image to server. but i am not able to do
1> calculate size of total image (say for example 5 image)
2>how to find no of image uploaded in total 5 image
```
private class FileUploadTask extends AsyncTask<Object, Integer,String> {
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(context);
dialog.setMessage("Uploading...");
dialog.setIndeterminate(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.show();
}
@Override
protected String doInBackground(Object... arg0) {
try {
File file = new File("/mnt/sdcard/DCIM/100MEDIA/IMAG0149.jpg");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fileInputStream.read(bytes);
fileInputStream.close();
URL url = new URL("http://android.com.bd/form.php");
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
OutputStream outputStream = connection.getOutputStream();
int bufferLength = 1024;
for (int i = 0; i < bytes.length; i += bufferLength) {
int progress = (int)((i / (float) bytes.length) * 100);
Log.i("progress",progress+"dfdf");
publishProgress(progress);
if (bytes.length - i >= bufferLength) {
outputStream.write(bytes, i, bufferLength);
} else {
outputStream.write(bytes, i, bytes.length - i);
}
}
publishProgress(100);
outputStream.close();
outputStream.flush();
InputStream inputStream = connection.getInputStream();
// read the response
inputStream.close();
return "ok";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
Log.v("sds", result);
try {
dialog.dismiss();
} catch(Exception e) {
}
}
}
``` | 2012/09/11 | [
"https://Stackoverflow.com/questions/12365958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/795688/"
] | Take a look at this TL;DR blog post/tutorial. You should be able to do something similar. You'll want to use a `ProgressDialog`, updating its state using an `ASyncTask`. If you're already using an `ASyncTask` for your image upload, you already have the pieces in place.
<http://toolongdidntread.com/android/android-multipart-post-with-progress-bar/>
Also take a look at this SO question - [Download a file with Android, and showing the progress in a ProgressDialog](https://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog/3028660). Your question has been answered before. You'll just need to adapt the solution to display the progress bar at 1/5, 2/5, etc by customizing `onProgressUpdate`. I haven't tested this code, but I'd imagine something along these lines will allow you to display the progress incrementally like you want.
```
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
if (progress[0] < 20) {
mProgressDialog.setProgress(0);
} else if (progress[0] < 40) {
mProgressDialog.setProgress(20);
}
else if (progress[0] < 60) {
mProgressDialog.setProgress(40);
}
else if (progress[0] < 80) {
mProgressDialog.setProgress(60);
}
else if (progress[0] < 100) {
mProgressDialog.setProgress(80);
}
else if (progress[0] == 100) {
mProgressDialog.setProgress(100);
}
}
``` | Where are your images? you have to do like
```
File fav = new File(Environment.getExternalStorageDirectory().getPath());
File[] filesav = fav.listFiles();
for (int i = 0; i < filesav.length; i++) {
inside you send your pictures and count
}
```
the variable i is your image number and filesav.length is your total image number |
33,525 | I am using TrueCrypt's 'Full Disk Encryption' and according to TrueCrypt's FAQ I should 'Permanently Decrypt System Partition/Drive' before reinstalling Windows. This does not make any sense to me. Would reinstalling Windows not undo the encryption in the first place?
The reason I would like to know, is because 'Permanently Decrypt System Partition/Drive' will take a long time.
>
> Note: If the system partition/drive is encrypted and you want to
> reinstall or upgrade Windows, you need to decrypt it first (select
> System > Permanently Decrypt System Partition/Drive). However, a
> running operating system can be updated (security patches, service
> packs, etc.) without any problems even when the system partition/drive
> is encrypted.
>
>
> | 2013/03/31 | [
"https://security.stackexchange.com/questions/33525",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/11351/"
] | Reading the FAQ in question the TrueCrypt folks are trying to explain relates to reinstalling Windows on a system with a data volume encrypted that you wish to keep. The idea is that even though you don't reformat that volume the details needed to access it are lost in the Windows installation and thus the data is no longer recoverable. | If the system partition/drive is encrypted and you want to reinstall or upgrade Windows, you need to decrypt it first (select System > Permanently Decrypt System Partition/Drive). However, a running operating system can be updated (security patches, service packs, etc.) without any problems even when the system partition/drive is encrypted. |
128,875 | The problem I have, is that most of the C++ books I read spend almost forever on syntax and the basics of the language, e.g. `for` and loops `while`, arrays, lists, pointers, etc.
But they never seem to build anything that is simple enough to use for learning, yet practical enough to get you to understand the philosophy and power of the language.
Then I stumbled upon [QT](http://qt.nokia.com) which is an amazing library!
But working through the demos they have, it seems like I am now in the reverse dilemma. I feel like the rich man's son driving round in a sports car subsidized by the father. Like I could build fantastic software, but have no clue what's going on under the hood.
As an example of my dilemma take the task of building a simple web browser. In pure C++, I wouldn't even know where to start, yet with the Qt library it can be done within a few lines on code.
I am not complaining about this. I am just wondering how to fill the knowledge void between the basic structure of the language and the high level interface that the Qt framework provides? | 2012/01/06 | [
"https://softwareengineering.stackexchange.com/questions/128875",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/41595/"
] | Do you want to know how stepping on the accelerator makes the car go faster, or do you only care that stepping on the accelerator makes the car go faster?
You are seeing the benefit to black box programming, which is a great way to design a system when all the boxes work. Someone has to make the black boxes though and if you want to be that guy/girl then you need to know more about the language than the guy using the box.
There are jobs that are good jobs in each style, so its up to you what you want to program. IMO you would be doing yourself a disservice though if you didn't put forth the effort to peel back some of the abstraction QT is giving you eventually. | Qt is widely used in the commercial world because it provides a full cross platform toolset and development environment, including a good GUI library.
It also fully supports internationalization, including the excellent 'Linguist' tool.
If you plan an academic career then I wouldn't bother with Qt. If, on the other hand, you like C++ and want to learn a marketable skill then Qt is worth learning.
And yes, Qt is C++, and you can mix in the standard and boost libraries to your hearts content if that makes you feel better. |
11,731,107 | How do I modify this so that if one sound is playing already and another is clicked on, the previous stops playing and the newly selected starts? Thanks everyone for their help in advance. (this is not all the code just the most important)
```
public class newBoard extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
Toast.makeText(this, "Thank you for using this App.", Toast.LENGTH_LONG).show();
// ads - load request to display
AdView layout = (AdView)this.findViewById(R.id.adView);
// ads - load display with an ad
AdRequest adRequest = new AdRequest();
adRequest.setTesting(true);
layout.loadAd(adRequest);
// import sound files
final MediaPlayer sound01 = MediaPlayer.create(this, R.raw.sound01);
final MediaPlayer sound02 = MediaPlayer.create(this, R.raw.sound02);
final MediaPlayer sound03 = MediaPlayer.create(this, R.raw.sound03);
final MediaPlayer sound04 = MediaPlayer.create(this, R.raw.sound04);
final MediaPlayer sound05 = MediaPlayer.create(this, R.raw.sound05);
final MediaPlayer sound06 = MediaPlayer.create(this, R.raw.sound06);
final MediaPlayer sound07 = MediaPlayer.create(this, R.raw.sound07);
final MediaPlayer sound08 = MediaPlayer.create(this, R.raw.sound08);
final MediaPlayer sound09 = MediaPlayer.create(this, R.raw.sound09);
final MediaPlayer sound10 = MediaPlayer.create(this, R.raw.sound10);
final MediaPlayer sound11 = MediaPlayer.create(this, R.raw.sound11);
final MediaPlayer sound12 = MediaPlayer.create(this, R.raw.sound12);
final MediaPlayer sound13 = MediaPlayer.create(this, R.raw.sound13);
final MediaPlayer sound14 = MediaPlayer.create(this, R.raw.sound14);
final MediaPlayer sound15 = MediaPlayer.create(this, R.raw.sound15);
final MediaPlayer sound16 = MediaPlayer.create(this, R.raw.sound16);
final MediaPlayer sound17 = MediaPlayer.create(this, R.raw.sound17);
final MediaPlayer sound18 = MediaPlayer.create(this, R.raw.sound18);
final MediaPlayer sound19 = MediaPlayer.create(this, R.raw.sound19);
final MediaPlayer sound20 = MediaPlayer.create(this, R.raw.sound20);
final MediaPlayer sound21 = MediaPlayer.create(this, R.raw.sound21);
final MediaPlayer sound22 = MediaPlayer.create(this, R.raw.sound22);
final MediaPlayer sound23 = MediaPlayer.create(this, R.raw.sound23);
final MediaPlayer sound24 = MediaPlayer.create(this, R.raw.sound24);
final MediaPlayer sound25 = MediaPlayer.create(this, R.raw.sound25);
// play sound files on clicks
Button s01 = (Button) findViewById(R.id.button01);
s01.setText(this.getString(R.string.quote01));
s01.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
sound01.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound01.start();
}
});
registerForContextMenu(s01);
Button s02 = (Button) findViewById(R.id.button02);
s02.setText(this.getString(R.string.quote02));
s02.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
sound02.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound02.start();
}
});
registerForContextMenu(s02);
Button s03 = (Button) findViewById(R.id.button03);
s03.setText(this.getString(R.string.quote03));
s03.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
sound03.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound03.start();
}
});
registerForContextMenu(s03);
Button s04 = (Button) findViewById(R.id.button04);
s04.setText(this.getString(R.string.quote04));
s04.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
sound04.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound04.start();
}
});
registerForContextMenu(s04);
Button s05 = (Button) findViewById(R.id.button05);
s05.setText(this.getString(R.string.quote05));
s05.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
sound05.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound05.start();
}
});
registerForContextMenu(s05);
Button s06 = (Button) findViewById(R.id.button06);
s06.setText(this.getString(R.string.quote06));
s06.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
sound06.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound06.start();
}
});
registerForContextMenu(s06);
``` | 2012/07/30 | [
"https://Stackoverflow.com/questions/11731107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972096/"
] | How about simply iterating through the array and compare the names?
```
resultObjectsArray = [NSMutableArray array];
for(NSDictionary *wine in allObjectsArray)
{
NSString *wineName = [wine objectForKey:@"Name"];
NSRange range = [wineName rangeOfString:nameString options:NSCaseInsensitiveSearch];
if(range.location != NSNotFound)
[resultObjectsArray addObject:wine];
}
```
Swift version is even simpler:
```
let resultObjectsArray = allObjectsArray.filter{
($0["Name"] as! String).range(of: nameString,
options: .caseInsensitive,
range: nil,
locale: nil) != nil
}
```
Cheers,
anka | remember to break; out your for loop once your object has been found |
26,705,215 | Is there any better way to write this type of code in Tweenmax?
```
TweenMax.to("#second-scene .layer-one", 0.5, {delay:0.2, top:0, onComplete: function() {
TweenMax.to("#second-scene .layer-two", 0.5, {top:0, onComplete: function() {
TweenMax.to("#second-scene .layer-three", 0.5, {left:0, onComplete: function() {
TweenMax.to("#second-scene .layer-four", 0.5, {left:0, onComplete: function() {
TweenMax.to("#second-scene .layer-five", 0.5, {left:0, onComplete: function() {
TweenMax.to("#second-scene .layer-six", 0.5, {top:0} );
}} );
}} );
}} );
}} );
}} );
```
And I would like to know if writing this way would affect performance.
Thanks in advance | 2014/11/02 | [
"https://Stackoverflow.com/questions/26705215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4208552/"
] | The comments above worked for me (`syntax spell toplevel`) and this setting works for me even when run later (so no need to copy anything from /usr). But I didn't want that setting to be active for all tex files - instead, I customize it for the given file in my *.vimrc*:
```
au BufNewFile,BufRead body.tex syntax spell toplevel
``` | I used a hack for this problem. Add the following to the top of your file:
```
\iffalse{}\section{vim-hack}\fi{}
```
This way, vim's syntax and spell algorithms find some token to get them started, but due to the "if" the section will be ignored by latex itself.
(I did not test whether more specialized editors ignore this dummy section, so there may be more hackery required if you use both vim and an editor.) |
361,498 | I installed Centos onto my server and I noticed that when I compared the date command's output to time.gov (same timezones, of course), the output was 4 minutes behind. This also affects my timestamps in MySQL so this is an annoying problem.
Is there some way to permanently fix this so that even after the server reboots, the current time is correct? | 2011/11/25 | [
"https://superuser.com/questions/361498",
"https://superuser.com",
"https://superuser.com/users/-1/"
] | Yes, there is -- you need to sync your system time with the external time servers. A high-end solution is to run `ntp`, a simpler solution is to just call `ntpclient`, or `ntpdate`.
Watch out that because too many Linux machines were hitting the same time servers, there are now some per-distro wrappers. E.g. on an Ubuntu machine here I have this in `/etc/crontab`:
```
03,23,43 * * * * root ntpdate-debian -s
```
where `ntpdate-debian` has this in its manual page:
>
> `ntpdate-debian` is identical to `ntpdate`(8) except that it uses the
> configuration in `/etc/default/ntpdate` by default. ntpdate sets the
> local date and time by polling Network Time Protocol (NTP) servers.
>
>
>
and then in `/etc/default/ntpdate` we see
```
# List of NTP servers to use (Separate multiple servers with spaces.)
# Not used if NTPDATE_USE_NTP_CONF is yes.
NTPSERVERS="ntp.ubuntu.com"
```
which points to the Ubuntu pool. | Install [ntp](http://www.ntp.org/). Or as a temporary fix run `ntpdate pool.ntp.org` in a terminal. |
22,303 | Godville is what's known as a ZPG (Zero Player Game) - it's a MMORPG where you - the player - don't actually control the hero in typical RPG way - the hero levels up without player doing any work. The player just sits around and rewards/punishers the hero.
There appear to be two **very similar** versions of Godville around - an English one ([godvillegame.com](http://godvillegame.com/)) and a Russian one ([godville.net](http://godville.net)).
<http://godvillegame.com/images/godville_screenshot_en.gif>
<http://godville.net/images/godville_screenshot_ru.gif>
As can be seen from the above screenshots, the two versions seem to be very close, apparently using nearly identical web back-ends (and there are even Andorid clients that can play both).
Please note that content-wise, they are somewhat different - Russian one is nearly 100% culture tropes and puns whereas English one seems to be more standard RPG content.
**The question: what is the exact relationship (organizational and software wise) between both games?**
* is it really the same exact game ported by the same company to two different markets?
* or is one of them an authorized clone using the same exact software (or starting off from the same software - there seem to be some divergent features) as the original;
* or is one just an unauthorized clone of another?
* Some other option I didn't think of? | 2011/05/16 | [
"https://gaming.stackexchange.com/questions/22303",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/7912/"
] | On many box arts and title screens, the buster is on his right arm, but in some it is on his left arm or in none of them. So, one can assume that he "morphs" his arm into a buster, and that he may do that with either of the arms, depending on how clear a shot would be in each case. I agree with Oscar Cheung, Megaman is probably ambidextrous. | Most people have covered the answer by now (he's an ambidextrous, which makes sense, because he's a *robot*.... why program something limiting like right or left-handedness? He's a SUPER FIGHTING ROBOT, he don't have time for that!)
Just wanted to add another source for that answer: The Megaman TV show. Anime/style aside, he often transforms either hand into the Megabuster (or whatever weapon he has "equipped"), as needed. He and Roll both can use both arms as weapons and are presumably ambidextrous. |
11,206,328 | I need some help with Java Swing components and its capabilities. I need to add a `JPanel` to a `JFrame` and paint an `Ellipse2D` on it. Onto the `Ellipse2D` I want to add another element, in my case it is a picture (right now I use an `ImageIcon`, maybe wrong). How can I achieve adding the `Ellipse2D` and the picture on the panel as shown in the image I attached?
The reason why I need the images separated is, because I need to change the filling color of the ellipse sometimes.
Thanks for any help. | 2012/06/26 | [
"https://Stackoverflow.com/questions/11206328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/599110/"
] | What you need is to create a custom `JPanel` implementation and override `paintComponent` method.
Inside it, you just do:
```
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw ellipse here
// Draw your image here. It will be drawn on top of the ellipse.
}
```
This way, you can hold the ellipse fill color in the `CustomPanel` class, and just call `repaint()` method after you change the color. | * your idea could be very good described (including code example) in the Oracles tutorial [How to Decorate Components with the JLayer Class](http://docs.oracle.com/javase/tutorial/uiswing/misc/jlayer.html)
* notice `JLayer` is available only for Java7, but its based on (for Java6) [JXLayer](http://java.net/projects/jxlayer/)
* you can use (I'm using) `GlassPane` too, with the same / similair output to the Swing GUI
EDIT
quite easy and nice output is by using [OverlayLayout](http://docs.oracle.com/javase/7/docs/api/javax/swing/OverlayLayout.html), there is possible to overlay `J/Component`(s) with `Graphics` e.g., [a few examples](http://www.java2s.com/Tutorial/Java/0240__Swing/OverlayLayoutforlayoutmanagementofcomponentsthatlieontopofoneanother.htm) |
5,446,295 | I'm trying to convert a url string into a label for a [Google Chart](http://code.google.com/apis/chart/docs/making_charts.html).
My question is this: my input is something like `www.mysite.com/link` and it needs to be encoded so it can itself be embedded into the Google charts URL.
Before: `www.mysite.com/link/test`
After: `www.mysite.com%2Flink%2Ftest`
How can I convert a regular string into a UTF-8 URL-encoded string in Rails? | 2011/03/27 | [
"https://Stackoverflow.com/questions/5446295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341583/"
] | There's also [`CGI.escape`](http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000093) from the standard library:
```
>> CGI.escape('www.mysite.com/link/test')
=> "www.mysite.com%2Flink%2Ftest"
``` | Rails 3.0 is based on [Rack](http://rack.rubyforge.org/), Rack provides a [Rack::Utils.escape](http://rack.rubyforge.org/doc/classes/Rack/Utils.src/M000082.html) method.
```
s = "www.mysite.com/link/test"
# => "www.mysite.com/link/test
Rack::Utils.escape(s)
# => "www.mysite.com%2Flink%2Ftest"
``` |
61,671,362 | I have a data which is a nested json. It contains some objects with count 0 which needs to be removed from the JSON. The data is given below
```
const data = {
"name": "A",
"desc": "a",
"count": 2,
"children": [
{
"name": "A1",
"desc": "a1",
"count": 2,
"children": [
{
"name": "A1-sub1",
"desc": "a1-sub1",
"count": 2,
},
{
"name": "A1-sub2",
"desc": "a1-sub2",
"count": 0,
},
]
},
{
"name": "A2",
"desc": "a2",
"count": 0
}
]
}
```
Here the object **A1-sub2** and **A2** has count 0 which needs to be removed.
I tried to delete the entire object but its not working. My code is as follows :
```
const deepCopy = (arr) => {
let copy = [];
arr.forEach(elem => {
if(Array.isArray(elem)){
copy.push(deepCopy(elem))
}else{
if (typeof elem === 'object') {
copy.push(deepCopyObject(elem))
} else {
copy.push(elem)
}
}
})
return copy;
};
const deepCopyObject = (obj) => {
let tempObj = {};
for (let [key, value] of Object.entries(obj)) {
if(key === "count"){
if(obj[key] === 0){
Object.keys(obj).forEach(function(key) {
delete obj[key];
});
}
}
if (Array.isArray(value)) {
tempObj[key] = deepCopy(value);
} else {
if (typeof value === 'object') {
tempObj[key] = deepCopyObject(value);
} else {
tempObj[key] = value
}
}
}
return tempObj;
};
console.log(deepCopyObject(data));
```
The expected outcome should be
```
const result = {
"name": "A",
"desc": "a",
"count": 2,
"children": [
{
"name": "A1",
"desc": "a1",
"count": 2,
"children": [
{
"name": "A1-sub1",
"desc": "a1-sub1",
"count": 2,
}
]
}
]
}
``` | 2020/05/08 | [
"https://Stackoverflow.com/questions/61671362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9567578/"
] | Instead of 2 look alike functions, you can do this in just one function.
The only problem with this function is that it reverses orders of keys of objects. If you don't need it in same order, then this function is fine.
```js
const filterObject = (obj) =>
Object.keys(obj)
.slice(0)
.reduce((accumulator, currentKey, _currentIndex, array) => {
if (obj.count === 0) {
array.splice(1);
return null;
}
if (currentKey === "children") {
accumulator.children = [];
for (let subObj of obj.children) {
if (!subObj["children"]) {
if (subObj.count > 0) accumulator.children.push(subObj);
} else {
let filtered = filterObject(subObj);
if (filtered) accumulator.children.push(filtered);
}
}
} else accumulator[currentKey] = obj[currentKey];
return accumulator;
}, {});
const data = {
name: "A",
desc: "a",
count: 2,
children: [{
name: "A1",
desc: "a1",
count: 2,
children: [{
name: "A1-sub1",
desc: "a1-sub1",
count: 2,
},
{
name: "A1-sub2",
desc: "a1-sub2",
count: 0,
},
],
},
{
name: "A2",
desc: "a2",
count: 0,
},
],
};
console.log(filterObject(data));
``` | beacuse you are deleting from obj not from tempObj which you are returning
```
if(obj[key] === 0){
Object.keys(obj).forEach(function(key) {
delete obj[key];
});
```
Following code is working for me
```
const deepCopy = (arr) => {
let copy = [];
arr.forEach(elem => {
if(Array.isArray(elem)){
copy.push(deepCopy(elem))
}else{
if (typeof elem === 'object') {
copy.push(deepCopyObject(elem))
} else {
copy.push(elem)
}
}
})
return copy;
};
const deepCopyObject = (obj) => {
let tempObj = {};
for (let [key, value] of Object.entries(obj)) {
if(key === "count"){
if(obj[key] === 0){
tempObj = null;
}
}
if (Array.isArray(value)) {
tempObj[key] = deepCopy(value);
} else {
if (typeof value === 'object') {
tempObj[key] = deepCopyObject(value);
} else if(tempObj != null) {
tempObj[key] = value
}
}
}
return tempObj;
};
const noNull = (v) => {
if (v && typeof v === 'object' && Array.isArray(v.children)) v.children =
v.children.filter(noNull);
return v !== null;
};
const input = require('./input');
const data = [deepCopyObject(input)];
console.log(JSON.stringify(data.filter(noNull)));
```
input is the data that you provided |
13,318,812 | Given a pair of lat/lng values, how do I determine if the pair is within a polygon? I need to do this in PHP. I see that Google Maps API has a `containsLocation` method: <https://developers.google.com/maps/documentation/javascript/reference>. Is there a way to leverage this from PHP? | 2012/11/10 | [
"https://Stackoverflow.com/questions/13318812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253976/"
] | very big thanks to David Strachan and Darel Rex Finley
i want to share my php version, is slightly different beacause it takes the point as an array ([lat, lng]) and the polygon as an array of point ([[lat, lng],[lat, lng],...])
```
function pointInPolygon($point, $polygon){//http://alienryderflex.com/polygon/
$return = false;
foreach($polygon as $k=>$p){
if(!$k) $k_prev = count($polygon)-1;
else $k_prev = $k-1;
if(($p[1]< $point[1] && $polygon[$k_prev][1]>=$point[1] || $polygon[$k_prev][1]< $point[1] && $p[1]>=$point[1]) && ($p[0]<=$point[0] || $polygon[$k_prev][0]<=$point[0])){
if($p[0]+($point[1]-$p[1])/($polygon[$k_prev][1]-$p[1])*($polygon[$k_prev][0]-$p[0])<$point[0]){
$return = !$return;
}
}
}
return $return;
}
``` | There are a copuple of ways to do this I think. The first would be to use this extension or something like this to determine if the point is inside the polygon:
[Google-Maps-Point-in-Polygon Extension](https://github.com/tparkin/Google-Maps-Point-in-Polygon)
Here is an explanation on the Ray casting algorithm that should help you out a little too:
[Point in polygon](http://en.wikipedia.org/wiki/Point_in_polygon)
The simple example from the extension shows it is pretty straight forward:
```
var coordinate = new google.maps.LatLng(40, -90);
var polygon = new google.maps.Polygon([], "#000000", 1, 1, "#336699", 0.3);
var isWithinPolygon = polygon.containsLatLng(coordinate);
``` |
42,199,903 | The problem I have is that I want to have a settings button which when the user clicks it, takes them to a specified path in the settings such as sound settings. The only issue is that every method I've tried has been outdated for more recent versions of iOS 10. Does anyone have any suggestions for a method which I can use? Any help will be greatly appreciated. | 2017/02/13 | [
"https://Stackoverflow.com/questions/42199903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7382004/"
] | I use this script in a file named "index.js" to "export default all exported default in every file in the current folder" sort of thing:
```
const files = require.context('.', false, /\.js$/)
const modules = {}
files.keys().forEach((key) => {
if (key === './index.js') return
modules[ key.replace(/(\.\/|\.js)/g, '') ] = files(key).default
})
export default modules
```
Then you can import the whole directory by importing it's name, just like this:
```
import folder from '../path/to/folder'
```
I hope this helps. | Based on Potray and Fosuze's working answers for easy reference:
```
const files = require.context('.', false, /\.vue$/)
const modules = {}
files.keys().forEach((key) => {
if (key === './index.js') return
modules[key.replace(/(\.\/|\.vue)/g, '')] = files(key)
})
export default modules
``` |
8,322,742 | Based on the JQuery-Mobile example of the [Split button list](http://jquerymobile.com/demos/1.0/docs/lists/lists-split.html) I am trying to generate a listview component in Android with two extra buttons to the right, one next to the other. The problem is that the code generates only one button and the second one is added as a link to the current item.
Here is my code:
```
<ul data-role="listview" data-filter="true" data-theme="b">
<li>
<a href="#" onclick="alert('the item!');">
<h3>The item</h3>
</a>
<a href="#" onclick="alert('1st splitbutton!');">1st link</a>
<a href="#" onclick="alert('2nd splitbutton!');">2nd link</a>
</li>
</ul>
```
This is what it generates:

And something like this is what I am trying to produce:

Is there a way to achieve this? Thank you in advance. | 2011/11/30 | [
"https://Stackoverflow.com/questions/8322742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1047055/"
] | I was able at last to achieve something similar:

In case anyone is interested, here is the final code:
```
<ul data-role="listview" data-filter="true" data-theme="b" style="margin-bottom: 50px;">
<li>
<a href="#" onclick="alert('the item!');">
<h3>The item</h3>
</a>
<a href="#" onclick="alert('1st splitbutton!');" class="split-button-custom" data-role="button" data-icon="gear" data-iconpos="notext">1st link</a>
<a href="#" onclick="alert('2nd splitbutton!');" class="split-button-custom" data-role="button" data-icon="arrow-r" data-iconpos="notext">2nd link</a>
<a href="#" style="display: none;">Dummy</a>
</li>
</ul>
```
And the new defined classes:
```
.split-button-custom {
float: right;
margin-right: 10px;
margin-top: -32px;
border-bottom-left-radius: 1em 1em;
border-bottom-right-radius: 1em 1em;
border-top-left-radius: 1em 1em;
border-top-right-radius: 1em 1em;
}
.split-button-custom span.ui-btn-inner {
border-bottom-left-radius: 1em 1em;
border-bottom-right-radius: 1em 1em;
border-top-left-radius: 1em 1em;
border-top-right-radius: 1em 1em;
padding-right: 0px;
}
.split-button-custom span.ui-icon {
margin-top: 0px;
right: 0px;
top: 0px;
position: relative;
}
``` | Inspired by Pablo's answer
```
<ul data-role="listview">
<li>
<a href="#">
<img class="cover" src="images/cover.jpg"/>
<h3>title</h3>
<p>description</p>
</a>
<div class="split-custom-wrapper">
<a href="#" data-role="button" class="split-custom-button" data-icon="gear" data-rel="dialog" data-theme="c" data-iconpos="notext"></a>
<a href="#" data-role="button" class="split-custom-button" data-icon="delete" data-rel="dialog" data-theme="c" data-iconpos="notext"></a>
</div>
</li>
</ul>
```
by placing the links in a wrapper div there's no need for a 'dummy' anchor (and can take more than two anchors).
css styling gives the buttons the same height as the listitem, so the accessibility is the same as the standard split button
```
.split-custom-wrapper {
/* position wrapper on the right of the listitem */
position: absolute;
right: 0;
top: 0;
height: 100%;
}
.split-custom-button {
position: relative;
float: right; /* allow multiple links stacked on the right */
height: 100%;
margin:0;
min-width:3em;
/* remove boxshadow and border */
border:none;
moz-border-radius: 0;
webkit-border-radius: 0;
border-radius: 0;
moz-box-shadow: none;
webkit-box-shadow: none;
box-shadow: none;
}
.split-custom-button span.ui-btn-inner {
/* position icons in center of listitem*/
position: relative;
margin-top:50%;
margin-left:50%;
/* compensation for icon dimensions */
top:11px;
left:-12px;
height:40%; /* stay within boundaries of list item */
}
``` |
2,422,050 | Are there any Pythonic solutions to reading and processing RAW images. Even if it's simply accessing a raw photo file (eg. cr2 or dng) and then outputting it as a jpeg.
Ideally a dcraw bindings for python, but anything else that can accomplish the came would be sufficient as well. | 2010/03/11 | [
"https://Stackoverflow.com/questions/2422050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96723/"
] | Here is a way to convert a canon CR2 image to a friendly format with [rawkit](https://github.com/photoshell/rawkit), that works with its current implementation:
```
import numpy as np
from PIL import Image
from rawkit.raw import Raw
filename = '/path/to/your/image.cr2'
raw_image = Raw(filename)
buffered_image = np.array(raw_image.to_buffer())
image = Image.frombytes('RGB', (raw_image.metadata.width, raw_image.metadata.height), buffered_image)
image.save('/path/to/your/new/image.png', format='png')
```
Using a numpy array is not very elegant here but at least it works, I could not figure how to use PIL constructors to achieve the same. | I'm not sure how extensive the RAW support in Python Imaging Library (PIL <http://www.pythonware.com/products/pil/>) is, but you may want to check that out.
Otherwise, you could just call dcraw directly since it already solves this problem nicely. |
4,292,756 | Sometimes when you run a piece of jQuery, you put a # symbol in the HREF attribute, but why? I do understand what # means, but i'm asking if you have this `<a href="#" id="runScript">Run</a>`
why would you actually put a # in the href and return false, could you just leave it blank and achieve the same results? | 2010/11/27 | [
"https://Stackoverflow.com/questions/4292756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478144/"
] | Leaving the `href` attribute blank will not accomplish the same as stopping the default action. A blank value may either be percieved by the browser as a non-value, causing it to render the element as a bookmark instead of a link, or as a link to the same page, causing a reload.
The value `#` is just an URL that causes a minimum of disturbance if the script fails to suppress the default action. If the script ends with an error, the default action will still kick in. | As the above posts said, it won't be styled as a clickable link. But instead you can just do:
```
a{
cursor:pointer;
}
```
in the CSS. |
24,277,734 | I am creating a tester class for a simple input database program. I do not have to store information nor delete anything, but there are two arrays in my the class I am running my tester class for.
This is my tester class:
```
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public Asst_3(){
this.keyboard = new Scanner(System.in);
}
public static void main(String[]args){
Policy insurance = new Policy();
insurance.setCustomerLast(null);
insurance.setCustomerFirst(null);
insurance.setPolicyNumber();
insurance.setAge();
insurance.setAccidentNumber();
insurance.setPremiumDueDate(00,00,0000);
//insurance.toString();
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
Scanner keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(null);
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.getPolicyNumber();
System.out.println("Customer's Policy Number is: " + keyboard.nextInt());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.getCustomerLast();
System.out.println("Customer's Last Name is: " + keyboard.nextInt());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.getCustomerFirst();
System.out.println("Customer's First Name is: " + keyboard.nextInt());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.getAge();
System.out.println("Customer's Age is: " + keyboard.nextInt());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.getAccidentNumber();
System.out.println("Customer's Amount of Accidents is: " + keyboard.nextInt());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.getPremiumDueDate();
System.out.println("Customer's Next Due Date is: " + keyboard.nextInt());
insurance.toString();
showMenuOptions();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
```
And the Null Pointer Error:
>
>
> ```
> Exception in thread "main" java.lang.NullPointerException
> at Asst_3.newPolicy(Asst_3.java:55)
> at Asst_3.intiateMenuSelection(Asst_3.java:40)
> at Asst_3.main(Asst_3.java:35)
>
> ```
>
>
This is the class I'm making my tester for:
```
import java.util.*;
public class Policy {
private int policyNumber;
private int age;
private int accidentNumber;
private String customerLast;
private String customerFirst;
private int [] months;
private int [] premiumDueDate;
public Policy() {
this.policyNumber = 0;
this.age = 0;
this.accidentNumber = 0;
this.customerLast = "";
this.customerFirst = "";
this.premiumDueDate = new int [3];
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
this.months = new int [12];
this.months[0] = this.months[2] = this.months[4] = this.months[6] = this.months[7] = this.months[9] = this.months[11] = 31;
this.months[1] = 28;
this.months[3] = this.months[5] = this.months[8] = this.months[10] = 30;
}
public int getPolicyNumber(){
return this.policyNumber;
}
public void setPolicyNumber(){
if(policyNumber < 1000){
policyNumber = 0;
}
if(policyNumber > 9999){
policyNumber = 0;
}
}
public int[] getPremiumDueDate(){
return this.premiumDueDate;
}
public void setPremiumDueDate(int month, int day, int year){
this.premiumDueDate[0] = month;
this.premiumDueDate[1] = day;
this.premiumDueDate[2] = year;
if(month < 0||month >= 12)
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
else if(day < 0 || day > this.months[month])
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
}
public int getAge(){
return this.age;
}
public void setAge(){
this.age = 0;
}
public int getAccidentNumber(){
return this.accidentNumber;
}
public void setAccidentNumber(){
this.accidentNumber = 0;
}
public String getCustomerLast(){
return this.customerLast;
}
public void setCustomerLast(String customerLast){
this.customerLast = customerLast;
}
public String getCustomerFirst(){
return this.customerFirst;
}
public void setCustomerFirst(String customerFirst){
this.customerFirst = customerFirst;
}
public String toString(){
return "\n Policy Number: " + this.policyNumber + "\n Customer Last Name: " + this.customerLast + "\n Customer First Name: " + this.customerFirst
+ "\n Customer age: " + this.age + "\n Number of Accidents in Past Three Years: " + this.accidentNumber + "\n Premium Due Date: " + this.premiumDueDate;
}
}
```
**Thank you everyone, your amazing!**
**Here's my edited code:**
The Tester
`import java.util.Scanner;`
`public class Asst_3 {`
```
private static Scanner keyboard;
public Asst_3(){
this.keyboard = new Scanner(System.in);
}
public static void main(String[]args){
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(new Policy());
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.setPolicyNumber(poliNum);
System.out.println("Customer's Policy Number is: " + insurance.getPolicyNumber());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.setCustomerLast(custLast);
System.out.println("Customer's Last Name is: " + insurance.getCustomerLast());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.setCustomerFirst(custFirst);
System.out.println("Customer's First Name is: " + insurance.getCustomerFirst());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.setAge(custAge);
System.out.println("Customer's Age is: " + insurance.getAge());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.setAccidentNumber(custAccident);
System.out.println("Customer's Amount of Accidents is: " + insurance.getAccidentNumber());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.setPremiumDueDate(dueDate, dueDate, dueDate);
System.out.println("Customer's Next Due Date is: " + insurance.getPremiumDueDate());
insurance.toString();
returnToMenu();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
```
}
And the class being tested:
`import java.util.*;`
`public class Policy {`
```
private int policyNumber;
private int age;
private int accidentNumber;
private String customerLast;
private String customerFirst;
private int [] months;
private int [] premiumDueDate;
public Policy() {
this.policyNumber = 0;
this.age = 0;
this.accidentNumber = 0;
this.customerLast = "";
this.customerFirst = "";
this.premiumDueDate = new int [3];
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
this.months = new int [12];
this.months[0] = this.months[2] = this.months[4] = this.months[6] = this.months[7] = this.months[9] = this.months[11] = 31;
this.months[1] = 28;
this.months[3] = this.months[5] = this.months[8] = this.months[10] = 30;
}
public int getPolicyNumber(){
return this.policyNumber;
}
public void setPolicyNumber(int policyNumber){
if(policyNumber < 1000){
policyNumber = 0;
}
if(policyNumber > 9999){
policyNumber = 0;
}
}
public int[] getPremiumDueDate(){
return this.premiumDueDate;
}
public void setPremiumDueDate(int month, int day, int year){
this.premiumDueDate[0] = month;
this.premiumDueDate[1] = day;
this.premiumDueDate[2] = year;
if(month < 0||month >= 12)
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
else if(day < 0 || day > this.months[month])
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
}
public int getAge(){
return this.age;
}
public void setAge(int age){
this.age = 0;
}
public int getAccidentNumber(){
return this.accidentNumber;
}
public void setAccidentNumber(int accidentNumber){
this.accidentNumber = 0;
}
public String getCustomerLast(){
return this.customerLast;
}
public void setCustomerLast(String customerLast){
this.customerLast = customerLast;
}
public String getCustomerFirst(){
return this.customerFirst;
}
public void setCustomerFirst(String customerFirst){
this.customerFirst = customerFirst;
}
public String toString(){
return "\n Policy Number: " + this.policyNumber + "\n Customer Last Name: " + this.customerLast + "\n Customer First Name: " + this.customerFirst
+ "\n Customer age: " + this.age + "\n Number of Accidents in Past Three Years: " + this.accidentNumber + "\n Premium Due Date: " + this.premiumDueDate;
}
```
}
But now I have a new error after executing the program:
```
Welcome to Drive-Rite Insurance Company
Choose a menu option:
(1) Create New Policies
(2) Search by age
(3) Search by due date
(4) Exit
Input Option Number ---> Exception in thread "main" java.lang.NullPointerException
at Asst_3.main(Asst_3.java:23)
```
Here's an updated version with that NPE fixed:
```
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public static void main(String[]args){
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
this.keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(new Policy());
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.setPolicyNumber(poliNum);
System.out.println("Customer's Policy Number is: " + insurance.getPolicyNumber());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.setCustomerLast(custLast);
System.out.println("Customer's Last Name is: " + insurance.getCustomerLast());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.setCustomerFirst(custFirst);
System.out.println("Customer's First Name is: " + insurance.getCustomerFirst());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.setAge(custAge);
System.out.println("Customer's Age is: " + insurance.getAge());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.setAccidentNumber(custAccident);
System.out.println("Customer's Amount of Accidents is: " + insurance.getAccidentNumber());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.setPremiumDueDate(dueDate, dueDate, dueDate);
System.out.println("Customer's Next Due Date is: " + insurance.getPremiumDueDate());
insurance.toString();
returnToMenu();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("----------------------------------------");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
```
}
The errors are I'm having issues with they keyboard variables. | 2014/06/18 | [
"https://Stackoverflow.com/questions/24277734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3751018/"
] | null pointer occurring in
```
private static void newPolicy(Policy insurance)
```
this method. For these lines
```
insurance.getPolicyNumber();
insurance.get....();
insurance.get....();
```
because the reference/object `insurance` coming as a parameter from where its being called . in you case you are passing null to the method
```
newPolicy(null); //try to pass a reference of Policy like 'newPolicy(new Policy())' .
``` | The `insurance` that you are passing to `newPolicy` is null
```
case 1: newPolicy(null);
```
hence
```
insurance.getPolicyNumber();
```
will throw a NPE |
40,128 | I wonder if the word "县子" colloquially exists in the Chinese language.
I’ve probably heard this word before, and I‘m not exactly sure, but I blurrily remember it was from a conversation between my grandparents.
I suppose this is like an infrequently used dialectical term in Chinese and the infrequency of its usage, and perhaps to a certain extent, its uncommonness makes it only conversationally and dialectically correct and particularly not acceptable in formal situations.
句子有:
她们几个去那儿的县子了。
Thank you in advance.
---
Thank you very much for your help! | 2020/07/18 | [
"https://chinese.stackexchange.com/questions/40128",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/25806/"
] | I need more examples. but "县" means "county, the administrative district one level lower than the city", such as "桐庐县" is a county in "杭州市", "宝应县" is a county in "扬州市". "子" is usually a suffix, has no actual meaning, like "桌子" "筷子". "县子" maybe is a dialect words means "县" or "县城". | 县子 = town
她们几个去那儿的县子了。
A few of the girls went to the town over there.
Especially in rural areas 县、县子 may still be used as town.
怀化市 (spoken: fyfashi, they don't like h in 怀化市!) 的 会同县 in 湖南省
省、市、县、区 |
56,756,906 | I have string like this: `$string = "1A1R0A"` and I want to split that $string into 2 arrays:
```
array1 (
[0] => 1
[1] => 1
[2] => 0
)
array2 (
[0] => A
[1] => R
[2] => A
)
```
Can you help me to do that ?
I've tried using `str_split` like this:
```
$subs = str_split($string,1);
```
but it doesn't work because it will make array like this:
```
Array (
[0] => 1
[1] => A
[2] => 0
[3] => R
[4] => 1
[5] => A
)
``` | 2019/06/25 | [
"https://Stackoverflow.com/questions/56756906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11430096/"
] | You can use a regex to match all patterns of numbers followed by non-numbers.
```
preg_match_all('/(\d+)(\D+)/', $string, $matches);
```
Your arrays of numbers/letters will be in the matches. You can work with them directly in `$matches[1]` and `$matches[2]`, or extract them into a more readable format.
```
$result = array_combine(['numbers', 'letters'], array_slice($matches, 1));
``` | `preg_match_all()` provides a direct, single-function technique without looping.
Capture the digits (`$out[1]`) and store the letters in the fullstring match (`$out[0]`). No unnecessary subarrays in `$out`.
Code: ([Demo](https://3v4l.org/9mu9U))
```
$string = "1A1R0A";
var_export(preg_match_all('~(\d)\K\D~', $string, $out) ? [$out[1], $out[0]] : [[], []]);
echo "\n--- or ---\n";
[$letters, $numbers] = preg_match_all('~(\d)\K\D~', $string, $out) ? $out : [[], []];
var_export($numbers);
echo "\n";
var_export($letters);
```
Output:
```
array (
0 =>
array (
0 => '1',
1 => '1',
2 => '0',
),
1 =>
array (
0 => 'A',
1 => 'R',
2 => 'A',
),
)
--- or ---
array (
0 => '1',
1 => '1',
2 => '0',
)
array (
0 => 'A',
1 => 'R',
2 => 'A',
)
```
---
If your string may start with a letter or your letter-number sequence is not guaranteed to alternate, you can use this direct technique to separate the two character categories.
Code: ([Demo](https://3v4l.org/mRisu))
```
$string = "B1A23R4CD";
$output = [[], []]; // ensures that the numbers array comes first
foreach (str_split($string) as $char) {
$output[ctype_alpha($char)][] = $char;
// ^^^^^^^^^^^^^^^^^^- false is 0, true is 1
}
var_export($output);
```
Output:
```
array (
0 =>
array (
0 => '1',
1 => '2',
2 => '3',
3 => '4',
),
1 =>
array (
0 => 'B',
1 => 'A',
2 => 'R',
3 => 'C',
4 => 'D',
),
)
``` |
9,778,033 | Hi I have configured the DSN settings for vertica in Ubuntu 10.10 32 bit version machine.
The settings are all fine and I have cross checked them.
Here is my odbc.ini file:
```
[VerticaDSN]
Description = VerticaDSN ODBC driver
Driver = /opt/vertica/lib/libverticaodbc_unixodbc.so
Servername = myservername
Database = mydbname
Port = 5433
UserName = myuname
Password = *******
Locale = en_US
```
Similarly I have a odbcinst.ini file.
when I run the command: isql -v VerticaDSN I get the following error:
```
[S1000][unixODBC][DSI] The error message NoSQLGetPrivateProfileString could not be found in the en-US locale. Check that /en-US/ODBCMessages.xml exists.
[ISQL]ERROR: Could not SQLConnect.
```
I have tried everything but I am not able to decipher this error.
Any help will be greatly appreciated. | 2012/03/19 | [
"https://Stackoverflow.com/questions/9778033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018818/"
] | From the error we can see you are using unixODBC and I presume "DSI" is what Vertica calls itself as ODBC error text is formatted with entries in [] from left to right as the path though the different components (see [Example diagnostic messages](http://www.easysoft.com/developer/interfaces/odbc/diagnostics_error_status_codes.html#ExampleDiagnosticMessages)).
I presume that message should be "No SQLGetPrivateprofileString could be found". SQLGetPrivateProfileString is an API provided by the ODBC driver manager to read entries from the odbc.ini file. I believe it should be found in the libodbcinst.so shared object however, some distributions (e.g., Ubuntu/Debian) strip symbols from shared objects so it is difficult to verify this.
In your DSN, the driver is the file "/opt/vertica/lib/libverticaodbc\_unixodbc.so". Although it is more usual to name the driver in the odbc.ini and add an entry to the odbcinst.ini file your DSN looks ok. e.g.:
```
/etc/odbcinst.ini:
[Easysoft ODBC-SQL Server SSL]
Driver=/usr/local/easysoft/sqlserver/lib/libessqlsrv.so
Setup=/usr/local/easysoft/sqlserver/lib/libessqlsrvS.so
Threading=0
FileUsage=1
DontDLClose=1
/etc/odbc.ini:
[SQLSERVER_SAMPLE_SSL]
Driver=Easysoft ODBC-SQL Server SSL
Description=Easysoft SQL Server ODBC driver
.
.
```
See in the above example doing it this way allows you to specify additional options associated with the driver like Threading (and a quick search on the net suggests Vertica can use Threading=1 which is less restrictive if using a threaded program) and DontDLClose. However, as I said things should work as you have them now.
Now the next bit depends on your platform and I didn't notice if you specified one. You need to examine that shared object for your ODBC Driver and see what it depends on. On Linux you do something like this:
```
$ ldd /usr/local/easysoft/sqlserver/lib/libessqlsrv.so
linux-gate.so.1 => (0xb76ff000)
libodbcinst.so.1 => /usr/lib/libodbcinst.so.1 (0xb75fe000)
libesextra_r.so => /usr/local/easysoft/lib/libesextra_r.so (0xb75fb000)
libessupp_r.so => /usr/local/easysoft/lib/libessupp_r.so (0xb75de000)
libeslicshr_r.so => /usr/local/easysoft/lib/libeslicshr_r.so (0xb75cd000)
libestdscrypt.so => /usr/local/easysoft/lib/libestdscrypt.so (0xb75c8000)
libm.so.6 => /lib/libm.so.6 (0xb75a2000)
libc.so.6 => /lib/libc.so.6 (0xb7445000)
libltdl.so.7 => /usr/lib/libltdl.so.7 (0xb743b000)
libpthread.so.0 => /lib/libpthread.so.0 (0xb7421000)
/lib/ld-linux.so.2 (0xb7700000)
libdl.so.2 => /lib/libdl.so.2 (0xb741d000)
```
which shows this ODBC driver depends on libodbcinst.so.1 and the dynamic linker found it. I imagine your Vertica driver should look similar in this respect although it is possible the Vertica driver dynamically loads this shared object itself on first being loaded. Either way, it looks like the Vertica driver cannot find the symbol SQLGetPrivateProfileString which is in libodbcinst.so so make sure a) you have libodbcinst.so b) your dynamic linker knows about it (how this is done depends on your platform - on Linux see /etc/ld.so.conf and LD\_LIBRARY\_PATH and the man page for ld.so) c) run ldd (or equivalent) on it to make there are no missing dependencies.
The vertica.ini file is probably where the driver stores driver specific configuration - some drivers do this. If the format of this file is like the odbc ones above it may also use SQLGetPrivateProfileString for this file as you can tell that ODBC API which file to use.
Beyond this I've no more ideas other than contact vertica. | Arun -- if you can let me know the version of the database and the version of the driver I can get you more detail. Also, I might try posting this on the official Vertica community forum.
<http://my.vertica.com/forums/forum/application-and-tools-area/client-drivers/>
If I had to guess what your issue is I think it might be related to this post :
<http://my.vertica.com/forums/topic/odbc-on-linux-issue/>
... specifically the comment at the end about 'ODBCInstLib'. |
23,167,703 | I have two buttons one for Groups and second is for Skills. when i click on groups button one popup will show and in the popup the groups are showing with checkbox. wheni select the groups and click on save button the checked groups will show on the uper of group button and popup will close.and this same is for skills button also.
My problem is that when i select groups it will show on groups button but when i select skill i lost the selected groups.
**right now i am doing this:**
```
function OnClickButton () {
var display = "";
checkboxes = document.getElementsByName("group");
for( var i=0; i<checkboxes.length; i++){
if( checkboxes[i].checked ){
display += " " + checkboxes[i].value;
}
}
window.location.href='job_posting.html?data='+display;
}
<button type="button" onclick="OnClickButton()" >Save</button>
```
**this is for Groups.**
```
function OnClickButton1 () {
var display1 = "";
checkboxes = document.getElementsByName("skill");
for( var i=0; i<checkboxes.length; i++){
if( checkboxes[i].checked ){
display1 += " " + checkboxes[i].value;
}
}
window.location.href='job_posting.html?data='+display1;
}
<button type="button" onclick="OnClickButton1()" >Save</button>
```
And this is for skills.
I get the groups and skills in the url .Not for get the url i try this
```
function getUrlParameters(parameter, staticURL, decode){
var currLocation = (staticURL.length)? staticURL : window.location.search,
parArr = currLocation.split("?")[1].split("&"),
returnBool = true;
for(var i = 0; i < parArr.length; i++){
parr = parArr[i].split("=");
if(parr[0] == parameter){
return (decode) ? decodeURIComponent(parr[1]) : parr[1];
returnBool = true;
}else{
returnBool = "";
}
}
if(!returnBool) return false;
}
function get_data()
{
var idParameter = getUrlParameters("data","",true);
var idParameter1 = getUrlParameters("data1","",true);
document.getElementById('display').innerHTML=idParameter;
document.getElementById('display1').innerHTML=idParameter1;
}
```
Call this on
```
<body onLoad="get_data();">
```
Thank You in advance | 2014/04/19 | [
"https://Stackoverflow.com/questions/23167703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3489787/"
] | No. You don't even need variable names in the declaration of a function. Their purpose there is documentation.
Obviously this can be trivially checked:
```
void foo(int); // or void foo(int bar);
int main()
{
foo(42);
}
#include <iostream>
void foo(int n)
{
std::cout << n << std::endl;
}
```
In general, I can see no reason to use different names, and the cases where you can use no name in the declaration without loss of information are few and far between. | No, the prototype doesn't need to match the definition of a function (either it is a member function of a `class` or a simple function).
You can have it like this,
```
class myClass {
public:
void myMethod (const int &name1);
}
```
And the definition.
```
void myClass::myMethod (const int &name2) {
// use name2 here.
}
```
You can even skip the name of argument(s) (variable names) in the function prototype.
Like,
```
class myClass {
public:
void myMethod (const int &);
}
```
Hope it helped you. If it doesn't. Read the related section in current C++ working draft. |
62,371,643 | I need to use kafka-node under typescript:
```
const kafkaHost = 'localhost:9092';
const client = new Client({ kafkaHost });
```
After launching index.ts I get this error:
```
Property '_write' in type 'ProducerStream' is not assignable to the same property in base type 'Writable'.
Type '(message: ProduceRequest, encoding: "utf8" | "buffer", cb: (error: any, data: any) => any) => void' is not assignable to type '(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null | undefined) => void) => void'.
Types of parameters 'encoding' and 'encoding' are incompatible.
Type 'BufferEncoding' is not assignable to type '"utf8" | "buffer"'.
Type '"ascii"' is not assignable to type '"utf8" | "buffer"'.
143 _write (message: ProduceRequest, encoding: 'buffer' | 'utf8', cb: (error: any, data: any) => any): void;
```
I think problem is in types, so I dont have installed `@types/kafka-node`, nevertheless it is deprecated.
How to fix it? | 2020/06/14 | [
"https://Stackoverflow.com/questions/62371643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | **July 22, 2020**
In [Room 2.3.0-alpha02](https://developer.android.com/jetpack/androidx/releases/room#2.3.0-alpha02) was added support for RxJava3 types.
Though it's still in alpha, but you can consider this option.
According to release description:
>
> Similar to RxJava2 you can declare DAO methods whose return type are
> Flowable, Single, Maybe and Completable.
>
> Additionally a new artifact
> `androidx.room:room-rxjava3` is available to support RxJava3
>
>
> | Currently updating a project and having the same problem.
I'm using room-rxjava2 to generate the DAOs (as before) with RxJava2 types.
But for my business logic I'm using <https://github.com/akarnokd/RxJavaBridge> to convert to RxJava3 types. |
924 | This question seems similar to [this one](https://photo.stackexchange.com/questions/533/how-can-i-backup-my-photos-while-travelling), but my needs are different :
* I shoot in RAW exclusively
* I'm looking for a 100% offline solution: while traveling, Internet won't be accessible
* the "laptop" solution is too heavy for me: I'm looking for a lightweight solution
* the simplest, the better: *one device to rule them all*
**EDIT:**
I'm using good old Compact Flash cards (yes, the bigger ones), so I need a device that can read it. If it can read from other cards, this question might be interesting for more people than myself - that's the whole purpose of the website.
---
**Also asked by [Rafal Ziolkowski](https://photo.stackexchange.com/users/1681/rafal-ziolkowski):**
Portable Storage Device while traveling
---------------------------------------
I need storage device which is able to read CF cards and make a backup of my photos while traveling. I do not want to carry laptop (it's bulky) and tablet (too little storage) but looking into some other solutions.
So far I found:
* Epson PXXXX - price is blocker for me
* Jobo Giga Vu - same as above
* Nexto DI - bit better, but still a lot
* Hyperdrive Colorspace UDMA - this looks the best for price/options
* Wolwerine PicPac - cheap, bad opinions
* DigitalFoci PhotoSafe - same as above
* Ex-Pro® Picture 2 Drive - didn't find much about it
So ladys & gents what do you use? | 2010/07/20 | [
"https://photo.stackexchange.com/questions/924",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/68/"
] | Unless weight and size are an over-over-overwhelming consideration then you would be very hard put to find something that beats a small netbook computer. It makes no sense to reject a computer solution absolutely - it should simply be put in the list along with the rest and compete on its own merits.
---
Netbook:
Downsides:
* Weight
* Size
* Battery life needs to be carefully maximised.
* Cost is an issue only if you allow it to be.
My wife has an ACER em350 'emachine" that is a superb travel tool.
WiFi. 160 GB drive. 1050 grams.
5 hour battery life with care on a stupidly small 3 cell battery.
Cost us about $US230 new. That was exceptional, but bargains happen.
Upside:
* Does just about everything conceivable.
---
>
> would like the solution to be powergrid independent (battery powerable)
>
>
>
Yes.
>
> raw => picturereviewing only valuable if rw2 format capable
>
>
>
Can do.
>
> would like to have some visual confirmation of backup/copying success, since I might reuse my memory cards for further shooting (=> backup becomes only copy)
>
>
>
Yes.
Backup MUST NEVER be only copy.
>
> need SDHC card slot
>
>
>
Card Reader. Maybe in slot.
>
> weight is an issue
>
>
>
Under to well under 1 kg possible.
Probably over 500 gram.
>
> Do you own such a device and can you recommend it or not?
>
>
>
I would unreservedly recommend a netbook as a backup device.
The penalties of size and weight - even when travelling light internationally, are minor when its advantages are considered.
I own an HP 5101 Netbook. 1250 grams with big aftermarket battery.
Similar and smaller can be under 1kg.
WiFi. Secondary backup to say 1 GB portable drive.
Internal 250 GB.
Utterly superior to alternatives once you accept carrying it - which is not that hard.
>
> Do you know more about the features of such a device (Can you create folders,does it support rw2/Link to a datasheet)?
>
>
>
A netbook can do anything :-) | I did all of this but today I simply use 2 CF oder 2 SD cards and make my camera write the images to both cards (many cameras have two card slots).
This has many advantages:
* no hard disk
* no SSD
* no card reader and usb cable
* no tablet or laptop
* you don't dive through your images at night during your trip
* cheapest solution
* low weight
* you can carry lots of cards with you
* you can distribute them against theft (1 suitcase, 1 hotel safe)
* you can easily hide them against theft
You can concentrate on photography, travel, holidays without being afraid of losing the images. |
2,032,881 | In C++, is there any way to query the type of an object and then use that information to dynamically create a new object of the same type?
For example, say I have a simple 3 class hierarchy:
```
class Base
class Foo : public Base
class Bar : public Base
```
Now suppose I give you an object cast as type Base -- which is in reality of type Foo.
Is there a way to query the type and use that info to later create new objects of type Foo? | 2010/01/09 | [
"https://Stackoverflow.com/questions/2032881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246991/"
] | Clone method
------------
There is nothing provided by the language that queries type and lets you construct from that information, but you can provide the capability for your class hierarchy in various ways, the easiest of which is to use a virtual method:
```
struct Base {
virtual ~Base();
virtual std::auto_ptr<Base> clone(/*desired parameters, if any*/) const = 0;
};
```
This does something slightly different: clone the current object. This is often what you want, and allows you to keep objects around as templates, which you then clone and modify as desired.
Expanding on [Tronic](https://stackoverflow.com/questions/2032881/creating-a-new-object-from-dynamic-type-info/2033034#2033034), you can even [generate](http://bitbucket.org/kniht/scraps/src/tip/cpp/clone.hpp) the [clone function](http://bitbucket.org/kniht/scraps/src/tip/cpp/test_clone.cpp).
Why *auto\_ptr*? So you can use *new* to allocate the object, make the transfer of ownership explicit, and the caller has no doubt that *delete* must deallocate it. For example:
```
Base& obj = *ptr_to_some_derived;
{ // since you can get a raw pointer, you have not committed to anything
// except that you might have to type ".release()"
Base* must_free_me = obj.clone().release();
delete must_free_me;
}
{ // smart pointer types can automatically work with auto_ptr
// (of course not all do, you can still use release() for them)
boost::shared_ptr<Base> p1 (obj.clone());
auto_ptr<Base> p2 (obj.clone());
other_smart_ptr<Base> p3 (obj.clone().release());
}
{ // automatically clean up temporary clones
// not needed often, but impossible without returning a smart pointer
obj.clone()->do_something();
}
```
Object factory
--------------
If you'd prefer to do exactly as you asked and get a factory that can be used independently of instances:
```
struct Factory {}; // give this type an ability to make your objects
struct Base {
virtual ~Base();
virtual Factory get_factory() const = 0; // implement in each derived class
// to return a factory that can make the derived class
// you may want to use a return type of std::auto_ptr<Factory> too, and
// then use Factory as a base class
};
```
Much of the same logic and functionality can be used as for a clone method, as *get\_factory* fulfills half of the same role, and the return type (and its meaning) is the only difference.
I've also covered factories a [couple](https://stackoverflow.com/questions/1832003/instantiating-classes-by-name-with-factory-pattern/1837665#1837665) [times](https://stackoverflow.com/questions/2032361/whats-polymorphic-type-in-c/2032368#2032368) already. You could adapt my [SimpleFactory class](http://bitbucket.org/kniht/scraps/src/tip/cpp/simple_factory.hpp) so your factory object (returned by *get\_factory*) held a reference to a global factory plus the parameters to pass to create (e.g. the class's registered name—consider how to apply *boost::function* and *boost::bind* to make this easy to use). | ```
class Base
{
public:
virtual ~Base() { }
};
class Foo : public Base
{
};
class Bar : public Base
{
};
template<typename T1, typename T2>
T1* fun(T1* obj)
{
T2* temp = new T2();
return temp;
}
int main()
{
Base* b = new Foo();
fun<Base,Foo>(b);
}
``` |
25,227,759 | Assume a text file with 40 lines of data. How can I remove lines 3 to 10, 13 to 20, 23 to 30, 33 to 40, in place using bash script?
I already know how to remove lines 3 to 10 with `sed`, but I wonder if there is a way to do all the removing, in place, with only one command line. I can use `for loop` but the problem is that with each iteration of loop the lines number will be changed and it needs some additional calculation of line numbers to be removed. | 2014/08/10 | [
"https://Stackoverflow.com/questions/25227759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2492151/"
] | ```
sed -i '3,10d;13,20d;23,30d;33,40d' file
``` | @Kent's answer is the way to go for this particular case, but in general:
```
$ seq 50 | awk '{idx=(NR%10)} idx>=1 && idx<=2'
1
2
11
12
21
22
31
32
41
```
The above will work even if you want to select the 4th through 7th lines out of every 13, for example:
```
$ seq 50 | awk '{idx=(NR%13)} idx>=4 && idx<=7'
4
5
6
7
17
18
19
20
30
31
32
33
43
44
45
46
```
its not constrained to N out of 10.
Or to select just the 3rd, 5th and 6th lines out of every 13:
```
$ seq 50 | awk 'BEGIN{split("3 5 6",tmp); for (i in tmp) tgt[tmp[i]]=1} tgt[NR%13]'
3
5
6
16
18
19
29
31
32
42
44
45
```
The point is - selecting ranges of lines is a job for awk, definitely not sed. |
54,439 | [Multani, Yavimaya's Avatar](http://gatherer.wizards.com/Pages/Search/Default.aspx?name=%2b%5bMultani%2c%5d%2b%5bYavimaya%27s%5d%2b%5bAvatar%5d)'s activated ability doesn't require having to declare any targets, and it only cost {1}{G} and returning two lands to hand. The ability doesn't say Multani has to be in the yard. Is there any rule or thing I'm missing that prevents me from activating the ability, returning the lands, and then the ability doing nothing? | 2021/03/19 | [
"https://boardgames.stackexchange.com/questions/54439",
"https://boardgames.stackexchange.com",
"https://boardgames.stackexchange.com/users/35644/"
] | You won't be able to active Multani on the battlefield. See Comprehensive Rules 113.6k:
>
> 113.6k An ability whose cost or effect specifies that it moves the object it's on out of a particular zone functions only in that zone, unless that ability's trigger condition, or a previous part of that ability's cost or effect, specifies that the object is put into that zone.
>
>
> Example: Reassembling Skeleton says "{1}{B}: Return Reassembling Skeleton from your graveyard to the battlefield tapped." A player may activate this ability only if Reassembling Skeleton is in his or her graveyard.
>
>
>
Multani states:
>
> (1)(G), Return two lands you control to their owner's hand: **Return Multani from your graveyard to your hand.**
>
>
>
Since it says it is returning from your graveyard, you can't active unless it is in your graveyard. | Generally, abilities of permanent cards and tokens *only* work on the battlefield.
>
> 113.6. Abilities of an instant or sorcery spell usually function only while that object is on the stack. Abilities of all other objects usually function only while that object is on the battlefield. The exceptions are as follows:
>
>
>
The exceptions can be summarized as follows: Characterstic-defining abilites work everywhere, and abilities that are obviously intended to work in other zones *only* work in those other zones.
The ability in question is obviously intended to work from the graveyard — to be able to return Multani from the graveyard, Multani must be in the graveyard — so it *only* works from the graveyard.
>
> 113.6k An ability whose cost or effect specifies that it moves the object it’s on out of a particular zone functions only in that zone, unless its trigger condition or a previous part of its cost or effect specifies that the object is put into that zone or, if the object is an Aura, that the object it enchants leaves the battlefield. The same is true if the effect of that ability creates a delayed triggered ability whose effect moves the object out of a particular zone.
>
>
> Example: Reassembling Skeleton says “{1}{B}: Return Reassembling Skeleton from your graveyard to the battlefield tapped.” A player may activate this ability only if Reassembling Skeleton is in their graveyard.
>
>
> |
58,997,142 | I have a variable which contains output from a shell command, I'm trying to 'grep' the variable but it seems that the output is all in one line without linebreaks. So when I 'grep' the variable everything is returned.
For example my variable contains this:
```
standalone 123 abc greefree ten1 stndalone 334 abc fregree ten1 stndalone 334 abc fregree ten2 stndalone 334 abc fregree ten2 stndalone 334 abc fregree ten1 stndalone 334 abc fregree ten2 stndalone 334 abc fregree ten1 stndalone 334 abc fregree ten1 stndalone 334 abc fregree ten2
```
I'd like to insert a line break everywhere there is ten1 or ten2. So that when I 'grep' the variable I am only returned a particular line.
Output similar to this
```
standalone 123 abc greefree ten1
stndalone 334 abc fregree ten1
stndalone 334 abc fregree ten2
stndalone 334 abc fregree ten2
stndalone 334 abc fregree ten1
stndalone 334 abc fregree ten2
stndalone 334 abc fregree ten1
stndalone 334 abc fregree ten1
stndalone 334 abc fregree ten2
```
Is there a bash command I can use or some type of regex expression? | 2019/11/22 | [
"https://Stackoverflow.com/questions/58997142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2226069/"
] | The environment you pass to `CreateProcessA` must include `SYSTEMROOT`, otherwise the Win32 API call `CryptAcquireContext` will fail when called inside python during initialization.
When passing in NULL as lpEnvironment, your new process inherits the environment of the calling process, which has `SYSTEMROOT` already defined. | To follow up with an example how this can very easily be triggered in pure Python software out in the real world, there are times where it is useful for Python to open up an instance of itself to do some task, where the sub-task need a specific `PYTHONPATH` be set. Often times this may be done lazily on less fussy platforms (i.e. not Windows) like so:
```
import sys
from subprocess import Popen
p = Popen([sys.executable, '-c', 'print("hello world")'], env={
'PYTHONPATH': '', # set it to somewhere
})
```
However, doing so on Windows, will lead to the following perplexing failure:
```
Python 3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:34:34) [MSC v.1928 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> from subprocess import Popen
>>> p = Popen([sys.executable, '-c', 'print("hello world")'], env={
... 'PYTHONPATH': ''
... })
Fatal Python error: _Py_HashRandomization_Init: failed to get random numbers to initialize Python
Python runtime state: preinitialized
```
The fix is obvious: clone the `os.environ` to ensure `SYSTEMROOT` is in place such that the issue pointed out by @Joe Savage's answer be averted, e.g.:
```
>>> import os
>>> env = os.environ.copy()
>>> env['PYTHONPATH'] = ''
>>> p = Popen([sys.executable, '-c', 'print("hello world")'], env=env)
hello world
```
A real world example where this type of fix was needed:
* [Glean SDK](https://github.com/mozilla/glean/pull/1908/commits/b44f9f7c0c10fde9b495f61794253b051a0d3f62) |
53,781,727 | I am trying to implement pagination but It's not working. Here is my code:
**pager.service.ts:**
```
import * as _ from 'underscore';
@Injectable({
providedIn: 'root',
})
export class PagerService {
getPager(totalItems: number, currentPage: number = 1, pageSize: number = 10) {
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
let startPage: number, endPage: number;
if (totalPages <= 10) {
// less than 10 total pages so show all
startPage = 1;
endPage = totalPages;
} else {
// more than 10 total pages so calculate start and end pages
if (currentPage <= 6) {
startPage = 1;
endPage = 10;
} else if (currentPage + 4 >= totalPages) {
startPage = totalPages - 9;
endPage = totalPages;
} else {
startPage = currentPage - 5;
endPage = currentPage + 4;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = _.range(startPage, endPage + 1);
// return object with all pager properties required by the view
return {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages
};
}
}
```
**quick-worker-list.component.ts:**
```
import { JobService } from '@app/services';
import { PagerService } from './../../../services/pager.service';
import { Component, OnInit, Input } from '@angular/core';
import * as _ from 'underscore';
@Component({
selector: 'app-quick-worker-list',
templateUrl: './quick-worker-list.component.html',
styles: []
})
export class QuickWorkerListComponent implements OnInit {
S3ImageUrl: string;
// array of all items to be paged
private workerData: any[];
// pager object
pager: any = {};
// paged items
pagedItems: any[];
constructor(private pagerService: PagerService, private jobService: JobService) {
}
ngOnInit() {
this.jobService.getQuickJobWorkerList(1301, 1)
.map((response: Response) => response.json())
.subscribe(data => {
// set items to json response
this.workerData = data;
// initialize to page 1
this.setPage(1);
});
}
setPage(page: number) {
if (page < 1 || page > this.pager.totalPages) {
return;
}
// get pager object from service
this.pager = this.pagerService.getPager(this.allItems.length, page);
// get current page of items
this.pagedItems = this.allItems.slice(this.pager.startIndex, this.pager.endIndex + 1);
}
}
```
I get this error:
>
> QuickWorkerListComponent\_Host.ngfactory.js? [sm]:1 ERROR Error:
> StaticInjectorError(AppModule)[QuickWorkerListComponent ->
> PagerService]: StaticInjectorError(Platform:
> core)[QuickWorkerListComponent -> PagerService]:
> NullInjectorError: No provider for PagerService!
> at NullInjector.push../node\_modules/@angular/core/fesm5/core.js.NullInjector.get
> (core.js:3228)
> at resolveToken (core.js:3473)
> at tryResolveToken (core.js:3417)
> at StaticInjector.push../node\_modules/@angular/core/fesm5/core.js.StaticInjector.get
> (core.js:3314)
> at resolveToken (core.js:3473)
> at tryResolveToken (core.js:3417)
> at StaticInjector.push../node\_modules/@angular/core/fesm5/core.js.StaticInjector.get
> (core.js:3314)
> at resolveNgModuleDep (core.js:19784)
> at NgModuleRef\_.push../node\_modules/@angular/core/fesm5/core.js.NgModuleRef\_.get
> (core.js:20473)
> at resolveNgModuleDep (core.js:19784)
>
>
> | 2018/12/14 | [
"https://Stackoverflow.com/questions/53781727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Following the error text, you have to import and add your `PagerService` in the **Provider** part of your `app.module.ts` file:
```
providers: [
PagerService,
],
```
And don't forget to declare it as `Injectable`:
```
@Injectable()
export class PagerService {
// ...
}
``` | Page Service or Job Service both should have Injectable attribute applied or check if you are injecting something in these services also then same applies to that also. |
5,391,268 | I am learning about handling UTF8 character sets and the recommendation is to explicitly set the encoding type in the output headers within your PHP script like so:
```
header('Content-Type: text/html; charset=utf-8');
```
My question is about where I should place this header. I have a config file that is included into every script and is run first. Should I place it at the top of that file so that this header is included first in every php file?
Will that affect my ability to set other headers, including a header location redirect down the line? Or should I place this just before any html output, such as the rendering of my template file? Ie- can this header be in place before ALL other php processing, and what are the consequences of doing that? Does it affect anything server side, or just the encoding of the output?
Thanks.! | 2011/03/22 | [
"https://Stackoverflow.com/questions/5391268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/97816/"
] | I'm only recommending this as an alternative. But the setting can be fixated in the php.ini using:
```
default_mimetype = "text/html; charset=UTF-8"
```
It's less common on shared hosters, where some of the users might depend on L1. But if you use your own server and want to ensure that it's correctly set regardless of code and whichever PHP script is invoked, then [this is your option](http://php.net/default_mimetype). | As long as it is inside the -tags and BEFORE you create any output (echo, print, print\_r and so on - or any HTML BEFORE the -tags).
OKAY METHOD:
```
<?php
$var = "hello world";
$var2 = "Goodbye world!";
header();
echo $var2;
?>
```
OKAY METHOD:
```
<?php
header();
$var = "hello world";
$var2 = "Goodbye world!";
echo $var2;
?>
```
NOT OKAY METHOD:
```
<?php
$var = "hello world";
$var2 = "Goodbye world!";
echo $var2;
header();
?>
```
Hope this helps! |
4,751,885 | Since a `struct` in C# consists of the bits of its members, you cannot have a value type `T` which includes any `T` fields:
```
// Struct member 'T.m_field' of type 'T' causes a cycle in the struct layout
struct T { T m_field; }
```
My understanding is that an instance of the above type could never be instantiated\*—any attempt to do so would result in an infinite loop of instantiation/allocation (which I guess would cause a stack overflow?\*\*)—or, alternately, another way of looking at it might be that the definition itself just doesn't make sense; perhaps it's a self-defeating entity, sort of like "This statement is false."
Curiously, though, if you run this code:
```
BindingFlags privateInstance = BindingFlags.NonPublic | BindingFlags.Instance;
// Give me all the private instance fields of the int type.
FieldInfo[] int32Fields = typeof(int).GetFields(privateInstance);
foreach (FieldInfo field in int32Fields)
{
Console.WriteLine("{0} ({1})", field.Name, field.FieldType);
}
```
...you will get the following output:
```
m_value (System.Int32)
```
It seems we are being "lied" to here\*\*\*. Obviously I understand that the primitive types like `int`, `double`, etc. must be defined in some special way deep down in the bowels of C# (you cannot define every possible unit within a system in terms of that system... can you?—different topic, regardless!); I'm just interested to know **what's going on here**.
How does the `System.Int32` type (for example) actually account for the storage of a 32-bit integer? More generally, how can a value type (as a definition of a kind of value) include a field whose type is *itself*? It just seems like [turtles all the way down](http://en.wikipedia.org/wiki/Turtles_all_the_way_down).
Black magic?
---
\*On a separate note: is this the right word for a value type ("instantiated")? I feel like it carries "reference-like" connotations; but maybe that's just me. Also, I feel like I *may* have asked this question before—if so, I forget what people answered.
\*\*Both [Martin v. Löwis](https://stackoverflow.com/questions/4751885/how-are-the-primitive-types-defined-non-recursively/4752034#4752034) and [Eric Lippert](https://stackoverflow.com/questions/4751885/how-are-the-primitive-types-defined-non-recursively/4753392#4753392) have pointed out that this is neither entirely accurate nor an appropriate perspective on the issue. See their answers for more info.
\*\*\*OK, I realize nobody's actually lying. I didn't mean to imply that I thought this was *false*; my suspicion had been that it was somehow an oversimplification. After coming to understand (I *think*) [thecoop's answer](https://stackoverflow.com/questions/4751885/how-are-the-primitive-types-defined-non-recursively/4751944#4751944), it makes a lot more sense to me. | 2011/01/20 | [
"https://Stackoverflow.com/questions/4751885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105570/"
] | As far as I know, within a field signature that is stored in an assembly, there are certain hardcoded byte patterns representing the 'core' primitive types - the signed/unsigned integers, and floats (as well as strings, which are reference types and a special case). The CLR knows natively how to deal with those. Check out Partition II, section 23.2.12 of the CLR spec for the bit patterns of the signatures.
Within each primitive struct (`[mscorlib]System.Int32`, `[mscorlib]System.Single` etc) in the BCL is a single field of that native type, and because a struct is exactly the same size as its constituent fields, each primitive struct is the same bit pattern as its native type in memory, and so can be interpreted as either, by the CLR, C# compiler, or libraries using those types.
From C#, `int`, `double` etc are synonyms of the mscorlib structs, which each have their primitive field of a type that is natively recognised by the CLR.
(There's an extra complication here, in that the CLR spec specifies that any types that have a 'short form' (the native CLR types) always have to be encoded as that short form (`int32`), rather than `valuetype [mscorlib]System.Int32`. So the C# compiler knows about the primitive types as well, but I'm not sure of the exact semantics and special-casing that goes on in the C# compiler and CLR for, say, method calls on primitive structs)
So, due to Godel's Incompleteness Theorem, there has to be something 'outside' the system by which it can be defined. This is the Magic that lets the CLR interpret 4 bytes as a native `int32` or an instance of `[mscorlib]System.Int32`, which is aliased from C#. | >
> My understanding is that an instance of the above type could never be instantiated any attempt to do so would result in an infinite loop of instantiation/allocation (which I guess would cause a stack overflow?)—or, alternately, another way of looking at it might be that the definition itself just doesn't make sense;
>
>
>
That's not the best way of characterizing the situation. A better way to look at it is that **the size of every struct must be well-defined**. An attempt to determine the size of T goes into an infinite loop, and therefore the size of T is not well-defined. Therefore, it's not a legal struct because every struct must have a well-defined size.
>
> It seems we are being lied to here
>
>
>
There's no lie. An int is a struct that contains a field of type int. An int is of known size; it is **by definition** four bytes. Therefore it is a legal struct, because the size of all its fields is known.
>
> How does the System.Int32 type (for example) actually store a 32-bit integer value
>
>
>
The *type* doesn't *do* anything. The type is just an abstract concept. The thing that does the storage is the *CLR*, and it does so by allocating four bytes of space on the heap, on the stack, or in registers. How else do you suppose a four-byte integer would be stored, if not in four bytes of memory?
>
> how does the System.Type object referenced with typeof(int) present itself as though this value is itself an everyday instance field typed as System.Int32?
>
>
>
That's just an object, written in code like any other object. There's nothing special about it. You call methods on it, it returns more objects, just like every other object in the world. Why do you think there's something special about it? |
117,611 | If I am predicting probability of a business to reach (x) milestone (classification 1), but the only data I have is live production data, how much of the production data should I use to train the model? My assumption is that if I use all the data, the probability of any business that hasn't reached the milestone already (classification of 0) will most likely stay 0... as I just trained the model that it should be 0.
As a caveat, I know that it is commonplace to use something like an 80/20 or 70/30 split for training/test sets -- most of my fruitless searches have brought up that answer, but my question is if I should take 10% of my production data to then split 80/20 or 70/30 between training and test, as to not overfit the model.
My dataset is 30k records, so my first inclination was to use 3-5k records out of that for training/test. | 2023/01/08 | [
"https://datascience.stackexchange.com/questions/117611",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/144636/"
] | You can use 100% of the data. The more data you feed to the model, the more accurate the prediction is going to be. If you have only two features - time and live production data, 30k records is not going to be a problem. Select a timepoint - somewhere between 70%-95% of the time passed, and use the data before the time point as training data and the data after the time point as test data. You want to use the newest data for testing. You can try using different time points to see how that will affect the model. | Note that your dataset might be considered time-series. In time-series it is common to evaluate a model via back-testing rather than a single train/test split. Back-testing uses as training data all data before time T, and as test data all data after time T, and then we do this for many different values of T and average the test performances for each T. |
61,648,096 | So I have a **Mongoose** Model called `Profile`:
```js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ProfileSchema = new Schema({
user: {
type: mongoose.Schema.ObjectId,
ref: "user",
},
company: {
type: String,
},
website: {
type: String,
},
location: {
type: String,
},
status: {
type: String,
required: true,
},
skills: {
type: [String],
required: true,
},
bio: {
type: String,
},
githubusername: {
type: String,
},
experience: [{
title: {
type: String,
required: true,
},
company: {
type: String,
required: true,
},
location: {
type: String,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
}, ],
education: [{
school: {
type: String,
required: true,
},
degree: {
type: String,
required: true,
},
fieldofstudy: {
type: String,
required: true,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
}, ],
social: {
youtube: {
type: String,
},
twitter: {
type: String,
},
facebook: {
type: String,
},
linkedin: {
type: String,
},
instagram: {
type: String,
},
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = Profile = mongoose.model("profile", ProfileSchema);
```
As you can see I have a bunch of nested subdocuments and I want to be able to update them. In particular I want to be able to able to update the `experience` with a `PUT` endpoint.
Here is the endpoint to add an experience:
```js
router.put(
"/experience", [
auth, [
check("title", "Title is required").not().isEmpty(),
check("company", "Company is required").not().isEmpty(),
check("from", "From date is required and needs to be from the past")
.not()
.isEmpty()
.custom((value, {
req
}) => (req.body.to ? value < req.body.to : true)),
],
],
async(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
const {
title,
company,
location,
from,
to,
current,
description,
} = req.body;
const newExp = {
title,
company,
location,
from,
to,
current,
description,
};
try {
const profile = await Profile.findOne({
user: req.user.id
});
profile.experience.unshift(newExp);
await profile.save();
res.json(profile);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
}
);
```
And this works I am able to add an `experience` to that array.
But When I try and Update it does not work here is what I have tried:
```js
router.put("/experience/:exp_id", auth, async(req, res) => {
try {
const profile = await Profile.experience.findByIdAndUpdate(
req.params._id, {
$set: req.body,
}, {
new: true
}
);
res.json(profile);
} catch (error) {
console.error(error);
return res.status(500).json({
msg: "Server error"
});
}
});
```
I get this error `TypeError: Cannot read property 'findByIdAndUpdate' of undefined` what am I doing wrong?
Here is a some `Profile` data I have when I create a `Profile`
```js
{
"social": {
"youtube": "https://youtube.com/user/mojara2009",
"twitter": null,
"instagram": null,
"linkedin": "https://linkedin.com/in/amen-ra",
"facebook": null
},
"skills": [
" HTML",
" CSS",
" JAVASCRIPT",
" REACT",
" REDUX",
" JEST"
],
"_id": "5eb1a19b83001bdb87e26492",
"user": {
"_id": "5eb10fecc3de3526caba5e50",
"name": "Amen Ra",
"avatar": "//www.gravatar.com/avatar/ee452fcb90a3913ca75ed4b4f06c4de6?s=200&r=pg&d=mm"
},
"__v": 19,
"bio": "I am a Senior Full Stack Developer for Web App Company",
"company": "Web App Company",
"githubusername": "mojaray2k",
"location": "Aventura, Fl",
"status": "Developer",
"website": "https://imaginationeverywhere.info",
"date": "2020-05-05T22:33:41.596Z",
"education": [{
"current": false,
"_id": "5eb2eccd659559371b2162f4",
"school": "Bethune-Cookman University",
"degree": "Bachelor of Arts",
"fieldofstudy": "Mass Communication",
"from": "1994-08-04T00:00:00.000Z",
"to": "1999-04-26T00:00:00.000Z",
"description": "Attended Bethune Cookman College in Daytona Beach, Fl"
},
{
"current": false,
"_id": "5eb2ecc2659559371b2162f3",
"school": "Manual High School",
"degree": "Diploma",
"fieldofstudy": "NA",
"from": "1990-09-01T00:00:00.000Z",
"to": "1994-06-01T00:00:00.000Z",
"description": "Attended High School my sophomore through senior year"
},
{
"current": false,
"_id": "5eb2ecb5659559371b2162f2",
"school": "John F. Kennedy High School",
"degree": "NA",
"fieldofstudy": "NA",
"from": "1989-09-01T00:00:00.000Z",
"to": "1990-06-01T00:00:00.000Z",
"description": "Attended High School my sophomore through senior year"
},
{
"current": false,
"_id": "5eb2ea28659559371b2162eb",
"school": "Kunsmiller",
"degree": "NA",
"fieldofstudy": "Middle School",
"from": "1988-02-01T05:00:00.000Z",
"to": "1989-06-01T04:00:00.000Z",
"description": "Attended Middle School There"
}
],
"experience": [{
"current": false,
"_id": "5eb356f74cc1ad499167567d",
"title": "Senior Full Stack Engineer",
"company": "Concept Solutions",
"location": "Aventura, Fl",
"from": "2016-01-03T00:00:00.000Z",
"to": "2018-02-28T00:00:00.000Z",
"description": "Worked as Full Stack Developer"
},
{
"current": false,
"_id": "5eb2de8fccd73b25fd1b2b39",
"title": "Senior Full Stack Engineer",
"company": "Jehovah Jireh, Inc",
"location": "Aventura, Fl",
"from": "2018-07-01T04:00:00.000Z",
"to": "2019-07-01T04:00:00.000Z",
"description": "Worked as Full Stack Developer"
},
{
"current": true,
"_id": "5eb203af1e004371b3284883",
"title": "Senior Full Stack Engineer",
"company": "Web App Company",
"location": "Aventura, Fl",
"from": "2019-07-01T04:00:00.000Z",
"description": "Worked as Full Stack Developer"
}
]
}
``` | 2020/05/07 | [
"https://Stackoverflow.com/questions/61648096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/333757/"
] | It is not possible to access a mongoose model schema as a Profile object. Instead if you want to update a specific part of the model, in this case `experience`, you can do as follows:
```js
try {
const await profile = Profile.findOneAndUpdate(
{ experience: { $elemMatch: { _id: req.params.exp_id } } },
{ $set: { 'experience.$': req.body } },
{ new: true }
);
res.json(profile);
} catch (error) {
console.error(error);
return res.status(500).json({ msg: 'Server error' });
}
```
Also I believe it be `req.params.exp_id` instead of `req.params._id`. | Thats a normal response for mongoose, Because Profile is a **Collection Model Schema**, not an **Profile object**. Also if you want to update an specific element on the array, You need to add query to help mongo to find which data will only update on the array.
Here's the alternate query for updating collection data on mongo.
```js
router.put("/:profile_id/experience/:exp_id", auth, async(req, res) => {
const {profile_id = '', exp_id = ''} = req.params
try {
const profile = await Profile.findOne(
{
_id: mongoose.mongo.ObjectId(profile_id)
}
);
if (!profile) {
throw new Error('No profile found.')
}
const index = profile.experience.findIndex((exp) => exp._id === mongoose.mongo.ObjectId(exp_id))
if (index === -1) {
throw new Error('No experience data found.')
}
const {_id, ...experience} = req.body
profile.experience[index] = experience
profile.save
res.json(profile);
} catch (error) {
console.error(error);
return res.status(500).json({
msg: "Server error"
});
}
});
``` |
1,295,973 | How do you calculate the following limits?
>
> $$\lim\_{n \to \infty} \left(1 + \frac{1}{n!}\right)^n$$ $$\lim\_{n \to \infty} \left(1
> + \frac{1}{n!}\right)^{n^n}.$$
>
>
>
I really don't have any clue about how to proceed: I know the famous limit that defines $e$ ($\lim\_{n \to \infty} \left(1 + \frac{1}{n}\right)^n=e$), but the factorials (and the exponent of the second one) here throw me off. Any ideas? | 2015/05/23 | [
"https://math.stackexchange.com/questions/1295973",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/174765/"
] | HINT:
$$
\lim\_{n \to \infty} \left(1 + \frac{1}{n!}\right)^n=\lim\_{n \to \infty} \left(\left(1 + \frac{1}{n!}\right)^{n!}\right)^{n/n!}
$$
and the inner limit is $e$, hence the final one is 1. The second case is similar. | First limit is easy. Let $$f(n) = \left(1 + \frac{1}{n!}\right)^{n}$$ We will use the fact that the sequence $a\_{n} = (1 + (1/n))^{n}$ is strictly increasing for $n \geq 3$ and tends to a positive limit (when $n \to \infty$) denoted by $e$. Also $2 < e < 3$. These facts can be proven (and given in many textbooks) without any standard theory of logarithms and exponentials. Another fact which we need to know is that if $A > 0$ then $A^{1/n}$ tends to $1$ as $n \to \infty$.
We thus have $a\_{n} = (1 + (1/n))^{n} < e$ for all $n$. Replacing $n$ by $n!$ we get that $(1 + (1/n!))^{n!} < e$. Hence we can see that $$1 < f(n) = \left(1 + \frac{1}{n!}\right)^{n} = \left(\left(1 + \frac{1}{n!}\right)^{n!}\right)^{1/(n - 1)!} < e^{1/(n - 1)!}$$ Again it is easy to prove that $1/(n - 1)! < 1/n$ for all $n > 3$ and hence we have $$1 < f(n) < e^{1/n}$$ for $n > 3$. Letting $n \to \infty$ and using Squeeze theorem we get $f(n) \to 1$ as $n \to \infty$.
---
For the function $$g(n) = \left(1 + \frac{1}{n!}\right)^{n^{n}}$$ we need to use the fact that $$a\_{n} = \left(1 + \frac{1}{n}\right)^{n} \geq 2$$ for $n$. Replacing $n$ by $n!$ we get $$\left(1 + \frac{1}{n!}\right)^{n!} \geq 2$$ for all $n$. And then we can see that $$g(n) = \left(1 + \frac{1}{n!}\right)^{n^{n}} = \left(\left(1 + \frac{1}{n!}\right)^{n!}\right)^{n^{n}/n!}\geq 2^{n^{n}/n!}\tag{1}$$ We next need to analyze the sequence $n^{n} / n!$. It turns out it is simpler to handle its reciprocal $b\_{n} = n!/n^{n}$. Clearly $$\frac{b\_{n + 1}}{b\_{n}} = \frac{(n + 1)!}{(n + 1)^{n + 1}}\cdot\frac{n^{n}}{n!} = \dfrac{1}{\left(1 + \dfrac{1}{n}\right)^{n}} \to \frac{1}{e} < 1$$ and hence the series $\sum b\_{n}$ is convergent (Ratio test) and hence $b\_{n} \to 0$.
It follows that $1/b\_{n} \to \infty$ as $n \to \infty$. It also follows that $2^{1/b\_{n}} \to \infty$ as $n \to \infty$. From $(1)$ we see that $g(n) \geq 2^{1/b\_{n}}$ and hence $g(n) \to \infty$ as $n \to \infty$.
---
**Note**: From the above it is seen that in most cases basic limit theorems and certain standard limits are sufficient to solve a problem without invoking advanced results. In this case for example we dealt with limits involving variable exponents like $n!$ and $n^{n}$ and yet their solution was possible without any theory of exponentials and logarithms. Unless we have to deal with irrational exponents (or say complex/imaginary) it does not make sense to invoke the general theory of logarithm and exponential. |
19,219,236 | I am creating a c# application which requires to use a database and i am also planning to create an installer for my application. I just want to ask which database would be best to use in my application and how do i install it on a user machine while installing my application through installer file.
I have thought of using MYSQL database but for that u need to have MYSQL installed.
Update
------
i want each user to have there own instance of database when they install the application | 2013/10/07 | [
"https://Stackoverflow.com/questions/19219236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2283679/"
] | You do not have to ship a full database server with your application; only the redistributable runtime which your application would use to connect to the actual database server remotely. In the case of MySQL, you only need the assemblies.
Applications I wrote relied heavily on SQL Server. In order to simplify evaluations and the initial deployment, the installer would install SQL Server Express (installed as an application specific instance). This is an approach I'd recommend if your application is intended to a centralised database.
What is key to understand, especially with commercial application, is that the database engine you install may have to co-exist with existing versions of the respective database engine. That is why application specific instances was created for SQL Server Express.
The alternatives, which are embedded, are:
1. [SQLite.net](http://www.nuget.org/packages/sqlite-net)
2. [SQL Server Compact Edition](http://www.microsoft.com/en-us/sqlserver/editions/2012-editions/compact.aspx). The [deployment process](http://msdn.microsoft.com/en-us/library/aa983326%28VS.80%29.aspx) is well defined.
3. [VistaDB](http://www.vistadb.net)
Embedded databases have some challenges when deployed as part of a server application. For many years, Microsoft refused to allow [SQL Server Compact Edition](http://www.microsoft.com/en-us/sqlserver/editions/2012-editions/compact.aspx) to be used for ASP.NET applications. If the database is per user, per device, an embedded database may be perfect.
Also be aware that MySQL has [license restrictions](http://www.mysql.com/about/legal/licensing/oem/) when shipped as part of commercial software (aka you're acting as an OEM, ISV or VAR). | Have a look at [SQL Server Express Edition](http://www.microsoft.com/en-us/sqlserver/editions/2012-editions/compact.aspx).
It's just a file which you can copy and a class library which allows to access it. And after you finished your installation you can just delete the files (or to keep them if you need them to uninstall the product). |
36,227,993 | I have a list of lists which are of variable length. The first value of each nested list is the key, and the rest of the values in the list will be the array entry. It looks something like this:
```
[[1]]
[1] "Bob" "Apple"
[[2]]
[1] "Cindy" "Apple" "Banana" "Orange" "Pear" "Raspberry"
[[3]]
[1] "Mary" "Orange" "Strawberry"
[[4]]
[1] "George" "Banana"
```
I've extracted the keys and entries as follows:
```
keys <- lapply(x, '[', 1)
entries <- lapply(x, '[', -1)
```
but now that I have these, I don't know how I can associate a key:value pair in R without creating a matrix first, but this is silly since my data don't fit in a rectangle anyway (every example I've seen uses the column names from a matrix as the key values).
This is my crappy method using a matrix, assigning rownames, and then using jsonLite to export to JSON.
```
#Create a matrix from entries, without recycling
#I found this function on StackOverflow which seems to work...
cbind.fill <- function(...){
nm <- list(...)
nm <- lapply(nm, as.matrix)
n <- max(sapply(nm, nrow))
do.call(cbind, lapply(nm, function (x)
rbind(x, matrix(, n-nrow(x), ncol(x)))))
}
#Call said function
matrix <- cbind.fill(entries)
#Transpose the thing
matrix <- t(matrix)
#Set column names
colnames(matrix) <- keys
#Export to json
json<-toJSON(matrix)
```
The result is good, but the implementation sucks. Result:
```
[{"Bob":["Apple"],"Cindy":["Apple","Banana","Orange","Pear","Raspberry"],"Mary":["Orange","Strawberry"],"George":["Banana"]}]
```
Please let me know of better ways that might exist to accomplish this. | 2016/03/25 | [
"https://Stackoverflow.com/questions/36227993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5597209/"
] | How about:
```
names(entries) <- unlist(keys)
toJSON(entries)
``` | I think this has already been sufficiently answered but here is a method using `purrr` and `jsonlite`.
```
library(purrr)
library(jsonlite)
sample_data <- list(
list("Bob","Apple"),
list("Cindy","Apple","Banana","Orange","Pear","Raspberry"),
list("Mary","Orange","Strawberry"),
list("George","Banana")
)
sample_data %>%
map(~set_names(list(.x[-1]),.x[1])) %>%
toJSON(auto_unbox=TRUE, pretty=TRUE)
``` |
16,112,513 | I am trying to exclude pages from wp\_nav\_menu
Here is the function to exclude pages from menu
Works well when
```
<?php $page = get_page_by_title('my title' );
wp_nav_menu( array( 'theme_location' => 'menu-2', 'exclude' => $page->ID ) ); ?>
```
Works properly
BUt when using
```
<?php $page = get_page_by_title('my title' );
$pag1 = get_page_by_title('my title 1' );
$pag2 = get_page_by_title('my title2' );
wp_nav_menu( array( 'theme_location' => 'menu-2', 'exclude' => $page->ID,$pag1->ID,$pag2->ID ) ); ?>
```
Doesn't work properly. | 2013/04/19 | [
"https://Stackoverflow.com/questions/16112513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820088/"
] | Here is the correct solution
I hope it helps some other people
```
<?php
$page = get_page_by_title('my title' );
$pag1 = get_page_by_title('my title 1' );
$pag2 = get_page_by_title('my title2' );
$ids = "{$page->ID},{$pag1->ID},{$pag2->ID}";
wp_nav_menu( array( 'theme_location' => 'menu-2', 'exclude' => $ids ) );
?>
``` | Managed it using the exclude method, but exclude by page id:
```
wp_nav_menu(
array(
'theme_location' => 'menu-2',
'exclude' => '599, 601'
)
);
```
(599 & 601 are page id's)
which is written here:
<http://bacsoftwareconsulting.com/blog/index.php/wordpress-cat/wordpress-tip-how-to-exclude-pages-from-wp_nav_menu-function/>
and finding the page id manually is written here:
<http://bacsoftwareconsulting.com/blog/index.php/wordpress-cat/how-to-find-tag-page-post-link-category-id-in-wordpress/> |
2,972,770 | Another way to look at it is $x^x = e$.
It seems possible, but I really don't know. It seems very helpful to know the exact value where a function's y value is the same as its slope. | 2018/10/26 | [
"https://math.stackexchange.com/questions/2972770",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/608979/"
] | Per the comment of clathratus, the Lambert W function is relevant here; since $x\ln x=1$, take $x=1/W(1)$ for some branch $W$ of the function. However, if you actually want a few decimal places of $x$ in a hurry, numerical methods such as the Newton-Raphson method are prudent. Define $f(x):=x\ln x-1$ so $f'=\ln x+1$ and $g(x):=x-\frac{f(x)}{f'(x)}=\frac{x+1}{\ln x+1}$; then we can use the recursion $x\_{n+1}=g(x\_n)$ (which is probably what ab123 did), provided we choose a sensible seed. The choice $x\_0$ should do. | This can be solved either by using **Lambert W function** or **Newton Raphson method**.
The above equation can be written as -> 1 = x\*ln(x)
**1. (Using Lambert W function):**
W(x\*ln(x)) = W(1) ---- [1]
as per Lambert W function: W(x\*ln(y)) = ln(y)
hence,
ln(x) = W(1) *{substituting in [1]}*
so,
x = e^(W(1))
but **W(1) is approximately equal 0.56714329**
refer: <https://en.wikipedia.org/wiki/Lambert_W_function>;
substituting the value (W(1)) above:
**x = 1.76322** (approximate value)
**2. (Newton Raphson Method):**
consider f(x) = x\*ln(x) - 1 & solve further using Newton Raphson Method formula for different values of x, starting with 0.
<https://en.wikipedia.org/wiki/Newton%27s_method>
Hope this helps! |
6,847,262 | Note: This question has been updated with new info. Please see the bottom half of this text. (The original quesiton is left here for context.)
---
Is there any way I can define my attribute so that if it's defined on a method that is overidden, the attribute is still applied?
The reason I ask is that I have an attribute which injects some behavior into the method, but the behavior is not applied when the method is called as in any of the cases in the child class, and I would like it to be.
```
class BaseClass
{
[MyThing]
virtual void SomeMethod()
{
// Do something fancy because of the attribute.
}
}
class ChildClass
{
override void SomeMethod()
{
// Fancy stuff does happen here too...
base.SomeMethod();
}
void AnotherMethod()
{
// ...but not here. And I'd like it to =(
base.SomeMethod();
}
}
```
The attribute is defined like so:
```
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MyThingAttribute : Attribute
```
The current code for finding methods with the attribute is the following:
```
var implementation = typeof(TheTypeWereCurrentlyInvestigating);
var allMethods = (from m in implementation.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy)
let attribs = (TransactionAttribute[]) m.GetCustomAttributes(typeof (TransactionAttribute), true)
where attribs.Length > 0
select Tuple.Create(m, attribs.Length > 0 ? attribs[0] : null)).ToList();
```
I didn't write that part, and I can't say I am 100% of what every part of it does... But we can assume, for now, that I am in control of all the involved code. (It's an opensource project, so I can at least create my own version, and submit a patch to the project owners...)
I have a couple of other cases too - basically I want to have this behavior injected whenever I call the method on the base class, no matter which way I got there - but if I solve this one I might get ideas on how to get the others working. If not, I'll get back with them.
---
UPDATE:
=======
OK, so I sat down with the Castle.Transactions project and created some very simple tests to see what works and what doesn't. It turns out that my original assumptions on what works and what doesn't were somewhat off.
**What I did:**
I created a test class which has one method, decorated with the attribute, and which calls an `Assert` method that verifies that the behavior was injected correctly (i.e. that there is a transaction). I then created a couple of classes which inherit this test class, to see in which cases everything works as I expect it to.
**What I found:**
By calling the test method directly on the test class and from various methods on the child classes, I discovered the following about what works and what doesn't:
```
Method called Access modifiers Does it work?
************* **************** *************
SomeMethod() on base class* N/A Yes
OtherMethod() on child neither NO <-- headache!
OtherMethod() on child hiding (new) No
SomeMethod() on child hiding (new) No
OtherMethod() on child overrides No
OtherMethod() on child* overrides Yes
SomeMethod() on child overrides Yes
```
In all cases except the one marked with `*`, `base.SomeMethod()` was called from the method applied in the test. In the first case the same method was called but directly from the test, since no child class is involved. In the second case (of the ones marked `*`), the overriding method was called, i.e. `this.SomeMethod()`, so that's really equivalent of the last case. I'm not using any redundant qualifiers, so in that method the call is simply `SomeMethod()`.
**What I want:**
It's the case marked "headache" that I really want to solve; how to inject behavior into the base class even though I'm calling it from my child class.
The reason I need that specific case to work is that I'm using this pattern in a repository, where the base class defines a `Save(T entity)` method decorated with the `Transaction` attribute. Currently, I have to override this method just to get the transaction orchestration, which makes it impossible to change the return type; on the base class it's `void`, but on my implementation I'd like to make it `Error<T>` instead. This is impossible when overriding, and since I can't solve the problem by naming the method differently, I'm at a loss. | 2011/07/27 | [
"https://Stackoverflow.com/questions/6847262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38055/"
] | Setting the `border: 0 none;` CSS property should fix that, if you wanted it to occur on all images wrapped in links, you could use it as such:
```
a img
{
border: 0 none;
}
```
**For use in an e-mail**, you may have to include a style block in the actual e-mail:
```
<style type='text/css'>
a img
{
border: 0 none;
}
</style>
```
[jsFiddle Example](http://jsfiddle.net/Sjydw/) | This question is a few months old, but I ended up here with the same question, so hopefully this may save someone the time I wasted.
The td has a background color of that neon blue, and by default has a bit of padding.
I just styled the td with...
```
style="background:none;"
```
I knew all about the border style defaults, and hadn't had the td background default in the mail clients I had previously tested, but it kept popping up in gmail. |
91,076 | 2 self driving vehicles are being tested. Both vehicles are exactly the same. Both are fitted with a camera on the
Dashboard, although in car A it is a slightly older model and is 1 kg heavier than in vehicle B. The M25 is 117 miles long. Vehicle A started 2 mins before vehicle B and they both crossed the line within 60 seconds of each other. Why is this? | 2019/11/11 | [
"https://puzzling.stackexchange.com/questions/91076",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/63734/"
] | This makes use of Stiv's observation above, but develops it differently.
>
> The extra weight of car A does make a small difference to its speed, but not a considerable one. This means that car B does over time catch up with car A. However, in order to pass car A, it has to pull out into an overtaking lane and is now actually driving a slightly longer route due to the M25 being circular and car B now travelling in a circle of a slightly larger diameter. This cancels out the slight advantage of weight and Car B is unable to overtake.
>
>
>
However:
>
> This does assume though that the M25 is perfectly circular, which it is not.
>
>
> | >
> They never mentioned that velocity(magnitude) of both car is same. Their velocity(in magnitude) would be different in order to follow that situation.
>
>
> |
32,017,354 | I know there are strong opinions about mixing plot types in the same figures, especially if there are two y axes involved. However, this is a situation in which I have no alternative - I need to create a figure using R that follows a standard format - a histogram on one axis (case counts), and a superimposed line graph showing an unrelated rate on an independent axis.
The best I have been able to do is stacked ggplot2 facets, but this is not as easy to interpret for the purposes of this analysis as the combined figure. The people reviewing this output will need it in the format they are used to.
I'm attaching an example below.

Any ideas?
For etiquette purposes, sample data below:
```
y1<-sample(0:1000,20,rep=TRUE)
y2<-sample(0:100,20,rep=TRUE)
x<-1981:2000
``` | 2015/08/14 | [
"https://Stackoverflow.com/questions/32017354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2186883/"
] | `?n2mfrow` finds a default layout for you; in fact, it's already used by `grid.arrange` if `nrow` and `ncol` are missing
```
grid.arrange(grobs = replicate(7, rectGrob(), simplify=FALSE))
```
[](https://i.stack.imgur.com/9Cfqj.png) | In practice there are a limited number of plots that can reasonably be displayed and few arrangements that are aesthetically pleasing, so you could just tabulate.
However, what we can do is specify a tolerance for the ratio of the larger dimension to the smaller. Then we find the closest two numbers that factor our target. If these are within tolerance, we are done. Otherwise, we add waste to our target. This terminates at the sooner of finding a suitable pair or at the next largest square. (Tolerance should be > 1).
Smallest of the closest two numbers that factor a given `n`
```
fact<-function(n) {
k<-floor(sqrt(n));
for(i in k:1) {if (n%%i == 0) return(i)}
}
```
Search for a near square within tolerance
```
nearsq<-function(n,tol=5/3+0.001) {
m<-ceiling(sqrt(n))^2;
for(i in n:m) {
a<-fact(i);
b<-i/a;
if(b/a < tol) return(c(a,b))
}
}
```
Examples
```
#probably too many plots
nearsq(83)
#> [1] 8 11
#a more reasonable range of plots, tabulated
cbind(12:36,t(Vectorize(nearsq)(12:36)))
```
```
[,1] [,2] [,3]
[1,] 12 3 4
[2,] 13 3 5
[3,] 14 3 5
[4,] 15 3 5
[5,] 16 4 4
[6,] 17 4 5
[7,] 18 4 5
[8,] 19 4 5
[9,] 20 4 5
[10,] 21 4 6
[11,] 22 4 6
[12,] 23 4 6
[13,] 24 4 6
[14,] 25 5 5
[15,] 26 5 6
[16,] 27 5 6
[17,] 28 5 6
[18,] 29 5 6
[19,] 30 5 6
[20,] 31 5 7
[21,] 32 5 7
[22,] 33 5 7
[23,] 34 5 7
[24,] 35 5 7
[25,] 36 6 6
``` |
14,116 | I have encrypted Android `so` library that decrypts itself on load. I want to get its unencrypted code. For me it looks good idea to dump that library from memory when application started.
I used `/proc/self/maps` to get loaded process memory map. I found 3 segments that correspond to the library in memory maps and used `/proc/self/mem` to dump these 3 segments to binary files. So, I got 3 binary files: code, writable data and read only data.
Does anyone know how to parse these 3 binary files and assemble them back to `so` file that Android can run & debug? | 2016/12/05 | [
"https://reverseengineering.stackexchange.com/questions/14116",
"https://reverseengineering.stackexchange.com",
"https://reverseengineering.stackexchange.com/users/18321/"
] | Frida is the way to go, you can simply do:
```
memorydump: function (address, size) {
Memory.protect(ptr(address), size, "rwx");
var a = Memory.readByteArray(ptr(address),size-1000);
return a;
}
moduleaddress: function (lib){
try{
var ret = [];
var module = Process.findModuleByName(lib);
var address = Module.findBaseAddress(lib);
var sz = module.size;
ret.push({
"addr": address,
"size": sz
});
return ret;
}
catch(err){
console.log('[!] Error: '+err);
}
}
```
If you are not comfortable with Frida you can use a wrapper:
<https://github.com/Ch0pin/medusa>
dumping the memory will be simply as: medusa>memops package\_name libname.so
and then just type dump :) | Maybe this helps: <https://www.andnixsh.com/2015/11/tutorial-how-to-decrypt-encrypted-dll.html>
You can create dump from memory using `gcore <path>` command and recover any plain files (.dex, .dll, .mp3, etc) using custom GDB for Android. I'm not sure if you can recover decrypted .so file.
Custom GDB only works on ARM-based devices running Android 4.4.4 and below. If you want to get it work for 5.x.x, you need to bypassing PIE security check but there is a risk of bricking your device. <https://www.alphagamers.net/threads/guide-bypassing-pie-security-check-android-5-0-up.242363/> |
49,808,616 | i'm trying to filter array that the results of value {purchase} id contain in array of {products.transactions.purchase} id.
I want to filter by transaction which have same purchase id value.
the data:
```
var data = [
{
"purchase": "5ace99b014a759325776aabb",
"products":
[{
"transactions":
[{
"purchase": "5ace99b014a759325776aabb",
"price": "25"
},
{
"purchase": "5ace99d714a759325776aac4",
"price": "23"
}],
"_id": "5ace995914a759325776aab0",
"product_name": "Milk",
},
{
"transactions":
[{
"purchase": "5ace99b014a759325776aabb",
"price": "20"
},
{
"purchase": "5ace99d714a759325776aac4",
"price": "15"
}],
"_id": "5ace995c14a759325776aab1",
"product_name": "Ketchup",
}]
},
{
"purchase": "5ace99d714a759325776aac4",
"products":
[{
"transactions":
[{
"purchase": "5ace99b014a759325776aabb",
"price": "22"
},
{
"purchase": "5ace99d714a759325776aac4",
"price": "21"
}],
"_id": "5ace995914a759325776aab0",
"nama_produk": "Milk",
},
{
"transactions":
[{
"purchase": "5ace99b014a759325776aabb",
"price": "14"
},
{
"purchase": "5ace99d714a759325776aac4",
"price": "13"
}],
"_id": "5ace995c14a759325776aab1",
"product_name": "Ketchup",
}]
}]
```
i have been tried but only show child array
```
function filter() {
let result = []
let filter = data.filter(a => {
return a.products.filter(b => {
return b.transactions.filter(c => {
if (a.purchase == c.purchase) result.push(c)
})
})
})
return result
}
console.log(filter())
// output
> Array [Object
{ purchase: "5ace99b014a759325776aabb", price: "25" }, Object
{ purchase: "5ace99b014a759325776aabb", price: "20" }, Object
{ purchase: "5ace99d714a759325776aac4", price: "21" }, Object
{ purchase: "5ace99d714a759325776aac4", price: "13" }]
```
how to the output of filtered array like below output:
```
[{
"purchase": "5ace99b014a759325776aabb",
"products":
[{
"transactions":
[{
"purchase": "5ace99b014a759325776aabb",
"price": "25"
}],
"_id": "5ace995914a759325776aab0",
"product_name": "Milk",
},
{
"transactions":
[{
"purchase": "5ace99b014a759325776aabb",
"price": "20"
}],
"_id": "5ace995c14a759325776aab1",
"product_name": "Ketchup",
}]
},
{
"purchase": "5ace99d714a759325776aac4",
"products":
[{
"transactions":
[{
"purchase": "5ace99d714a759325776aac4",
"price": "21"
}],
"_id": "5ace995914a759325776aab0",
"nama_produk": "Milk",
},
{
"transactions":
[{
"purchase": "5ace99d714a759325776aac4",
"price": "13"
}],
"_id": "5ace995c14a759325776aab1",
"product_name": "Ketchup",
}]
}]
```
Thank you. | 2018/04/13 | [
"https://Stackoverflow.com/questions/49808616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5834822/"
] | I was not able to directly pipe the input, but did it in two steps:
```
searchBar.rx.text
.orEmpty
.subscribe(onNext: {query in
self.shownGenes.value = AllGenes.filter { $0.hasPrefix(query) }
})
self.shownGenes
.asObservable()
.bind(to: tableView.rx.items(cellIdentifier: cellIdentifier,
cellType: GeneSeachTableViewCell.self)) { row, gene, cell in
cell.textLabel?.text = "\(gene) \(row)"
}
.disposed(by: disposeBag)
```
Where `shownGenes = Variable<[String]>([])`. And I also removed `UISearchBar and SearchDisplayController` and substituted it for just `UISearchBar`. | I had this problem when the `UISearchBar` delegate had been set to my view controller in the storyboard. Try opening up the storyboard in interface builder and right-clicking on the search bar. If you see a connection for the delegate then remove it. Hope that helps |
26,334,565 | I've got this, and it works. It just takes a large amount of time for numbers 100000+ I'm looking to cut it down so that it can calculate the 1,000,000th prime in less than 3 minutes. I've set it so that our number (chk) is only having numbers (odds) being divided into it, to check for divisibility, up to the square root of chk. The program is set to find the nth prime number up to the 1000000th. Thanks.
```
goal=int(input("Enter a number n, 1-1,000,000 to find the nth prime number.")) #how many primes we need to find
if goal>1000000: #closes the program if the number doesn't fit the parameters
exit()
if goal==1: #takes care of the first prime, which is 2
print("2")
if goal==2: #and then the second, which is 3
print("3")
chk=5 #the next odd number after 3, which is already taken care of above
primes=2 #the number of primes recorded, after counting 2 and 3.
x=0 #the last recorded prime number
while primes<goal:
if chk<9: #if the number is odd and below 9....
primes+=1 #it's prime
x=chk #record that number
chk+=2 #and check the next odd number
else: #if it's =>9......
odds=3 #check to see if it's divisible by the smallest odd number
sqrtk=chk**.5 #all the way up to the square root of chk
while odds<sqrtk or odds==sqrtk: #if at any time...
if chk%odds==0: #...chk is divisible by this odd number....
chk+=2 #then raise the value of chk to the next odd number
break #and start the check from the beginning with next k
else: #if not...
odds+=2 #check to see if it's divisible by the next odd number.
if odds>sqrtk: #if chk isn't divisible by any odds up to the square root of chk
primes+=1 #we have a prime number
x=chk #record that number
chk+=2 #check the next odd number to see if it's prime
odds=3 #and reset odds back to 3 to use it next time
if primes==goal: #once we've reached the desired amount of prime numbers
print("The",goal,"prime number is:",x) #print that prime number
``` | 2014/10/13 | [
"https://Stackoverflow.com/questions/26334565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4131923/"
] | A better way would be to generate a list of prime numbers as you go along, and check if the number can be divided by a number of that list
```
list = [ ]
while primes < goal:
found = false
for n in list
if chk % n = 0
# is prime
found = true
break
if not found
list.append(chk)
```
To generate the list in less time, try using a different programming language. Below is the program in C++, which can generate the first 1.000.000 in under 10 seconds (depending on what you're using).
To do so, a few math assumptions were considered:
1) Only check odd numbers
2) Only check against numbers lower than the square root of the current number
Also, a few C optimizations were done:
1) Define the array size at first. By doing so, we don't have to deal with the costly operations of reallocating memory
2) Use "register" to speed up time critical processing blocks
3) pre-compute sqrt(chk) to speed up
```
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <time.h>
#include <iostream>
#include <math.h>
#define NUMBERS 1000000
using namespace std;
main(int argc, char **argv)
{
unsigned *list = (unsigned*)malloc(NUMBERS * sizeof(unsigned) );
if(!list)
exit(1);
list[0] = 2;
register unsigned primes = 1;
unsigned goal = NUMBERS;
unsigned chk = 3;
clock_t tStart = clock();
bool found;
while(primes < goal) {
found = false;
register unsigned sq = sqrt(chk);
for(register unsigned i = 1 ; i < primes ; i++) {
if(list[i] > sq)
break;
if(chk % list[i] == 0) {
found = true;
break;
}
}
if(!found) {
list[primes++] = chk;
}
chk += 2;
}
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
for(int i = 0 ; i < primes ; i++)
cout << list[i] << " ; ";
cout << endl << endl;
free(list);
}
```
The same program in python took 126s to run, under the 180s.
```
import sys
import os
import datetime
import csv
import time
import math
list = [ 2 ]
goal = 1000000
primes = 1
chk = 3
start = time.time()
while primes < goal:
found = False
sq = math.sqrt(chk)
for n in list:
if sq < n:
break
if chk % n == 0:
# is prime
found = True
break
if not found:
list.append(chk)
primes = primes + 1
chk = chk + 2
end = time.time()
print end - start
``` | If you only care about the first million primes, the easiest solution is to pre-compute the list of the first million primes, using the Sieve of Eratosthenes, then index into the list to find the nth prime. Here's a simple Sieve of Eratosthenes:
```
def primes(n): # sieve of eratosthenes
i, p, ps, m = 0, 3, [2], n // 2
sieve = [True] * m
while p <= n:
if sieve[i]:
ps.append(p)
for j in range((p*p-3)/2, m, p):
sieve[j] = False
i, p = i+1, p+2
return ps
```
The millionth prime is 15485863, so pre-compute and store the first million primes:
```
ps = primes(15485863)
```
Then you can easily look up the nth prime:
```
def nthPrime(n):
return ps[n-1]
```
Here are some examples:
```
>>> nthPrime(1)
2
>>> nthPrime(10000)
104729
>>> nthPrime(1000000)
15485863
```
Pre-computing the first million primes takes only a few seconds, and looking up the nth prime is instant. |
4,595,964 | I access my MySQL database via PDO. I'm setting up access to the database, and my first attempt was to use the following:
The first thing I thought of is `global`:
```
$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'root', 'pwd');
function some_function() {
global $db;
$db->query('...');
}
```
This is considered a bad practice. After a little search, I ended up with the [Singleton pattern](http://www.php.net/manual/en/language.oop5.patterns.php), which
>
> "applies to situations in which there needs to be a single instance of a class."
>
>
>
According to the example in the manual, we should do this:
```
class Database {
private static $instance, $db;
private function __construct(){}
static function singleton() {
if(!isset(self::$instance))
self::$instance = new __CLASS__;
return self:$instance;
}
function get() {
if(!isset(self::$db))
self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd')
return self::$db;
}
}
function some_function() {
$db = Database::singleton();
$db->get()->query('...');
}
some_function();
```
Why do I need that relatively large class when I can do this?
```
class Database {
private static $db;
private function __construct(){}
static function get() {
if(!isset(self::$db))
self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd');
return self::$db;
}
}
function some_function() {
Database::get()->query('...');
}
some_function();
```
This last one works perfectly and I don't need to worry about `$db` anymore.
How can I create a smaller singleton class, or is there a use-case for singletons that I'm missing in PHP? | 2011/01/04 | [
"https://Stackoverflow.com/questions/4595964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407054/"
] | Consider simply how your solution differs from the one presented in the PHP docs. In fact, there is just one "small" difference: your solution provides callers of the getter with a `PDO` instance, while the one in the docs provides callers of `Database::singleton` with a `Database` instance (they then use the getter on that to get a `PDO` instance).
So what conclusion do we reach?
* In the documentation code, callers get a `Database` instance. The `Database` class may expose (in fact, it *should* expose if you 're going to all this trouble) a richer or higher-level interface than the `PDO` object it wraps.
* If you change your implementation to return another (richer) type than `PDO`, then the two implementations are equivalent. There's no gain to be had from following the manual implementation.
On the practical side, Singleton is a pretty controversial pattern. This is mainly because:
* It's overused. Novice programmers grok Singleton much easier than they grok other patterns. They then go on to apply their newfound knowledge everywhere, even if the problem at hand can be solved better without Singleton (when you 're holding a hammer, everything looks like a nail).
* Depending on the programming language, implementing a Singleton in an airtight, non-leaky manner can prove to be a titanic task (especially if we have advanced scenarios: a singleton depending on another singleton, singletons that can be destroyed and re-created, etc). Just try to search for "the definitive" Singleton implementation in C++, I dare you (I own Andrei Alexandrescu's groundbreaking Modern C++ Design, which documents much of the mess).
* It imposes additional workload both when coding the Singleton and when writing code to access it, workload which you can do without by following a few self-imposed constraints on what you try to do with your program variables.
**So, as a final conclusion:** your singleton is just fine. Not using Singleton at all is just fine most of the time as well. | When programming there is not "right" and "wrong"; there is "good practice" and "bad practice".
Singletons are generally created as a class to be reused later. They need to be created in such a way that the programmer doesn't accidentally instantiate two instances while drunkenly coding at midnight.
If you have a simple little class that *shouldn't* be instantiated more than once, you don't *need* to make it a singleton. It's just a safety net if you do.
it's not **always** bad practice to have global objects. If you know that you're going to use it globally/everywhere/all the time, it may be one of the few exceptions. However, globals are generally considered "bad practice" in the same way that `goto` is considered bad practice. |
22,823,204 | This might be a very common question but i searched lot and finally decided to get some expert advice.
I was wondering if someone have uploaded file directly from URL to cPanel file manager. I can upload file from my computer using upload tab in file manager but not able to find any option for extracting data from URL.
I have tried several forums, Q/A websites but got nothing. I will really appreciate if someone can brought this question on to expert's attention.
I have looked
<http://forums.cpanel.net/f145/filemanager-upload-url-215911.html>
<http://forums.cpanel.net/f5/upload-via-url-305691.html>
and my other places but found nothing but the question. | 2014/04/02 | [
"https://Stackoverflow.com/questions/22823204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2044188/"
] | You can use [RapidLeech](http://rapidleech.com/forum/). It's a CMS to "Transload" files (server-to-server) instead of uploading. But the Hosts usually ban you for using RL, because it consumes too much resources. But it has really cool functions. You can get Youtube videos directly with any screen size you want, and also you can transload your files back to famous file uploading websites such as 4shared by providing your account info. | Best Way
========
This Worked For Large Files
---------------------------
1. First create a file on the public\_html "get.php"
2. Copy blow code and save
3. Replace YOUR\_URL with your URL
4. Open the sitename.com/get.php
5. Enjoy :)
code:
```
<?PHP
ini_set('max_execution_time', '0');
define('BUFSIZ', 4095);
$url = 'YOUR_URL';
$rfile = fopen($url, 'r');
$lfile = fopen(basename($url), 'w');
while(!feof($rfile))
fwrite($lfile, fread($rfile, BUFSIZ), BUFSIZ);
fclose($rfile);
fclose($lfile);
?>
``` |
275,020 | I would like to plot a sequence of functions in one plot.
My function is defined piecewise:
```
f[x_] := Piecewise[{{-1, -1 <= x < -(1/n)}, {n x, -(1/n) <= x <= 1/n}, {1,
1/n < x <= 1}}];
```
I would like to plot the functions for let's say
```
n = {1,2,3}
```
in one plot.
How could I do that?
My ideas were to use Map, Apply or MapApply but all of them did not work. | 2022/10/22 | [
"https://mathematica.stackexchange.com/questions/275020",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/34881/"
] | * If the `quarter circle` means the region of disk.
```
RegionPlot[x^2 + y^2 <= 4^2, {x, 0, 4}, {y, 0, 4}]
```
[](https://i.stack.imgur.com/PIOZ9.png)
* If the `quarter circle` means only the circumference.
```
RegionPlot[ImplicitRegion[x^2 + y^2 == 4^2, {{x, 0, 4}, {y, 0, 4}}],
BoundaryStyle -> Blue, PlotStyle -> None]
```
[](https://i.stack.imgur.com/XQpNo.png)
* If the `quarter circle` means the boundary of disk.
```
RegionPlot[x^2 + y^2 <= 4^2, {x, 0, 4}, {y, 0, 4},
BoundaryStyle -> Blue, PlotStyle -> None]
```
[](https://i.stack.imgur.com/RaaBu.png) | ```
RegionPlot[Norm[{x, y}] < 4 && x > 0 && y > 0, {x, -4, 4}, {y, -4, 4}]
```
[](https://i.stack.imgur.com/zIu67.png)
---
Also try:
```
Manipulate[
RegionPlot[Norm[{x, y}, p] < 4
, {x, -4, 4}, {y, -4, 4}]
, {{p, 2}, 1, 6}
]
``` |
53,919,995 | My header css is giving me pain. It's effecting what comes after it. I just want to put 3 links/button in center of the content. But when I try to make it. Not working properly. `p` tag or `h1` tags doesn't matter, Always stuck behind the header. I used clear fix but not quite working. I am not sure why next div stuck behind the header. And also when I try to give css to `a` tag which is inside row div. It doesn't take effect too.
```css
body {
margin: 0;
font-family: Helvetica, sans-serif;
background-color: #f4f4f4;
}
a {
color: #000;
}
/* header */
.header {
background-color: #fff;
box-shadow: 1px 1px 4px 0 rgba(0,0,0,.1);
position: fixed;
width: 100%;
}
.header ul {
margin: 0;
padding: 0;
list-style: none;
overflow: hidden;
background-color: #fff;
}
.header li a {
display: block;
padding: 20px 20px;
border-right: 1px solid #f4f4f4;
text-decoration: none;
}
.header li a:hover,
.header .menu-btn:hover {
background-color: #f4f4f4;
}
.header .logo {
display: block;
float: left;
font-size: 2em;
padding: 10px 20px;
text-decoration: none;
}
/* menu */
.header .menu {
clear: both;
max-height: 0;
transition: max-height .2s ease-out;
}
/* menu icon */
.header .menu-icon {
cursor: pointer;
display: inline-block;
float: right;
padding: 28px 20px;
position: relative;
user-select: none;
}
.header .menu-icon .navicon {
background: #333;
display: block;
height: 2px;
position: relative;
transition: background .2s ease-out;
width: 18px;
}
.header .menu-icon .navicon:before,
.header .menu-icon .navicon:after {
background: #333;
content: '';
display: block;
height: 100%;
position: absolute;
transition: all .2s ease-out;
width: 100%;
}
.header .menu-icon .navicon:before {
top: 5px;
}
.header .menu-icon .navicon:after {
top: -5px;
}
/* menu btn */
.header .menu-btn {
display: none;
}
.header .menu-btn:checked ~ .menu {
max-height: 240px;
}
.header .menu-btn:checked ~ .menu-icon .navicon {
background: transparent;
}
.header .menu-btn:checked ~ .menu-icon .navicon:before {
transform: rotate(-45deg);
}
.header .menu-btn:checked ~ .menu-icon .navicon:after {
transform: rotate(45deg);
}
.header .menu-btn:checked ~ .menu-icon:not(.steps) .navicon:before,
.header .menu-btn:checked ~ .menu-icon:not(.steps) .navicon:after {
top: 0;
}
html {
font-family: Helvetica Neue;
}
.clearfix:after {
content: ".";
visibility: hidden;
display: block;
height: 0;
clear: both;
}
.row {
margin: auto;
text-align: center;
width: 85%;
color: black;
}
.button a:link {
text-decoration: none;
background-color: black;
border: 1px solid red;
padding: 15px;
}
a:visited {
text-decoration: none !important;
}
/* 48em = 768px */
@media (min-width: 48em) {
.header li {
float: left;
}
.header li a {
padding: 20px 30px;
}
.header .menu {
clear: none;
float: right;
max-height: none;
}
.header .menu-icon {
display: none;
}
}
```
```html
<header class="header">
<a href="" class="logo">GO</a>
<input class="menu-btn" type="checkbox" id="menu-btn" />
<label class="menu-icon" for="menu-btn"><span class="navicon"></span></label>
<ul class="menu">
<li><a href="#">Menu 1</a></li>
<li><a href="#">Menu 2</a></li>
<li><a href="#">Menu 3</a></li>
</ul>
</header>
<div class="clearfix"></div>
<div class="row">
<a href="#" class="button">Click</a>
</div>
```
Any idea why this happening? | 2018/12/25 | [
"https://Stackoverflow.com/questions/53919995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If anyone wants to use command which is recommended for creating pem file,
then here is solution on [my gist](https://gist.github.com/mrugeshtank/8c3b8014c34f57bb599f7f9d06c6da25).
1. `openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem`
2. `openssl pkcs12 -nocerts -in PushChatKey.p12 -out PushChatKey.pem`
3. `cat PushChatCert.pem PushChatKey.pem > ck.pem`
First 3 commands will generate pem, but if you want to test then 4th and 5th command will be necessary.
If you got error that about unknown command 'telnet' then install telnet from brew. | `openssl x509 -inform der -in certificate.cer -out certificate.pem`
Look no further. This is all that it takes. |
9,806,887 | **I have a Enumeration as shown in below program**
```
public class Test {
public static void main(String args[]) {
Vector v = new Vector();
v.add("Three");
v.add("Four");
v.add("One");
v.add("Two");
Enumeration e = v.elements();
load(e) ; // **Passing the Enumeration .**
}
}
```
**There is also a Student Object**
```
public Student
{
String one ;
String two ;
String three ;
String four ;
}
```
**i need to pass this Enumeration to another method as shown below**
```
private Data load(Enumeration rs)
{
Student stud = new Student();
while(rs.hasMoreElements())
{
// Is it possible to set the Values for the Student Object with appropiate values I mean as shown below
stud.one = One Value of Vector here
stud.two = Two Value of Vector here
stud.three = Three Value of Vector here
stud.four = Four Value of Vector here
}
}
```
Please share your ideas on this .
Thanks | 2012/03/21 | [
"https://Stackoverflow.com/questions/9806887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/784597/"
] | Sure. You could use the `elementAt` method, [documented here](http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html#elementAt%28int%29), to get the value you wanted. Do you have a specific reason you are using a Vector? Some of the `List` implementations might be better. | Enumerations don't have the idea of "first value", "second value", etc. They just have the current value. You could work around this in various ways:
1. The easy way -- convert it to something easier to work with, like to a `List`.
```
List<String> inputs = Collections.list(rs);
stud.one = inputs.get(0);
stud.two = inputs.get(1);
// etc.
```
2. Keep track of the position yourself.
```
for(int i = 0; i <= 4 && rs.hasNext(); ++i) {
// Could use a switch statement here
if(i == 0) {
stud.one = rs.nextElement();
} else if(i == 1) {
stud.two = rs.nextElement();
} else {
// etc.
}
}
```
I really don't recommend either of these things, for the following reasons:
* If you want your parameters in a particular order, just pass them in that way. It's much easier and it's also easier to maintain (and for other people to read).
```
void example(String one, String two, String three, String four) {
Student student = new Student();
student.one = one;
student.two = two;
// etc.
}
```
* You shouldn't use `Enumeration` at all, since it's been replaced with `Iterator` and `Iterable` since Java 1.2. See [ArrayList](http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html) and [Collection](http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html). |
57,413,739 | I have a CircleCI config in which I am running machine executor, starting up my application using docker-compose, then running E2E tests in Cypress, that are not in docker, against this app. Cypress basically spins up a headless browser and tries to hit the specified url.
Now, no matter what my first test always fails. I have created 10 tests that just hit the root url and click a button. I have those tests run first. First one always fails.
The error is
```
CypressError: cy.visit() failed trying to load:
http://localhost:3000/
```
Which basically means there was no response or a 4-500
I though the app might not be ready yet, so I added a sleep before starting tests. I set that to 9 minutes (10 minutes times out on CircleCI). First test failed. I ratcheted that down to 2 minutes. First test fails.
Again to be clear, the first 10 tests are the same, so it’s not test specific.
Update
------
I have [crossposted this to the CircleCI forum](https://discuss.circleci.com/t/first-test-always-fails-no-matter-what-the-test-is/31819). | 2019/08/08 | [
"https://Stackoverflow.com/questions/57413739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/494150/"
] | I think your server isn’t ready.
Before run cypress test, you have to wait for server.
If so, don't use sleep.
You can use wait-on or start-server-and-test.
You can check this doc. <https://docs.cypress.io/guides/guides/continuous-integration.html#Boot-your-server> | I had the same issue. Solved it by server/route/wait. I first start the server, then create a rout alias, wait for it to call the Api endpoint (which triggers the app to fill the dom) then do the rest (cy.get/click).
Example before:
```
cy.get('myCssSelector')
```
**After server/route/wait:**
```
cy.server()
cy.route('GET', '*/project/*').as('getProject')
cy.wait('@getProject')
.then(resp => {
expect(resp.status).to.eq(201)
})
cy.get('myCssSelector')
``` |
22,855,140 | I am trying to show a form when a button is clicked. But it shows for a second or so and then hides again. i have tried to debug it with console.log() but my jQuery is not reaching in the anonymous function in click event in chrome console it is showing me this error "Failed to load resource: the server responded with a status of 400 (Bad Request)" Here is my code
```
<asp:Panel id="dynamicSubForm" class="container" runat="server" DefaultButton="btnAdd" DefaultFocus="txtSegment">
<div class="subForm">
<div id="subHeader" class="divRow">
<div class="headCol">
<asp:Label ID="Label1" runat="server"
Text="Sources"></asp:Label>
</div>
</div>
<div class="subFormRow">
<div> </div>
</div>
<div class="subFormRow">
<div class="subFormFstCol">
<asp:Label ID="lblSource" runat="server" Text="Source:"></asp:Label>
</div>
<div class="subFormScndCol">
<asp:DropDownList ID="ddlSource" runat="server"
CssClass="whiteCtrl" DataSourceID="dsIrrigationSource"
DataTextField="title" DataValueField="id">
</asp:DropDownList>
<asp:SqlDataSource ID="dsIrrigationSource" runat="server"
ConnectionString="<%$ ConnectionStrings:MIS4BOSConnectionString %>"
SelectCommand="SELECT [id], [title] FROM [IrrigationSource]">
</asp:SqlDataSource>
</div>
</div>
<div class="subFormRow">
<div class="subFormFstCol">
<asp:Label ID="lblSegment" runat="server" Text="Area Segment:"></asp:Label>
</div>
<div class="subFormScndCol">
<asp:TextBox ID="txtSegment" runat="server" CssClass="whiteCtrl"></asp:TextBox>
%<br />
<asp:RegularExpressionValidator ID="revArea0" runat="server"
ControlToValidate="txtSegment" Display="Dynamic"
ErrorMessage="Percentage must be all digits." ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>
</div>
</div>
<div class="subFormRow">
<div class="subFormFstCol">
<asp:Label ID="lblDesc" runat="server" Text="Description:"></asp:Label>
</div>
<div class="subFormScndCol">
<asp:TextBox ID="txtDesc" runat="server" Height="70px" TextMode="MultiLine"
CssClass="whiteCtrl"></asp:TextBox>
</div>
</div>
<div class="subFormRow">
<div class="subFormFstCol">
</div>
<div class="subFormScndCol">
<asp:Button ID="btnAdd" runat="server" CssClass="blueBtn" Text="Add"
onclick="btnAdd_Click" />
<asp:Button ID="btnAddCancel" runat="server" CssClass="whiteBtn"
Text="Cancel" onclick="btnAddCancel_Click" />
<br />
<asp:Label ID="lblSubMsg" runat="server" CssClass="usrMsg" Text="Label"
Visible="False"></asp:Label>
</div>
</div>
</div>
</asp:Panel>
enter code here
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
var subForm = $("#MainContent_dynamicSubForm");
var addBtn = $("#irrAdd");
console.log("before hide");
subForm.hide();
console.log("after hide");
addBtn.on("click", function () {
console.log('in anonymous func');
subForm.show();
});
});
</script>
``` | 2014/04/04 | [
"https://Stackoverflow.com/questions/22855140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3496690/"
] | The form is probably submitting, do it like this
```
addBtn.on("click", function (e) {
e.preventDefault();
console.log('in anonymous func');
subForm.show();
});
```
Note that the id `irrAdd` does not seem to exist in the markup, and that you could also change the buttons type to `button` | Use jquery toggle(); function
```
$(document).ready(function () {
var subForm = $("#MainContent_dynamicSubForm");
var addBtn = $("#irrAdd");
console.log("before hide");
subForm.hide();
console.log("after hide");
addBtn.on("click", function () {
console.log('in anonymous func');
subForm.toggle();
});
});
``` |
1,848,390 | I have 2 buttons next to a textbox and another textbox after the 2 buttons. The tabindex for the first textbox is 1000, the first button is 1001 and the second button is 1002. The second textbox has a tabindex of 1003.
When I press tab, the tabindex works fine in all browsers except for Safari, where it immediately moves from the first textbox to the second textbox although the tabindex has been set properly. Any ideas on how to prevent this issue? | 2009/12/04 | [
"https://Stackoverflow.com/questions/1848390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81711/"
] | By default tab-access is disabled in safari(!). To enable it, check "Preferences > Advanced > Press tab to highlight each item on a page". | Making Safari and a Mac accessible:
Testing on a Mac:
System Preferences -> Keyboard -> ShortCuts (tab) -> Full Keyboard Access -> All Controls
For Tabbing to work on Safari:
Preferences -> Advanced -> Press tab to highlight each item on a page (check this) |
22,524,149 | I went to the Oracle site to download the release JDK 8 for ARM and the version labeled as JDK 8 is actually JDK 7 update 40. Does anyone know where to find the JDK 8 for ARM or how to let Oracle know about the problem? | 2014/03/20 | [
"https://Stackoverflow.com/questions/22524149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814270/"
] | You can find a couple of logically pure, monotone implementations of list intersection and union in [my answer](https://stackoverflow.com/a/29819232/4609915) to the related question "[Intersection and union of 2 lists](https://stackoverflow.com/questions/9615002/intersection-and-union-of-2-lists)".
Let's see a sample query:
```
?- list_list_intersection([3,4,5,6],[5,1,0,2,4],Intersection).
Intersection = [4,5]. % **succeeds deterministically**
```
As the proposed implementation is **monotone**, you can also use it in more general ways and still get **logically sound answers**:
```
?- L2 = [_,_,_], list_list_intersection([3,4,5,6],L2,[4,5]).
L2 = [ 4, 5,_A], dif(_A,6), dif(_A,3) ;
L2 = [ 4,_A, 5], dif(_A,6), dif(_A,5), dif(_A,3) ;
L2 = [ 5, 4,_A], dif(_A,6), dif(_A,3) ;
L2 = [_A, 4, 5], dif(_A,6), dif(_A,5), dif(_A,4),dif(_A,3) ;
L2 = [ 5,_A, 4], dif(_A,6), dif(_A,4), dif(_A,3) ;
L2 = [_A, 5, 4], dif(_A,6), dif(_A,5), dif(_A,4),dif(_A,3) ;
false.
``` | Usually `sets` in Prolog are represented with sorted lists, then avoiding the *ambiguity* of the representation that arises in presence of duplicate elements. Let's ignore this problem...
This fact `setIntersection([], [], []).` is *subsumed* by `setIntersection([], _, []).`, then can (should!) be deleted.
The same for `keepDuplicates([], [], []).` (why do you invert clauses order here ?)
You have a singleton Zs: `...,keepDuplicates(X, Y, [Z|Zs]),...` and you should pay attention to that warning (of course, if your compiler display it), since it's often symptom of a true mistake.
Also, that predicate cannot cover all the cases: when X is *not* in Y, what do you associate to Z ?
To be true, I think you're doing it more complicated than required. Ignoring duplicates, the whole could be easy as
```
?- L1=[3,4,5,6],L2=[5,1,0,2,4],findall(C, (member(C,L1),memberchk(C,L2)), I).
``` |
2,626,649 | In the following JavaScript code main() is called.
My question is why the second constructor is called rather than the first one ?
What am I missing here ?
Thanks !!
```
function AllInputs() {
alert("cons 1");
this.radioInputs = [];
alert(this);
}
function AllInputs(radioElement) {
alert("cons 2");
this.radioInputs = [radioElement];
alert(this);
}
AllInputs.prototype.toString = function() {
return "[object AllInputs: radioInputs: " + this.radioInputs.length + "]";
}
function main() {
var result = new AllInputs();
}
``` | 2010/04/13 | [
"https://Stackoverflow.com/questions/2626649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] | Javascript does not support overloaded functions.
When you define the same function twice, the second definition replaces the first one.
Instead, you should make a single function, and check `arguments.length` to see how many arguments were passed.
For example:
```
function AllInputs(radioElement) {
this.radioInputs = arguments.length ? [radioElement] : [];
alert(this);
}
``` | In JavaScript, the last definition of an identifier is used:
```
function foo() { return "bar"; }
var foo = "foo";
alert(foo);
```
In that case, `foo` was a variable with the value "foo". Had `foo` been a function, it would have simply said that `foo` was a function. If you don't believe it, try using `alert(foo())` instead of just `alert(foo)`. You'll most likely get an error in your console log with no visible output like you had with `alert(foo)` (the variable...not the function call). |
18,332,244 | I have 2 different system, lets say SystemA and SystemB.
In SystemB, there is page, say calculate.aspx, where it receive certain parameter and will perform some calculation. This page doesn't display and info, and only serves to execute the code behind.
Now i have a page in SystemA, lets say execute.aspx, that will need to call calculate.aspx in SystemB to run the desired calculation. I cannot use redirect, since that will redirect me to the calculation.aspx page on SystemB.
I had tried using HttpWebRequest but it doesn't call to the page. The code is as below:
```
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(nUrl + '?' + fn);
myRequest.Method = "GET";
WebResponse response = myRequest.GetResponse();
```
Does anyone know what is the correct way of doing it? Thanks.
**EDIT**
Manage to get it done after changing my codes to above. Thank you all. | 2013/08/20 | [
"https://Stackoverflow.com/questions/18332244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1158142/"
] | You can either use a web service which would be the preferred way or use AJAX to send data to the page and get result in response. | try this
```
namespace SampleService // this is service
{
public class Service1 : IService1
{
public string GetMessage()
{
return "Hello World";
}
public string GetAddress()
{
return "123 New Street, New York, NY 12345";
}
}
}
protected void Page_Load(object sender, EventArgs e) // calling the service
{
using (ServiceClient<IService1> ServiceClient =
new ServiceClient<IService1>("BasicHttpBinding_IService1"))
{
this.Label1.Text = ServiceClient.Proxy.GetMessage();
//once you have done the build inteli sense
//will automatically gets the new function
this.Label2.Text = ServiceClient.Proxy.GetAddress();
}
}
```
refer this link
<http://www.codeproject.com/Articles/412363/How-to-Use-a-WCF-Service-without-Adding-a-Service> |
10,510,319 | There are lots of times Eclipse can't connect to emulator that I turned on from AVD Manager, and just starts a new emulator by itself,( two emulators are the same ):((. How can I make eclipse find the emulator ? | 2012/05/09 | [
"https://Stackoverflow.com/questions/10510319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1377713/"
] | I guess that you might suffer from the issue that the manually started emulator got disconnected somehow, shown with a message like
`Error: emulator-5554 disconnected`
in the Eclipse console view. There are several related questions and answers on stackoverflow like [Why do I get a emulator-5554 disconnected message](https://stackoverflow.com/questions/2333273/why-do-i-get-a-emulator-5554-disconnected-message),
but for me none of those answers helped.
Whenever I see the error message for disconnection occur, I just shutdown that emulator and start it again. Normally that already "fixes" the problem, it just works on the next attempt (for me). | If the emulator is still active, you can use adb to connect to it via tcp. In this way you can connect a disconnected emulator to your development system's loopback one port higher, just like if you are using emulator-5554, you can connect to it by using a higher port.
```
adb connect localhost:5555
```
There was been an issue with this technique, where the emulator control becomes inactive, and the developer cannot send GPS coordinates or SMSs or calls to emulator.
There is a one click method to do this
1. Open notepad
2. Type the below code
@echo off
adb connect localhost:5555
3. Save the file as your\_file\_name.BAT
4. Copy the file to Android SDK/platform\_tools
5. Create a shortcut, give it a custom icon, use it anywhere you like |
39,723,320 | I'm not able to find the logs of application I have submitted on the the yarn on ambari cluster via log search service. | 2016/09/27 | [
"https://Stackoverflow.com/questions/39723320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3338663/"
] | Try this
```
import sys, os, django
sys.path.append("/path/to/store") #here store is root folder(means parent).
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "store.settings")
django.setup()
from store_app.models import MyModel
```
This script you can use anywhere in your system. | Django standalone script.
* Place it in the same directory as manage.py file
* Rename PROJECT\_NAME to your project's name
```
import os
PROJECT_NAME = 'ENTER YOUR PROJECT NAME HERE'
def main():
# import statemts
# from app.models import Author,Category,Book
# code logic - anything you want
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % PROJECT_NAME)
import django
django.setup()
main()
``` |
64,532,025 | I know there have been multiple instances of this question such as [Print all lines between two patterns, exclusive, first instance only (in sed, AWK or Perl)](https://stackoverflow.com/questions/55220417/print-all-lines-between-two-patterns-exclusive-first-instance-only-in-sed-aw)
but my question is for if the two patterns may not be paired - for instance
given input
```
PATTERN1
bbb
ccc
ddd
eee
fff
PATTERN1
ggg
hhh
iii
PATTERN2
jjj
PATTERN2
kkk
```
I would expect the shortest range as output:
```
ggg
hhh
iii
```
Is this possible? | 2020/10/26 | [
"https://Stackoverflow.com/questions/64532025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14519899/"
] | Could you please try following, written and tested based on your shown samples only in GNU `awk`.
```none
awk '
/PATTERN1/ && found1 && !found2{
found1=found2=val=""
}
/PATTERN1/{
found1=1
next
}
/PATTERN2/{
found2=1
if(found1){
print val
}
found1=found2=val=""
next
}
{
val=(val?val ORS:"")$0
}
' Input_file
```
Output for given samples will be:
```
ggg
hhh
iii
```
***Explanation:*** Adding detailed explanation for above.
```
awk ' ##Starting awk program from here.
/PATTERN1/ && found1 && !found2{ ##Checking if PATTERN1 in current line and found1 is SET and found2 is NOT SET then do following.
found1=found2=val="" ##Nullifying found1, found2 and val variables here.
}
/PATTERN1/{ ##Checking condition if PATTERN1 is found then do following.
found1=1 ##Setting found1 here for flagging.
next ##next will skip all further statements from here.
}
/PATTERN2/{ ##Checking condition if PATTERN2 is found then do following.
found2=1 ##Setting found2 here for flagging.
if(found1){ ##Checking condition if found1 is SET then do following.
print val ##Printing val here.
}
found1=found2=val="" ##Nullifying found1, found2 and val here.
next ##next will skip all further statements from here.
}
{
val=(val?val ORS:"")$0 ##Creating val which has current line value and keep appending it with new line.
}
' Input_file ##Mentioning Input_file name here.
``` | If `Perl` happens to be your option, would you please try:
```
perl -0777 -ne '/.*PATTERN1\n(.*?)PATTERN2/s && print $1' input
```
Result:
```
ggg
hhh
iii
```
* `-0777` option tells `Perl` to slurp all lines at once.
* `s` option to the regex tells `Perl` to include newline character in metacharacter `.`.
* `.*PATTERN1\n` winds the position until the end of last `PATTERN1`.
* `(.*?)` specifies the shortest match and assign `$1` to the matched lines. |
9,547 | Every time I apply for a job I write a new cover letter, research statement, and teaching statement. While each statement is personalized for the specific job, I tend to do a lot of cutting and pasting and little new writing (yes I have a whole collection of past statements). This seems like something that might be useful to keep under version control. how do people manage the different versions of the cover letter, research statement, and teaching statement? | 2013/04/22 | [
"https://academia.stackexchange.com/questions/9547",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/929/"
] | I am in the middle of my job search and I do the following to keep myself organised:
Directory structure: ('#' for comments and '/' for directories)
```
/Interested
/<deadline>-University1
#job ad and README.txt in here
/<deadline>-University2
/Not Interested or Expired
/<deadline>-University3
/Submitted
/<deadline>-University4
/Application Materials #pdfs, copied over from git repos
/RS-git #git repo
#possibly a generic Research Statement in here
/<year>
/University4
#Latest Research Statement in one of these
#similarly for TS, CV, CL
/TS-git #git repo for Teaching Statements
/CV-git #git repo for CV
/CL-git #git repo for Cover Letters
```
For each job ad I have a directory for the ad, a readme with notes to myself, and a directory for the application I am building/submitting. I then create related directories in each of the RS, TS, CV, CL directories, so that I can quickly start the application without affecting other concurrent ones. Importantly **I never have to pull an earlier commit or mess around with branches to switch between job applications**. This last bit is important because I often work on two applications at the same time, either to copy-paste between them, or simply to meet simultaneous deadlines.
One last note, my are in ISO format, so they appear in order of submission deadline. | While I keep my correspondence in version control, I don't have the same document for cover letters that go to different schools. I simply prepend the name of the school to all of my correspondence for that school, and/or file everything into folders with the school's name.
As you point out, you end up personalizing almost everything (even CVs), so we aren't talking about one document for which you need version control. You want version control for *all* the documents, but each document has its own identity.
Now, if you do have a unique document that will be sent to different schools, you would want to create one document, and then create a [*symbolic link*](http://en.wikipedia.org/wiki/Symbolic_link) (or an [alias](http://en.wikipedia.org/wiki/Alias_%28Mac_OS%29)) from one original to each school folder where it will be sent. Then, when you update the original, all the symbolic links point to the same file.
Finally, you may want to consider using a word processor that has the ability to use templates, but I find that is sometimes just as much work as simply duplicating a file and changing the duplicate. |
32,487,502 | So I understand somewhat what the command sll is doing, as I read [this](http://chortle.ccsu.edu/assemblytutorial/Chapter-12/ass12_2.html) and its pretty much just shifting all the bits left by 1. I'm just wondering why would I do this?
I have an assignment from class with an example of it...
Where $s6 and $s7 is the base address for an array and $s1/$s2 are just some variables.
```
sll $t0, $s0, 2
add $t0, $s6, $t0
sll $t1, $s1, 2
add $t1, $s7, $t1
...
```
Why shift a bit? What is it doing in simple terms? My first thought it has something to do with indexing the variables in the array...but I'm not sure. | 2015/09/09 | [
"https://Stackoverflow.com/questions/32487502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4282688/"
] | >
> its pretty much just shifting all the bits left by 1
>
>
>
The example they showed was a shift by 1 bit. The `sll` instruction isn't limited to just shifting by 1 bit; you can specify a shift amount in the range 0..31 (a shift by 0 might seem useless, but `SLL $zero, $zero, 0` is used to encode a `NOP` on MIPS).
[A logical left shift](https://en.wikipedia.org/wiki/Logical_shift) by `N` bits can be used as a fast means of multiplying by `2^N` (2 to the power of N). So the instruction `sll $t0, $s0, 2` is multiplying `$s0` by 4 (2^2) and writing back to `$t0`. This is useful e.g. when scaling offsets to be used when accessing a word array. | Shifting a number one bit to the left is the same as multiplying that number by 2.
More generally, shifting a number N bits to the left is the same as multiplying that number by 2^N.
It is widely used to compute the offset of an array, when each element of the array has a size that is a power of 2. |
174,555 | Please, help me with this query:
Table conversation\_reply:
```
#id reply from_id to_id timestamp
--------------------------------------------------------------------
1 Hello 1 2 2017/05/23 12:26:40
2 Hi 2 1 2017/05/23 12:26:42
3 Hello 3 2 2017/05/22 01:26:40
4 What R U Doin? 1 2 2017/05/25 09:48:40
```
Table users:
```
#id name ipAddress
--------------------------------
1 Tin 78.78.78.78
2 Leo 78.78.78.77
3 Max 78.78.78.76
```
Table conversation:
```
#id from_id to_id timestamp
---------------------------------------------------
1 1 2 2017/05/23 12:26:40
2 2 1 2017/05/23 12:26:42
3 3 2 2017/05/22 01:26:40
4 1 2 2017/05/25 09:48:40
```
How can I achieve query to get results that look like this:
```
#id name reply
-----------------------------------
1 Tin Hello
2 Leo Hi
3 Tin What R U Doin?
```
I'm lost | 2017/05/25 | [
"https://dba.stackexchange.com/questions/174555",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/99512/"
] | Assuming that you are looking to get conversation between two users displayed in order of how the conversation/chat proceeds.
Also assuming that you will be using this query in an application where the two users chatting are known to the application (i.e. logged in to the system). In this case I will assume that these users are users.id 1 and 2.
Note that table `conversation` is not required to get the desired results.
Now for the query:
```
SELECT cr.id,
u.name,
cr.reply
FROM
users u INNER JOIN conversation_reply cr ON cr.from_id=u.id
WHERE cr.from_id in (1,2)
ORDER BY cr.`timestamp` ASC;
``` | ```
SELECT
Crep.[#id],
u.name,
crep.reply
FROM
conversation_reply Crep join users u on Crep.[from_id] = u.[#id]
order by Crep.[#id]
``` |
13,829,648 | I'm an experienced .NET programmer, but I'm new to this whole web programming thing. My ASP.NET MVC website has a global layout that includes some content (menu links at the top of the page) that I want to hide under conditions that are detected dynamically by controller code.
My inclination -- the simple approach that uses the tools I've learned about thus far -- is to shove a Boolean HideGlobal value into the ViewBag, and to put the global markup in \_Layout.cshtml that I want to hide inside of an @if (ViewBag.HideGlobal){} block.
I just want to know if this is the "proper" way to do it, or is there some Razor magic that I should be using for reasons that are not yet evident to me? | 2012/12/11 | [
"https://Stackoverflow.com/questions/13829648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1637105/"
] | I dislike using the view model of the action outside of the view returned by the action. Using base view model for this scenario feels very clunky.
I believe it's cleaner and more obvious to just use a separate (child) action that contains the logic for specifying how the global menu should be displayed. This action returns the global menu view. Call that action from your layout page.
Or you can create an action for the entire header where the menu's state is determined -- or do an if/else to render a partial view of the global menu.
The example below encapsulates the needs of a header/global menu and offers a future proof way of changing your header/menu with minimal effect on your code infrastructure (base view model).
**~/Controllers/LayoutController.cs**
```
public class LayoutController : Controller
{
[ChildActionOnly]
public ActionResult Header()
{
var model = new HeaderViewModel();
model.ShowGlobalMenu = ShowGobalMenu();
return View(model);
}
}
```
**~/Views/Layout/Header.cshtml**
```
@model HeaderViewModel
@{
Layout = "";
}
<header>
<a href="/">Home</a>
@if(Model.ShowGlobalMenu)
{
<ul>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
}
</header>
```
**~/Views/Shared/\_Layout.cshtml**
```
<html>
<body>
@Html.Action("Header", "Layout")
<p>Stuff</p>
</body>
</body>
``` | What you've described (putting a bool into the ViewBag) will work fine. But personally, I like the strongly-typed model experience, so when I want to have UI logic like what you're describing in the master/layout page (which is pretty much always), I prefer to put those flags into a base model that my other models inherit from.
```
public class BaseModel
{
public bool HideGlobal { get; set; }
}
```
And at the top of the \_Layout.cshtml page, I specify that I'm expecting a BaseModel:
```
@model Company.Project.BaseModel
```
Other views can, of course, require other model types, but if they're using this layout, those model types should derive from BaseModel.
Finally, when I want to check the flag, rather than having a mysterious, undocumented field in the ViewBag, I've got the lovely intellisense and feel-good strongly-typed member of the model:
```
@if (!Model.HideGlobal)
{
<div>...</div>
}
```
Edit: I should probably add that it's often nice to also have a base controller whose job it is to populate the fields in BaseModel. Mine usually look like this:
```
public class BaseController : Controller
{
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
var result = filterContext.Result as ViewResultBase;
if (result != null)
{
var baseModel = result.Model as BaseModel;
if (baseModel != null)
{
//Set HideGlobal and other BaseModel properties here
}
}
}
}
```
First answer here, be gentle :-) |
3,131,979 | So, I've spent hours on this question and it's frustrating me way too much so I created an account for StackExchange just to understand how you solve this problem.
Let me start by sharing the question: *"Sally has hidden her brother's birthday present somewhere in the backyard. When writing instructions for finding the present, she used a coordinate system with each unit on the grid representing 1 m. The positive y-axis of this grid points north. The instructions read "Start at the origin, walk halfway to (8,6), turn 90 degrees left, and then walk twice as far." Where is the present?"* By the way, you have to answer the question algebraically and the answer in the textbook is (-2,11)
**What I Know**
*Let P represent the coordinate of the present*
*Let M represent the midpoint between (0,0) and (8,6)*
* M is at (4,3) which is solved using the midpoint formula.
* The distance from P to M is 10 m.
* The equation for the line from the origin to the midpoint is:
**y= $\frac{3x}{4}$**
* The equation for line PM is:
**y= $\frac{-4x}{3}$ + $\frac{25}{3}$**
* Using the distance formula for two coordinates I know that the distance from M to P can be represented in this equation: *$100=(4-x)^2 + (3-y)^2$* The x and y in the equation represents the x,y coordinates of the point P. I don't know how to simplify this equation further.
**My troubles**
I come to this point where I don't know what to do anymore. Please explain how you solved this problem.
***Thank you so much*** | 2019/03/02 | [
"https://math.stackexchange.com/questions/3131979",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/649776/"
] | If you know complex numbers, the problem becomes almost trivial to solve. Complex numbers lend themselves very naturally to mapping to vectors and points on the 2-d plane.
So you start at the origin (point $0+0i$) and walk halfway to $8+6i$, which means you end up at $4+3i$. At this point you turn ninety degrees to your left (which is counter-clockwise), and the vector for the new direction can be found by multiplying the previous one by $i$. And since you're walking twice as far, this is equivalent to again multiplying the result by two. So you're now taking the path $2i(4+3i) = -6 + 8i$. The final position is simply the sum of $4+3i$ and $-6+8i$, i.e. $4+3i -6+8i = -2 + 11i$. This is the point $(-2,11)$ as required. | Go to (4,3), and then walk in the direction of slope -4/3, i.e., left 3 and up 4, twice as far, i.e., left 6 and up 8. So, 4-6=-2, and 3+8=11. There’s a 3,4,5 right triangle and a 6,8,10 right triangle involved.
Solving quadratic equations is serious overkill. |
49,117,365 | Has anyone ran across this error when querying with erlang odbc:
>
> {:error, :process\_not\_owner\_of\_odbc\_connection}
>
>
>
I am writing a connection pool and the :ODBC.connect('conn string) is ran inside the genserver and the returned pid is put into the state... But when i get that PID back out of the gen server, I get the above error when trying to run an :odbc.param\_query with that pid... How are we suppose to create a connection pool if we can use pids created in a genserver?
Anyone have any ideas?
GenServer:
```
defmodule ItemonboardingApi.ConnectionPoolWorker do
use GenServer
def start_link([]) do
IO.puts "Starting Connection Pool"
GenServer.start_link(__MODULE__, nil, [])
end
def init(_) do
:odbc.start
{ok, pid} = :odbc.connect('DSN=;UID=;PWD=', [])
IO.inspect pid
{:ok, pid}
end
def handle_call(:get_connection, _from, state) do
IO.puts "Inspecting State:"
IO.inspect state
IO.puts("process #{inspect(self())} getting odbc connection")
{:reply, state, state}
end
end
```
Calling Function:
```
def get_standards_like(standard) do
:poolboy.transaction(
:connection_pool,
fn pid ->
connection = GenServer.call(pid, :get_connection)
IO.inspect connection
val =
String.upcase(standard)
|> to_char_list
# Call Stored Proc Statement
spstmt = '{call invlibr.usp_vm_getStandards (?)}'
case :odbc.param_query(connection, spstmt, [
{{:sql_char, 50}, [val]}
])
|> map_to_type(ItemonboardingCore.Standard)
do
{:ok, mapped} ->
{:ok, mapped}
{:updated, affected_count} ->
{:ok, affected_count}
{:executed, o, a} ->
{:ok, o, a}
{:error, _} ->
{:bad}
end
end
)
end
```
I have confirmed that the pids in the genserver are infect the correct odbc pids and the GenServer.Call returns one of them.
\*\*\*\*EDIT\*\*\*\*
Here is what I did to fix the issue. I didnt know that the process that created the connection, had to be the process that runs the query. A slight change to my worker to pass the query into has fixed my issue. This is a rough first pass, a few things still need to be done to the worker.
```
defmodule ItemonboardingApi.ConnectionPoolWorker do
use GenServer
def start_link([]) do
IO.puts "Starting Connection Pool"
GenServer.start_link(__MODULE__, nil, [])
end
def init(_) do
:odbc.start(:app)
{ok, pid} = :odbc.connect('DSN=;UID=;PWD=', [])
IO.inspect pid
{:ok, pid}
end
def handle_call(:get_connection, _from, state) do
{:reply, state, state}
end
def handle_call({:query, %{statement: statement, params: params}}, _from, state) do
#TODO Check if pid is alive and start if needed.
{:reply, :odbc.param_query(state, to_charlist(statement), params), state}
end
end
``` | 2018/03/05 | [
"https://Stackoverflow.com/questions/49117365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959912/"
] | That's going to be a problem, like Kevin pointed out you can't transfer connection ownership for odbc and other drivers like mysql/otp.
If you want to use a connection pool, take a look at this instead <https://github.com/mysql-otp/mysql-otp-poolboy>
Otherwise, you can use any pool but the process that executes the sql queries has to be the one that opened the connections.
---
example in Erlang
-----------------
```
sql_query_priv(Conn, Conn_Params, {SQL, Params}) ->
lager:debug("~p:sql_query_priv trying to execute query: ~p, with params: ~p, conn = ~p~n", [?MODULE, SQL, Params, Conn]),
case Conn of
null -> try mysql:start_link(Conn_Params) of
{ok, NewConn} ->
lager:info("~p:sql_query_priv Connection to DB Restored", [?MODULE]),
try mysql:query(NewConn, SQL, Params) of
ok -> {ok, NewConn, []};
{ok, _Columns, Results} -> {ok, NewConn, Results};
{error, Reason} ->
lager:error("~p:sql_query_priv Connection To DB Failed, Reason: ~p~n", [?MODULE, {error, Reason}]),
exit(NewConn, normal),
{error, null, Reason}
catch
Exception:Reason ->
lager:error("~p:sql_query_priv Connection To DB Failed, Exception:~p Reason: ~p~n", [?MODULE, Exception, Reason]),
{error, null, {Exception, Reason}}
end;
{error, Reason} ->
lager:error("~p:sql_query_priv Connection To DB Failed, Reason: ~p~n", [?MODULE, {error, Reason}]),
{error, Conn, Reason}
catch
Exception:Reason ->
lager:error("~p:sql_query_priv Connection To DB Failed, Exception:~p Reason: ~p~n", [?MODULE, Exception, Reason]),
{error, Conn, {Exception, Reason}}
end;
Conn -> try mysql:query(Conn, SQL, Params) of
ok -> {ok, Conn, []};
{ok, _Columns, Results} -> {ok, Conn, Results};
{error, Reason} ->
try exit(Conn, normal) of
_Any -> ok
catch
_E:_R -> ok
end,
lager:error("~p:sql_query_priv Connection To DB Failed, Reason: ~p~n", [?MODULE, {error, Reason}]),
{error, null, Reason}
catch
Exception:Reason ->
try exit(Conn, normal) of
_Any -> ok
catch
_E:_R -> ok
end,
lager:error("~p:sql_query_priv Connection To DB Failed, Exception:~p Reason: ~p~n", [?MODULE, Exception, Reason]),
{error, null, {Exception, Reason}}
end
end.
``` | According to the [relevant documentation](http://erlang.org/doc/man/odbc.html#connect-2), an `odbc` connection is private to the `Genserver` process that created the connection.
>
> Opens a connection to the database. The connection is associated with
> the process that created it and can only be accessed through it. This
> function may spawn new processes to handle the connection. These
> processes will terminate if the process that created the connection
> dies or if you call disconnect/1.
>
>
>
You can compare this to `ETS` tables that can be set to `private`, except that in the case of `ETS` tables you can make them `public`. This is not possible with `odbc` connections, as such you should move your code inside the `Genserver` |
65,463,442 | I am coding a solution to the LeetCode problem "Odd Even Linked List" which can be read [here](https://leetcode.com/problems/odd-even-linked-list/).
My code is failing the test case with the error
```
================================================================
==31==ERROR: AddressSanitizer: heap-use-after-free on address 0x6020000000d8 at pc 0x0000003d7f1d bp 0x7fff37cf9640 sp 0x7fff37cf9638
READ of size 8 at 0x6020000000d8 thread T0
```
However, when I run the code in Visual Studio to diagnose the error, everything works. The solution for LeetCode is here:
```
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (!head){
return head;
}
ListNode* odd_head = head;
ListNode* even_head = odd_head->next;
if (!even_head){
return head;
}
ListNode* last_odd = odd_head;
ListNode* last_even = even_head;
ListNode* next_node = even_head->next;
bool flag = true;
while(true){
if (!next_node){
break;
}
if (flag){
last_odd -> next = next_node;
last_odd = next_node;
} else {
last_even -> next = next_node;
last_even = next_node;
}
flag = !flag;
next_node = (next_node->next);
}
last_odd->next = even_head;
return odd_head;
}
};
```
The code I am using to test the above is here:
```
#include "oddevenlinkedlist.h"
#include <iostream>
int main() {
ListNode* l1 = new ListNode(1);
ListNode* l2 = new ListNode(2);
l1->next = l2;
ListNode* l3 = new ListNode(3);
l2->next = l3;
ListNode* l4 = new ListNode(4);
l3->next = l4;
ListNode* l5 = new ListNode(5);
l4->next = l5;
Solution solution{};
ListNode* result = solution.oddEvenList(l1);
ListNode* next_node = result;
for (int i = 0; i < 5; ++i) {
std::cout << next_node->val << " ";
next_node = next_node->next;
}
delete l1;
delete l2;
delete l3;
delete l4;
delete l5;
return 0;
}
```
If you wish to test this, you will want the definition of a `ListNode` which is here:
```
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
```
Because the code works on my compiler, I am having trouble diagnosing the error. While of course I hope someone can identify the error, my question is this: **why is MSVS not catching the "heap-use-after-free" error?** | 2020/12/27 | [
"https://Stackoverflow.com/questions/65463442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14091616/"
] | ### Underlying Problem
At least from the looks of things, the problem is that you're failing to terminate your linked list correctly.
You're starting with a single linked list, and separating it into odd and even pieces just fine.
Then at the end, you (correctly) concatenate the `evens` list to the end of the `odds` list.
But then you missed one point: the last node in the `evens` list (at least potentially) has a non-null `next` pointer. Specifically, if the last element of the list was an odd element, that last even element will still have a pointer to the last odd element.
So for a 5 element list you'll get something like this:
[](https://i.stack.imgur.com/3BxSU.png)
Obviously, when you put the two pieces together, after the `last_odd->next = even_head;`, you need to add something like `last_even->next = nullptr;` so the concatenated list will be terminated.
### The Difference
In the code you've shown above, you start by allocating five nodes, and then finish by deleting exactly the same five nodes, ignoring the structure of the linked list.
But the online judge apparently walks through the linked list, and deletes nodes as it gets to them in the linked list. So, when it walks through the linked list you returned, after it gets to the last node, it follows the non-null next pointer to the last `odd` node, and tries to delete it--but since it's already been deleted, an error is generated. | Most things that you can do wrong in a C++ program fall into the category of [undefined behaviour](https://en.cppreference.com/w/cpp/language/ub). Using memory after is has been freed, dereferencing a null pointer, reading an uninitialised variable, reading or writing beyond the bounds of an array, all of these invoke undefined behaviour.
Undefined behaviour means that the C++ standard does not require any particular behaviour from an affected program. Producing an error message, throwing an exception, working apparently normally and crashing are all permitted behaviours (as is anything else). So it's not wrong that MSVS did not produce any kind of error.
Beginners especially sometimes have a hard time with undefined behaviour, but when they do its a philosophical problem, the concept itself is quite simple.
The reason that C++ has the concept of undefined behaviour is also simple. Checking for errors takes time. Code that detects errors will run slower than code that doesn't even if the errors don't occur. Undefined behaviour permits compiler writers not to check for errors and therefore to produce faster code.
Now checking for errors is obviously useful, especially for debugging. So most compilers have various options whereby some errors are detected. It makes sense that a compiler running as an online judge would have the error detection turned up as high as possible. |
13,285,664 | We are having a little problem with a functional test with casper.js.
We request the same resource twice, first with the GET and then with POST method.
Now when waiting for the second resource (POST) it matches the first resource and directly goes to the "then" function.
We would like to be able to check for the HTTP method in the "test" function, that way we can identify the resource properly. For now we use the status code (res.status), but that doesn't solve our problem fully, we really need the http method.
```
// create new email
this.click(xPath('//div[@id="tab-content"]//a[@class="button create"]'));
// GET
this.waitForResource('/some/resource',
function then() {
this.test.assertExists(xPath('//form[@id="email_edit_form"]'), 'Email edit form is there');
this.fill('form#email_edit_form', {
'email_entity[email]': 'test.bruce@im.com',
'email_entity[isMain]': 1
}, true);
// POST
this.waitForResource(
function test(res) {
return res.url.search('/some/resource') !== -1 && res.status === 201;
},
function then() {
this.test.assert(true, 'Email creation worked.');
},
function timeout() {
this.test.fail('Email creation did not work.');
}
);
},
function timeout() {
this.test.fail('Email adress creation form has not been loaded');
});
```
Or maybe there is a better way to test this scenario? Although since this is a functional test we need to keep all those steps in one test. | 2012/11/08 | [
"https://Stackoverflow.com/questions/13285664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1808618/"
] | You must place the code in a function
```
$(document).ready(function() {
$('.login-popover').popover({
placement: 'bottom',
title: 'Sign in to the website builder',
content: 'testing 123',
trigger: 'click'
});
});
```
or
```
$(function () {
$(".login-popover").popover();
});
```
then it works. But why are you defining the popover settings twice (both in script and as data attributes)?
**Eureka!**
It seems that you have changed the default styling in bootstrap.css. The content of the popover IS actually shown, in a `<p>`, but you have
```
.btn-group {
font-size: 0;
white-space: nowrap;
}
```
obvious, by changing font-size: 0; the content will be visible (tested in chrome inspector) Add to your CSS
```
.btn-group {
font-size: 12px; /*or whatever size */
}
``` | As I checked the current version (v2.2.2) this bug had been resolved. Please download the latest one. |
39,189,400 | I wondering if anyone has a clever way of ensuring the last element of an array is selected during a array\_slice operation. The first element is easily selected, but if an offset is applied you cannot be sure the last element is selected unless you add an additional `if else` logic after the loop.
For example here is the basis of the problem without the `if else statement`.
```
$latlong[] = [1,2];
$latlong[] = [3,4];
$latlong[] = [5,6];
$latlong[] = [7,8];
$latlong[] = [9,10];
$latlong[] = [11,12];
$latlong[] = [19,110];
$latlong[] = [21,132];
$off = 3;
for ($i=0; $i < count($latlong); $i+=$off){
print_r( array_slice($latlong, $i,1));
}
```
In the example here you will see that only the pairs `[1,2], [7,8], [19,110]` are selected and the last element `[21,132]` would need to be included some other way.
The relevance is to ensure only a certain number of 'waypoints' are selected to stay within a limit, but that the first and last elements are included in that limit. | 2016/08/28 | [
"https://Stackoverflow.com/questions/39189400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6743474/"
] | For your example, this code works:
```
<?php
$latlong[] = [1,2];
$latlong[] = [3,4];
$latlong[] = [5,6];
$latlong[] = [7,8];
$latlong[] = [9,10];
$latlong[] = [11,12];
$latlong[] = [19,110];
$latlong[] = [21,132];
$off = 3;
for ($i=0; $i < count($latlong); $i+=$off){
if(count($latlong) - $i <= $off){
$last_element = end($latlong);
}
print_r( array_slice($latlong, $i,1));
}
print_r($last_element);
?>
```
The ***if*** statement, in that case, verifies if you set any offset on your code, **$last\_element** variable always contains the last element of your array. | I'm sure there are other ways like calculating the modulus but this works:
```
for ($i=0; $i < count($latlong); $i+=$off){
$data[] = array_slice($latlong, $i,1);
$last = $i;
}
var_dump(array_slice($latlong, $last+1));
```
If I add 2 other elements to the array, it will be empty. Also, you might want to take a look at a php variant of pythons xrange().
```
function xrange($start, $end, $step = 1){
for ($i = $start; $i <= $end; $i += $step){
yield $i;
}
}
foreach(xrange(0, count($latlong), $off) as $last){
$data[] = array_slice($latlong, $last,1);
}
var_dump(array_slice($latlong, $last+1));
``` |
41,147,768 | I tried to find the solution for the below problem, but none of them worked for me. I am developing **Angular + Spring Boot** application using **MySQL + flyway**. Please guide whats going wrong here.
```
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally : -1729781252
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:305) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1124) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1113) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at com.boot.App.main(App.java:9) [classes/:na]
Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally : -1729781252
at org.flywaydb.core.Flyway.doValidate(Flyway.java:1108) ~[flyway-core-3.2.1.jar:na]
at org.flywaydb.core.Flyway.access$300(Flyway.java:62) ~[flyway-core-3.2.1.jar:na]
at org.flywaydb.core.Flyway$1.execute(Flyway.java:1012) ~[flyway-core-3.2.1.jar:na]
at org.flywaydb.core.Flyway$1.execute(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
at org.flywaydb.core.Flyway.execute(Flyway.java:1418) ~[flyway-core-3.2.1.jar:na]
at org.flywaydb.core.Flyway.migrate(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:66) ~[spring-boot-autoconfigure-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
... 18 common frames omitted
```
**application.properties**
```
logging.level.org.springframework.web=DEBUG
server.port=8080
spring.h2.console.enabled=true
spring.h2.console.path=/h2
## For H2 DB
#spring.datasource.url=jdbc:h2:file:~/dasboot
#spring.datasource.username=sa
#spring.datasource.password=
#spring.datasource.driver-class-name=org.h2.Driver
## For MYSQL DB
spring.datasource.url=jdbc:mysql://localhost:3306/dasboot
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-active=10
spring.datasource.max-idle=8
spring.datasource.max-wait=10000
spring.datasource.min-evictable-idle-time-millis=1000
spring.datasource.min-idle=8
spring.datasource.time-between-eviction-runs-millis=1
flyway.baseline-on-migrate=true
spring.jpa.hibernate.ddl-auto=false;
#datasource.flyway.url=jdbc:h2:file:~/dasboot
#datasource.flyway.username=sa
#datasource.flyway.password=
#datasource.flyway.driver-class-name=org.h2.Driver
datasource.flyway.url=jdbc:mysql://localhost:3306/dasboot
datasource.flyway.username=root
datasource.flyway.password=root
datasource.flyway.driver-class-name=com.mysql.jdbc.Driver
```
**pom.xml**
```
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<name>das-boot</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
```
**V2\_\_create\_shipwreck.sql**
```
-- For H2 DB
--CREATE TABLE SHIPWRECK(
-- ID INT AUTO_INCREMENT,
-- NAME VARCHAR(255),
-- DESCRIPTION VARCHAR(2000),
-- CONDITION VARCHAR(255),
-- DEPTH INT,
-- LATITUDE DOUBLE,
-- LONGITUDE DOUBLE,
-- YEAR_DISCOVERED INT
--);
CREATE TABLE `dasboot`.`shipwreck` (
`ID` INT NOT NULL AUTO_INCREMENT,
`NAME` VARCHAR(255) NULL,
`DESCRIPTION` VARCHAR(2000) NULL,
`CONDITION` VARCHAR(255) NULL,
`DEPTH` INT NULL,
`LATITUDE` DOUBLE NULL,
`LONGITUDE` DOUBLE NULL,
`YEAR_DISCOVERED` INT NULL,
PRIMARY KEY (`ID`));
```
[](https://i.stack.imgur.com/QXWut.png) | 2016/12/14 | [
"https://Stackoverflow.com/questions/41147768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I had the same issue and I believe this occurred because of checksum between linux and windows (also mac).
you can `use repair()` command in flyway.
```
flyway.repair();
```
Be careful , if you are in production environment , make sure that you did not change the migration SQL file; because when you run the `flyway.repair();` it means you saying to flyway that your are sure about the migration version and their checksum and then the flyway repair them ! | If you have your problem in production, you must have **V2\_\_create\_shipwreck.sql** identically to the one you have in your latest version where it has not been modified.
Then the checksum will be correct again |
2,064,282 | I have the following method (below), as you can see it serializes an object to an XML file. The main problem I am having is I want to get the function to overwrite a file if it exists.
I know I could delete the file first if it does exist, but this would also mean that I might induce some error drag into my application. So I want it an all or nothing, overwrite method...
Here is the function, any ideas on how this can be accomplished?
```
/// <summary>
/// Serializes an object to an xml file.
/// </summary>
/// <param name="obj">
/// The object to serialize.
/// </param>
/// <param name="type">
/// The class type of the object being passed.
/// </param>
/// <param name="fileName">
/// The filename where the object should be saved to.
/// </param>
/// <param name="xsltPath">
/// Pass a null if not required.
/// </param>
public static void SerializeToXmlFile(object obj, Type type, string fileName, string xsltPath )
{
var ns = new XmlSerializerNamespaces();
ns.Add(String.Empty, String.Empty);
var serializer = new XmlSerializer(type);
var settings = new XmlWriterSettings {Indent = true, IndentChars = "\t"};
using (var w = XmlWriter.Create(fileName,settings))
{
if (!String.IsNullOrEmpty(xsltPath))
{
w.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + xsltPath + "\"");
}
serializer.Serialize(w, obj, ns);
}
}
``` | 2010/01/14 | [
"https://Stackoverflow.com/questions/2064282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41543/"
] | The FileStream and XMLWriter should be placed in a using block
```
using (FileStream fs = File.Create(filename))
using (var w = XmlWriter.Create(fs, settings))
{
// your code
}
```
I believe that using the code below will fail to release the file stream. So if you run the code twice in one session it will fail
```
using (var w = XmlWriter.Create(File.Create(filename), settings))
``` | Make a Backup of the Destination file if exist, if an error occurred, write back the file. |
171,302 | I am trying to understand the principles of asymmetric encryption, and have read the following in a book:
>
> One key is completely public and can be read and used by everyone. The
> other part is private and should never be shared with someone else.
> When you encrypt something with the public key, it can be decrypted by
> using the private key, and vice versa.
>
>
>
Looks like the public key is not secret. But if I encrypt with the private key, someone can decrypt with the public key which is easily accessible. Where's the logic in that? | 2017/10/15 | [
"https://security.stackexchange.com/questions/171302",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/161270/"
] | **The usage of asymmetric keys** is as follows:
* Encryption is done using the *public key*
* Signing is done using the *private key*
**Encryption:**
* The data is encrypted using the *public key*
* The encrypted data is decrypted using the *private key*
+ Only the owner of the private key can read the encrypted message
**Signing**
* The HASH of the data is encrypted using the *private key*
* The receiver use the *public key* on the encrypted hash data, and compare it to the the HASH of the data he calculate himself
+ Only the owner of the private key can sign the message | Yes it can be done. This will be useful in the case when you are trying to verify that the person (Bob) has encrypted the file by himself and not by any other person (Eve), as it will be only decrypted by the bob's public key. |
54,958 | At the end of my assault on the Cerberus Headquarters I unfortunately didn't meet the Illusive Man in person so that I could put a bullet in his brain. He left his assassin Kai Leng though to deal with me.

I have to say, compared to him the Reapers are just pushovers, I'm having a hard time even just surviving long enough to scratch his shields. His shields can take an enormous amount of punishment, and when I finally got them down once his health bar didn't seem to move at all. Shortly afterwards he had his shields up again, came to close to me and just killed me.
So, how do I defeat Kai Leng? | 2012/03/10 | [
"https://gaming.stackexchange.com/questions/54958",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/4103/"
] | An important thing to note is that during the melee cutscenes, you should be pressing the melee button to fight back. It took a lot of searching to find this, considering I instinctively tried every button besides the melee button because intuitively it does not come to mind to use the melee button (which is 'F' on the computer). | Well, as Soldier the Geth Shotgun and Garrus wih Widow worked for me. After second recharge, got him! |
18,721,968 | I've recently been looking into the networking aspect of the iOS platform. And I want to incorporate JSON feeds into my application. So I have few questions:
1. What's the best built-in class to parse JSON objects and retrieve them ?
2. When the JSON data is downloaded, how do I store and use it ?
Do I use `NSURL` and `NSURLRequest`?
I'm new to iOS development please help me. Thank You. | 2013/09/10 | [
"https://Stackoverflow.com/questions/18721968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648067/"
] | I suggest you to use the `AFNetworking` framework
you can donwload it [here](https://github.com/AFNetworking/AFNetworking)
Here is the documentation about the JSON requests :
<http://cocoadocs.org/docsets/AFNetworking/1.3.2/Classes/AFJSONRequestOperation.html>
You can also have a look [here](http://samwize.com/2012/10/25/simple-get-post-afnetworking/) for an example of how to use it. | For JSON posts in my app I use SBJson. This method uses an NSURLConnection along with a HTTP Post request. The return data, when parsed, will come in the form of keys and strings in an NSDictionary. (jsonData is an NSDictionary established somewhere elese) (Apparently NSJSONSerialization does the same thing though)
```
(void) doJson:(NSString *)post {
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, FALSE);
NSURL *url=[NSURL URLWithString:@"youraddress"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
// [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
SBJsonParser *jsonParser = [SBJsonParser new];
jsonData = [jsonParser objectWithString:responseData error:nil];
NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];
``` |
1,633,213 | What could be the optimum programming languages (Perl, PHP, Java, Python or something else) to implement server (multi-threaded?) using tcp/ip socket serving like 1000's of clients with the streaming data? | 2009/10/27 | [
"https://Stackoverflow.com/questions/1633213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197473/"
] | Python with Twisted Framework
www.twistedmatrix.com
Java with XSocket or Apache Mina Frameworks (which Red5 Flash/video streaming media sever based on)
mina.apache.org
xsocket.sourceforge.net
They all are multithreaded , easy and very powerful. | Erlang of course :-) But then again, your requirements are not clear ;-)
It was designed from ground up to handle multi-threaded networking applications. It's origin comes from Ericsson: they use Erlang in (some of) their networking products. |
3,813,291 | I'm solving this exercise in Klenke's book:
Let $X\_1,X\_2, \dots $ be i.i.d. nonnegative random variables. By virtue of the Borel-Cantelli lemma, show that for every $c \in(0,1)$,
$$\sum\_{n=1}^\infty e^{X\_n} c^n \begin{cases}
< \infty \textrm{ a.s.} & \textrm{if } \mathbb E[X\_1] < \infty; \\
= \infty \textrm{ a.s.} & \textrm{if } \mathbb E[X\_1] = \infty
\end{cases}$$
There are different ways to prove the statement using the Borel-Cantelli lemma (here's a thread with different answers: [link](https://math.stackexchange.com/questions/3003869/iid-random-variables-x-n-have-sum-ex-n-cn-infty-a-s))
However I wanted to try a different approach. I defined $S\_k := \sum\_{n=1}^k e^{X\_n} c^n $ which given the nonnegativity of its elements converges from below to $S:= \sum\_{n=1}^\infty e^{X\_n} c^n $ . We can prove using the 0-1 Law that $S=a$ almost surely where $ a \in [-\infty, \infty]$ is a constant. And now applying the monotone convergence theorem and taking the expectations delivers:
$$
a=\mathbb{E}[S]=\sum\_{n=1}^\infty \mathbb{E}[e^{X\_n}] c^n =\mathbb{E}[e^{X\_1}] \sum\_{n=1}^\infty c^n
$$
Which means that $a$ is finite iff $\mathbb{E}[e^{X\_1}] < \infty$. This however is not equivalent to the statement in the exercise. Does anyone see where the argument fails? | 2020/09/03 | [
"https://math.stackexchange.com/questions/3813291",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/573277/"
] | **Hint:**
After cheating with WA, here is the solution: notice that "by magic",
$$\int\frac{x^2(1-\log x)}{(\log x)^4-x^4}dx
=\int\frac{\dfrac{1-\log x}{x^2}}{\dfrac{(\log x)^4}{x^4}-1}dx
=\int\frac1{\dfrac{(\log x)^4}{x^4}-1}d\frac{\log x}x.$$
Now
$$\frac1{u^4-1}=\frac1{4 (u-1)} -\frac 1{4 (1 + u)} - \frac1{2 (1 + u^2)}$$ which is easy to integrate. | Let $u=\frac{\ln x }{x}$ then $du = \frac{1 - \ln x }{x^2} dx$ so $dx =\frac{x^2 du}{1-\ln x } $
$$\int \frac{x^2 (1-\ln x )}{x^4 (u^4-1)}\frac{x^2 du}{1-\ln x } $$ |
2,855,483 | >
> Let $f:\mathbb{R}\to \mathbb{R}$ be continuous at $x$ for every $x\in I$ where $I\subset \mathbb R$ could be arbitrary. Does there always exist a function $F:\mathbb{R}\to \mathbb{R}$ differentiable on $I$ and $F'(x) = f(x)$ for every $x \in I$?
>
>
>
The definition of a primitive is naturally defined on an interval. A mathematical curiosity is to understand the difficulties that can be encountered when trying to define this notion on any part of $\mathbb{R}$.
A first difficulty is to try to find a good definition of the notion of a primitive on any part of $\mathbb{R}$. That was the purpose of this thread
"[Correct definition of antiderivative function](https://math.stackexchange.com/questions/2854891/correct-definition-of-antiderivative-function/2855112#2855112)."
If we ask $F$ to be differentiable on an open set $J$ containing $I$, the thread "[Existence of an antiderivative for a continuous function on an arbitrary subset of $\mathbb{R}$](https://math.stackexchange.com/questions/2853575/existence-of-an-antiderivative-for-a-continuous-function-on-an-arbitrary-subset)" gives a counterexample to the question.
If $I$ is an interval, the answer to the question is positive. If $I$ is an open set, the answer to the question is also positive. (see comment) | 2018/07/18 | [
"https://math.stackexchange.com/questions/2855483",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/417942/"
] | Please do not upvote this answer! It's just a detailed version of an answer that appeared on [MO](https://mathoverflow.net/questions/306472/existence-of-an-antiderivative-function-on-an-arbitrary-subset-of-mathbbr/306502#306502); if you feel the need to upvote something please upvote that answer instead.
$\newcommand\ui[2]{\overline{\int\_{#1}^{#2}}}$
The obvious thing to try is $$F(x)=\int\_0^x f(t)\,dt.$$Except "trying" that is stupid, since it's clear the integral need not exist. I thought about replacing $f$ by some nicer function $g$ such that $g(x)=f(x)$ if $f$ is continuous at $x$, as in a comment to the question on MO; couldn't make that work. The lightbulb Pietor Majer had is this: Use the [upper Darboux integral](https://en.wikipedia.org/wiki/Darboux_integral#Darboux_integrals), which we will denote $$\ui ab f(x)\,dx.$$
The beauty of this is that if $f:[a,b]\to\Bbb R$ is any function whatever then $\ui ab f$ exists, at least as an element of $[-\infty,\infty]$, and if $f$ is any bounded function then $\ui ab f\in\Bbb R$.
Of course the upper Darboux integral probably doesn't really deserve to be called an *integral*, since it's not linear. But it does retain a shred of linearity:
>
>
> >
> > **Lemma.** If $a<b<c$ and $f:[a,c]\to\Bbb R$ is bounded then $\ui acf=\ui ab f+\ui bc f$.
> >
> >
> >
>
>
>
Proof: Exercise. Easy or not, depending on who you are. If you get stuck you should be able to extract a proof from a proof that $\int\_a^c=\int\_a^b+\int\_b^c$ for the Riemann integral. Note that of course you need to find a proof in a context where the author defined the RIemann integral in terms of "upper and lower (Darboux) sums" instead of using Riemann sums. I *suspect* the proof in baby Rudin will qualify, not sure since I don't have a copy.
It follows that the upper Darboux integral satisfies a version of FTC sufficient for our purposes:
>
>
> >
> > **Lemma (UDI-FTC).** Suppose $f:(a.b)\to\Bbb R$ is bounded and $p\in(a,b)$. Define $F:(a,b)\to\Bbb R$ by $F(x)=\ui pxf(t)\,dt$ (with the convention that $\ui\beta\alpha=-\ui\alpha\beta$). If $f$ is continuous at $x\in(a,b)$ then $F$ is differentiable at $x$ and $F'(x)=f(x)$.
> >
> >
> >
>
>
>
Proof: **Hint:** The previous lemma shows that $$\frac{F(x+h)-F(x)}{h}
=\frac1h\ui x{x+h}f(t)\,dt;$$if $h$ is small then $f(t)$ is close to $f(x)$ on $[x,x+h]$ (or $[x+h,x]$, whichever makes sense).
If that's not enough note that $F'(x)=f(x)$ is explained in somewhat more detail in the answer on MO.
Of course it's not clear how that helps, since $f$ is not bounded. But it's clear that $f$ is "locally bounded" on a neighborhood of $I$, and that that's enough. (This is the part where I'm adding details to the answer on MO, if anyone was wondering; at least one other person and I were both initially confused about this.)
>
>
> >
> > **Definition** If $f:\Bbb R\to\Bbb R$ and $S\subset \Bbb R$ then $f$ is *locally bounded on $S$* if for every $x\in S$ there exists $\delta>0$ such that $f$ is bounded on $(x-\delta,x+\delta)$.
> >
> >
> > **Triviality** If $f$ is locally bounded on $S$ and $K\subset S$ is compact then $f$ is bounded on $K$.
> >
> >
> > **Corollary (UDI-FTC v2)** The UDI-FTC above holds if we assume just that $f$ is locally bounded on $(a,b)$.
> >
> >
> >
>
>
>
Proof: Given $x\in(a,b)$, choose $c,d$ with $a<c<d<b$ and $x,p\in(c,d)$. Since $f$ is bounded on $[c,d]$ the definition of $F(s)$ makes sense for $s\in(c,d)$, and the proof of the original UDI-FTC shows that $F'(x)=f(x)$.
And now we're in business:
>
>
> >
> > **Theorem.** Suppose that $f:\Bbb R\to\Bbb R$, $I\subset \Bbb R$, and $f$ is continuous at $x$ for every $x\in I$. There exists $F:\Bbb R\to\Bbb R$ such that $F$ is differentiable at $x$ and $F'(x)=f(x)$ for every $x\in I$.
> >
> >
> >
>
>
>
Proof. If $x\in I$ there exists an open interval $I\_x$ such that $x\in I\_x$ and $f$ is bounded on $I\_x$. Let $$V=\bigcup\_{x\in I}I\_x.$$So $V$ is open, $I\subset V$, and $f$ is locally bounded on $V$.
Say $V=\bigcup\_kJ\_k$, where the $J\_k$ are the connected components of $V$. UID-FTC v2 above shows that for each $k$ there exists $F\_k:J\_k\to\Bbb R$ such that $$F\_k'(x)=f(x)\quad(x\in I\cap J\_k).$$Define $F:\Bbb R\to\Bbb R$ by $$F(x)=\begin{cases}F\_k(x),&(x\in J\_k),
\\0,&(x\notin V).\end{cases}$$ | A few comments: If the answer is yes I have no idea how to prove it.
**Edit:** Maybe it's not hopeless. Given $f:\Bbb R\to\Bbb R$ the set of $x$ such that $f$ is continuous at $x$ is a $G\_\delta$. So we can assume that $I$ is a $G\_\delta$. It's certainly true if $I$ is open, so perhaps...
Of course the answer would be no if you asked for $F$ to be differentiable on $\Bbb R$, for example $I=(-\infty,0)\cup(0,\infty)$, $f(t)=-1$ for $t<0$, $f(t)=1$ for $t>0$.
Otoh if the answer is no a counterexample can't be very simple. Because the answer is yes if $I$ is closed (in that case there exists $g\in C(\Bbb R)$ which agrees with $f$ on $I$), and the answer is yes if $f$ is locally Lebesgue integrable, in which case the indefinite integral works. |
11,518,631 | I am trying to push values onto an array like so:
```
$scoreValues[$i][] = $percent ;
$scoreValues[$i][] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ;
```
I basically want to link together the $percent with the string, so I get an output like:
```
array (0 > array('46.5', '<span etc etc')
```
I then plan to sort by the percent sub-array so I have the highest scoring strings at the top. | 2012/07/17 | [
"https://Stackoverflow.com/questions/11518631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1320129/"
] | Simplest way would be to use two arrays :
```
$percents[$i] = $percent;
$scores[$i] = "<span....>");
```
Or one array, but indexed like this
```
$data = new arrray('percents' => array(), 'scores' => array());
$data['percents'][$i] = $percent;
$data['scores'][$i] = "<span....>");
```
Once this is done, you then sort your arrays using [`array_multisort`](http://php.net/manual/fr/function.array-multisort.php) :
```
array_multisort(
$data['percents'], SORT_DESC,
$data['scores']);
``` | Try this:
```
$val = array(
'percent' => $percent,
'html' => '<span id="item' . $i .
'" class="suggestElement" data-entityid="'.$row['id'].
'" data-match="'.$percent.'">'.rawurldecode($row['name']).
'</span>'
);
// This just pushes it onto the end of the array
$scoreValues[] = $val ;
// Or you can insert it at an explicit location
//$scoreValues[$i] = $val;
``` |
277,510 | Considering the full list of PDC videos published [here](http://channel9.msdn.com/posts/pdc2008/RSS/Default.aspx) what are, in your opinion, the best session to download and see, considering their relevance to your work, technology and so on? Pleas, one session per answer (exception only for the sessions split in two parts) and please vote it so to move the best ones to the top. | 2008/11/10 | [
"https://Stackoverflow.com/questions/277510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11673/"
] | I would have to say that my favorite session was the "future of C#" video, very nice to be able to see what is coming in the future for C# and the .NET framework. | Scott Hanselmans
**Microsoft .NET Framework: Overview and Applications for Babies** <http://channel9.msdn.com/pdc2008/TL49/> |
6,965,932 | Im new to Java and JSP. Pls help me in resolving this problem.
I have two files Page1.jsp and Page2.jsp under WebContent/web/jsp directory. When I click a hyperlink (using a href tag) in Page1.jsp, it should navigate to Page2.jsp.
Here is the code below written in Page1.jsp:
```
Navigate to Page2 <a href="../jsp/Page2.jsp">here</a>
```
I used below path also:
```
Navigate to Page2 <a href="../web/jsp/Page2.jsp">here</a>
```
Both the times, I am getting the error `"The requested resource (/Sample/web/jsp/Page2.jsp) is not available".`
'Sample' is my project name specified in web.xml. And I am using Tomcat 6.0 server.
Please help me on this. | 2011/08/06 | [
"https://Stackoverflow.com/questions/6965932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/881662/"
] | Just set font-size to 1px; IE is limiting height of this div to font size. | It's really hard to tell without the context... aside from resetting the padding to 0 it could have to do with other elements (probably above). Especially if they're floated. May also try clear:both; Also make sure it doesn't have display:inline; anywhere... It's block by default, and should be block.
It's really poking in the dark without the context. |
1,278,290 | It's come to my attention that I don't actually understand what a square root really is (the operation). The only way I know of to take square roots (or nth root, for that matter) it to know the answer! Obviously square root can be rewritten as $x^{1/2}$ , but how does one actually multiply something by itself half a time?
How do calculators perform the operation? | 2015/05/12 | [
"https://math.stackexchange.com/questions/1278290",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/233527/"
] | >
> *How does one actually multiply something by itself half a time ?*
>
>
>
Zen Buddhism has a similar question: *What is the sound of one hand clapping ?* When my father told me, in passing, one day, that $\sqrt x=x^{1/2}$ I had pretty much the same reaction. But then I started thinking to myself: What is the fundamental property of an n-th root, $\sqrt[\Large^n]x$ ? It is basically the number which, when multiplied *n* times with itself, yields the desired value. At the same time, $x^{1/n}$ multiplied *n* times with itself, also yields the same value, since $\big(x^a\big)^b=x^{ab}$. | Lazy people should use be careful to avoid having to perform a division in each step of Newton's method. They should consider the equation:
$$\frac{1}{x^2}- \frac{1}{y} = 0$$
This then yields the recursion:
$$x\_{n+1} = \frac{x\_n}{2}\left(3-\frac{x\_n^2}{y}\right)$$
Here, you only have division by fixed numbers in each step. |
28,089,599 | Default build openjdk 7,target version is:
>
> Target Build Versions:
>
>
> JDK\_VERSION = 1.7.0
>
>
> MILESTONE = internal
>
>
> RELEASE = 1.7.0-internal
>
>
> FULL\_VERSION = 1.7.0-internal-senrsl\_2015\_01\_22\_20\_38-b00
>
>
> BUILD\_NUMBER = b00
>
>
>
but I will build version name this:
>
> RELEASE = 1.7.0
>
>
>
or this:
>
> RELEASE = 1.7.0\_xx
>
>
>
I try
>
> export MILESTONE=''
>
>
>
or
>
> export MILESTONE=
>
>
>
or
>
> export MILESTONE=null
>
>
>
or
>
> export MILESTONE=""
>
>
>
but all can't generate version name : RELEASE = 1.7.0
what I will to do? | 2015/01/22 | [
"https://Stackoverflow.com/questions/28089599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3655363/"
] | It's actually a little bit complicated, you have to get an array with the numbers from the `.sum` elements, then find the highest number, then remove all those from the array, then find the next highest number, and finally target all elements containing those two numbers.
In code, that would look like
```
var sum = $('.sum');
var arr = sum.map(function(_,x) { return +$(x).text() }).get();
var max = Math.max.apply( Math, arr );
var out = arr.filter(function(x) { return x != max });
var nxt = Math.max.apply( Math, out );
sum.filter(function() {
var numb = +$(this).text();
return numb == max || numb == nxt;
}).css('font-weight', 'bold');
```
[**FIDDLE**](http://jsfiddle.net/odftqhd3/10/) | Ok this take me a while. To find max number was kinda easy using the following code:
```
//declare a variable for max taking the value of first td
var max = $("#table-results tr:last td:eq(1)").text();
//iterate through the last row of the table
$("#table-results tr:last td").each(function () {
//get the value of each td
var tdVal = ~~this.innerHTML;
//compare the value with max value
if (tdVal > max) {
//change the font-weight when is max
$(this).css("font-weight", "bold");
}
});
```
But the tricky part to find second max. I used code from @Jack answer from this question [stack](https://stackoverflow.com/questions/17039770/how-do-i-get-the-second-largest-element-from-an-array-in-javascript/17040125#17040125) and ended up to this result:
```js
//declare a variable for max taking the value of first td
var max = $("#table-results tr:last td:eq(1)").text();
var arr = [];
//iterate through the last row of the table and keep the values in an array
$("#table-results tr:last td").each(function() {
arr.push(~~this.innerHTML);
});
//get the second max from the array
var secMax = secondMax(arr);
//iterate through the last row of the table
$("#table-results tr:last td").each(function() {
//get the value of each td
var tdVal = ~~this.innerHTML;
//compare the value with max value
if (tdVal > max) {
//change the font-weight when is max
$(this).css("font-weight", "bold");
}
//comapre the second max value with the current one
if (tdVal == secMax) {
$(this).css("font-weight", "bold");
}
});
function secondMax(arr) {
///with this function i find the second max value of the array
biggest = -Infinity,
next_biggest = -Infinity;
for (var i = 0, n = arr.length; i < n; ++i) {
var nr = +arr[i]; // convert to number first
if (nr > biggest) {
next_biggest = biggest; // save previous biggest value
biggest = nr;
} else if (nr < biggest && nr > next_biggest) {
next_biggest = nr; // new second biggest value
}
}
return next_biggest;
}
```
```css
.text-bold {
text-weight: 700;
}
table {
margin: 16px 0;
color: #333;
border-width: 1px;
border-color: #666;
border-collapse: collapse;
}
table th {
border-width: 1px;
padding: 4px;
border-style: solid;
border-color: #666;
background-color: #FBDD9B;
}
table td {
border-width: 1px;
padding: 4px;
border-style: solid;
border-color: #666;
background-color: #fff;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table-results">
<tr>
<th>Question</th>
<th>inovation</th>
<th>all-round</th>
<th>coordination</th>
<th>keeper</th>
<th>analytic</th>
</tr>
<tr>
<td>I.</td>
<td>D=2</td>
<td>A=1</td>
<td>E=10</td>
<td>C=8</td>
<td>B=4</td>
</tr>
<tr>
<td>II.</td>
<td>A=6</td>
<td>C=1</td>
<td>B=2</td>
<td>D=5</td>
<td>E=1</td>
</tr>
<tr>
<td>III.</td>
<td>E=4</td>
<td>B=1</td>
<td>D=3</td>
<td>A=2</td>
<td>C=7</td>
</tr>
<tr>
<td>Suma</td>
<td class="sum">12</td>
<td class="sum">3</td>
<td class="sum">15</td>
<td class="sum">15</td>
<td class="sum">12</td>
</tr>
</table>
``` |
41,018 | So I've found this command:
```
dd if=/dev/sdx of=/directory/for/image bs=1M
```
But that gives me this error:
```
dd: failed to open ‘directory/for/image’: Is a directory
```
So I found that the directory has to be unmounted. Trying the same command, but changing the directory to my `/home/user` directory got the same error. Well, lucky for me, the original location is an extra partition I use for independent storage between my OSes, so I unmounted it and tried again. This time I got this error:
```
dd: failed to open ‘/directory/for/image’: No such file or directory
```
So that doesn't work either. But it doesn't make sense that it has to be unmounted because the majority of people don't have another partition for storage. I found another post that said you have to be operating from the directory where the .img file is, but I'm trying to read the whole card and write an image of it, so there isn't an image file yet. So I tried one more time, executing the command from within the directory I am writing to and got the same error as I got first:
```
dd: failed to open ‘/directory/for/image’: Is a directory
```
So what the heck is going on and how in the world do you use the `dd` tool?
Ubuntu 15.04
Thanks! | 2016/01/13 | [
"https://raspberrypi.stackexchange.com/questions/41018",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/39783/"
] | Your `of` must be the disk image name you want to give it. So:
`sudo dd bs=1m if=/path/to/sdcard of=/path/to/image/backup.img` | Here are commands that can be used. Make sure you know the actual device name of the SD card. It is /dev/sdc on my system:
```
wget https://downloads.raspberrypi.org/raspbian_latest
unzip raspbian_latest
dd bs=4M if=2015-11-21-raspbian-jessie.img of=/dev/sdc
```
The rasbian\_latest version (2015-11021) will be different when a new raspian is released.
EDIT: As was pointed out, I went the wrong way. Here is the correct command (again with /dev/sdc):
```
dd bs=4M of=sd.img if=/dev/sdc
``` |
68,812,153 | I would like to do the following:
```
from typing import Union, Literal
YES = 1
NO = 0
ValidResponse = Union[Literal[YES], Literal[NO]]
```
Of course, Python won't let me do this because `YES` and `NO` are considered to be variables, not literal numbers.
Obviously I can do `ValidResponse = Union[Literal[1], Literal[0]]`, but as a programmer editing this file later, it seems odd that in order to change what constant `YES` used (for example `YES = 'yes'`), I would need to change it in two different places.
**What's the best way to handle this scenario?** | 2021/08/17 | [
"https://Stackoverflow.com/questions/68812153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5049813/"
] | [The `enum` solution](https://stackoverflow.com/a/68812189/13990016) is often the cleaner solution in these situations, but note that it is *possible* to do this kind of thing with `typing.Literal`. You have to explicitly annotate your variables as being of a "literal" type. The `YesType` and `NoType` aliases that I've introduced aren't strictly necessary, but may be helpful for clarity:
```
from typing import Union, Literal
YesType = Literal[1]
NoType = Literal[0]
YES: YesType = 1
NO: NoType = 0
ValidResponse = Union[YesType, NoType]
``` | You should almost certainly just be using an `enum` instead:
```
import enum
class ValidResponse(enum.Enum):
YES = 1
NO = 0
```
Now you can use `ValidResponse` as an annotation:
```
def foo(response: ValidResponse) -> whatever:
# do something with response
``` |
5,000 | Let's say you are playing a game. Then suddenly, you make a bad move and e.g. blunder material. How should you react afterwards? What mind-set should you have? Can you even benefit from the blunder? | 2014/03/12 | [
"https://chess.stackexchange.com/questions/5000",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/2001/"
] | After a blunder, it helps to ***look objectively at the position*** once again and forget the history. You might have been better or worse; but that doesn't matter now after the blunder. What matters is how you go from here.
There could be many possibilities of salvaging a draw or even snatching a win by making the position very complicated and causing your opponent to blunder (I sometimes jokingly call this a "***counter-blunder***"). The least you want to ensure is to not make it psychologically easy for your opponent to win after your blunder. Make it difficult for the opponent. Play good moves. Do not be gloomy lest you blunder again.
Yes, there are times when you can even benefit from a blunder. A blunder may often give a player a kind of "***license to thrill***"! Now that you've blundered and your game is lost, you've got nothing more to lose! So why not embark on a nice sacrificial attack on the opponent's king (for example) and see if the opponent cracks under pressure? (A friend of mine actually tried this after blundering a piece and he won the game. Too bad I don't have the game). | I'd say play like the computers do, i.e. just look for the best move in the ensuing positions and continue to play tough. A little aggression wouldn't hurt either, as another respondent has indicated. Put the pressure on and give your opponent the chance to blunder in turn. It's happened. Don't by any means just trade away pieces into a losing ending, which I've also seen happen. |
18,273,278 | I have two separate types:
```
public class Person
{
public string Name { get; set; }
public bool IsActive { get; set; }
public Contact ContactDetails { get; set; }
}
public class Contact
{
[RequiredIfActive]
public string Email { get; set; }
}
```
What I need is to perform conditional declarative validation of internal model field, based on some state of the parent model field - in this particular example an `Email` has to be filled, if `IsActive` option is enabled.
I do not want to reorganize these models taxonomy, while in the same time I need to use attribute-based approach. It seems that from within an attribute there is no access to the validation context of the parent model. How to reach or inject it there?
```
public class RequiredIfActiveAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
/* validationContext.ObjectInstance gives access to the current
Contact type, but is there any way of accessing Person type? */
```
**Edit:**
I know how conditional validation can be implemented using Fluent Validation, but I'm NOT asking about that (I don't need support regarding Fluent Validation). I'd like to know however, if exists any way to access parent model from inside `System.ComponentModel.DataAnnotations.ValidationAttribute`. | 2013/08/16 | [
"https://Stackoverflow.com/questions/18273278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270315/"
] | **Swift Version**
```
func getMixedImg(image1: UIImage, image2: UIImage) -> UIImage {
var size = CGSizeMake(image1.size.width, image1.size.height + image2.size.height)
UIGraphicsBeginImageContext(size)
image1.drawInRect(CGRectMake(0,0,size.width, image1.size.height))
image2.drawInRect(CGRectMake(0,image1.size.height,size.width, image2.size.height))
var finalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return finalImage
}
```
**You will get your image to call this function like this :**
```
var myimage1 = UIImage(named: "image1.png")
var myimage2 = UIImage(named: "image2.png")
var finalMixedImage = getMixedImg(myimage1!, image2: myimage2!)
``` | This implementation works for variadic arguments, so you can pass an unlimited number of images to merge vertically:
```
public static func mergeVertically(images: UIImage...) -> UIImage? {
let maxWidth = images.reduce(0.0) { max($0, $1.size.width) }
let totalHeight = images.reduce(0.0) { $0 + $1.size.height }
UIGraphicsBeginImageContextWithOptions(CGSize(width: maxWidth, height: totalHeight), false, 0.0)
defer {
UIGraphicsEndImageContext()
}
let _ = images.reduce(CGFloat(0.0)) {
$1.draw(in: CGRect(origin: CGPoint(x: 0.0, y: $0), size: $1.size))
return $0 + $1.size.height
}
return UIGraphicsGetImageFromCurrentImageContext()
}
``` |
58,649,687 | I can't define webelement as it has dynamic id and name. There are iframe in another iframe. Attributes id and name for second iframe are dynamic. I need to define the second iframe to switch on it
<http://prntscr.com/pqshpr>
Please help me with defining this dynamic elements.
```
WebElement chartFrameFirst = driver.findElement(By.xpath("(.//iframe)[1]"));
driver.switchTo().frame(chartFrameFirst);
click(By.xpath(".//div[@id=\"tv_chart_container\"]"));
WebElement chartFrameSecond = driver.findElement(By.xpath(".//iframe[@id=\"tradingview_1d329\"]"));
driver.switchTo().frame(chartFrameSecond);
``` | 2019/10/31 | [
"https://Stackoverflow.com/questions/58649687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12304846/"
] | Did you try ,
Storage::get("app/public/uploads/myImageIsHere.jpeg");
<https://laravel.com/docs/5.8/filesystem> | use this instead
```
<img src="{{ URL::to("/images/abc.jpg") }}">
```
this will return an image namely abc.jpg inside "public/images" folder. |
89,495 | I am trying to understand what instantiation means, at the moment I believe it is the act of assigning a property to an object, is this correct?
If so, can a property be instantiated by another property? | 2022/02/11 | [
"https://philosophy.stackexchange.com/questions/89495",
"https://philosophy.stackexchange.com",
"https://philosophy.stackexchange.com/users/50018/"
] | It's not true. It is possible I kill my dog, but it's therefore not necessary to do. Even in the case of serial big bangs, where we are born again over and over, it's not necessary. A universe with infinite entropic time doe not exist. Only universes with a beginning a middle part, and an end exist.
On the other hand, for something to be necessary it has to be possible. | I do not think this is true, for example this just holds true for all the scientific possibilities in our world. But this does not encompass all the logically possible worlds. The existence of a nuclear fusion supporting star smaller than a red dwarf is not possible to the existing science, however it is logically possible in another possible world different from ours which has different physical laws or no such laws at all(it can be conceived of).So accordingly, if our universe were to go on into an infinite future, no fluctuation whatsoever can ever create such a thing. Therefore if we are talking about material possibilities than yes, possibility in this case may imply necessity. But not in the case of logical possibilities. Also the question has one assumption, i.e of an infinite universe which will go on forever carrying its normal operations. Now what if someone were to ask whether the possibility of an infinite universe implies the necessity of one? Now since time has a different ontological existence than the material things spacetime encompass.## Heading ## |
31,440 | When Vim is invoked on multiple files from the command line, then if any of those files have not been visited with `:next` or via buffer switching, the `:q` command pointlessly warns about the situation with a message like "43 files left to edit" and refuses to quit, even though nothing has been modified. Is there a way to eliminate this behavior?
In the `:help` documentation, we have:
```
:q[uit] Quit the current window. Quit Vim if this is the last
window. This fails when changes have been made and
Vim refuses to abandon the current buffer, and when
the last file in the argument list has not been
edited.
If there are other tab pages and quitting the last
window in the current tab page the current tab page is
closed tab-page.
Triggers the QuitPre autocommand event.
See CTRL-W_q for quitting another window.
```
which just confirms the behavior: "fails ... when the last file in the argument list has not been edited".
The forced execution `:q!` will work, but is not acceptable because it will discard unsaved changes.
**The documentation does not seem to mention that if the command fails due to the last file not having been edited, simply repeating the command will then force it.** | 2021/05/31 | [
"https://vi.stackexchange.com/questions/31440",
"https://vi.stackexchange.com",
"https://vi.stackexchange.com/users/13611/"
] | The `:cabbrev`-answer has downsides because the abbreviation is active everywhere in the `:` command line, even if restricted to that type of command using the `<expr>` mechanism.
Ideally, Vim would have a command execution hook: a piece of code that could be executed each time a command is run, or at least an interactive command. That hook could rewrite the command.
Turns out, we can use `:autocmd` as a close facsimile. Vim's `:autocmd` has useful hooks, one of which is `QuitPre`. And so, with this simple line in the `.vimrc`, all seems good:
```
:au QuitPre * qa
```
When the `QuitPre` event is triggered on any buffer, we issue the `qa` command. This effectively rewrites `q` to `qa`.
Various experiments are confirming to me that it has the right behavior, and fixes `:x` also. When multiple files are being edited, and there are no changes, both `:x` and `:q` quit, as desired.
When there are unsaved changes, `:q` still fails, and `:x` fails if other buffers are unsaved.
A curious behavior occurs with `:q!`, though all seems well nonetheless. When there are unsaved changes, it quits as expected. However, Vim's admonishments that there are unsaved changes briefly flash on the display for a fraction of a second. | Yet another alternative is to `:set confirm`. Then `:q` will prompt in this case, and you hit `y` (or a localized equivalent) to continue. No new habits. |
24,331 | So I got an internship and we had the orientation and everything. I am going to my actual workplace tomorrow and thinking of taking a box of doughnuts for everybody. Would that be okay? | 2014/05/21 | [
"https://workplace.stackexchange.com/questions/24331",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/19636/"
] | There are some risks to bringing snacks for everyone:
* There may be a few people who don't eat certain things, whether it's for allergies, diabetes or religious reasons.
There may be an unspoken rule that no-one brings snacks for everyone in consideration of those who may not eat it.
Worse yet, there may be a spoken rule to only brings snacks conforming to certain requirements, and perhaps due to a lack of judgement or obliviousness to the fact that it was brought by a new employee, someone may eat something they're allergic to and end up in the hospital, or worse.
* It may be seen as sucking up.
This certainly varies between cultures though.
* Perhaps some are on diets and may not appreciate the temptation.
* You may not bring enough.
It probably won't come across particularly well if you just bring enough for half the employees.
On the other hand:
* Despite any of the above, it could be seen as well-meaning.
* It might be seen as a fairly standard (i.e. expected) thing to do in some cultures [speculation].
Bottom line:
There are risks either way. Based on the factors mentioned above and any knowledge regarding them you might have, you should decide whether it would be a good idea or not. | I think it would depend on how you bring the doughnuts. If there's a lunchroom that you could just leave them in, I doubt anybody could take exception to that.
However, if you bring them in to a meeting or pass them out to people in such a way that they are certain to know exactly who brought the doughnuts, it might get you labeled as socially needy. Also a bit presumptuous. Once you have worked with these folks for a while it might be okay, but give it a month or two. Also, you didn't mention your gender but on the off chance that you may be female I'd be doubly cautious. Bringing food, (especially food that you have baked yourself, btw), may lose you professional respect. Sad, but reality often is.
If you don't want to pass them out anonymously because they are intended as an overture of friendship or camaraderie, there are better ways to do that.
Give it a few days, then inquire around and ask about the office culture. Do people go out to lunch together, or generally bring their own lunches? If you ask around, that lets people know that you are open to going to lunch with them. Leave it to them to invite you, at least until you get to know people.
If you have been there a few weeks and no invitations, you might casually say "I was thinking of going to lunch at (pick someplace with wide appeal, not too expensive, but not fast food) and was wondering if anybody wanted to go with me?". Best to invite in a group of at least two or three; if you extend individual invitations people are likely to feel you are trying to get too personal with them. *Especially* if you are inviting someone of a different gender. |
60,767 | The following scenario has become the Most-FAQ in the trio of investigator (I), reviewer/editor (R, not related to CRAN) and me (M) as plot creator. We can assume that (R) is the typical medical big boss reviewer, who only knows that each plot must have error bar, otherwise it is wrong. When a statistical reviewer is involved, problems are much less critical.
**Scenario**
In a typical pharmacological cross-over study, two drugs A and B are tested for their effect on glucose level. Each patient is tested twice in random order and under the assumption of no carry-over. The primary endpoint is the difference between glucose (B-A), and we assume that a paired t-test is adequate.
(I) wants a plot that shows the absolute glucose levels in both cases. He fears (R)'s desire for error bars, and asks for standard errors in bar graphs. Let's not start the bar graph war here .\_)

(I): That cannot be true. The bars overlap, and we have p=0.03? That's not what I have learned in high school.
(M): We have a paired design here. The requested error bars are totally irrelevant, what counts is the SE/CI of the paired differences, which are not shown in the plot. If I had a choice and there were not too many data, I would prefer the following plot

**Added 1:** This is the parallel coordinate plot mentioned in several responses
(M): The lines show the pairing, and most lines go up, and that's the right impression, because the slope is what counts (ok, this is categorical, but nevertheless).
(I): That picture is confusing. Nobody understands it, and it has no error bars (R is lurking).
(M): We could also add another plot that shows the relevant confidence interval of the difference. The distance from the zero-line gives an impression of the effect size.
(I): Nobody does it
(R): And it wastes precious trees
(M): (As a good German): Yes, point on the trees is taken. But I nevertheless use this (and never get it published) when we have multiple treatments and multiple contrasts.

**Any suggestions**? The R-Code is below, if you want to create a plot.
```
# Graphics for Crossover experiments
library(ggplot2)
library(plyr)
theme_set(theme_bw()+theme(panel.margin=grid::unit(0,"lines")))
n = 20
effect = 5
set.seed(4711)
glu0 = rnorm(n,120,30)
glu1 = glu0 + rnorm(n,effect,7)
dt = data.frame(patient = rep(paste0("P",10:(9+n))),
treatment = rep(c("A","B"), each=n),glucose = c(glu0,glu1))
dt1 = ddply(dt,.(treatment), function(x){
data.frame(glucose = mean(x$glucose), se = sqrt(var(x$glucose)/nrow(x)) )})
tt = t.test(glucose~treatment,paired=TRUE,data=dt,conf.int=TRUE)
dt2 = data.frame(diff = -tt$estimate,low=-tt$conf.int[2], up=-tt$conf.int[1])
p = paste("p =",signif(tt$p.value,2))
png(height=300,width=300)
ggplot(dt1, aes(x=treatment, y=glucose, fill=treatment))+
geom_bar(stat="identity")+
geom_errorbar(aes(ymin=glucose-se, ymax=glucose+se),size=1., width=0.3)+
geom_text(aes(1.5,150),label=p,size=6)
ggplot(dt,aes(x=treatment,y=glucose, group=patient))+ylim(0,190)+
geom_line()+geom_point(size=4.5)+
geom_text(aes(1.5,60),label=p,size=6)
ggplot(dt2,aes(x="",y=diff))+
geom_errorbar(aes(ymin=low,ymax=up),size=1.5,width=0.2)+
geom_text(aes(1,-0.8),label=p,size=6)+
ylab("95% CI of difference glucose B-A")+ ylim(-10,10)+
theme(panel.border=element_blank(), panel.grid.major.x=element_blank(),
panel.grid.major.y=element_line(size=1,colour="grey88"))
dev.off()
``` | 2013/06/03 | [
"https://stats.stackexchange.com/questions/60767",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/8433/"
] | The question does not seem to be about error bars so much as about the best ways of plotting paired data.
In essence error bars here are at most a way of summarizing uncertainty: they do not, and they necessarily cannot, say much about any fine structure in the data.
Parallel coordinate plots -- sometimes called profile plots, a term that means different things in different fields -- have been mentioned in the question. Basic scatter plots have already been suggested by @Ray Koopman.
A specialized scatter plot popular here and there is a plot of difference (here $A - B$, say) versus mean (or sum) $(A + B)/2$ or $A + B$. In medicine this is often known as a [bland-altman-plot](/questions/tagged/bland-altman-plot "show questions tagged 'bland-altman-plot'") (perhaps because it was earlier used by Oldham) and in statistics it is often known as a Tukey mean-difference plot.
Another source for this plot is Neyman, J., Scott, E. L. and Shane, C. D. 1953. On the spatial distribution of galaxies: a specific model. *Astrophysical Journal* 117: 92–133.
In broad terms such plots resemble the idea of plotting residuals versus fitted, also popularised by Tukey and his brother-in-law-squared Anscombe.
The key idea of such plots is that the horizontal line of no difference $A - B = 0$ is naturally equivalent to the line of equality $A = B$, but it is often easier psychologically to work with a horizontal reference line. In addition, if $A$ and $B$ are broadly similar, a scatter plot uses much of its space in emphasising that fact, whereas the structure of the differences should be of greater interest.
A neglected design is the parallel-line plot of McNeil, D.R. 1992.
On graphing paired data. *American Statistician* 46: 307–310. This is also discussed in the two references below.
Stata-linked reviews, with several references, are in
2004, Graphing agreement and disagreement. *Stata Journal*
4: 329-349.
.pdf accessible at <http://www.stata-journal.com/sjpdf.html?articlenum=gr0005>
Paired, parallel, or profile plots for changes, correlations, and other comparisons. *Stata Journal* 9: 621-639.
.pdf accessible at <http://www.stata-journal.com/sjpdf.html?articlenum=gr0041>
Non-Stata users should able to skip and hum their way through the Stata code while working out how to implement the graphs in their own favourite software.
In all cases if the ratio of $A$ and $B$ is of interest rather than its difference, exactly the same ideas should be used, but employing logarithmic scales. | Why not just plot the difference\* for each patient? You could then use a histogram, a box plot or a normal probability plot and overlay a 95% confidence interval for the difference.
* In some scenarios it might be the difference of the logarithms. See, for example, Patterson & Jones, "Bioequivalence and Statistics in Clinical Pharmacology", Chapman, 2006. |
5,771,075 | I need to **generate random single-source/single-sink flow networks** of different dimensions so that I can measure the performance of some algorithms such as the Ford-Fulkerson and Dinic.
Is the Kruskal algorithm a way to generate such graphs? | 2011/04/24 | [
"https://Stackoverflow.com/questions/5771075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/466153/"
] | To create a generic flow network you just need to create an adjancency matrix.
adj[u][v] = capacity from node u to node v
So, you just have to randomly create this matrix.
For example, if n is the number of vertices that you want ( you could make that random too ):
```
for u in 0..n-1:
for v in 0..u-1:
if (rand() % 2 and u != sink and v != source or u == source):
adj[u][v] = rand()
adj[v][u] = 0
else:
adj[u][v] = 0
adj[v][u] = rand()
``` | Himadris answer is partly correct. I had to add some constraints to make sure that single-source/single-sink is satisfied.
For single source only one column has to be all 0 of the adjacency matrix as well as one row for single sink.
```py
import numpy
def random_dag(n):
adj = np.zeros((n, n))
sink = n-1
source = 0
for u in range(0, n):
for v in range(u):
if (u != sink and v != source or u == source):
adj[u, v] = np.random.randint(0, 2)
adj[v, u] = 0
else:
adj[u, v] = 0
adj[v, u] = np.random.randint(0, 2)
# Additional constraints to make sure single-source/single-sink
# May be further randomized (but fixed my issues so far)
for u in range(0, n):
if sum(adj[u]) == 0:
adj[u, -1] = 1
adj[-1, u] = 0
if sum(adj.T[u]) == 0:
adj.T[u, 0] = 1
adj.T[0, u] = 0
return adj
```
You can visualize with the following code:
```py
import networkx
import matplotlib.plot as plt
def show_graph_with_labels(adjacency_matrix, mylabels):
rows, cols = np.where(adjacency_matrix == 1)
edges = zip(rows.tolist(), cols.tolist())
gr = nx.DiGraph()
gr.add_edges_from(edges)
nx.draw(gr, node_size=500, labels=mylabels, with_labels=True)
plt.show()
n = 4
show_graph_with_labels(random_dag(n), {i: i for i in range(n)})
``` |
17,999,067 | **CodePen: <http://codepen.io/leongaban/pen/hbHsk>**
I've found multiple answers to this question on stack [here](https://stackoverflow.com/questions/12533508/only-allow-numbers-in-input-tage-without-javascript) and [here](https://stackoverflow.com/questions/773843/iphone-uiwebview-how-to-force-a-numeric-keyboard-is-it-possible)
However they all suggest the same fix, using `type="number"` or `type="tel"`
None of these are working in my codepen or project :(

Do you see what I'm missing? | 2013/08/01 | [
"https://Stackoverflow.com/questions/17999067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168738/"
] | Firstly, what browsers are you using? Not all browsers support the HTML5 input types, so if you need to support users who might use old browsers then you can't rely on the HTML5 input types working for all users.
Secondly the HTML5 input validation types aren't intended to do anything to stop you entering invalid values; they merely do validation on the input once it's entered. You as the developer are supposed to handle this by using CSS or JS to determine whether the field input is invalid, and flag it to the user as appropriate.
If you actually want to prevent non-digit characters from ever getting into the field, then the answer is yes, you need to use Javascript (best option is to trap it in a `keyUp` event).
You should also be careful to ensure that any validation you do on the client is also replicated on the server, as any client-side validation (whether via the HTML5 input fields or via your own custom javascript) can be bypassed by a malicious user. | Firstly, in your Codepen, your inputs are not fully formatted correctly in a form.... Try adding the `<form></form>` tags like this:
```html
<form>
<lable>input 1 </lable>
<input type='tel' pattern='[0-9]{10}' class='added_mobilephone' name='mobilephone' value='' autocomplete='off' maxlength='20' />
<br/>
<lable>input 2 </lable>
<input type="number" pattern='[0-9]{10}'/>
<br/>
<lable>input 3 </lable>
<input type= "text" name="name" pattern="[0-9]" title="Title"/>
</form>
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.