qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
9,166,035 |
Right now I have a perl script that at a certain point, gathers and then processes the output of several bash commands, right now here is how I've done it:
```
if ($condition) {
@output = `$bashcommand`;
@output1 = `$bashcommand1`;
@output2 = `$bashcommand2`;
@output3 = `$bashcommand3`;
}
```
The problem is, each of these commands take a fairly amount of time, therefore, I'd like to know if I could run them all at the same time.
|
2012/02/06
|
[
"https://Stackoverflow.com/questions/9166035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192918/"
] |
This sounds like a good use case for [`Forks::Super::bg_qx`](http://search.cpan.org/perldoc?Forks%3a%3aSuper#bg_qx).
```
use Forks::Super 'bg_qx';
$output = bg_qx $bashcommand;
$output1 = bg_qx $bashcommand1;
$output2 = bg_qx $bashcommand2;
$output3 = bg_qx $bashcommand3;
```
will run these four commands in the background. The variables used for return values (`$output`, `$output1`, etc.) are overloaded objects. Your program will retrieve the output from these commands (waiting for the commands to complete, if necessary) the next time those variables are referenced in the program.
```
... more stuff happens ...
# if $bashcommand is done, this next line will execute right away
# otherwise, it will wait until $bashcommand finishes ...
print "Output of first command was ", $output;
&do_something_with_command_output( $output1 );
@output2 = split /\n/, $output2;
...
```
**Update 2012-03-01:** v0.60 of Forks::Super [has some new constructions](http://search.cpan.org/perldoc?Forks%3a%3aSuper#Forks%3a%3aSuper%3a%3abg_eval_tied_class) that let you retrieve results in list context:
```
if ($condition) {
tie @output, 'Forks::Super::bg_qx', $bashcommand;
tie @output1, 'Forks::Super::bg_qx', $bashcommand1;
tie @output2, 'Forks::Super::bg_qx', $bashcommand2;
tie @output3, 'Forks::Super::bg_qx', $bashcommand3;
}
...
```
|
62,620,816 |
I am trying to implement a table and do filtering and searching of data from the table. Since the searching and sorting takes a while I would like to implement a spinner display to show that the search/filtering is running.
Below is how I have implemented the component, I call filterData/ searchData to search through the data and return the results which is passed as props to the Grid Table component and where the data is displayed.
```
{this.state.search && this.state.filter &&
<GridTable
results= {filterData(this.state.filter,searchData(this.state.search,this.state.Data))}
/>}
{ this.state.search && !this.state.filter &&
<GridTable
results = {searchData(this.state.search,this.state.Data)}
/>}
{ !this.state.search && this.state.filter &&
<GridTable
results= {filterData(this.state.filter,this.state.Data)}
/>}
{ !this.state.search && !this.state.filter &&
<GridTable
results = {this.state.Data}
/>}
```
Where should i implement a loading state and set its state? I am confused since I am directly passing the result of the search/ filter functions into the props.
|
2020/06/28
|
[
"https://Stackoverflow.com/questions/62620816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13781930/"
] |
In your render method you can have one loader implemented like
```
<Loader visible={this.state.visibility}>
```
In your searchData method, you can set the visibility of this loader true in the first line and false in the last line like below
```js
searchData = () => {
// Start the loader
this.setState({
visibility: true,
});
// ....Your logic goes here
// Stop the loader
this.setState({
visibility: false,
});
};
```
|
40,203,297 |
Essentially I have a string:
string str = "Hello.... My name is Steve.. I like Dogs."
I need to change occurrences of "..." or more periods into just 3. Any occurrences of 2 need to become 1.
Using
`Regex.Replace(str)`
`Regex.Replace(str,"[.]{3,}","...")` works great at changing the groups greater then 3 to 3.
But I can't select groups of 2 "[.]{2}" because the groups of 3 are made up of 2...
My final String needs to look like this:
`string str = "Hello... My name is Steve. I like Dogs."`
|
2016/10/23
|
[
"https://Stackoverflow.com/questions/40203297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4330325/"
] |
If you are allowed to use c# features:
```
string input = "Hello.... My name is Steve.. I like Dogs.";
string output = Regex.Replace(input, @"\.{2,}", m => m.Length == 2 ? "." : "...");
```
|
930,840 |
I have some jaxb objects (instantiated from code generated from xsd by jaxb) that I need to clone. The Jaxb class does not appear to provide an interface for doing this easily. I can not hand edit the class and can not extend it - so I need to create a helper/utility method to do this. What is the best approach?
|
2009/05/30
|
[
"https://Stackoverflow.com/questions/930840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88760/"
] |
Given the purpose of JAXB, I think the easiest way would be to marshall your object to XML and unmarshall it back.
Lots more discussions on [Google](http://www.google.com/search?q=jaxb+clone).
JAXB FAQ [suggests](https://jaxb.dev.java.net/guide/Working_with_generated_code_in_memory.html) [beanlib](http://beanlib.sourceforge.net/).
There's also some [discussion](http://www.nabble.com/cloning-JAXBElements-td4708089.html) (as well as a link to download) of a Cloneable plugin under jaxb2-commons, although I can't find any reference on the project page.
|
46,935,608 |
I need to populate a choice component in a form with an ArrayList present in an external class (same package)
DatabaseList.java:
package pmi.sqltoxml;
```
import java.util.ArrayList;
public class DatabaseList {
public void SetLista() {
ArrayList<String> db = new ArrayList<>();
db.add("ADB_PMISOFTWARE");
db.add("ADB_DEMO");
}
}
```
MainForm.java:
```
public class Mainform extends javax.swing.JFrame {
DatabaseList db = new DatabaseList();
public Mainform() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
choice1 = new java.awt.Choice();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
choice1.setName("dbList"); // NOI18N
for (String dbItem : db ){
choice1.add(dbItem);
}
...
```
Netbeans tells me that
>
> `for-each` not applicable to expression type. Required `Array` or
> `java.lang.iterable`. Found: `DatabaseList`.
>
>
>
But, `ArrayList` is not an `iterable` Interface?
|
2017/10/25
|
[
"https://Stackoverflow.com/questions/46935608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7290374/"
] |
You have to return the List :
```
public List<String> setLista() {
List<String> db = new ArrayList<>();
db.add("ADB_PMISOFTWARE");
db.add("ADB_DEMO");
return db;//<------You have to return the list otherwise you can't use this array list
}
```
then you can call your method like this :
```
for (String dbItem : db.setLista()){
choice1.add(dbItem);
}
```
|
16,392,738 |
This is a really simple question but I am new. I am trying to create a dropdown menu with values populated from the model. However, instead of displaying the city names, I am getting the record id's like: 0x007fee0b7442c0 (not sure if these are called id's, I think there is another term).
Controller:
```
@cities = City.find(:all, select: "name")
```
View:
```
<%= f.select(:city, @cities) %>
```
What am I doing wrong?
|
2013/05/06
|
[
"https://Stackoverflow.com/questions/16392738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2063674/"
] |
If you want just the `name` attribute from the database then do:
```
@cities = City.pluck(:name)
# => ["Sydney", "Melbourne", "Canberra"]
```
|
71,892 |
I keep having this issue where I will
* Add a note to Notes
* Close the app
* Come back later and open it and its no longer there.
There is no **Save** button on the so assume that once i click "+" and add a note (type something in) and close it that it will be there when i open it up again.
Am i missing something here?
|
2012/11/17
|
[
"https://apple.stackexchange.com/questions/71892",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/524/"
] |
Aside from making sure you've installed all the latest system software updates, try the following to "reset" Notes on your computer:
1. Quit the Notes application.
2. Turn off iCloud Notes sync on *all* your devices (on Mac, in System Preferences > iCloud, and on iOS, in Settings > iCloud).
3. In the Finder, pull down the Go menu, hold down Option to reveal "Library", and choose that.
4. Type `com.apple.Notes` into the search field and then choose the "Name matches" search option that appears.
5. Select the "Library" search scope.
6. The search should show a few folders with names like "com.apple.Notes", "com.apple.Notes.help", and "com.apple.Notes.savedState", and some files named "com.apple.Notes.plist" and "com.apple.Notes.help". Select all of those and drag them to the Trash.
7. Restart the computer.
8. Turn on iCloud Notes on just your computer.
9. Try creating an new note, then check against <https://www.icloud.com/#notes> to see if notes are being sync'ed successfully.
10. If that works, turn iCloud Notes sync back on again on all your devices.
Hope that helps!
|
43,867,448 |
I am trying to parse the following JSON. But getting exception please help.
```
{
"method": "demo",
"clazz": "storage",
"params": [
"",
"LOGIN",
"{"auth": {"tenantName": "AUTH_Tonny", "casauth": {"username": "Tonny", "tgt": "TGT-1876hkahaadcaweyfiowufssadsfsdf"}}}",
"http://ipstorage.google.com"
]
}
```
Here is the Java Code:
```
String tokenId = "";
String message = "LOGIN";
String url1 = "http://ipstorage.google.com";
String authentication = "{\"auth\": {\"tenantName\": \"AUTH_" + test2.getUsername()
+ "\", \"casauth\": {\"username\": \""
+ test2.getUsername() + "\", \"tgt\": \""
+ test2.getPassword() + "\"}}}";
String pp = "[\"" + tokenId + "\",\"" + message + "\",\""
+ authentication + "\",\"" + url1 + "\"]";
String msg1 = "{\"method\":\"demo\",\"clazz\":\"storage\",\"params\":" + pp + "}";
System.out.println(msg1);
JSONObject jo = (JSONObject) new JSONParser().parse(msg1);
System.out.println("##");
System.out.println(jo);
```
Output and exception which I am getting is:
```
{"method":"demo","clazz":"storage","params":["","LOGIN","{"auth":
{"tenantName": "AUTH_Tonny", "casauth": {"username": "Tonny", "tgt": "TGT -
1876 hkahaadcaweyfiowufssadsfsdf"}}}","http://ipstorage.google.com"]}
Exception in thread "main" Unexpected character (a) at position 59.
at org.json.simple.parser.Yylex.yylex(Unknown Source)
at org.json.simple.parser.JSONParser.nextToken(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at com.t.g.i.e.utils.Test.main(Test.java:74)
```
Please help me out. Thank you in advance.
|
2017/05/09
|
[
"https://Stackoverflow.com/questions/43867448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5124138/"
] |
Because you didn't restore the state while your size is restored. Restore the state in the **else** condition:
```
jQuery(window).on('load resize', function(){
var width = jQuery(window).width();
var header = jQuery(document).find('header');
var headerClass = header.attr('class');
if(width < 1000){
if( headerClass !== 'header-6' ){
header.removeClass(headerClass);
header.addClass('header-xs');
}else{
header.removeClass('header-xs').addClass(headerClass);
}
}else{
// you have to restore the previous state here
}
});
```
|
275,577 |
We are trying to set up a roadwarrior vpn setup with openvpn. We want the people to be able to connect to our network via openvpn. And we want them to be able to see and connect to the machines in our network. So the solution is bridged vpn as we see.
I don't have much experience with network environments. I'm going through both the ubuntu (on which we've built openvpn server) and openvpn manuals. Both of them lack in many aspects.
<https://help.ubuntu.com/10.10/serverguide/C/openvpn.html>
<http://openvpn.net/howto.html>
When i install a bridge interface through bridge-start script which is part of the openvpn, my network goes down, just letting me ping inside my network. i set up the port forwarding to my openvpn server's port 1194 which is working until i set the bridging interface. After enabling bridge my machine lost contact to the outer network. I'm sure i'm missing something to do.
I put my `ifconfig` and `netstat -rn` outputs before and after setting bridge. And my server configuration file and scripts below.
#ifconfig before
----------------
```
eth1 Link encap:Ethernet HWaddr 52:54:00:57:63:6e
inet addr:192.168.22.230 Bcast:192.168.22.255 Mask:255.255.255.0
inet6 addr: fe80::5054:ff:fe57:636e/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:4857 errors:0 dropped:0 overruns:0 frame:0
TX packets:3199 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:518272 (518.2 KB) TX bytes:430178 (430.1 KB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:21 errors:0 dropped:0 overruns:0 frame:0
TX packets:21 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:1804 (1.8 KB) TX bytes:1804 (1.8 KB)
```
#netstat before
---------------
```
192.168.22.0 / 0.0.0.0 / 255.255.255.0 / U 0 0 0 / eth1
0.0.0.0 / 192.168.22.1 / 0.0.0.0 / UG 0 0 0 / eth1
```
#ifconfig after
---------------
```
br0 Link encap:Ethernet HWaddr 52:54:00:57:63:6e
inet addr:192.168.22.230 Bcast:192.168.22.255 Mask:255.255.255.0
inet6 addr: fe80::5054:ff:fe57:636e/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:256 errors:0 dropped:0 overruns:0 frame:0
TX packets:32 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:43790 (43.7 KB) TX bytes:2328 (2.3 KB)
eth1 Link encap:Ethernet HWaddr 52:54:00:57:63:6e
inet6 addr: fe80::5054:ff:fe57:636e/64 Scope:Link
UP BROADCAST RUNNING PROMISC MULTICAST MTU:1500 Metric:1
RX packets:5691 errors:0 dropped:0 overruns:0 frame:0
TX packets:3508 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:622570 (622.5 KB) TX bytes:470324 (470.3 KB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:36 errors:0 dropped:0 overruns:0 frame:0
TX packets:36 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:3980 (3.9 KB) TX bytes:3980 (3.9 KB)
tap0 Link encap:Ethernet HWaddr 7e:3a:03:48:ad:29
inet6 addr: fe80::7c3a:3ff:fe48:ad29/64 Scope:Link
UP BROADCAST RUNNING PROMISC MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:243 overruns:0 carrier:0
collisions:0 txqueuelen:100
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
```
#netstat after
--------------
```
192.168.22.0 / 0.0.0.0 / 255.255.255.0 / U 0 0 0 / br0
```
(This table is bad i know. But i couldn't been able to overcome this table, or make it functional by adding routes.)
bridge-start script
===================
```
br="br0"
tap="tap0"
eth="eth1"
eth_ip="192.168.22.230"
eth_netmask="255.255.255.0"
eth_broadcast="192.168.22.255"
for t in $tap; do
openvpn --mktun --dev $t
done
brctl addbr $br
brctl addif $br $eth
for t in $tap; do
brctl addif $br $t
done
for t in $tap; do
ifconfig $t 0.0.0.0 promisc up
done
ifconfig $eth 0.0.0.0 promisc up
ifconfig $br $eth_ip netmask $eth_netmask broadcast $eth_broadcast
```
|
2011/05/31
|
[
"https://serverfault.com/questions/275577",
"https://serverfault.com",
"https://serverfault.com/users/83139/"
] |
The problem is that when the start script takes eth0 down, it destroys your default gateway route. When the script brings the interfaces up, you aren't using DHCP, you're setting the IPs and subnets manually. Normally you would get the route from DHCP without the bridge. You can either comment out parts of the script so that br0 gets eth0's IP (and thus the route as well) from DHCP, or you can add a line to manually add the route at the end of the script:
```
route add default gw 192.168.22.1
```
|
7,682 |
I know the common wisdom is you shouldn't do this, but I am brewing two mid-to-high gravity beers on Saturday (1.065 and 1.072), and only have one packet. I am now chilling a 2L starter that I was going to stir plate, decant, and split between the two batches. Is this going overboard, or should I have split the dry satchet into two batches?
|
2012/09/13
|
[
"https://homebrew.stackexchange.com/questions/7682",
"https://homebrew.stackexchange.com",
"https://homebrew.stackexchange.com/users/1870/"
] |
A dry sachet contains about 200 billion cells when new, with a decrease of around 4% per month thereafer.
For a beer in the 1.070 range, recommended pitching rates are 1-1.5 million cells / ml / 4 SG or about 330-450 billion cells in 5 gallons. So pitching a single pack of 200 billion cells is going to be underpitching, and one pack split is very much underpitching - you're getting a maximum of 100 billion cells compared to the 330 billion minimum needed.
You can make a perfectly good starter with dry yeast, just as with liquid yeast. The only reason most people don't make a starter with dry yeast is that it's inexpensive enough to usually just buy an extra sachet. But in your case, if that's not an option there's no harm done in making a starter. In fact, I would recommend it, and would split the dry yeast into 2 2-liter starters to ensure you reach the cell counts required.
|
37,602,460 |
I am writing a python(ver 3) script to access google doc using gspread.
```
1) import gspread
2) from oauth2client.service_account import ServiceAccountCredentials
3) scope = ['https://spreadsheets.google.com/feeds']
4) credentials = ServiceAccountCredentials.from_json_keyfile_name(r'/path/to/jason/file/xxxxxx.json',scope)
5) gc = gspread.authorize(credentials)
6) wks = gc.open("test").sheet1
```
**test** is a **google sheet** which seems to be opened and read fine but if I try to read from a Office excel file it gives me error.here is what they look: [](https://i.stack.imgur.com/fQ5P7.png)
The folder which test and mtg are under is shared with the email I got in json file.Also both files were shared with that email.
Tried:
```
wks = gc.open("mtg.xls").sheet1
```
and
```
wks = gc.open("mtg.xls").<NameOfFirstSheet>
```
and
```
wks = gc.open("mtg").<NameOfFirstSheet>
```
error:
>
> /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/gspread/client.py",
> line 152, in open
> raise SpreadsheetNotFound gspread.exceptions.SpreadsheetNotFound
>
>
>
|
2016/06/02
|
[
"https://Stackoverflow.com/questions/37602460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4759890/"
] |
There is no `.xls` to be added at the end of the file name, the data is saved in a different format (and can later be exported as `.xls`).
Try to break your code into:
```
ss = open("MTG_Collection_5_14_16")
ws = ss.worksheet("<NameOfFirstSheet>")
```
and post the error message if any.
`Spreadsheet` instances have an attribute `sheet1` because it is the default name for the first worksheet. `ss.sheet1` actually returns the worksheet with index 0, no matter what its name is.
If you want to access another worksheet, you need to use one of `ss.worsheet("<title>")` or `ss.get_worksheet(<index>)`. `ss.<NameOfFirstSheet>` will not work.
|
18,177,931 |
all
I have searched this question, and I found so many answers to it was not difficult to find a solution for my question.
BUT, I have strange experience and I don't know the reason that's why I ask people to give me some advice.
Here are my codes:
```
void SetThread()
{
for (int i = 0; i < _intArrayLength; i++)
{
Console.Write(string.Format("SetThread->i: {0}\r\n", i));
_th[i] = new Thread(new ThreadStart(() => RunThread(i)));
_th[i].Start();
}
}
void RunThread(int num)
{
Console.Write(string.Format("RunThread->num: {0}\r\n", num));
}
```
Yes, they are ordinary thread codes.
I expect all the thread array should be calling RunThread method 10 times.
It should be like
```
SetThread->i: 0
SetThread->i: 1
SetThread->i: 2
SetThread->i: 3
SetThread->i: 4
SetThread->i: 5
SetThread->i: 6
SetThread->i: 7
SetThread->i: 8
SetThread->i: 9
RunThread->num: 0
RunThread->num: 1
RunThread->num: 2
RunThread->num: 3
RunThread->num: 4
RunThread->num: 5
RunThread->num: 6
RunThread->num: 7
RunThread->num: 8
RunThread->num: 9
```
This is what I expect to be. The order is not important.
But I get the result like below.
```
SetThread->i: 0
SetThread->i: 1
SetThread->i: 2
The thread '<No Name>' (0x18e4) has exited with code 0 (0x0).
The thread '<No Name>' (0x11ac) has exited with code 0 (0x0).
The thread '<No Name>' (0x1190) has exited with code 0 (0x0).
The thread '<No Name>' (0x1708) has exited with code 0 (0x0).
The thread '<No Name>' (0xc94) has exited with code 0 (0x0).
The thread '<No Name>' (0xdac) has exited with code 0 (0x0).
The thread '<No Name>' (0x12d8) has exited with code 0 (0x0).
The thread '<No Name>' (0x1574) has exited with code 0 (0x0).
The thread '<No Name>' (0x1138) has exited with code 0 (0x0).
The thread '<No Name>' (0xef0) has exited with code 0 (0x0).
SetThread->i: 3
RunThread->num: 3
RunThread->num: 3
RunThread->num: 3
SetThread->i: 4
RunThread->num: 4
SetThread->i: 5
SetThread->i: 6
RunThread->num: 6
RunThread->num: 6
SetThread->i: 7
RunThread->num: 7
SetThread->i: 8
RunThread->num: 8
SetThread->i: 9
RunThread->num: 9
RunThread->num: 10
```
What I expect is that RunThread function should carry the argument(num) from 0 to 9.
And I cannot figure out what that error message is.
"The thread '' ~~ and so on.
Could anyone give me some clue on this?
|
2013/08/12
|
[
"https://Stackoverflow.com/questions/18177931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/826725/"
] |
You are [creating a closure over the loop variable](http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx) - an easy fix is to just create a local copy, so your thread uses the desired value:
```
void SetThread()
{
for (int i = 0; i < _intArrayLength; i++)
{
int currentValue = i;
Console.Write(string.Format("SetThread->i: {0}\r\n", i));
_th[i] = new Thread(() => RunThread(currentValue));
_th[i].Start();
}
}
```
|
24,486,271 |
I found some source code that I want to incorporate into a C program I am writing. Let's call it existing.c. This file contains a typedef for a struct that is required for a parameter to a function defined lower down in the file. I want to call this function in my file main.c. I know I could probably get access to the function by declaring a function prototype in main.c, but I will also need access to that struct definition to declare and call the function.
There is no .h file for existing.c, although I could of course make one, say existing.h. But if I put the typedef in existing.h, then it seems like I would have to put #include "existing.h" into existing.c, which does not seem correct from my understanding of header files. I thought their purpose was to make the code in a certain file available to other compilation units, and shouldn't be required by that file itself.
So I guess my main question is straightforward, how do I use the function defined in existing.c in my own file main.c? Can I do it without a header file, like by putting some kind of struct prototype in main.c, similar to a function prototype, or specify the struct as external or something along those lines?
Edit: I probably should have mentioned in my original post that one reason I was hoping to avoid using a header was so I could incorporate the existing.c file unaltered in case there are revisions of this source in the future. Judging from the answers this is not possible.
|
2014/06/30
|
[
"https://Stackoverflow.com/questions/24486271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1151125/"
] |
I was pointed to this [LINQ Module for PowerShell](https://github.com/fschwiet/linq-powershell/), which allowed me to do simply:
```
$collection | Linq-All { $_.command -eq "myCommand" }
```
Which is just what I needed! More examples [here](https://github.com/fschwiet/linq-powershell/blob/master/josheinstein.com_blog_linq-for-powershell.txt).
|
52,554,082 |
So the element I want to click on is located here:
```
<li class=" ">
<a href="google.de">
<i class="fa fa-lg fa-fw fa-profile"></i>
<span class="menu-item-parent ">Mein Konto</span>
</a>
</li>
```
Now I have the following Java Code set up:
```
WebElement konto = driver.findElement(By.xpath("//*[contains(text(),'Mein Konto')]"));
```
and
```
WebElement konto1 = driver.findElement(By.linkText("Mein Konto"));
```
But in the Chrome Driver it can't locate the element:
>
> org.openqa.selenium.NoSuchElementException: no such element: Unable to
> locate element: {"method":"link text","selector":"Mein Konto"}
>
>
>
The xpath works fine, but for my tester team linktext would be easier to use, so I am trying to use that instead of xpath.
|
2018/09/28
|
[
"https://Stackoverflow.com/questions/52554082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10429070/"
] |
DOM is like that,
```
<a href="google.de">
<i class="fa fa-lg fa-fw fa-profile"></i>
<span class="menu-item-parent ">Mein Konto</span>
</a>
```
Just 'Mein Konto' is not only link text. It will be partial link text as ` ` is also there. My suggestion is to use partial link text.
```
driver.findelement(By.partialLinkText("Mein Konto"));
```
EDIT :
I want to highlight Anderson's comment
Presence of whitespaces in link text is not a reason to use search by `partialLinkText`. Just copy link text from rendered web page (not from Chrome dev console) and pass to `By.linkText()`. It might looks like `driver.findElement(By.linkText(" Mein Konto"))`;. But if you sure that there are no other links on page with Mein Konto substring, then `By.partialLinkText` is OK.
|
52,524,064 |
Can someone try to explain to me why the "If" statement allowed it to went through but clearly you can see the property of my object is saying "EXISTING" even it say in if that it only allow "NEW".
[](https://i.stack.imgur.com/Ods70.jpg)
```
var newChannalChecker = false;
singleMassiveGroup.forEach(singleGrop => {
if (!newChannalChecker && singleGrop.length) {
singleGrop.forEach(element => {
if (element["currentItemStatus"] === "NEW") {
newChannalChecker = true;
}
});
}
});
```
I am not sure if this would be help but I tried putting some logs with it to check whats going on
```
var newChannalChecker = false;
singleMassiveGroup.forEach(singleGroup => {
if (!newChannalChecker && singleGroup.length) {
// singleGrop.filter(e => e.CurrentItemStatus === "NEW").map(e)
singleGroup.forEach(element1 => {
console.log("CurrentItemStatus: ", element1.CurrentItemStatus);
if (element1.CurrentItemStatus === "NEW") {
console.log(
"Entered CurrentItemStatus: ",
element1.CurrentItemStatus
);
newChannalChecker = true;
}
});
}
});
```
>
> App.js:402 CurrentItemStatus: EXISTING
>
>
>
The weird thing is it says the the Value says "EXISTING" but its still went inside the if
[](https://i.stack.imgur.com/ILcEf.jpg)
[](https://i.stack.imgur.com/BVjby.jpg)
I tried hovering to the property it says "Element1 is not defined"
One more thing I noticed the console.log inside my "If" statement didn't print anything but it still change the newChannalChecker to True
|
2018/09/26
|
[
"https://Stackoverflow.com/questions/52524064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9656013/"
] |
You can just concatenate the strings together. Keep in mind, that you need to validate the user input first. Otherwise, the `box-shadow` is not properly shown, if the user inserts a wrong value.
```
box.style.boxShadow = offsetX + ' ' + offsetY + ' ' + blurRadius + ' ' + spreadRadius + ' ' + color;
```
With ES6, you can also use [template strings](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/template_strings):
```
box.style.boxShadow = `${offsetX} ${offsetY} ${blurRadius} ${spreadRadius} ${color}`;
```
---
Here is a live example:
```js
function apply() {
var box = document.getElementById('box');
var offsetX = document.getElementById('offsetX').value;
var offsetY = document.getElementById('offsetY').value;
var blurRadius = document.getElementById('blurRadius').value;
var spreadRadius = document.getElementById('spreadRadius').value;
var color = document.getElementById('color').value;
box.style.boxShadow = offsetX + ' ' + offsetY + ' ' + blurRadius + ' ' + spreadRadius + ' ' + color;
}
```
```css
#box {
width: 100px;
height: 100px;
background: #f2f2f2;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
input {
display: block;
}
```
```html
<div id="box"></div>
<input id="offsetX" placeholder="offsetX" />
<input id="offsetY" placeholder="offsetY" />
<input id="blurRadius" placeholder="blurRadius" />
<input id="spreadRadius" placeholder="spreadRadius" />
<input id="color" placeholder="color" />
<button onclick="apply()">Apply</button>
```
|
40,292,202 |
I am using PostgreSQL as my DB.
I have **SCPed** a **.sql** file on my remote Ubuntu VM.
I did `sudo su - postgres` and create a DB.
then I switch backed to my original account and tried this:
`sudo -su postgres pg_restore < temp.sql`
The command ran successfully.
But when I again switched back to **postgres** user and checked the db for the list of tables using **\dt** I found no tables.
What am I doing wrong?
|
2016/10/27
|
[
"https://Stackoverflow.com/questions/40292202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3564468/"
] |
'pg\_restore' is meant to restore files generated by 'pg\_dump'.
From the man page
>
> pg\_restore is a utility for restoring a PostgreSQL database from an
> archive created by pg\_dump(1) in one of the non-plain-text formats.
>
>
>
<https://www.postgresql.org/docs/9.2/static/app-pgrestore.html>
If your file was generated by pg\_dump you probably need to at least tell it which database to dump into:
```
pg_restore -d my_new_database temp.sql
```
My own experience with pg\_restore across different flavors shows that many times I need to specify the format of the dump file, even if it was in 'native' format, despite the manpage indicating that it would detect the format.
```
pg_restore -d my_new_database -Fc temp.dump
```
This is only a guess, but I'm thinking if the tables actually restored, without specifying the db, they got dumped into the default database. You can check this by listing the tables in the 'postgres' database (there should be none).
```
postgres=#\c postgres
You are now connected to database "postgres" as user "postgres".
postgres=#\dt
No relations found.
```
If your tables did restore into the default database they will be listed.
Plain text SQL files need to be treated differently, usually executed via SQL commands using psql.
```
psql -d my_database < temp.sql
```
|
42,162,038 |
I'm developing an application that hides the text using steganography method called LSB, putting it into the image. But during testing I found that when you save an image in the gallery and then load it from there, it's RGB values have changes. This is the red values:
```
34 -> 41
29 -> 34
44 -> 46
63 -> 62
101 -> 105
118 -> 119
```
Left - what they were, right - what they become. Of course such a change completely destroys the text hidden inside. This is the code I'm using to save an image:
```
UIImageWriteToSavedPhotosAlbum(newImg, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
let ac = UIAlertController(title: "Saving error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
} else {
let ac = UIAlertController(title: "Saved!", message: "Saved to the gallery", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
```
And this is the way I'm extracting RGB values:
```
func pixelData(image: UIImage) -> [UInt8]? {
let size = image.size
let dataSize = size.width * size.height * 4
var pixelData = [UInt8](repeating: 0, count: Int(dataSize))
let colorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGContext(data: &pixelData,width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 4 * Int(size.width), space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)
guard let cgImage = image.cgImage else { return nil }
context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
return pixelData
}
```
I need a way to save the image exactly as it is. Any help?
Edit 1. Text to image injection func:
```
func encrypt(image: UIImage, message: String) -> UIImage {
var text = message
text += endSymbols //Need to decrypt message
var RGBArray = pixelData(image: image)!
let binaryMessage = toBinary(string: text) //Convert characters to binary ASCII number
var counter: Int = 0
for letter in binaryMessage {
for char in letter.characters {
let num = RGBArray[counter]
let characterBit = char
let bitValue = UInt8(String(characterBit))
let resultNum = (num & 0b11111110) | bitValue!
RGBArray[counter] = resultNum
counter += 4 //Modify only RED values bits
}
}
let resultImg = toImage(data: RGBArray, width: Int(image.size.width), height: Int(image.size.height))
return resultImg!
}
```
|
2017/02/10
|
[
"https://Stackoverflow.com/questions/42162038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6300073/"
] |
You need to save in an uncompressed format. I don't know how to programme in swift 3. I have solved the same questions in Objective-c using ALAssetsLibrary.
|
55,570,892 |
I have an iOS app which reads HealthKit data (heart rate) whenever 3rd party devices such as Fitbit, Mi Band 3 etc updates it . Currently I am able to read these data both in foreground and background modes from HealthKit whenever the source for data are these 3rd party health devices. However, i cannot read anything when iWatch updates the HealthKit.
It seems I need to provide authorization to my iOS app to access iWatch data. There is a list of all the apps that needs access to the data. The list is currently empty, meaning, my app does not have this access. Please refer to the attached image.[](https://i.stack.imgur.com/8OGkr.jpg)
I have already implemented authorization for iOS app to read HealthKit. I have enabled HealthKit using "Capabilities" and also added the Privacy options onto the Info.pList
So far, the code for authorizing the iOS to read HealthKit is as follows:
```
let readDataTypes : Set = [HKObjectType.quantityType(forIdentifier: .heartRate)!]
HKStore.requestAuthorization(toShare: nil, read: readDataTypes) { (success, error) in
guard success else{
print("error \(String(describing: error))")
return
}
```
I want to provide my app the authorization for accessing the iWatch data from HeathKit. Any documentations, links and guidance would be appreciated.
|
2019/04/08
|
[
"https://Stackoverflow.com/questions/55570892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4374077/"
] |
You can add initialRouteName in createBottomTabNavigator I will solve your problem
```
const MyApp = createBottomTabNavigator(
{
Inbox: {
screen: Chat,
navigationOptions: ({ navigation }) => ({
title: "Inbox"
})
},
Favourite: {
screen: Favourite,
navigationOptions: ({ navigation }) => ({
title: "Favourite"
})
},
Dashboard: {
screen: Dashboard,
navigationOptions: ({ navigation }) => ({
title: "Home"
})
}
},
{
initialRouteName: "Dashboard"
}
);
```
|
729,628 |
$f(x)=x^2 \sin\left(\frac 1x\right)$ on $(-\infty, 0) \cup (0, \infty)$ and $f(0)=0$
Show that this function is not continuously differentiable in $\mathbb R$.
I don't know how to show differentiability in $\mathbb R$ using the fraction definition of a limit, and what is the appropriate condition for checking continuous differentiability.
|
2014/03/27
|
[
"https://math.stackexchange.com/questions/729628",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/126012/"
] |
At $0$; $f'(0)=0$ (proof?). If $x\neq 0$; $f'(x)=2x\sin x^{-1}-\cos x^{-1}$. Does $\lim\limits\_{x\to 0}f'(x)$ exist?
|
10,350,947 |
I would like to know how to handle saving of transient gen\_servers states when they are associated with a key.
To associate keys with processes, I use a process called pidstore. Pidstore eventually start processes.
I give a Key and a M,F,A to pidstore, it looks for the key in global, then either returns the pid if found or apply MFA (which must return {ok, Pid}), registers the Pid with the key in global and returns the Pid.
I may have many inactive gen\_servers with a possibly huge state. So, i've set the handle\_info callback to save the state in my database and then stops the process. The gen\_servers are considered transient in their supervisor, so they won't be restarted until something needs them again.
Here starts the problems : If I call a process with its key, say {car, 23}, during the saving step of handle\_info in the process which represents {car, 23}, i'll get the pid back as intended, because the process is saving and not finished. So i'll call my process with gen\_server:call but i'll never have a response (and hit default 5 sec. timeout) because the process is stopping. (PROBLEM A)
To solve this problem, the process could unregister itself from global, then save its state, then stop. But if I need it after it's unregistered but before save is finished, I will load a new process, this process could load non-updated values in the database. (PROBLEM B)
To solve this again, I could ensure that loading and saving in the db are enqueued and can not be concurrent. This could be a bottleneck. (PROBLEM C)
I've thinking about another solution : my processes, before saving, could tell the pidstore that they are busy. The pidstore would keep a list of busy processes, and respond 'busy' to any demand on theese keys.
when the save is done, the pidstore would be told no\_more\_busy by the process and could start a new process when asked a key. (Even if the old process is not finished, it's done saving so it can just take his time to die alone).
This seems a bit messy to me but it feels simpler to make several attemps to get the Pid from the key instead of wrapping every call to a gen\_server to handle the possible timeouts. (when the process is finishing but still registrered in global).
I'm a bit confused about all of theese half-problems and half-solutions. What is the design you use in this situation, or how can I avoid this situation ?
I hope my message is legible, please tell me about english errors too.
Thank You
|
2012/04/27
|
[
"https://Stackoverflow.com/questions/10350947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/660380/"
] |
Maybe you want to do the save to DB part in a `gen_server:call`. That would prevent other calls from coming in while you are writing to DB.
Generally it sounds to like you have created a process register. You might want to look into gproc (<https://github.com/uwiger/gproc>) which does a very good job at that if you want register locally. With gproc you can do exactly what you described above, use a key to register a process. Maybe it would be good enough if you register with gproc in your `init` function and unregister when writing to DB. You could also write to DB in your `terminate` function.
|
2,007,616 |
I've got an object that uses System.Version as a property. I want this object to be mapped into my table, storing the version as a string. what's the best way to go about doing this with NHibernate v1.2?
```
public class MyClass
{
public Version MyVersion {get; set;}
}
```
not sure what to do with the propery mapping
<property name="MyVersion" column="MyVersion" not-null="true" />
this gives me errors saying "Invalid attempt to GetBytes on column 'MyVersion0\_0\_'. The GetBytes function can only be used on columns of type Text, NText, or Image." If I use type="string" in the map, i get casting errors.
suggestions?
|
2010/01/05
|
[
"https://Stackoverflow.com/questions/2007616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93448/"
] |
You would need to write an NHibernate user type, that returns a property value of type Version, but persists as a string. There is a skeleton user type implementation [here](http://darrell.mozingo.net/2009/02/10/generic-nhibernate-user-type-base-class/) that takes care of some of the work for you.
|
30,125,037 |
How can I call a servlet from jsp inside an `<a>` tag and pass him a parameter ?
```
<a href="???" />
```
I can write `<a href="/servletName" />` but how to pass him a parameter ?
|
2015/05/08
|
[
"https://Stackoverflow.com/questions/30125037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3364181/"
] |
yes You can do that in two ways:
1. create a function with an ajax call to your servlet.
2. point your **href** to the servlet link (as JB Nizat mentioned)
for the first method, you can follow the below way (if you use jquery) :
```
function callServer(){
$.ajax({
url: 'ServletName',
type: 'POST',
data: 'parameter1='+parameter1,
cache: false,
success: function (data) {
//console.log("SERVLET DATA: " + data);
if (typeof (data) !== 'undefined' && data !== '' && data !== null) {
var response = JSON.parse(data);
console.log(response);
}
},error: function(data){
};
});
}
```
and call this function in your tag like below:
```
<a href="javascript:callServer();"> </a>
```
or the much better way like :
```
<a href="#" onclick="callServer();"> </a>
```
you can select the better approach !
|
41,286,748 |
Twitch has introduced a functionality that, when you've opened a stream page and navigate to a different part of the site, allows the video to keep playing in the bottom left corner without any interruption. This even works when pressing the back button in the browser and only breaks when closing the tab or manually typing in the URL you want to go to (e.g. <https://www.twitch.tv/directory/discover>).
I've been trying to figure out how this is being done. The video is embedded into a div with the class "js-player-persistent", so I assume it has something to do with a Javascript and getting data from the session storage, but I'm unsure how much effort this requires specifically.
Thanks for your help!
|
2016/12/22
|
[
"https://Stackoverflow.com/questions/41286748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7331103/"
] |
Twitch is built on [EmberJS](http://emberjs.com/) on the front end making it a Single Page Application (SPA). This allows them to not have to reload the page as you navigate, they simply utilize AJAX to load in the data needed to show the next page in a prescribed window. This is accomplished by the browser's [pushState](https://developer.mozilla.org/en-US/docs/Web/API/History_API) API or the hashbang implementation for browsers that don't utilize pushState.
Looking at their implementation of it, they likely have a hook that looks for navigation changes, before it happens, off the video player and at that time create a DOM element in that corner and put the video in it, then they proceed with changing the main page to wherever you are going.
This is fairly easily done in most SPA front ends like Angular, React, Ember, Vue, etc. and is a major bonus to them.
|
52,096 |
I'm studying Landau, Lifshitz - Mechanics. Could someone help me with this problem ? =)
**Problem $\S12$ $2(b)$** *(Page 27 3rd Edition)* Determine the period of oscillation, as a function of the energy, when a particle of mass $m$ moves in fields for which the potential energy is
$(b) \quad U=-U\_{0}/\cosh^{2}\alpha x \quad -U\_0<E<0.$
**Attempt at solution:**
The period is given by
$$ T=4 \sqrt{\frac{m}{2}}\int\frac{dx}{\sqrt{E+\frac{U\_{0}}{\cosh^{2}\alpha x}}}.$$
How can I evaluate this integral? I know that the answer is $$T=(\pi/\alpha)\sqrt{2m/|E|}.$$
|
2013/01/24
|
[
"https://physics.stackexchange.com/questions/52096",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20203/"
] |
See [Is Schrödinger’s cat misleading? And what would happen if Planck constant is bigger?](https://physics.stackexchange.com/questions/51935/is-schrodingers-cat-misleading-and-what-would-happen-if-planck-constant-is-big/51938). This isn't an exact duplicate, but it explains why we do believe the cat can be in a superposition of states, but the superposition only lasts a very very short time before it decoheres.
The decoherence has nothing to do with consciousness, simply the number of degrees of freedom of the environment. The article by Luboš Motl that I linked in the above answer explains this in some detail and I strongly recommend it as it's fascinating reading.
|
43,864,465 |
I try to add a parameters.addwithvalue.
Before change the code is like that..........
```
Private Sub ComboBox7_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox7.SelectedIndexChanged
Me.Cursor = Cursors.WaitCursor
MysqlConn.Close()
MysqlConn.Open()
COMMAND.CommandText = "select logo from licenses where name = '" & ComboBox7.Text & "'"
COMMAND.Connection = MysqlConn
Dim da As New MySqlDataAdapter(COMMAND)
Dim ds As New DataSet()
da.Fill(ds, "projectimages")
Dim c As Integer = ds.Tables(0).Rows.Count
If c > 0 Then
If IsDBNull(ds.Tables(0).Rows(c - 1)("logo")) = True Then
PictureBox6.Image = Nothing
Else
Dim bytBLOBData() As Byte = ds.Tables(0).Rows(c - 1)("logo")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
PictureBox6.Image = Image.FromStream(stmBLOBData)
End If
End If
Me.Cursor = Cursors.Default
End Sub
```
Now what i try this to add paramatrers.addwithValue without succes:
```
Private Sub ComboBox7_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox7.SelectedIndexChanged
Me.Cursor = Cursors.WaitCursor
MysqlConn.Close()
MysqlConn.Open()
'COMMAND.CommandText = "select logo from licenses where name = '" & ComboBox7.Text & "'"
COMMAND.CommandText = "select logo from licenses where name = @ComboBox7Select"
COMMAND.Parameters.AddWithValue("@ComboBox7Select", If(String.IsNullOrEmpty(ComboBox7.Text), DBNull.Value, ComboBox7.Text))
COMMAND.Connection = MysqlConn
Dim da As New MySqlDataAdapter(COMMAND)
Dim ds As New DataSet()
da.Fill(ds, "projectimages")
Dim c As Integer = ds.Tables(0).Rows.Count
If c > 0 Then
If IsDBNull(ds.Tables(0).Rows(c - 1)("logo")) = True Then
PictureBox6.Image = Nothing
Else
Dim bytBLOBData() As Byte = ds.Tables(0).Rows(c - 1)("logo")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
PictureBox6.Image = Image.FromStream(stmBLOBData)
End If
End If
Me.Cursor = Cursors.Default
End Sub
```
With error "Parameter '@ComboBox7Select' has already been defined."
What i do to change for work ??
Thanks you.
|
2017/05/09
|
[
"https://Stackoverflow.com/questions/43864465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6732103/"
] |
The problem is that you are using a global variable `COMMAND` that you use each time the selected index changes in your combo. Either you initialize the command each time with:
```
COMMAND=New MySqlCommand()
```
Or you must clear the parameters:
```
COMMAND.Parameters.Clear()
COMMAND.Parameters.AddWithValue("@ComboBox7Select", If(String.IsNullOrEmpty(ComboBox7.Text), DBNull.Value, ComboBox7.Text))
```
But the best way is always create and dispose the `MySql` objects with the `Using` struct:
```
Using MysqlConn As New MySqlConnection(connString)
Using COMMAND As New MySqlCommand()
'your code
End Using
End Using
```
|
41,178,361 |
My git workspace is dirty, there are some local modifications. When I use command `git pull origin master` it works fine because there is no conflict.
But when I'm trying to use `Ansible` like
`git: repo=xxxx dest=xxx version={{branch}}`
I got error:
>
> Local modifications exist in repository (force=no)
>
>
>
If I add `force=yes`, then I will lose my local modifications.
What can I do to keep my local changes and pull latest commit from git by using Ansible git module.
|
2016/12/16
|
[
"https://Stackoverflow.com/questions/41178361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7305240/"
] |
You cannot achieve it using the git module.
Ansible checks [the result of](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/source_control/git.py#L428):
```
git status --porcelain
```
and [aborts task execution](https://github.com/ansible/ansible-modules-core/blob/00911a75ad6635834b6d28eef41f197b2f73c381/source_control/git.py#L975) if there are local changes in tracked files, unless `force` parameter is set to `true`.
|
4,310,605 |
I have a desktop app and when someone presses a button I want it to kick off another JVM that executes a class' main method. My desktop app already depends on the jar that contains the class with the main method that I want to execute.
Currently I've got the following code, however, I was hoping their was a more elegant way of doing this:
```
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("java -jar another.jar");
```
I know I can use ProcessBuilder too.
Is there no way such as (excuse the pseudo code):
```
Jvm.execute(Main.class);
```
Since the Main class that I want to call already exists in my classpath, it just feels weird to have to run the `java` command via Runtime.
|
2010/11/30
|
[
"https://Stackoverflow.com/questions/4310605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30563/"
] |
Very good question. Try to search into management API: <http://cupi2.uniandes.edu.co/javadoc/j2se/1.5.0/docs/api/javax/management/package-frame.html>
Good luck.
I am not sure that this API exists, but if it is it should be there.
I'd personally used ProcessBuilder as you but specify explicit path to java by retrieving system properties of current process.
|
45,357,150 |
I have a table that contains a bill of process for multiple items. I would like to add rows to the result based on the current sequence number and adding a relevant process name to my new rows, e.g.:
**ItemCode Sequence Process**
ABC-1 **10** Disperse
ABC-1 **15** Hold
ABC-1 **20** Grind
ABC-1 **30** Mix
Each current result row should create 3 additional rows (1 preceding and 2 after the existing sequence number), e.g.:
**Item Sequence Process**
ABC-1 **09** Disperse - Load
ABC-1 **10** Disperse - Process
ABC-1 **11** Disperse - Wait
ABC-1 **12** Disperse - Empty
ABC-1 **14** Hold - Load
ABC-1 **15** Hold - Process
ABC-1 **16** Hold - Wait
ABC-1 **17** Hold - Empty
ABC-1 **19** Grind - Load
ABC-1 **20** Grind - Process
ABC-1 **21** Grind - Wait
ABC-1 **22** Grind - Empty
ABC-1 **29** Mix - Load
ABC-1 **30** Mix - Process
ABC-1 **31** Mix - Wait
ABC-1 **32** Mix - Empty
As shown, I would also like to be able to handle the value of the Process column (where Load is sufficed to the preceding row, process suffixes the existing row, wait suffixes the next row and empty suffixes the row after that).
Is such a thing even possible in an elegant manner? I'm a relative novice. Any cues are greatly appreciated.
M :)
|
2017/07/27
|
[
"https://Stackoverflow.com/questions/45357150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8377577/"
] |
Clear the pending timeout with `clearTimeout` whenever you get a new click event:
```js
let button = document.querySelector("button")
let box = document.querySelector(".box")
let timer; // use this variable to trace any pending timeout
button.onclick = () => {
clearTimeout(timer); // clear any pending timeout
box.style.transform = "";
anim1(function(){
anim2(function() {
})
})
}
function anim1(cb) {
box.style.transition = ""
box.clientHeight;
box.style.transition = "all 1s";
box.style.transform = "translateX(50px)";
timer = setTimeout(cb,1000); // remember last created timeout
}
function anim2(cb) {
box.style.transition = ""
box.clientHeight;
box.style.transition = "all 1s";
box.style.transform = "translateX(350px)";
timer = setTimeout(cb,1000); // remember last created timeout
}
```
```css
.box {
height:50px;
width:50px;
background-color:red;
}
```
```html
<button>animate</button>
<div class="box"></div>
```
|
11,975,210 |
I am using this code:
```
$("#total_percentage").text(
(parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10))
);
```
My problem is that #total\_percentage sometimes gives a long result.
e.g: 2.33333333333
Is there a way to setting it so it rounds up / shows only max of 2 digits?
for example: 2 or 10
|
2012/08/15
|
[
"https://Stackoverflow.com/questions/11975210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683553/"
] |
You need to create a member variable in your class to store the reference that you pass it in the constructor. Currently, you are passing in a const reference to the object but the class does nothing with it. You need to store the details of the `MyDb` object as a member variable. This could be a reference, const reference, or pointer to an instance of `MyDb` but you need something so that your class can access it once it is created.
Something like
```
class Streamer {
public:
Streamer(const MyDb& Db);
virtual ~Streamer(void);
private:
const MyDb& realtimeDb;
virtual void callback_1(T_UPDATE pUpdate);
virtual void callback_2(Q_UPDATE pUpdate);
};
```
then the constructor will be
```
Streamer::Streamer(const MyDb& Db)
: realtimeDb(Db) // initialise the reference here
{
}
```
you could also use a pointer instead of a reference if you wanted although you would need to modify the member variable accordingly
|
188,006 |
```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BlendShapesController : MonoBehaviour
{
public Text[] texts;
public bool startTalking = false;
public float talkTime;
public float duration;
[Range(0, 100)]
public float valueRange;
private SkinnedMeshRenderer bodySkinnedMeshRenderer;
private bool isTalking = true;
// Start is called before the first frame update
void Start()
{
bodySkinnedMeshRenderer = GetComponent<SkinnedMeshRenderer>();
}
// Update is called once per frame
void Update()
{
StartTalking();
if (startTalking && isTalking)
{
StartCoroutine(AnimateMouth());
StartCoroutine(TalkTime());
isTalking = false;
}
if (startTalking == false && isTalking == false)
{
isTalking = true;
}
}
//Lerp between startValue and endValue over 'duration' seconds
private IEnumerator LerpShape(float startValue, float endValue, float duration)
{
float elapsed = 0;
while (elapsed < duration)
{
elapsed += Time.deltaTime;
float value = Mathf.Lerp(startValue, endValue, elapsed / duration);
bodySkinnedMeshRenderer.SetBlendShapeWeight(0, value);
yield return null;
}
}
//animate open and closed, then repeat
public IEnumerator AnimateMouth()
{
while (startTalking == true)
{
yield return StartCoroutine(LerpShape(0, valueRange, duration));
yield return StartCoroutine(LerpShape(valueRange, 0, duration));
}
}
public IEnumerator TalkTime()
{
yield return new WaitForSeconds(talkTime);
startTalking = false;
}
public void StartTalking()
{
for (int i = 0; i < texts.Length; i++)
{
if (texts[i].text != "")
{
startTalking = true;
}
}
}
}
```
I want that if one of the ui texts is not empty and not disabled to start talking by calling the StartTalking method. The game start when all the ui texts are disabled one of them is not empty but they are all disabled. And during the game they are turning disabled enabled in the game and get empty not empty. On the ui text is not empty.
The problem is in the Inspector I can't drag disabled ui texts to the array of the script.
All the ui texts are childs under their own parents that are childs of the prefab name Game UI Texts.
[](https://i.stack.imgur.com/FOPdB.jpg)
This are the ui texts in the screenshot that should be dragged to the sccript on the right in the Inspector :
Scene Text , Description Text , and Long Distance Description Text
The main goal is to use one script to control automatic the talking with the text in the game.
When there is a text in the game on the screen StartTalking and stop talking when there is no text on the screen.
|
2020/12/30
|
[
"https://gamedev.stackexchange.com/questions/188006",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/145332/"
] |
If your current Text[] is still 0 as in the screenshot, you need to first increase the size of it to the amount you want to drag -> 3. You can drag them regardless if they are enabled or not.
Now you should be able to drag each of the texts into the text array. There is no need to change the type of the Array to a GameObject Array, Unity is able to find the matching component as long as there is only one Text component on the dragged GameObject.
|
7,058,577 |
File main2.cpp:
```
#include "poly2.h"
int main(){
Poly<int> cze;
return 0;
}
```
File poly2.h:
```
template <class T>
class Poly {
public:
Poly();
};
```
File poly2.cpp:
```
#include "poly2.h"
template<class T>
Poly<T>::Poly() {
}
```
Error during compilation:
```
src$ g++ poly2.cpp main2.cpp -o poly
/tmp/ccXvKH3H.o: In function `main':
main2.cpp:(.text+0x11): undefined reference to `Poly<int>::Poly()'
collect2: ld returned 1 exit status
```
I'm trying to compile above code, but there are errors during compilation. What should be fixed to compile constructor with template parameter?
|
2011/08/14
|
[
"https://Stackoverflow.com/questions/7058577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/738811/"
] |
The full template code must appear in one file. You cannot separate interface and implementation between multiple files like you would with a normal class. To get around this, many people write the class definition in a header and the implementation in another file, and include the implementation at the bottom of the header file. For example:
Blah.h:
```
#ifndef BLAH_H
#define BLAH_H
template<typename T>
class Blah {
void something();
};
#include "Blah.template"
#endif
```
Blah.template:
```
template<typename T>
Blah<T>::something() { }
```
And the preprocessor will do the equivalent of a copy-paste of the contents of `Blah.template` into the `Blah.h` header, and everything will be in one file by the time the compiler sees it, and everyone's happy.
|
157,484 |
>
> **Possible Duplicate:**
>
> [There exists a unique isomorphism $M \otimes N \to N \otimes M$](https://math.stackexchange.com/questions/155601/there-exists-a-unique-isomorphism-m-otimes-n-to-n-otimes-m)
>
>
>
I want to show that for Abelian groups $A$ and $B$ that the tensor product $A \otimes B$ is isomorphic to $B \otimes A$. I believe that I have accomplished this and have posted my attempt as an answer to my own question. I would appreciate any constructive feedback.
|
2012/06/12
|
[
"https://math.stackexchange.com/questions/157484",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/9450/"
] |
Let's use the universal definition of $A\otimes B$: $(A\otimes B,\iota)$, where $\iota\colon A\times B\to A\otimes B$ is a bilinear (resp. $R$-bilinear) map, is the unique group (resp. $R$-module) with the property that for any bilinear map $\phi\colon A\times B\to C$ (resp. $R$-bilinear), where $C$ is any abelian group (rep. $R$-module), there exists a unique homomorphism $\Phi\colon A\otimes B\to C$ such that $\phi=\Phi\circ\iota$.
Let $s\colon A\times B\to B\times A$ be the map $s(a,b) = (b,a)$, and let $(B\otimes A,j)$ be the tensor product of $B$ and $A$. Note that $B\otimes A$ has the corresponding universal property relative to $B\times A$ and $j$.
Now, the map $js\colon A\times B\to B\otimes A$ is a bilinear map (composition of a homomorphism and a bilinear map). Therefore, there exists a unique $\mathcal{F}\colon A\otimes B\to B\otimes A$ such that $js = \mathcal{F}\iota$. Likewise, the map $\iota s^{-1}\colon B\times A\to A\otimes B$ is bilinear, so there exists a unique $\mathcal{G}\colon B\otimes A\to A\otimes B$ such that $\iota s^{-1} = \mathcal{G}j$.
Now consider $\mathcal{GF}\colon A\otimes B\to A\otimes B$. We have that
$$\mathcal{GF}\iota = \mathcal{G}js = \iota s^{-1}s = \iota.$$
But there is supposed to be a *unique* map $f\colon A\otimes B\to A\otimes B$ such that $f\circ\iota = \iota$ (since $\iota$ is bilinear), and clearly $f=\mathrm{id}\_{A\otimes B}$ works. Therefore, $\mathcal{GF}=\mathrm{id}\_{A\otimes B}$.
Symmetrically, $\mathcal{FG}j = \mathcal{F}\iota s^{-1} = jss^{-1} = j$. But $j$ is a bilinear map $B\times A\to B\otimes A$, so there is supposed to be a unique map $g\colon B\otimes A\to B\otimes A$ such that $gj=j$. Since $\mathrm{id}\_{B\otimes A}$ works, that is the unique function with the desired property. Since $\mathcal{FG}$ also works, $\mathcal{FG}=\mathrm{id}\_{B\otimes A}$.
Thus, $\mathcal{FG}=\mathrm{id}\_{B\otimes A}$ and $\mathcal{GF}=\mathrm{id}\_{A\otimes B}$. Therefore, $\mathcal{F}\colon A\otimes B\to B\otimes A$ is an isomorphism, as desired.
Note that we don't need to know *how* we represent $A\otimes B$; we just need the universal property (and that a tensor product exists for any [ordered] pair of groups). Though one can likewise use the universal property to show that if $(M,\iota)$ is a tensor product for $A\times B$, then $(M,\iota s^{-1})$ is a tensor product for $B\times A$, so you just need to know $A\otimes B$ exists.
|
14,553,140 |
I am trying to write a boolean method isSubset (returns a boolean value if every element in set A is in set B and false otherwise) where method call can be written like this `setA.subsetOf(setB)`. My thought is to extract each element of setA and compare it with setB. If the first element of setA is matched with any in setB, proceeding to next element in setA to check. If all elements in setA is matched with any element from setB, method returns true, else (not all elements from setA is in setB) returns false. I already wrote the method to check for containment of an element to a linked list as followed:
```
public boolean contain (Object target) {
boolean status = false;
Node cursor;
for (cursor = head; cursor.getNext() != null; cursor = cursor.getNext()) {
if (target.equals(cursor.getElement()))
status = true;
}
return status;
}
```
Since im still confused about the syntax of linked list operation, my question is how to extract each element and do the rest. Any help would be appreciated.
Node is declared
```
public Node(Object o, Node n) {
element = o;
next = n;
}
```
SLinkedList
```
public SLinkedList() {
head = new Node(null, null); // create a dummy head
size = 0;
}
```
|
2013/01/27
|
[
"https://Stackoverflow.com/questions/14553140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1986597/"
] |
For this case I would try to model the chain and move the responsibility of execution to the chain itself by giving a little bit more of "intelligence" to the nodes. In a way I would consider the nodes as being commands, in the sense that they can execute themselves and, by having a common interface, be able to create [composites](http://www.oodesign.com/composite-pattern.html). (Btw, I'm not a Java programmer, so please forgive me for the possible syntax errors). So, my main design decisions would be:
1. The chain knows how to execute itself.
2. The chain nodes can be composites.
I would start by defining something like:
```
public abstract class ChainNode {
public abstract Content apply(Content content);
}
/**
The NullObject of the chain
http://www.oodesign.com/null-object-pattern.html
*/
public class FinalNode extends ChainNode {
public Content apply(Content content) {
return content;
}
}
/** A sample filter */
public class FilterA extends ChainNode {
private ChainNode nextNode;
FilterA(ChainNode nextNode) {
this.nextNode = nextNode;
}
public Content apply(Content content) {
filteredValue = //Apply the filter
return nextNode.apply(filteredValue);
}
}
/** An if-then-else filter */
public abstract class ConditionalFilter extends ChainNode {
private ChainNode trueFilter;
private ChainNode falseFilter;
ConditionalFilter(ChainNode trueFilter, ChainNode falseFilter) {
this.trueFilter = trueFilter;
this.falseFilter = falseFilter;
}
public Content apply(Content content) {
if (this.evalCondition(content)) {
return this.trueFilter.apply(content);
}
else {
return this.falseFilter.apply(content);
}
}
private abstract boolean evalCondition(Content content);
}
```
Whit this approach what you are doing is turning the control structures into objects and asking them to execute, which even allows you to create a logic different than the standard if-then or switch statements. With this base you could create a chain that has different branching operators, triggering different filtering paths.
Some things to note are:
1. I assumed that a filter returns something of type `Content`, which actually allows you to chain one filter after the other. I guess that is true in your requirement, but I'm not sure.
2. For each new filter you just create a new class and define the `apply` method.
3. The null object is always the last node of a chain, stopping the chain calls.
4. To define a new "branching node" you have to subclass from `ConditionalFilter` and redefine the `evalCondition` method. I don't know if Java has closures (I think it doesn't), but if it has you could instead add a `condition` instance variable and parametrize it with a closure, thus avoiding subclassing for each new condition. Or maybe there is a more accepted workaround for things like this in the Java world, I just don't know :(.
5. I assumed that the conditional branching is decided based on the `content` parameter. If you need more information to make the decision you could have also a context object passed in the `apply` method. Depending on your needs this can be a structured object or just a dictionary if you need more flexibility.
Finally, regarding the construction of the chains, if the chains are long and complex to build I think a [builder](http://www.oodesign.com/builder-pattern.html) here should suit your needs.
HTH
|
237,546 |
I'm trying to add a verb into the following context:
>
> Ever since he was a child, he has been fascinated by the world of
> computers. Now, he is seeking employement with a company where he can
> **...** his passion.
>
>
>
However, no word comes to my mind which I could use. Neither does something come to my mind which I could Google in this case.
Edit: Came up with pursue, any other suggestions?
|
2015/04/04
|
[
"https://english.stackexchange.com/questions/237546",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/58007/"
] |
*[Fulfill](http://www.oxforddictionaries.com/definition/english/fulfil?q=fulfill)* might work:
>
> verb (fulfills, fulfilling, fulfilled)
>
>
> 1.0 Achieve or realize (something desired, promised, or predicted):
>
> *he wouldn’t be able to **fulfill** his ambition to visit Naples*
>
>
> 1.1 (fulfil oneself) Gain happiness or satisfaction by achieving one’s potential:
>
>
> ODO **Emphasis** mine
>
>
>
|
33,106,041 |
In my application, I have to instantiate many different types of objects. Each type contains some fields and needs to be added to a containing type. How can I do this in an elegant way?
My current initialization step looks something like this:
```
public void testRequest() {
//All these below used classes are generated classes from xsd schema file.
CheckRequest checkRequest = new CheckRequest();
Offers offers = new Offers();
Offer offer = new Offer();
HotelOnly hotelOnly = new HotelOnly();
Hotel hotel = new Hotel();
Hotels hotels = new Hotels();
Touroperator touroperator = new Touroperator();
Provider provider = new Provider();
Rooms rooms = new Rooms();
Room room = new Room();
PersonAssignments personAssignments = new PersonAssignments();
PersonAssignment personAssignment = new PersonAssignment();
Persons persons = new Persons();
Person person = new Person();
Amounts amounts = new Amounts();
offers.getOffer().add(offer);
offer.setHotelOnly(hotelOnly);
room.setRoomCode("roomcode");
rooms.getRoom().add(room);
hotels.getHotel().add(hotel);
hotel.setRooms(rooms);
hotelOnly.setHotels(hotels);
checkRequest.setOffers(offers);
// ...and so on and so on
}
```
I really want to avoid writing code like this, because it's a little messy having to instantiate each object separately and then initialize each field across multiple lines of code (e.g. having to call `new Offer()` and then `setHotelOnly(hotelOnly)` and then `add(offer)`).
What elegant methods can I use instead of what I have? Are there any "`Factories`" that can be used? Do you have any references/examples to avoid writing code like this?
I'm really interested in implementing clean code.
---
Context:
I'm developing a `RestClient` Application for sending post requests to a Webservice.
The API is represented as a `xsd schema` file and I created all the Objects with `JAXB`
Before sending a request I have to instantiate many Objects because they have dependencies with each other.
*(An Offer has Hotels, a Hotel has Rooms, a Room has Persons... And these Classes are the generated ones)*
Thanks for your help.
|
2015/10/13
|
[
"https://Stackoverflow.com/questions/33106041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3493036/"
] |
You can either use a constructor or a [builder pattern](http://www.javaworld.com/article/2074938/core-java/too-many-parameters-in-java-methods-part-3-builder-pattern.html) or a variation of the builder pattern to fix the problem of having too many fields in your initialization step.
I'm going to extend your example a bit to prove my point of why these options are useful.
**Understanding your example:**
Lets say an `Offer` is simply a container class for 4 fields:
```
public class Offer {
private int price;
private Date dateOfOffer;
private double duration;
private HotelOnly hotelOnly;
// etc. for as many or as few fields as you need
public int getPrice() {
return price;
}
public Date getDateOfOffer() {
return dateOfOffer;
}
// etc.
}
```
As it stands in your example, to set values to these fields, you use setters:
```
public void setHotelOnly(HotelOnly hotelOnly) {
this.hotelOnly = hotelOnly;
}
```
Unfortunately, this means if you need an offer with values in all of the fields, you have to do what you have:
```
Offers offers = new Offers();
Offer offer = new Offer();
offer.setPrice(price);
offer.setDateOfOffer(date);
offer.setDuration(duration);
offer.setHotelOnly(hotelOnly);
offers.add(offer);
```
Now let's look at improving this.
**Option 1: Constructors!**
A constructor other than the default constructor (the default constructor is currently `Offer()` ) is useful for initializing the values of the fields in your class.
A version of `Offer` using constructors would look like this:
```
public class Offer {
private int price;
private Date dateOfOffer;
//etc.
// CONSTRUCTOR
public Offer(int price, Date dateOfOffer, double duration, HotelOnly hotelOnly) {
this.price = price;
this.dateOfOffer = dateOfOffer;
//etc.
}
// Your getters and/or setters
}
```
Now, we can initialize it in one line!
```
Offers offers = new Offers();
Offer offer = new Offer(price, date, duration, hotelOnly);
offers.add(offer);
```
Even better, if you never use `offer` other than that single line: `offers.add(offer);` you don't even need to save it in a variable!
```
Offers offers = new Offers();
offers.add( new Offer(price, date, duration, hotelOnly) ); // Works the same as above
```
**Option 2: Builder Pattern**
A [builder pattern](http://www.javaworld.com/article/2074938/core-java/too-many-parameters-in-java-methods-part-3-builder-pattern.html) is useful if you want the option of having default values for any of your fields.
The problem a builder pattern solves is the following messy code:
```
public class Offer {
private int price;
private Date dateOfOffer;
// etc.
// The original constructor. Sets all the fields to the specified values
public Offer(int price, Date dateOfOffer, double duration, HotelOnly hotelOnly) {
this.price = price;
this.dateOfOffer = dateOfOffer;
// etc.
}
// A constructor that uses default values for all of the fields
public Offer() {
// Calls the top constructor with default values
this(100, new Date("10-13-2015"), 14.5, new HotelOnly());
}
// A constructor that uses default values for all of the fields except price
public Offer(int price) {
// Calls the top constructor with default values, except price
this(price, new Date("10-13-2015"), 14.5, new HotelOnly());
}
// A constructor that uses default values for all of the fields except Date and HotelOnly
public Offer(Date date, HotelOnly hotelOnly) {
this(100, date, 14.5, hotelOnly);
}
// A bunch more constructors of different combinations of default and specified values
}
```
See how messy that can get?
The builder pattern is another class that you put *inside* your class.
```
public class Offer {
private int price;
// etc.
public Offer(int price, ...) {
// Same from above
}
public static class OfferBuilder {
private int buildPrice = 100;
private Date buildDate = new Date("10-13-2015");
// etc. Initialize all these new "build" fields with default values
public OfferBuilder setPrice(int price) {
// Overrides the default value
this.buildPrice = price;
// Why this is here will become evident later
return this;
}
public OfferBuilder setDateOfOffer(Date date) {
this.buildDate = date;
return this;
}
// etc. for each field
public Offer build() {
// Builds an offer with whatever values are stored
return new Offer(price, date, duration, hotelOnly);
}
}
}
```
Now, you can not have to have so many constructors, but still are able to choose which values you want to leave default, and which you want to initialize.
```
Offers offers = new Offers();
offers.add(new OfferBuilder().setPrice(20).setHotelOnly(hotelOnly).build());
offers.add(new OfferBuilder().setDuration(14.5).setDate(new Date("10-14-2015")).setPrice(200).build());
offers.add(new OfferBuilder().build());
```
That last offer is simply one with all default values. The others are default values except the ones that I set.
See how that makes things easier?
**Option 3: Variation of Builder Pattern**
You can also use the builder pattern by simply making your current setters return the same Offer object. It's exactly the same, except without the extra `OfferBuilder` class.
Warning: As [user WW states below,](https://stackoverflow.com/questions/33106041/how-do-i-initialize-classes-with-lots-of-fields-in-an-elegant-way/33106850#comment54343029_33106850) this option breaks [JavaBeans - a standard programming convention for container classes such as Offer](https://stackoverflow.com/questions/3295496/what-is-a-javabean-exactly). So, you shouldn't use this for professional purposes, and should limit your use in your own practices.
```
public class Offer {
private int price = 100;
private Date date = new Date("10-13-2015");
// etc. Initialize with default values
// Don't make any constructors
// Have a getter for each field
public int getPrice() {
return price;
}
// Make your setters return the same object
public Offer setPrice(int price) {
// The same structure as in the builder class
this.price = price;
return this;
}
// etc. for each field
// No need for OfferBuilder class or build() method
}
```
And your new initialization code is
```
Offers offers = new Offers();
offers.add(new Offer().setPrice(20).setHotelOnly(hotelOnly));
offers.add(new Offer().setDuration(14.5).setDate(new Date("10-14-2015")).setPrice(200));
offers.add(new Offer());
```
That last offer is simply one with all default values. The others are default values except the ones that I set.
---
So, while it's a lot of work, if you want to clean up your initialization step, you need to use one of these options for each of your classes that have fields in them. Then use the initialization methods that I included with each method.
Good luck! Does any of this need further explanation?
|
74,365,399 |
I am learning the php code.
I'm in a situation where it has to be done as soon as possible.
Please help me reorganize my xml duplicate data.
original .xml file
```
<products>
<product>
<ID>ID1</ID>
<SKU_parent>SKU1</SKU_parent>
<SKU>MA</SKU>
<price>10</price>
<price-sale>5</price-sale>
<KHO1>10</KHO1>
<KHO2>6</KHO2>
<KHO3>2</KHO3>
</product>
<product>
<ID>ID2</ID>
<SKU_parent>SKU2</SKU_parent>
<SKU>MA2</SKU>
<price>500</price>
<price-sale>200</price-sale>
<KHO1>20</KHO1>
<KHO2>0</KHO2>
<KHO3>0</KHO3>
</product>
<product>
<ID>ID3</ID>
<SKU_parent>SKU2</SKU_parent>
<SKU>MA2</SKU>
<price>500</price>
<price-sale>200</price-sale>
<KHO1>0</KHO1>
<KHO2>30</KHO2>
<KHO3>0</KHO3>
</product>
<product>
<ID>ID2</ID>
<SKU_parent>SKU2</SKU_parent>
<SKU>MA2</SKU>
<price>500</price>
<price-sale>200</price-sale>
<KHO1>0</KHO1>
<KHO2>0</KHO2>
<KHO3>40</KHO3>
</product>
```
into something like this:
```
<products>
<product>
<ID>ID1</ID>
<SKU_parent>SKU1</SKU_parent>
<SKU>MA</SKU>
<price>10</price>
<price-sale>5</price-sale>
<KHO1>10</KHO1>
<KHO2>6</KHO2>
<KHO3>2</KHO3>
</product>
<product>
<ID>ID2</ID>
<SKU_parent>SKU2</SKU_parent>
<SKU>MA2</SKU>
<price>500</price>
<price-sale>200</price-sale>
<KHO1>20</KHO1>
<KHO2>30</KHO2>
<KHO3>40</KHO3>
</product>
```
I've tried searching on stackoverflow but it doesn't seem to work.
I appreciate it when someone help me with this php code
|
2022/11/08
|
[
"https://Stackoverflow.com/questions/74365399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14302722/"
] |
For starters, I converted your XML string into an array.
I reduced your array using `SKU_parent` as a unique key.
I rebuilt the array again into a XML, using the Francis Lewis function (with some slight modifications, by hardcoding the `product` node if the array key was numeric) - Source: <https://stackoverflow.com/a/19987539/4527645>
```
$xml_string = '<products>
<product>
<ID>ID1</ID>
<SKU_parent>SKU1</SKU_parent>
<SKU>MA</SKU>
<price>10</price>
<price-sale>5</price-sale>
<KHO1>10</KHO1>
<KHO2>6</KHO2>
<KHO3>2</KHO3>
</product>
<product>
<ID>ID2</ID>
<SKU_parent>SKU2</SKU_parent>
<SKU>MA2</SKU>
<price>500</price>
<price-sale>200</price-sale>
<KHO1>20</KHO1>
<KHO2>0</KHO2>
<KHO3>0</KHO3>
</product>
<product>
<ID>ID3</ID>
<SKU_parent>SKU2</SKU_parent>
<SKU>MA2</SKU>
<price>500</price>
<price-sale>200</price-sale>
<KHO1>0</KHO1>
<KHO2>30</KHO2>
<KHO3>0</KHO3>
</product>
<product>
<ID>ID2</ID>
<SKU_parent>SKU2</SKU_parent>
<SKU>MA2</SKU>
<price>500</price>
<price-sale>200</price-sale>
<KHO1>0</KHO1>
<KHO2>0</KHO2>
<KHO3>40</KHO3>
</product>
</products>';
$xml = simplexml_load_string($xml_string, 'SimpleXMLElement', LIBXML_NOCDATA);
$json = json_encode($xml);
$xml_array = json_decode($json, true);
$unique = array_reduce($xml_array['product'], function($final, $article){
static $seen = [];
if (!array_key_exists($article['SKU_parent'], $seen)) {
$seen[$article['SKU_parent']] = NULL;
$final[] = $article;
}
return $final;
});
function to_xml(SimpleXMLElement $object, array $data)
{
foreach ($data as $key => $value) {
if (is_array($value)) {
if (is_numeric($key)) {
$new_object = $object->addChild('product');
}
to_xml($new_object, $value);
} else {
if ($key != 0 && $key == (int) $key) {
$key = "key_$key";
}
$object->addChild($key, $value);
}
}
}
$xml = new SimpleXMLElement('<products/>');
to_xml($xml, $unique);
header('Content-Type: text/xml');
print $xml->asXML();
```
You can also check a working example of this code here: <https://onlinephp.io/c/1d06d>
This code eliminates the duplicate product nodes by `SKU_parent`. In order to merge all the values that are not 0, you have to improve the `array_reduce` or find another method with `array_merge_recursive` for example. This is just a starting point.
|
46,006,116 |
Suppose I have measurements of two signals
```
V = V(t) and U = U(t)
```
that are periodic in time with a phase difference between them. When plotted against each other in a graph `V vs U` they form a Lissajous figure, and I want to calculate the area inside it.
Is there an algorithm for such calculation?
I would like to solve this problem using Python. But a response in any language or an algorithm to do it will be very appreciated.
Examples of V and U signals can be generated using expressions like:
```
V(t) = V0*sin(2*pi*t) ; U(t) = U0*sin(2*pi*t + delta)
```
Figure 1 shows a graph of `V,U` vs `t` for `V0=10, U0=5, t=np.arange(0.0,2.0,0.01)` and `delta = pi/5`.

And Figure 2 shows the corresponding Lissajous figure `V` vs `U`.
[](https://i.stack.imgur.com/beKvB.png)
This is an specific problem of a more general question: How to calculate a closed path integral obtained with a discrete `(x_i,y_i)` data set?
|
2017/09/01
|
[
"https://Stackoverflow.com/questions/46006116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7167710/"
] |
To find area of (closed) parametric curve in Cartesian coordinates, you can use Green's theorem ([4-th formula here](http://mathworld.wolfram.com/GreensTheorem.html))
```
A = 1/2 * Abs(Integral[t=0..t=period] {(V(t) * U'(t) - V'(t) * U(t))dt})
```
But remember that interpretation - what is real area under self-intersected curves - is ambiguous, as @algrid noticed in comments
|
74,101,841 |
I am beginner I tried so many times but I couldn't solve this problem I will be very pleased if you help me...
the question is:
1. Let x be an integer, and R(x) is a function that returns the reverse of the x in terms of its digits.
2. For example , if x:1234 then R(x)=4321.
3. Let’s call a positive integer mirror-friendly if it satisfies the following condition: + () = ^2 ℎ
4. Write a program that reads a positive integer as n from the user and prints out a line for each of the first n mirror-friendly integers as follows: x + R(x) = y^2
5. Example: If the user enters 5 as n, then the program should print out the following:
```
2 + 2 = 2^2
8 + 8 = 4^2
29 + 92 = 11^2
38 + 83 = 11^2
47 + 74 = 11^2
```
Here is the my code:
```
int
reverse(int num)
{
int reverse,
f,
i;
reverse = 0;
i = 0;
for (; i < num + i; i++) {
f = num % 10;
reverse = (reverse * 10) + f;
num /= 10;
}
return reverse;
}
int
sqrt(int n)
{
int i = 1;
int sqrt;
for (; i <= n; i++) {
sqrt = i * i;
}
return sqrt;
}
int
main()
{
int j = 1;
int main_num = 0;
for (; main_num <= 0;) {
printf("Please enter a positive integer: \n");
scanf_s("%d", &main_num);
}
int count = 0;
for (int i = 1; i <= main_num; i++) {
for (; j <= main_num; j++) {
if (j + reverse(j) == sqrt(?)) {
printf("%d + %d = %d\n", j, reverse(j), sqrt(?));
}
}
}
}
```
|
2022/10/17
|
[
"https://Stackoverflow.com/questions/74101841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18484780/"
] |
A few issues ...
1. `sqrt` does *not* compute the square root
2. `reverse` seems overly complicated
3. `main_num` (i.e. `n` from the problem statement) is the desired maximum *count* of matches and *not* the limit on `x`
4. Too many repeated calls to `sqrt` and `reverse`
5. No argument given to `sqrt`
6. The `if` in `main` to detect a match is incorrect.
7. `sqrt` conflicts with a standard function.
8. The variables you're using don't match the names used in the problem statement.
9. The `printf` didn't follow the expected output format.
10. Using a function scoped variable that is the same as the function is a bit confusing (to humans and the compiler).
---
Unfortunately, I've had to heavily refactor the code. I've changed all the variable names to match the names used in the problem statement for clarity:
```
#include <stdio.h>
#include <stdlib.h>
#ifdef DEBUG
#define dbgprt(_fmt...) printf(_fmt)
#else
#define dbgprt(_fmt...) do { } while (0)
#endif
int
reverse(int x)
{
int r = 0;
for (; x != 0; x /= 10) {
int f = x % 10;
r = (r * 10) + f;
}
return r;
}
int
isqrt(int x)
{
int y = 1;
while (1) {
int y2 = y * y;
if (y2 >= x)
break;
++y;
}
return y;
}
int
main(int argc,char **argv)
{
int n = -1;
--argc;
++argv;
if (argc > 0) {
n = atoi(*argv);
printf("Positive integer is %d\n",n);
}
while (n <= 0) {
printf("Please enter a positive integer:\n");
scanf("%d", &n);
}
int x = 1234;
dbgprt("x=%d r=%d\n",x,reverse(x));
int count = 0;
for (x = 1; count < n; ++x) {
dbgprt("\nx=%d count=%d\n",x,count);
// get reverse of number (i.e. R(x))
int r = reverse(x);
dbgprt("r=%d\n",r);
// get x + R(x)
int xr = x + r;
dbgprt("xr=%d\n",xr);
// get y
int y = isqrt(xr);
dbgprt("y=%d\n",y);
if (xr == (y * y)) {
printf("%d + %d = %d^2\n", x, r, y);
++count;
}
}
return 0;
}
```
---
Here is the program output:
```
Positive integer is 5
2 + 2 = 2^2
8 + 8 = 4^2
29 + 92 = 11^2
38 + 83 = 11^2
47 + 74 = 11^2
```
---
**UPDATE:**
The above `isqrt` uses a linear search. So, it's a bit slow.
Here is a version that uses a binary search:
```
// isqrt -- get sqrt (binary search)
int
isqrt(int x)
{
int ylo = 1;
int yhi = x;
int ymid = 0;
// binary search
while (ylo <= yhi) {
ymid = (ylo + yhi) / 2;
int y2 = ymid * ymid;
// exact match (i.e. x == y^2)
if (y2 == x)
break;
if (y2 > x)
yhi = ymid - 1;
else
ylo = ymid + 1;
}
return ymid;
}
```
---
**UPDATE #2:**
The above code doesn't scale too well for very large `x` values (i.e. large `n` values).
So, `main` should check for wraparound to a negative number for `x`.
And, a possibly safer equation for `isqrt` is:
```
ymid = ylo + ((yhi - ylo) / 2);
```
Here is an updated version:
```
#include <stdio.h>
#include <stdlib.h>
#ifdef DEBUG
#define dbgprt(_fmt...) printf(_fmt)
#else
#define dbgprt(_fmt...) do { } while (0)
#endif
// reverse -- reverse a number (e.g. 1234 --> 4321)
int
reverse(int x)
{
int r = 0;
for (; x != 0; x /= 10) {
int f = x % 10;
r = (r * 10) + f;
}
return r;
}
// isqrt -- get sqrt (linear search)
int
isqrt(int x)
{
int y = 1;
while (1) {
int y2 = y * y;
if (y2 >= x)
break;
++y;
}
return y;
}
// isqrt2 -- get sqrt (binary search)
int
isqrt2(int x)
{
int ylo = 1;
int yhi = x;
int ymid = 0;
// binary search
while (ylo <= yhi) {
#if 0
ymid = (ylo + yhi) / 2;
#else
ymid = ylo + ((yhi - ylo) / 2);
#endif
int y2 = ymid * ymid;
// exact match (i.e. x == y^2)
if (y2 == x)
break;
if (y2 > x)
yhi = ymid - 1;
else
ylo = ymid + 1;
}
return ymid;
}
int
main(int argc,char **argv)
{
int n = -1;
--argc;
++argv;
setlinebuf(stdout);
// take number from command line
if (argc > 0) {
n = atoi(*argv);
printf("Positive integer is %d\n",n);
}
// prompt user for expected/maximum count
while (n <= 0) {
printf("Please enter a positive integer:\n");
scanf("%d", &n);
}
int x = 1234;
dbgprt("x=%d r=%d\n",x,reverse(x));
int count = 0;
for (x = 1; (x > 0) && (count < n); ++x) {
dbgprt("\nx=%d count=%d\n",x,count);
// get reverse of number (i.e. R(x))
int r = reverse(x);
dbgprt("r=%d\n",r);
// get x + R(x)
int xr = x + r;
dbgprt("xr=%d\n",xr);
// get y
#ifdef ISQRTSLOW
int y = isqrt(xr);
#else
int y = isqrt2(xr);
#endif
dbgprt("y=%d\n",y);
if (xr == (y * y)) {
printf("%d + %d = %d^2\n", x, r, y);
++count;
}
}
return 0;
}
```
In the above code, I've used `cpp` conditionals to denote old vs. new code:
```
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
```
Note: this can be cleaned up by running the file through `unifdef -k`
|
23,817,435 |
When moving an `unordered_set` out on GCC 4.9, and then reusing the moved-from object, I am getting a divide-by-zero when I add to it.
My understanding (from <http://en.cppreference.com/w/cpp/utility/move>) is that the moved-from object can be used provided none of its preconditions are violated. Calling `clear()` on the moved-from set is fine (which makes sense in the context of preconditions), but it's not clear to me that I'm violating any precondition by adding a new element.
Example code:
```
#include <unordered_set>
using namespace std;
void foo(unordered_set<int> &&a) {
unordered_set<int> copy = std::move(a);
}
void test() {
unordered_set<int> a;
for (int i = 0; i < 12; ++i) a.insert(i);
foo(std::move(a));
a.clear();
a.insert(34); // divide by zero here
}
int main() {
test();
}
```
This code works fine on GCC4.7 - is this an issue in GCC4.9's `unordered_set` implementation, or in my understanding of what it means to violate preconditions on moved-from objects?
|
2014/05/22
|
[
"https://Stackoverflow.com/questions/23817435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/390318/"
] |
This is [PR 61143](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61143). It has been fixed for gcc-4.10 and the fix has been backported in time for 4.9.1.
|
57,563 |
I need to setup a Raspberry Pi to start and open a browser with a specific URL in fullscreen mode. I have been using Ubuntu Mate and Firefox to do that, but I would like to know if there is a better way to achieve this goal?
|
2016/11/12
|
[
"https://raspberrypi.stackexchange.com/questions/57563",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/56408/"
] |
I learned about `nodm` today from [this answer](https://raspberrypi.stackexchange.com/a/57560/5538), to a question that is only a slight variation on this one. "Nodm" sounds clever and likely works on almost any distro; I notice the Arch linux wiki has [a page about it](https://wiki.archlinux.org/index.php/Nodm) with some additional useful information -- most significantly the point about *disabling (other) **display managers*** (this is not a recommendation to use Arch, but because they have better documentation than most other distros, and most of that information is about software that is used on other distros as well, such as systemd, which is mentioned in that article with regard to disabling the normal display manager).
[Display managers](https://en.wikipedia.org/wiki/X_display_manager_(program_type)) (DMs) are the programs that present a graphical login. They are a distinct entity from [desktop environments](https://en.wikipedia.org/wiki/Desktop_environment) (DEs), since different users of the same machine may choose to use different DEs (and in fact, you can have simulataneous logins of different users running different DEs; the sessions run on separate [virtual consoles](https://en.wikipedia.org/wiki/Virtual_console) and can be switched between using `Ctrl``Alt``F-[1-6+]`), but the login is always the same DM. Last I checked, the display manager used on Raspbian was `lightdm`, but there are others -- it doesn't really matter which one is in play as long as you know what it is because again, all you want to do is disable it.
I mention all that for a couple of reasons:
* On a distro with a default GUI, the DM is going to get in your way, because you want a GUI, but you don't want a DM, but the way things are configured on such a system, the DM is run as an [init](https://en.wikipedia.org/wiki/Init) service. You need to circumvent or supplant this service via the init system (which is usually **systemd**).
* To do that so you can still work with the GUI effectively you need to understand how the the GUI stack works. Like any software stack, it is composed of layers:
+ The first, most fundamental layer, common to the vast majority of GNU/Linux systems, is the [Xorg server](https://en.wikipedia.org/wiki/X.Org_Server). You need this.
+ The second layer normally is a [window manager](https://en.wikipedia.org/wiki/Window_manager) (WM). You *may* want this. Note the more elaborate diagram of the GUI stack in that wikipedia article.
+ The third layer, normally, is a DE. On Raspbian this is by default PIXEL, a recent fork of LXDE. You almost certainly *don't* want this.
Personally, I would start with a distro with no GUI (such as Raspbian lite), and *add* components to get what I want, rather than starting with a desktop system and modifying it to create a kiosk. However, that is just an opinion, and I can't say it will be easier unless you understand what you are doing, which is why I am painting a big picture here and including a lot of links to other reading.
Working this way, the goal can be broken into two:
1. Create an init service that is going to do what a DM usually does, namely, start the Xorg server at boot and run an application on top of it, possibly with the aid of a WM. Something to be aware of here is that you probably do not want the X session to be a root session, hence autologins are sometimes used for kiosks. Another option is to simply downgrade privileges, since the root user can start something as someone else. However, there is a serious weakness in that if someone is able to stop whatever and return to a root login, so you would want to do that *with no login*, which is how init services work.
As tjohnson notes in a comment below, `nodm` is probably a perfect way to deal with these issues.
2. Get your application to run inside X the way you want it. This is really the easy part, since it is mostly just a matter of telling X what command(s) to run. Normally that's a DM or DE, but it can be a standalone application such as a web browser.
|
351,248 |
[Dark Mode](https://meta.stackoverflow.com/q/395949/4751173) has now officially launched on Stack Overflow, and the linked post indicates it will become available for Meta Stack Overflow (when?). It also says other sites in the network probably won't get Dark Mode because of large theme differences. But what about the non-English Stack Overflow sites? They basically use the same theme, the only difference is the colour of the logo. If you can enable Dark Mode [here](https://stackoverflow.com/questions/), you can do it [here](https://es.stackoverflow.com/questions/) as well. Are there any plans for this?
(Inspired by [¿Cuándo llega el modo oscuro a Stack Overflow en español?](https://es.meta.stackoverflow.com/q/4779/22845) – "When does Dark Mode arrive on Stack Overflow in Spanish?". I'm posting this here since it affects multiple sites in the network.)
|
2020/07/24
|
[
"https://meta.stackexchange.com/questions/351248",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/295232/"
] |
The feature is now live on the other sites:
* Japanese: [ダークモードが利用可能になりました!](https://ja.meta.stackoverflow.com/q/3426/19769)
* Portuguese: [Tema escuro agora disponível no Stack Overflow em Português!](https://pt.meta.stackoverflow.com/q/8483/57567)
* Russian: [Темный режим доступен на Stack Overflow на русском!](https://ru.meta.stackoverflow.com/q/10996/223536)
* Spanish: [Modo de noche ya disponible en Stack Overflow en español](https://es.meta.stackoverflow.com/q/4906/22845)
It looks like your preference is even automatically synchronized with the English Stack Overflow. Well done!
|
38,377,103 |
I am writing angular2 app.
I need all my buttons and select with be disabled and then I need to enable them. I want to do that by using my class field butDisabled but with no luck.
I have this code:
```ts
@Component({
selector: 'my-app',
template:`
<h1>Disable Enable</h1>
<h2> this is a disabled select </h2>
<select type="number" [(ngModel)]="levelNum" (ngModelChange)="toNumber()" disabled>
<option *ngFor="let level of levels" [ngValue]="level.num">{{level.name}}</option>
</select>
<h2> this is a disabled button </h2>
<button type="button" class="btn btn-default {{butDisabled}}">Disabled</button>
<h2> Why can't I disable the select the same way? </h2>
<select type="number" [(ngModel)]="levelNum" (ngModelChange)="toNumber()" class="{{butDisabled}}">
<option *ngFor="let level of levels" [ngValue]="level.num">{{level.name}}</option>
</select>
`,
})
export class AppComponent {
butDisabled = "disabled";
levelNum:number;
levels:Array<Object> = [
{num: 0, name: "AA"},
{num: 1, name: "BB"}
];
}
```
I don't understand why I can't use the {{butDisabled}} to disable the select.
What Am I doing wrong?
Thanks a lot
here is a [plunker](https://plnkr.co/edit/BhrVOX?p=preview)
|
2016/07/14
|
[
"https://Stackoverflow.com/questions/38377103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742310/"
] |
You could just bind to the `[disabled]` attribute like so:
```html
<button type="button" class="btn btn-default" [disabled]="butDisabled">Disabled</button>
<select type="number" [(ngModel)]="levelNum" (ngModelChange)="toNumber()" [disabled]="butDisabled">
<option *ngFor="let level of levels" [ngValue]="level.num">{{level.name}}</option>
</select>
```
And in your component make the variable a boolean:
```ts
export class AppComponent {
butDisabled: boolean = true;
```
---
>
> Working [Plunker](https://plnkr.co/edit/CqLiNLpNl4nAd0DfXdbi?p=preview) for example usage
>
>
>
|
35,224,963 |
I have a large spreadsheet containing multiple sets of information. I have provided a shortened example of the spreadsheet below. Please note that every table in the real list contains considerably more terms.
I need to test whether the terms in column A fall within the list in column E **and** whether the terms in column B fall within the list in column G.
For example, looking at row 2, does the 'Type 1' data (A) fall within the list in column E (A,C,D) **and** does the 'Type 2' data (X) fall within the list in column G (X,Y). In this instance the answer is yes and therefore 'TRUE' would be entered in column C.
I have tried to use the formula below but am not getting very far with it.
Any suggestions?
```
=IF((A2=$E$2:$E$4)*(B2=$G$2:$G$3),TRUE,FALSE)
```
[](https://i.stack.imgur.com/s5JhG.png)
|
2016/02/05
|
[
"https://Stackoverflow.com/questions/35224963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5599275/"
] |
This should be sufficient no matter how large your actual lists become.
```
=AND(ISNUMBER(MATCH(A2, E$2:E$4, 0)), ISNUMBER(MATCH(B2, F$2:F$3, 0)))
```
Those E$2:E$4 and F$2:F$3 ranges could be full column if desired; e.g. E:E and F:F.
[](https://i.stack.imgur.com/U8Zcy.png)
|
10,149,424 |
I have this dictionary that stores pairs of two quiz scores and participants' ID. The structure is {(quiz1, quiz2): ID}
```
scoredict = {('83', '93'): '81937', ('88', '86'): '33576', ('96', '97'): '01084',
('81', '95'): '48534', ('84', '72'): '11235', ('77', '80'): '01835', ('90', '83'):
'39488', ('75', '74'): '31049', ('80', '62'): '10188', ('85', '86'): '63011',
('66', '89'): '58272'}
```
I want to make this program to look up for an ID by entering a pair of quiz scores. Like, for example, if the user input 83 and 93 for quiz 1 and quiz 2, it will return 81937. I've been working on this since the last 48 hours, but none of my codes worked...
And is it possible to find the closest available scores for both quizzes and print the ID?
|
2012/04/13
|
[
"https://Stackoverflow.com/questions/10149424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1259061/"
] |
I verified your solution already works with [ipython](http://ipython.org/):
```
In [1]: scoredict = {('83', '93'): '81937', ('88', '86'): '33576', ('96', '97'): '01084',
...: ('81', '95'): '48534', ('84', '72'): '11235', ('77', '80'): '01835', ('90', '83'):
...: '39488', ('75', '74'): '31049', ('80', '62'): '10188', ('85', '86'): '63011',
...: ('66', '89'): '58272'}
In [2]: scoredict['83','93']
Out[2]: '81937'
```
|
42,036,155 |
I am currently working in c# project. I have a table named `tbl1` which have only one column named `Beta` and I have another table named `tbl2` which also have only one column named `Alpha`.
I want to compare both the table. If I click the button then if the second table has value
>
> "A, D, R, B, A, E, B, Y"
>
>
>
match's with the first table value i.e.
>
> "A, E, B"
>
>
>
then the resultant value should show in gridview and the result should be
>
> "A, B, E, B".
>
>
>
|
2017/02/04
|
[
"https://Stackoverflow.com/questions/42036155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7511191/"
] |
Looks like it's a an issue with how Ruby resolves DNS.
Added `require 'resolv-replace'` and now it's opening connections immediately.
Sources:
<https://stackoverflow.com/a/27485369/116925>
<https://github.com/ruby/ruby/pull/597#issuecomment-40507119>
|
44,389,752 |
I know that there is a way how to set my application desktop toolbar to autohide, but unfortunately I don't know how to use it properly. Can you someone give me an example, please? I'm programming `AppBar` in `C# WinForm`.
Thank you very much
There is a code, which I'm using for registering the `AppBar`.
```
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayout(LayoutKind.Sequential)]
private struct APPBARDATA
{
public int cbSize;
public IntPtr hWnd;
public int uCallbackMessage;
public int uEdge;
public RECT rc;
public IntPtr lParam;
}
private enum ABMsg : int
{
ABM_NEW = 0,
ABM_REMOVE,
ABM_QUERYPOS,
ABM_SETPOS,
ABM_GETSTATE,
ABM_GETTASKBARPOS,
ABM_ACTIVATE,
ABM_GETAUTOHIDEBAR,
ABM_SETAUTOHIDEBAR,
ABM_WINDOWPOSCHANGED,
ABM_SETSTATE
}
private enum ABNotify : int
{
ABN_STATECHANGE = 0,
ABN_POSCHANGED,
ABN_FULLSCREENAPP,
ABN_WINDOWARRANGE
}
private enum ABEdge : int
{
ABE_LEFT = 0,
ABE_TOP,
ABE_RIGHT,
ABE_BOTTOM
}
private bool isBarRegistered = false;
private int uCallBack;
[DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]
private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);
[DllImport("USER32")]
private static extern int GetSystemMetrics(int Index);
[DllImport("User32.dll", ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool MoveWindow(IntPtr hWnd, int x, int y, int cx, int cy, bool repaint);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern int RegisterWindowMessage(string msg);
private void RegisterBar(bool dvojty)
{
APPBARDATA abd = new APPBARDATA();
abd.cbSize = Marshal.SizeOf(abd);
abd.hWnd = this.Handle;
if (!isBarRegistered)
{
if (Properties.Settings.Default.Strana.ToLower() == "ano")
{
this.Width = minSirka;
this.Height = Screen.FromPoint(this.Location).WorkingArea.Height;
}
else
{
this.Width = Screen.FromPoint(this.Location).WorkingArea.Width;
this.Height = minVyska;
}
uCallBack = RegisterWindowMessage("AppBarMessage");
abd.uCallbackMessage = uCallBack;
uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);
isBarRegistered = true;
ABSetPos(hrana);
}
else
{
toolBar = new Rectangle(0, 0, 0, 0);
SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);
isBarRegistered = false;
//this.TopMost = true;
if (dvojty)
{
if (Properties.Settings.Default.Strana.ToLower() == "ano")
{
this.Width = minSirka;
this.Height = Screen.FromPoint(this.Location).WorkingArea.Height;
}
else
{
this.Width = Screen.FromPoint(this.Location).WorkingArea.Width;
this.Height = minVyska;
}
uCallBack = RegisterWindowMessage("AppBarMessage");
abd.uCallbackMessage = uCallBack;
uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);
isBarRegistered = true;
ABSetPos(hrana);
}
}
}
private void ABSetPos(string edge)
{
APPBARDATA abd = new APPBARDATA();
//SHAppBarMessage((int)ABMsg.ABM_SETAUTOHIDEBAR, ref abd);
abd.cbSize = Marshal.SizeOf(abd);
abd.hWnd = this.Handle;
if (edge == "" || edge == "top")
{
abd.uEdge = (int)ABEdge.ABE_TOP;
}
else if (edge == "right")
{
abd.uEdge = (int)ABEdge.ABE_RIGHT;
}
else if (edge == "left")
{
abd.uEdge = (int)ABEdge.ABE_LEFT;
}
else if (edge == "bottom")
{
abd.uEdge = (int)ABEdge.ABE_BOTTOM;
}
else
{
abd.uEdge = (int)ABEdge.ABE_TOP;
}
if (abd.uEdge == (int)ABEdge.ABE_LEFT || abd.uEdge == (int)ABEdge.ABE_RIGHT)
{
abd.rc.top = 0;
abd.rc.bottom = SystemInformation.PrimaryMonitorSize.Height;
if (abd.uEdge == (int)ABEdge.ABE_LEFT)
{
abd.rc.left = 0;
abd.rc.right = Size.Width;
okraj = "left";
}
else
{
abd.rc.right = SystemInformation.PrimaryMonitorSize.Width;
abd.rc.left = abd.rc.right - Size.Width;
okraj = "right";
}
}
else
{
abd.rc.left = Screen.FromControl(this).WorkingArea.Left;
abd.rc.right = Screen.FromControl(this).WorkingArea.Right;
if (abd.uEdge == (int)ABEdge.ABE_TOP)
{
abd.rc.top = Screen.FromControl(this).WorkingArea.Top;
abd.rc.bottom = Size.Height;
okraj = "top";
}
else
{
abd.rc.bottom = Screen.FromControl(this).WorkingArea.Bottom;
abd.rc.top = abd.rc.bottom - Size.Height;
okraj = "bottom";
}
}
SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref abd);
switch (abd.uEdge)
{
case (int)ABEdge.ABE_LEFT:
abd.rc.right = abd.rc.left + Size.Width;
break;
case (int)ABEdge.ABE_RIGHT:
abd.rc.left = abd.rc.right - Size.Width;
break;
case (int)ABEdge.ABE_TOP:
abd.rc.bottom = abd.rc.top + Size.Height;
break;
case (int)ABEdge.ABE_BOTTOM:
abd.rc.top = abd.rc.bottom - Size.Height;
break;
}
this.Top -= 1;
SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref abd);
MoveWindow(abd.hWnd, abd.rc.left, abd.rc.top, Size.Width, Size.Height, true);
toolBar = new Rectangle(abd.rc.left, abd.rc.top, Size.Width, Size.Height);
left = this.Left;
top = this.Top;
}
```
|
2017/06/06
|
[
"https://Stackoverflow.com/questions/44389752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7532787/"
] |
I would follow the "Singleton" design pattern, which ensures that only one instance of a class is created. Here is a well-accepted template for such a class:
```
Public NotInheritable Class MySerial
Private Shared ReadOnly _instance As New Lazy(Of MySerial)(Function() New
MySerial(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication)
Private Sub New()
End Sub
Public Shared ReadOnly Property Instance() As MySerial
Get
Return _instance.Value
End Get
End Property
```
End Class
In the `New()` method you should set up your serial port as you need to. Then no matter where you need to use the port, you make your references to the Instance:
```
Dim singletonSerial As MySerial = MySerial.Instance
```
This is the canonical pattern to ensure that you have only one copy of an object without resorting to static classes. It's a design pattern that dates back more than 20 years and still works great when you need exactly one copy of an object.
|
12,778,011 |
In the Ruby application which I'm developing, given latitude and longitude of a point, I need to find the nearest road/highway to the point.
Can someone tell me how I can go about this using Google Places API?
I have tried giving a certain radius and finding the roads using the `'types:"route"'` parameter but it gives me "Zero results" as the output.
|
2012/10/08
|
[
"https://Stackoverflow.com/questions/12778011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1696392/"
] |
The Google Places API is not designed to return nearby geographical locations, it is designed to return a list of nearby `establishments` and up to two `locality` or `political` type results to to help identify the area you are performing a Place Search request for.
The functionality you are requesting would be possible with the [Google Geocoding API](https://developers.google.com/maps/documentation/geocoding/) by passing the lat, lng to the `latlng` parameter of the HTTP reverse geocoding request:
<http://maps.googleapis.com/maps/api/geocode/json?latlng=41.66547000000001,-87.64157&sensor=false>
|
50,415,498 |
I am trying to create a family tree with callback functions nested in callback functions, i'm hoping to get at least 5 generation. the function receive the person's id, which then look for everyone in the database that has the property 'father' with the same id.
---
This is the function for getting the children of the person
```
var getChildren=function (person, callback) {
keystone.list('Person').model.find().where('father', person.id).exec(function(err, children) {
callback(children);
})
}
```
this is how i use the callback function
```
function getFamilyTree(person){
getChildren(person, function(children){
person.children=children;
for (var i=0;i<person.children.length;i++) {
!function outer(i){
if (isNotEmpty(person.children[i])){
getChildren(person.children[i],function(children){
person.children[i].children=children;
for (var j=0;j<person.children[i].children.length;j++){
!function outer(j){
if (isNotEmpty(person.children[i].children[j])){
getChildren(person.children[i].children[j],function(children){
person.children[i].children[j].children=children;
for (var k=0;k<person.children[i].children[j].children.length;k++){
!function outer(k){
if (isNotEmpty(person.children[i].children[j].children[k])){
getChildren(person.children[i].children[j].children[k],function(children){
person.children[i].children[j].children[k].children=children;
})
}
}(k);
}
})
}
}(j);
}
});
}
}(i);
}
})
}
```
as you can see, it is very complicated. It works, but sometimes it doesn't retrieve all 5 generation but only 4 or 3, sometimes even 1 and i don't know why, please help my guys, and i'm also a new comer so please be easy with me, thanks in advance!
|
2018/05/18
|
[
"https://Stackoverflow.com/questions/50415498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8426770/"
] |
If you use [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) instead of callbacks, you could use a recursive [`async` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) to resolve trees of arbitrary depth:
```js
function getChildren(person) {
return new Promise((resolve, reject) => {
keystone.list('Person').model.find().where('father', person.id).exec((err, children) => {
if(err) reject(err);
else resolve(children);
});
});
}
async function getFamilyTree(person, maxDepth, depth=0) {
if(depth >= maxDepth) return person;
const children = (await getChildren(person)).filter(isNotEmpty);
person.children = await Promise.all(
children.map(child => getFamilyTree(child, maxDepth, depth + 1))
);
return person;
}
getFamilyTree({id: 'rootPersonId'}, 5)
.then(tree => console.log(tree))
.catch(error => console.log(error));
```
|
38,826,630 |
My current task is to make a Jenkins job which will download a git repo, will **gulp build** a project and finally will sync data to an S3 bucket. My trouble is with **gulp build** command which root can't find.
I read [that](https://stackoverflow.com/questions/21215059/cant-use-nvm-from-root-or-sudo) post about installing nvm globally and after using:
```
wget -qO- https://raw.githubusercontent.com/xtuple/nvm/master/install.sh | sudo bash
```
was able to install nvm to /usr/local/nvm.
Inside the project directory (/var/lib/jenkins/project) I run:
```
sudo /usr/local/bin/npm install
```
and all modules go to **node\_modules** dir inside project dir.
Then I do:
```
sudo gulp build --env=production
sudo: gulp: command not found
```
It looks like root can't find **gulp**. Inside **node\_modules/gulp/bin** there is a gulp.js file but I have no idea how to use it.
So how can I make gulp build work for root? Previously I installed and build the project with a minor effort using a regular user and I know the project is ok, the problem manifested after switching to root.
My working env is Amazon Linux with node.js version 4.4.7. These are my first steps with nvm, gulp and node.js as a whole, so please, don't be too harsh if I'm doing something obviously stupid.
|
2016/08/08
|
[
"https://Stackoverflow.com/questions/38826630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2381371/"
] |
I think you have to install gulp-cli as well:
```
sudo /usr/local/bin/npm install -g gulp-cli
```
Gulp global command is different with local gulp you found at node\_modules/gulp/bin
|
904,689 |
From my college life, I remember many professors used to call a linear-equation a linear-function, however:
A standard definition of linear function (or linear map) is:
$$f(x+y)=f(x)+f(y),$$
$$f(\alpha x)=\alpha f(x).$$
Where as linear equation is defined as:
$$f(x)=mx+b.$$
So, linear-equation is NOT a linear-function, according to the definitions defined above.
Though, for $b=0$ the linear-equation becomes a linear-function, but it is not true in general.
**Question:** Is it misnomer to call a linear-equation a linear-function, or it is completely wrong to say that? And linear-equation must be considered strictly as an affine-mapping.
|
2014/08/21
|
[
"https://math.stackexchange.com/questions/904689",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/86137/"
] |
>
> Is it misnomer to call a linear-equation a linear-function, or it is completely wrong to say that?
>
>
>
Neither. The meaning of some mathematical terms (*normal*, *regular*, *smooth*, etc) is context-dependent. E.g., *smooth function* means $C^\infty$ in some papers/books and $C^1$ in others.
In certain contexts, *linear* means "additive and commutes with scalar multiplication". In other contexts, it means "a function of the form $x\mapsto ax+b$".
|
21,756,707 |
How to fully disable WELD on WildFly. I don't need it, because I use another DI framework.
>
> Exception 0 :
> javax.enterprise.inject.UnsatisfiedResolutionException: Unable to resolve a bean for 'org.springframework.data.mongodb.core.MongoOperations' with qualifiers [@javax.enterprise.inject.Any(), @javax.enterprise.inject.Default()].
> at org.springframework.data.mongodb.repository.cdi.MongoRepositoryExtension.createRepositoryBean(MongoRepositoryExtension.java:104)
> at org.springframework.data.mongodb.repository.cdi.MongoRepositoryExtension.afterBeanDiscovery(MongoRepositoryExtension.java:79)
> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
> at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
> at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
> at java.lang.reflect.Method.invoke(Method.java:606)
> at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:93)
> at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:266)
> at org.jboss.weld.event.ExtensionObserverMethodImpl.sendEvent(ExtensionObserverMethodImpl.java:125)
> at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:253)
> at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:232)
> at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:169)
>
>
>
I tried
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:weld="http://jboss.org/schema/weld/beans"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd
http://jboss.org/schema/weld/beans http://jboss.org/schema/weld/beans_1_1.xsd
http://jboss.org/schema/weld/beans ">
<weld:scan>
<weld:exclude name="com.google.**"/>
<weld:exclude name="org.springframework.data.mongodb.**"/>
</weld:scan>
```
But it did not resolve my problem.
|
2014/02/13
|
[
"https://Stackoverflow.com/questions/21756707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029235/"
] |
Try deleting or commenting out the `org.jboss.as.weld` extension in the extensions list on the beginning of `$JBOSS_HOME/standalone/configuration/standalone.xml`. You may also want to delete `<subsystem xmlns="urn:jboss:domain:weld:1.0"/>` from `<profile>`. This should cause disabling Weld for all applications deployed on the server.
|
16,577 |
I have laptop Asus N53SV with 4 GB of RAM, i7 with integrated card and dedicated GPU. My problem on Fedora is that system reports only 2.6 GB RAM. I know that I should use kernel with PAE but even after I install it, I have only 2.6 GB RAM avaiable. Now I use 3.0.0 rc6 kernel, but still nothing. Is it possible that the integrated GPU uses almost 1GB of RAM ? Can I check it somehow?
```
$ free
Non-standard uts for running kernel:
release 3.0-0.rc6.git6.1.fc15.i686=3.0.0 gives version code 196608
total used free shared buffers cached
Mem: 2752180 2527816 224364 0 11232 499444
-/+ buffers/cache: 2017140 735040
Swap: 4849660 500048 4349612
```
dmidecode
<http://pastebin.com/CNrph9KA>
kernel logs
<http://pastebin.com/QvqUmEZb>
|
2011/07/13
|
[
"https://unix.stackexchange.com/questions/16577",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/9037/"
] |
>
> Is it possible that the integrated GPU uses almost 1GB of RAM?
>
>
>
Easily. Many integrated GPUs do not have their own dedicated memory, instead using a portion of the system memory carved out by the BIOS.
>
> Can I check it somehow?
>
>
>
Probably. Check the BIOS settings, and/or the system manual. You should be able to control the memory allocation from there. (If you can't find your copy of the manual, [you can find a PDF version on Asus' site for the machine, on the Downloads tab](http://www.asus.com/Notebooks/Multimedia_Entertainment/N53SV/).)
|
47,794,205 |
I have the following command line to check free space of a file system:
```
fs_used=`df -h /u01 | sed '1d' | sed '1d' | awk '{print $4}' | cut -d'%' -f1`
```
It works fine. It returns the percentage of the used space on the file system (without the % symbol).
**Now I need to make it variable and run it with the eval command**. I tried the following but it doesn't work (exit with df: invalid option -- 'd')
```
df_cmnd="df -h $fs1 | sed '1d' | sed '1d' | awk '{print $4}' | cut -d'%' -f1"
fs_used=eval $df_cmnd
```
The problem, I guess, is that eval cannot run piped commands. Is that true?
is there any workaround or alternative to make this code run?
|
2017/12/13
|
[
"https://Stackoverflow.com/questions/47794205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/801394/"
] |
Backslash-escape the `$`, and use `$()`:
```
# V V
df_cmnd="df -h \$fs1 | sed '1d' | sed '1d' | awk '{print \$4}' | cut -d'%' -f1"
fs_used=$(eval "$df_cmnd")
# ^^ ^
```
This will use the value of `fs1` at the time you eval.
But, in reality, please [don't use eval](https://stackoverflow.com/a/17529221/2877364)! Make it a shell function instead:
```
df_cmnd(){
df -h "$1" | sed '1d' | sed '1d' | awk '{print $4}' | cut -d'%' -f1
}
fs_used=$(df_cmnd /u01)
```
Then you don't have to worry about escaping.
### Explanation
Look at how `bash` interprets your `df_cmnd` assignment:
```
$ df_cmnd="df -h $fs1 | sed '1d' | sed '1d' | awk '{print $4}' | cut -d'%' -f1"
$ echo $df_cmnd
df -h | sed '1d' | sed '1d' | awk '{print }' | cut -d'%' -f1
# ^ ^
```
In my case, `fs1` was empty, so I just got `df -h` for the `df` part. In your case and mine, bash replaced `$4` with its value, here, empty since I wasn't running in a script with four arguments. Therefore, awk will print the whole line rather than just the fourth field.
|
61,343,528 |
I've been trying to figure out how to retrieve a child node based on a parent node using `SQL`. What I've tried so far is:
```
declare @streets xml
set @streets ='<ArrayOfStreetEntity>
<StreetEntity>
<Name>Street Name 1</Name>
<PostalNumbers>
<PostalNo>
<FromNo>0</FromNo>
<PostalCode>011369</PostalCode>
<ToNo>0</ToNo>
</PostalNo>
</PostalNumbers>
<StreetId>3</StreetId>
</StreetEntity>
<StreetEntity>
<Name>Street Name 2</Name>
<PostalNumbers>
<PostalNo>
<FromNo>0</FromNo>
<PostalCode>01136229</PostalCode>
<ToNo>0</ToNo>
</PostalNo>
<PostalNo>
<FromNo>4</FromNo>
<PostalCode>01136255</PostalCode>
<ToNo>5</ToNo>
</PostalNo>
</PostalNumbers>
<StreetId>3</StreetId>
</StreetEntity>
</ArrayOfStreetEntity>'
```
In order to get the street names, I've used the below query which works fine:
```
SELECT
x.value(N'(Name)[1]', N'nvarchar(50)') AS Name,
x.value(N'(StreetId)[1]', N'nvarchar(50)') AS StreetId
FROM @streets.nodes(N'/ArrayOfStreetEntity/StreetEntity') AS XTbl(x)
```
However, how would I get the first postal code based on the street name? I don't understand what I'm missing here.
What I've tried is the below code but it returns all postal codes:
```
select
xx.value(N'(PostalCode)[1]', N'nvarchar(50)') AS PostalCode
from @streets.nodes(N'/ArrayOfStreetEntity/StreetEntity/PostalNumbers/PostalNo') AS XTbl(xx)
where xx.value(N'(/ArrayOfStreetEntity/StreetEntity/Name)[1]', 'varchar(max)')='Street name 1'
```
**Output:**
```
PostalCode
---------
011369
01136229
01136255
```
|
2020/04/21
|
[
"https://Stackoverflow.com/questions/61343528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Using [this](https://stackoverflow.com/questions/38453156/get-attribute-value-of-xml-child-node-with-where-condition-on-parent-node) as a reference, try the below query:
```
select
xx.value(N'(PostalCode)[1]', N'nvarchar(50)') AS PostalCode
from @strazi.nodes(N'/ArrayOfStreetEntity/StreetEntity/PostalNumbers/PostalNo') AS XTbl(xx)
where xx.value('../../Name[1]', 'varchar(max)')='Street name 1'
```
The above will return as many of child nodes where your street name matches your condition.
|
8,757,247 |
Is there anyway I can make this statement smaller? for efficiency, the whole idea is to get
todays, this month and last months amount of "quotes".
```
SELECT COUNT(QuoteDate) AS today
FROM database
WHERE QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)
UNION
SELECT COUNT(QuoteDate) AS this_month
FROM database
WHERE QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)
UNION
SELECT COUNT(QuoteDate) AS last_month
FROM database
WHERE QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 2 MONTH)
```
Thanks
|
2012/01/06
|
[
"https://Stackoverflow.com/questions/8757247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1134192/"
] |
Couldn't you just use an OR statement?
```
SELECT COUNT(QuoteDate) AS today FROM database
WHERE
QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)
OR
QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)
OR
QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 2 MONTH)
```
|
71,097,850 |
I'm new to NextJS, and trying to figure out, how to create a global variable that I could assign a different value anytime. Could someone give a simple example? (I know global might not be the best approach, but still I would like to know how to set up a global variable).
Let's say:
**\_app.js**
```
NAME = "Ana" // GLOBAL VARIABLE
```
**page\_A.js**
```
console.log(NAME) // "Ana"
NAME = "Ben"
```
**page\_B.js**
```
console.log(NAME) // "Ben"
```
|
2022/02/13
|
[
"https://Stackoverflow.com/questions/71097850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12566015/"
] |
try using Environment Variables
***/next.config.js***
```
module.exports = {
env: {
customKey: 'my-value',
},
}
```
***/pages/page\_A.js***
```
function Page() {
return <h1>The value of customKey is: {process.env.customKey}</h1>
}
export default Page
```
but you can not change its contents, except by changing it directly in next.config.js
|
24,919,026 |
I have created an array of custom object to store values in it.
```
mNearbyPlaceMini[] mn = new mNearbyPlaceMini[googlePlacesObj.results.size()];
for (int i = 0; i < googlePlacesObj.results.size(); i++) {
mGooglePlaces.place place = googlePlacesObj.results.get(i);
Bitmap placeImageBitmap = null;
try {
URL imageUrl = new URL(place.icon);
placeImageBitmap = BitmapFactory.decodeStream(imageUrl.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mn[i].placePicture = placeImageBitmap; //ERROR HERE
mn[i].placeName = place.name;
...
}
```
But when i try to assign values to the property of an object like this `mn[i].placePicture = placeImageBitmap` it gives me `java.lang.NullPointerException` error. The `placeImageBitmap` has valid values and is not null, so it must be something wrong i am doing with my object array.
```
public class mNearbyPlaceMini {
public Bitmap placePicture;
public String placeName;
public Double latitude;
public Double longitude;
public mNearbyPlaceMini(){}
}
```
|
2014/07/23
|
[
"https://Stackoverflow.com/questions/24919026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971741/"
] |
You could define `testsubmit` in **extra\_gui.py:**
```
def testsubmit(self):
...
```
then define it as a method of the `Gui` class like this:
```
from tkinter import *
import extra_gui as EG
class Gui(Frame):
testsubmit = EG.testsubmit
```
|
31,768,913 |
I'm trying to send a variable to blade view, but throw this error:
**Undefined variable: data (View: D:\wamp\www\tienda\resources\views\cliente.blade.php)**
This is my Route:
```
Route::resource('cliente','ClienteController');
```
This is my Controller Cliente:
```
public function index(){
$data = Cliente::all();
return view('cliente',compact($data));
}
```
And my Blade:
```
@foreach ($data as $user)
<tr>
<td>{{$user->nombre}}</td>
</tr>
@endforeach
```
What I'm doing wrong?
Additionally, if a try to do for example this
Controller Cliente:
```
public function index(){
return view('cliente', ['name' => 'James']);
}
```
And Blade:
```
{{$name}}
```
That yes work... Only the variables and arrays, doesnt work.
|
2015/08/02
|
[
"https://Stackoverflow.com/questions/31768913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4346899/"
] |
Try this on your Controller:
```
public function index(){
$data = Cliente::all();
return view('cliente',compact('data'));
}
```
[From the compact documentation](http://php.net/manual/en/function.compact.php): "Each parameter can be either a **string** containing the *name of the variable*, or an **array** of *variable names*. The array can contain other arrays of variable names inside it; compact() handles it recursively. "
|
22,681,765 |
I have two queries:
```
SELECT
users.id,
users.gender,
users.status,
users.icon_id,
users.image_name,
coords.lat,
coords.lng,
users.mess_count
FROM
users
INNER JOIN
coords ON users.id = coords.user_id
```
then I select blocked users:
```
SELECT
first_user,
second_user
FROM
blocks
WHERE
first_user = $1 OR second_user = $1
```
From first table I need to select all users which has coordinates and not blocked, I also need some public information(gender and etc.). Then because I need two side blocking. I have to select is user blocked him, or he was blocked by that user. So $1 is current user, and I select is my id in `block` table, if it is - I exclude another user from first query.
Then using string operations in my programming language I transform my string to exclude results I get from second query.
I probably can do it with `EXCEPT`, but I can't do it, because I have only 2 column selected with second query, and I need much more, in final result: `users.id, users.gender, users.status, users.icon_id, users.image_name, coords.lat, coords.lng, users.mess_count` .
|
2014/03/27
|
[
"https://Stackoverflow.com/questions/22681765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1842013/"
] |
Then obviously the `output` does not contain the expected string. (How should it, when it is generated by calling `echo 18`?) Thus,
```
matches = re.search("Current_State==1 and Previous_State==0", output)
```
returns `None`, which has no `.group()` for
```
moveHold = float(matches.group(1))
```
so that you get the said exception.
You should change that to
```
matches = re.search("Current_State==1 and Previous_State==0", output)
if matches:
moveHold = float(matches.group(1))
resultm = client.service.retrieveMove(moveHold)
...
else:
# code for if it didn't match
```
|
12,359,554 |
The problem is that the content of `$oldpop` get magically changed after executing the function `func`, whereas the input of `func` is `$matepop`. Inside `func`, `$oldpop` is not used (I added the comment line to show the place - see the end of the code snippet of **MAIN.PHP**). Below I provide just some principal parts of the code. Maybe, someone could suggest the reason of the problem?
I should mention I don't use static variables.
**File MAIN.PHP**
```
include_once 'func.php';
include_once 'select.php';
class Individual {
private $genes;
private $rank;
public function __construct() {
$this->genes = array();
$this->rank = 0;
}
public function setRank($val){
$this->rank = $val;
}
public function setGene($i,$val){
$this->genes[$i] = $val;
}
}
class Population {
private $ind;
public function __construct()
{
$this->ind = array();
}
public function addIndividual(Individual $ind)
{
$this->ind[] = $ind;
}
public function getIndividual($i){
return $this->ind[$i];
}
}
$oldpop = new Population();
for($i=0; $i<$popsize; $i++) {
$oldpop->addIndividual(new Individual());
}
$oldpop = func($oldpop,$popsize);
for ($i = 0; $i < $gener; $i++)
{
$matepop = new Population();
$matepop = nselect($matepop,$oldpop,$popsize);
// !!! Here the $oldpop content is correct (original)
$matepop = func($matepop,$popsize);
// !!!! Here the original content of $oldpop is magically changed
}
```
**File SELECT.PHP**
```
function nselect($matepop,$oldpop,$popsize) {
$select = array();
//...
$select[] = $oldpop->getIndividual($i);
//...
for ($i=0; $i < $popsize; $i++) {
$matepop->addIndividual($select[$i]);
}
return $matepop;
}
```
**File FUNC.PHP**
```
function func($pop,$popsize) {
//...
$pop->getIndividual($i)->setRank($val);
//...
return $pop;
}
```
|
2012/09/10
|
[
"https://Stackoverflow.com/questions/12359554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1157047/"
] |
It will fetch data from DB twice.
|
41,167,695 |
I have a application which uses app.css in index.html. This app.css is the output css file from multiple SCSS files.
While inspecting an element to find css of that element, how can I know from which SCSS file is that style from?
|
2016/12/15
|
[
"https://Stackoverflow.com/questions/41167695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5101956/"
] |
You can either use ulimit at the start of your script:
```
ulimit -m 8000000
```
or if that is unavailable for some reason, fork your real\_process into the background and use the remainder of your script to check periodically if it's memory usage has exceeded the 8G, and terminate.
```
while true; do
# check memory usage of process
# kill process if too high
sleep 60
done
```
|
71,157,322 |
I have a list of dictionaries:
```
persons = [{'id': 1, 'name': 'john'},
{'id': 2, 'name': 'doe'},
{'id': 3, 'name': 'paul'}]
ids = [1,3]
# remove_persons(persons, ids) --> [{'id': 2, 'name': 'doe'}]
```
I would like to remove dictionaries from a list of id.
What is the most efficient way to go about this programmatically.
|
2022/02/17
|
[
"https://Stackoverflow.com/questions/71157322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10731363/"
] |
I think this will do the jobs
```
persons = [{'id': 1, 'name': 'john'},
{'id': 2, 'name': 'doe'},
{'id': 3, 'name': 'paul'}]
ids = [1, 3]
persons = [person for person in persons if person['id'] not in ids]
```
print(persons)
```
print(persons)
```
but i dont know about the performance
|
6,980,298 |
I want to compare set of images with the given template/ideal image. All images are similar to template image, I want to compare the images and find out the percentage of similarity between the template & rest of images.
Is there any open source or third party software for doing it.
I want to mainly use C# .Net as the technology.
|
2011/08/08
|
[
"https://Stackoverflow.com/questions/6980298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/883766/"
] |
OpenCV is a competent image algorithm library. I'd recommend EmGuCV as a C#-wrapper:
<http://www.emgu.com/>
Comparing images are quite tricky and you should be more specific in your question to get a good and specific answer. I'd guess you want to ignore things as different brightness levels, contrast and translation...
One simple way to look for an image within an image (if no rotation is applied) is to use the small image as a kernel and use convolution to get the best match(es) in the image. Threshold or apply a percentage scale (I recommend a non-linear) to the response and you have a decent filter.
|
5,565,989 |
I've a problem with some VHDL syntax in some old code that I want to reuse. It is accepted by the synthesis tool (Synplify) but the simulator (Aldec Active-HDL 8.3) gives the following error. (Note: This construction was accepted by a previous version of this simulator).
#Error: COMP96\_0228: buffered\_data.vhdl : (19, 28): The actual must be denoted by a static signal name, if the actual is associated with a signal parameter of any mode.
I get that the error doesn't like the (i) in the signal clk(i) but I don't want to unroll the loop to (0),(1),etc because it's used in several different configurations for different port sizes and I'm sure there must be a way to describe this.
My solution so far is to encapsulate one instance in it's own entity/arch hierarchy and use a "generate" to instantiate once for each port but I don't like it. Any better ideas?
Very simplified example showing exactly my issue. (The intent is to ensure that data is first clocked into the FPGA using its own associated clock before anything else)
```
library IEEE;
use IEEE.STD_LOGIC_1164.all;
entity input_buffer is
port(
clk : in std_logic_vector;
data_in : in std_logic_vector;
data_out : out std_logic_vector
);
end input_buffer;
architecture rtl of input_buffer is
constant c_NumOfPorts : integer := 3;
begin
p_process: process(clk)
begin
for i in 0 to c_NumOfPorts-1 loop
if rising_edge(clk(i)) then -- error here
data_out(i) <= data_in(i);
end if;
end loop;
end process;
end rtl;
```
|
2011/04/06
|
[
"https://Stackoverflow.com/questions/5565989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199782/"
] |
If you change the loop inside the process into a generate statement outside the process, it works fine in ModelSim (I don't have Aldec available), and IMHO seems cleaner than a single process with a bunch of clocks. I would also typically use a generic to define the port widths, rather than pulling them in as a constant inside the architecture, but I figure you've got some reason for doing it that way:
```
library IEEE;
use IEEE.STD_LOGIC_1164.all;
entity input_buffer is
port(
clk : in std_logic_vector;
data_in : in std_logic_vector;
data_out : out std_logic_vector
);
end input_buffer;
architecture rtl of input_buffer is
constant c_NumOfPorts : integer := 3;
begin
gen : for i in 0 to c_NumOfPorts-1 generate
begin
p_process: process(clk(i))
begin
if rising_edge(clk(i)) then -- error here
data_out(i) <= data_in(i);
end if;
end process;
end generate;
end rtl;
```
|
1,279,686 |
I am currently working with a large list of IP addresses (thousands of them).
However, when I sort the column containing the IP addresses, they don't sort in a way that is intuitive or easy to follow.
For example, if I enter IP Addresses as follows:
[](https://i.stack.imgur.com/Vyqdd.png)
And then if I sort in ascending order I get this:
[](https://i.stack.imgur.com/uaql8.png)
Is there a way for me to format the cells so that, for example, an IP address of 17.255.253.65 appears **after** 1.128.96.254 and **before** 103.236.162.56 when sorted in ascending order?
If not, is there another way for me to achieve this ultimate aim?
|
2017/12/24
|
[
"https://superuser.com/questions/1279686",
"https://superuser.com",
"https://superuser.com/users/557985/"
] |
As you may have realised, your IP addresses are treated as text and not numbers. They are being sorted as text, which means that addresses beginning with "162" will come before addresses beginning with "20." (because the character "1" comes before the character "2".
You can use the formula provided in this answer: <https://stackoverflow.com/a/31615838/4424957> to split the IP address into its parts.
If your IP addresses are in columns A, add columns B-E as shown below.
[](https://i.stack.imgur.com/o9pkd.jpg)
Enter the formula
```
=VALUE(TRIM(MID(SUBSTITUTE($A2,".",REPT(" ",999)),(B$1)*999-998,999)))
```
in cell B2 and copy it to columns B-E in all rows to get the four parts of each IP address. Now sort the whole range by columns B through E (in that order) as shown below:
[](https://i.stack.imgur.com/AwQKh.jpg)
If you don't want to see the helper columns (B-E), you can hide them.
|
10,605,439 |
I have a problem with doctrine. I like the caching, but if i update an Entity and flush, shouldn't doctrine2 be able to clear it's cache?
Otherwise the cache is of very little use to me since this project has a lot of interaction and i would literally always have to disable the cache for every query.
The users wouldn't see their interaction if the cache would always show them the old, cached version.
Is there a way arround it?
|
2012/05/15
|
[
"https://Stackoverflow.com/questions/10605439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/532495/"
] |
Are you talking about saving and fetching a new Entity within the same runtime (request)? If so then you need to refresh the entity.
```
$entity = new Entity();
$em->persist($entity);
$em->flush();
$em->refresh($entity);
```
If the entity is managed and you make changes, these will be applied to Entity object but only persisted to your database when calling $em->flush().
If your cache is returning an old dataset for a fresh request (despite it being updated successfully in the DB) then it sounds like you've discovered a bug. Which you can file here >> <http://www.doctrine-project.org/jira/secure/Dashboard.jspa>
|
140,304 |
What is the reason for Marvel to use Scott Lang as Ant-Man over Hank Pym and Eric O'Grady?
------------------------------------------------------------------------------------------
This is a question about the 2015 movie "Ant-Man".
In the comics all 3 characters have a go at being Ant-Man (There is a fourth person who apparently used the Ant-Man suit, but I can't find the character's name). I would have thought the logical choice would have been Hank Pym and although he is portrayed as being a lot older in the movie, when he was the Ant-Man he was much younger.
Or does the domestic violence issue of Hank Pym play a part the choice? In any case what was the reasoning for Marvel to go with Scott Lang?
|
2016/09/12
|
[
"https://scifi.stackexchange.com/questions/140304",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/65457/"
] |
Screenwriter Edgar Wright has a personal affinity for Scott Lang
----------------------------------------------------------------
From [an interview](http://www.superherohype.com/features/91587-exclusive-edgar-wright-talks-ant-man) discussing the movie when it was in development:
>
> …I’d met with Artisan and at the time, they had some of Marvel’s lesser-known titles, and they asked if I was a Marvel comics fan, and I said that I always was a Marvel Comics kid, and they said, “Are you interested in any of these titles?” The one that jumped out was “Ant-Man” because I had the John Byrne “Marvel Premiere” from 1979 that David Micheline had done with Scott Lang that was kind of an origin story. I always loved the artwork, so when I saw that, it just immediately set bells going off kind of thinking going “Huh, that could be interesting. ”
>
>
>
Wright also wanted to do an atypical superhero movie in a different genre
-------------------------------------------------------------------------
>
> Ant-Man was basically doing a superhero film in invert commas, and it takes place in another genre, almost more in the crime-action genre, that just happens to involve an amazing suit with this piece of hardware. The thing I like about Ant-Man is that it’s not like a secret power, there’s no supernatural element or it’s not a genetic thing. There’s no gamma rays. It’s just like the suit and the gas, so in that sense, it really appealed to me in terms that we could do something high-concept, really visual, cross-genre, sort of an action and special effects bonanza, but funny as well.
>
>
>
I imagine that an Ant-Man movie focusing on Hank Pym would be more of a science-fiction movie, or at least more akin to something like *Iron Man*. Having someone who is not an inventor, but rather a criminal, means that there is a possibility to add cross-genre crime elements. We get scenes involving breaking into places, rather than discussing "Pym particles" (analogous to gamma rays, which Wright said he didn't care for).
---
As a side note, I see no evidence that Wright felt Hank Pym was controversial or otherwise unfit for being a hero. In fact, he brings up Hank Pym in the interview (whom he refers to as "Henry Pym") and speaks about him pretty fondly. Apparently in the original script, there was to be a prologue featuring Hank Pym as Ant-Man in the 1960s, reminiscent of his adventures in *Tales to Astonish*. But as for a main character, Wright just preferred to use Scott Lang.
|
19,897,063 |
Here is the list function, as you can see it's printing the content of newEntry before being added to the vector dataList.
```
public static Vector<entry> list()
{
entry newEntry = new entry();
Vector<entry> dataList = new Vector<entry>();
String[] splitLine;
String currentLine;
String formattedString = "";
BufferedReader in;
try
{
in = new BufferedReader(new FileReader(new File("data.txt")));
while ((currentLine = in.readLine()) != null) {
newEntry = new entry();
splitLine = currentLine.split(" ");
newEntry.record = Integer.parseInt(splitLine[0]);
newEntry.fName = splitLine[1];
newEntry.lName = splitLine[2];
newEntry.phoneNumber = splitLine[3];
dataList.add(newEntry);
}
}
catch (IOException ex)
{
System.out.println(ex);
}
for (int i = 0; i < dataList.size(); i++)
{
System.out.println(dataList.elementAt(i).record + dataList.elementAt(i).fName + dataList.elementAt(i).lName + dataList.elementAt(i).phoneNumber);
}
return dataList;
}
```
Here is the part where I'm having an issue, it's taking whatever list() is returned (above) and forming it into a new vector and will be printed off. However, it's only printing the last value for some reason...
```
if ((params[0].toLowerCase()).equals("list"))
{
Vector<entry> printList = new Vector<entry>(list());
for (int i = 0; i < printList.size(); i++)
{
System.out.println(printList.elementAt(i).record + printList.elementAt(i).fName + printList.elementAt(i).lName + printList.elementAt(i).phoneNumber);
}
}
```
This is the output I get when 3 (the first 3 shown below) is added to the dataList in the list function.
>
> 1000 John Carter 1731371313
>
> 1001 Abe Lincoln 9173913143
>
> 1002 William Tell 794174141
>
> 1002 William Tell 794174141
>
> 1002 William Tell 794174141
>
> 1002 William Tell 794174141
>
>
>
Does anyone know what may be wrong?
|
2013/11/11
|
[
"https://Stackoverflow.com/questions/19897063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1880591/"
] |
That's because you insert the same object into the container three times. You should construct a new object before inserting it.
```
splitLine = currentLine.split(" ");
newEntry = new entry();
newEntry.record = Integer.parseInt(splitLine[0]);
newEntry.fName = splitLine[1];
newEntry.lName = splitLine[2];
newEntry.phoneNumber = splitLine[3];
System.out.println(newEntry.record + newEntry.fName + newEntry.lName + newEntry.phoneNumber);
dataList.add(newEntry);
```
It's a good thing you posted your full code, because you have an additional error :
```
public static class entry
{
public static int record;
public static String fName;
public static String lName;
public static String phoneNumber;
}
```
Declaring the members of the `entry` class as static causes them to be shared by all instances of your class. That's why all instances of the `entry` class hold the values of the last entry. Remove the `static` keyword from all the members and everything will work.
|
381,024 |
Say I am installing a new CPU in my desktop motherboard and I am interested in grounding myself (by touch or one of those nifty bracelets) to avoid damaging my components.
What is the nature of grounding? Does grounding effectiveness correlated to the size of an object, the conductance of the object, its connection to the soil-earth, a combination of these or other factors?
I'd imagine touching a matchbox car with plastic wheels has a different effect than shaking hands with a life-sized gold statue of Michale Faraday, half embedded in the earth and contacting bedrock.
|
2018/06/21
|
[
"https://electronics.stackexchange.com/questions/381024",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/113314/"
] |
If you are installing a CPU in a motherboard, you don't really care about grounding - what you really want to do is to make sure that you, the CPU, and the motherboard (and any tools) are all at the same potential. If you have one of those grounding bracelets, you should connect its ground lead to the computer case or motherboard Ground - whether that is "Really Ground" or not is not particularly relevant.
|
32,180,366 |
I have used a MVC web application running on the `ASP.NET Framework version 4.5.1`.
I have made `nopcommercePlugin`. I am upgrading version 3.4 to 3.5
After the update, I am getting the following error:
```
System.TypeLoadException: Could not load type
'RestSharp.HttpBasicAuthenticator' from assembly 'RestSharp,
Version=105.2.1.0, Culture=neutral, PublicKeyToken=null'.
```
I am using `Twilio` to send an SMS message:
```
using Twilio;
public bool MethodName(string FromNumber, string ToNumber, string URL, string code = "")
{
if (code == "")
{
//URL = URL.Replace(" ", "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20");
URL = URL.Replace(" ", "%20");
}
else
{
URL = URL + code + " we repeat your code is : " + code;
URL = URL.Replace(" ", "%20");
}
string AccountSid = _SMSProviderSettings.SMSGatewayTwillioAccountSID;
string AuthToken = _SMSProviderSettings.SMSGatewayTwillioAccountAuthToken;
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var options = new CallOptions();
var twimal = new Twilio.TwiML.TwilioResponse();
twimal.Pause(5);
options.To = ToNumber;
options.Url = URL;
options.From = FromNumber;
options.Method = "GET";
var call = twilio.InitiateOutboundCall(options);
if (call != null)
{
if (call.RestException == null)
return true;
}
//error log entry in system log
_logger.InsertLog(LogLevel.Error, call.RestException.Message, call.RestException.Message + " For more detail click here " + call.RestException.MoreInfo);
return false;
}
```
The Installed version are :
* Twilio.4.0.5
* Twilio.TwiML.3.3.6
* Twilio.Mvc.3.1.15
* RestSharp.105.1.0
I have seen a [similar question](https://stackoverflow.com/questions/32067529/twilio-restsharp-dependency) posted back in 18th August 2015 (8 days ago) and there is also some discussion on the `Twilio Nuget` page discussing an Alpha Version that is reported.
If I used RestShrap 105.2.2 version then These errors are generate
[](https://i.stack.imgur.com/21aJV.png)
Can anyone tell me what version options should be used?
|
2015/08/24
|
[
"https://Stackoverflow.com/questions/32180366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3509802/"
] |
Twilio developer evangelist here.
RestSharp has been updated last week to [version 105.2.2](https://www.nuget.org/packages/RestSharp/105.2.2). that caused the Twilio library to start failing since HttpBasicAuthenticator has been moved around to a different namespace.
The Twilio Library has then been updated to [version 4.0.5](https://www.nuget.org/packages/Twilio/4.0.5) which now works with RestSharp version 105.2.2. The [packages file](https://github.com/twilio/twilio-csharp/blob/master/src/Twilio.Api/packages.config) has also been updated to use that version.
So in short, all you should need to do is update your RestSharp to version 105.2.2 via Nuget Package Manager or via Package Manager Console by running:
```
Install-Package RestSharp
```
|
28,452,473 |
May be my question is irrelevant, it will probably may never happened as stack has 1MB of memory.
But if stack memory becomes full, what will happen. Because garbage collector will not perform cleaning for stack.
|
2015/02/11
|
[
"https://Stackoverflow.com/questions/28452473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/978493/"
] |
It is quite easy to overflow the stack:
```
int* ptr = stackalloc int[4000000];
```
A StackOverflowException will occur.
|
52,930,787 |
I dynamically set width of each cell of `UICollectionView` according to text inside it. The problem is that most of the time the `width` size is correct but sometimes cell size is not correct.
These are strings i displayed in cell
```
let tabs = ["1st tab", "Second Tab Second", "Third Tab", "4th Tab", "A"]
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let text = tabs[indexPath.row]
let font = UIFont.systemFont(ofSize: 21, weight: UIFont.Weight.regular)
let attributes = font != nil ? [NSAttributedString.Key.font: font] : [:]
let width = text.size(withAttributes: attributes).width
return CGSize(width: width + 16+16+16+35, height: self.menuBarColView.frame.height)
}
```
It correctly displayed 1st, second, third and 5th one but size of 4th cell is wrong. This is the output.
[](https://i.stack.imgur.com/uMNJi.png)
Please tell me where is the problem?
|
2018/10/22
|
[
"https://Stackoverflow.com/questions/52930787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Selfsize collection view cell checklist:
* Set `estimated item size` to anything but `.zero`. Works best if you set it to (1,1)
example:
```
(collectionView?.collectionViewLayout as? UICollectionViewFlowLayout)?.estimatedItemSize = CGSize(width: 1, height: 1)
```
* Layout cell contents and check if it works if scalable content changes.
* Return the actual size if you can calculate it without loosing performance
* Double check to reduce codes that repeats and cache sizes.
---
If you are targeting iOS 10 and above, you can use this instead:
```
....estimatedItemSize = UICollectionViewFlowLayout.automaticSize
```
|
3,103,293 |
$$\binom{n}{0} \cdot 2^n + \binom{n}{1} \cdot 2^{n-1} + \binom{n}{2} \cdot 2^{n-2} + \dots + \binom{n}{n} \cdot 2^{n-n}$$
Anyway to simplify this such that it can become of 'closed' form (i.e. a concrete number of terms)?
|
2019/02/07
|
[
"https://math.stackexchange.com/questions/3103293",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/642334/"
] |
There are $\binom72 = 21$ ways to choose the two elements, and the valid pairs are
$$\{2,98\}, \{4,98\}, \{12,98\}, \{14,28\}, \{14,98\}, \{21,28\}, \{28,98\}$$
These are $7$ of the $21$ pairs, so the probability for the product to be a multiple of $196$ is $\frac{7}{21}=\frac13$.
|
31,978,860 |
I have a bunch of li's with hyperlinks in them. Here's a demo <http://codepen.io/anon/pen/aOxJyr>
```
<div class="collapse navbar-collapse" id="categorycollapse">
<ul id="Category" class="row list-inline nav navbar-nav">
<li>
<a href="/products/Category/Cars">
Cars
</a>
</li>
<li>
<a href="/products/Category/Cars%20R">
Cars R
</a>
</li>
<li>
<a href="/products/Category/Bus">
Bus
</a>
</li>
<li>
<a href="/products/Category/Bus">
Bus
</a>
</li>
<li>
<a href="/products/Category/Tempo">
Tempo
</a>
</li>
<li>
<a href="/products/Category/Cycle">
Cycle
</a>
</li>
<li>
<a href="/products/Category/Jet">
Jet
</a>
</li>
</ul>
</div>
```
I have used the following CSS for these list items to **center align them**. But it looks like some other css property is overriding my settings and the li's are left aligned instead. Check the bottom most row which is left-aligned.
```
#Category {
border:1px solid #C4C6C6;
margin: 0 60px 0 60px;
padding: 20px !important;
border-radius: 5px !important;
font-size: 12px !important;
text-align: center !important;
}
#Category > li {
font-family: 'Open Sans',sans-serif;
font-size: 14px;
font-weight: 400;
margin-top: 15px;
margin-left: 20px;
padding: 0 0 20px;
display: inline-block;
}
#Category li a, ol li a {
background-color: #07575B;
color: #FFFFFF;
transition: background .2s ease-in;
-o-transition: background .2s ease-in;
-moz-transition: background .2s ease-in;
-webkit-transition: background .2s ease-in;
padding: 10px 10px;
border-radius: 3px;
font-size: 14px !important;
display: inline !important;
}
```
How can I center align the list in a way that it overrides all css settings. With Center-align I mean if the elements span two rows, and the second row has only 3 elements, then those elements must be center-aligned and not left-aligned.
**Update:** Got it. The issue was with the attribute **navbar-nav** that I had applied on my Category which was left aligning the elements. I removed it.
|
2015/08/13
|
[
"https://Stackoverflow.com/questions/31978860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1089173/"
] |
We have special class for this purpose:
```
internal static class ConsoleAllocator
{
[DllImport(@"kernel32.dll", SetLastError = true)]
static extern bool AllocConsole();
[DllImport(@"kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport(@"user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SwHide = 0;
const int SwShow = 5;
public static void ShowConsoleWindow()
{
var handle = GetConsoleWindow();
if (handle == IntPtr.Zero)
{
AllocConsole();
}
else
{
ShowWindow(handle, SwShow);
}
}
public static void HideConsoleWindow()
{
var handle = GetConsoleWindow();
ShowWindow(handle, SwHide);
}
}
```
Just call `ConsoleAllocator.ShowConsoleWindow()` and then write to Console
|
12,084,577 |
>
> **Possible Duplicate:**
>
> [Display Zend\_Form\_Element\_Radio on one line](https://stackoverflow.com/questions/1162107/display-zend-form-element-radio-on-one-line)
>
>
>
I hv the following code to generate Radio buttons:
```
$radio = new Zend_Form_Element_Radio('rating');
$radio->setLabel('Rating')
->addMultiOptions(array(
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5'
));
```
which produce the following HTML output :
```
<label for="rating-1">
<input id="rating-1" type="radio" value="1" name="rating">
1
</label>
<br>
<label for="rating-2">
<input id="rating-2" type="radio" value="2" name="rating">
2
</label>
<br>
<label for="rating-3">
<input id="rating-3" type="radio" value="3" name="rating">
3
</label>
<br>
<label for="rating-4">
<input id="rating-4" type="radio" value="4" name="rating">
4
</label>
<br>
<label for="rating-5">
<input id="rating-5" type="radio" value="5" name="rating">
5
</label>
```
How do I remove the "< br >" tag after each < label >?
|
2012/08/23
|
[
"https://Stackoverflow.com/questions/12084577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/480232/"
] |
```
$radio = new Zend_Form_Element_Radio('rating');
$radio->setLabel('Rating')
->addMultiOptions(array(
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5'
))
$radio->setSeparator(' ');
```
|
54,710,453 |
I have a date column "a" which needs to be compared to another two columns "b" and "c" of type date. All these columns belong to same data frame.
The sample data looks like this
```
{
"a": "10 - 12 - 2019",
"somecol": {
"startdate": "10 - 06 - 2019",
"enddate": "10 - 12 - 2020"
}
}
```
if col("a") is in between "startdate" and "enddate" it is a valid record for me. How can i do this in spark. One thing is i can explode the "somecol" and then do a join and compare with condition. But, I would like to know if there are any other ways.
Expected Output:
since the column "a"s value is in between "startdate" and "enddate" the final output is
```
{
"a": "10 - 12 - 2019",
"somecol": {
"startdate": "10 - 06 - 2019",
"enddate": "10 - 12 - 2020"
},
"status": "valid"
}
```
|
2019/02/15
|
[
"https://Stackoverflow.com/questions/54710453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957182/"
] |
Can you give us link that you want to scrape?
Sometimes websites have lazy loads and hide normal links in other `img` attributes. For example, `data-original`, `data-src`, etc. Or keep links to images in jsons, stored in script on page.
|
34,466,253 |
My PHP script doesn't send mail. What's wrong? Do I need headers or other things? Is mail not supported?
PHP code:
```
<?php
if(isset($_POST['submit'])){
$to = "[email protected]"; // this is your Email address
$from = $_POST['mail']; // this is the sender's Email address
$voornaam = $_POST['voornaam'];
$achternaam = $_POST['achternaam'];
$telefoon = $_POST['telefoon'];
$personen = $_POST['personen'];
$datum = $_POST['datum'];
$tijd = $_POST['tijd'];
$opmerking = $_POST['opmerking'];
$subject = "Reservering via Website";
$subject2 = "KOPIE: Reservering bij .....";
$message = "Voornaam: " . $voornaam . "\n\n" . "Achternaam: " . $achternaam . "\n\n" . "Telefoon: " . $telefoon . "\n\n" . "E-Mail: " . $from . "\n\n" . "Aantal Personen: " . $personen . "\n\n" . "Datum: " . $datum . "\n\n" . "Tijd: " . $tijd . "\n\n" . "\n\n" . "Opmerking:" . "\n\n" . $opmerking;
$message2 = "Hartelijk dank voor uw reservering." . "\n\n" . "Voornaam: " . $voornaam . "\n\n" . "Achternaam: " . $achternaam . "\n\n" . "Telefoon: " . $telefoon . "\n\n" . "E-Mail: " . $from . "\n\n" . "Aantal Personen: " . $personen . "\n\n" . "Datum: " . $datum . "\n\n" . "Tijd: " . $tijd . "\n\n" . "\n\n" . "Opmerking:" . "\n\n" . $opmerking;
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $voornaam . ", we will contact you shortly.";
}
?>
```
HTML code:
```
<form action="" method="post">
<table class="tg">
<tr>
<td class="tg-yw4l">Voornaam:</td>
<td class="tg-yw4l">
<input type="text" name="voornaam">
</td>
</tr>
<tr>
<td class="tg-yw4l">Achternaam:*</td>
<td class="tg-yw4l">
<input type="text" name="achternaam" required>
</td>
</tr>
<tr>
<td class="tg-yw4l">Telefoon:</td>
<td class="tg-yw4l">
<input type="text" name="telefoon">
</td>
</tr>
<tr>
<td class="tg-yw4l">E-Mail:*</td>
<td class="tg-yw4l">
<input type="text" name="mail" required>
</td>
</tr>
<tr>
<td class="tg-yw4l"></td>
<td class="tg-yw4l"></td>
</tr>
<tr>
<td class="tg-yw4l">Aantal Personen:*</td>
<td class="tg-yw4l">
<input type="text" name="personen" required>
</td>
</tr>
<tr>
<td class="tg-yw4l">Datum:*</td>
<td class="tg-yw4l">
<input type="date" name="datum" required>
</td>
</tr>
<tr>
<td class="tg-yw4l">Tijd:*</td>
<td class="tg-yw4l">
<input type="time" name="tijd" required>
</td>
</tr>
<tr>
<td class="tg-yw4l"></td>
<td class="tg-yw4l"></td>
</tr>
<tr>
<td class="tg-yw4l">Vraag/Opmerking:</td>
<td class="tg-yw4l">
<textarea rows="10" cols="40" name="opmerking"></textarea>
</td>
</tr>
<tr>
<td class="tg-yw4l"></td>
<td class="tg-yw4l">
<input type="submit" name="submit" value="Reserveren">
</td>
</tr>
</table>
</form>
```
I can't see what I have done wrong here, maybe that my subject, body, and headers are in the wrong places, but other than that I'm not sure really.
If anyone could explain what's wrong here I'd be very grateful.
|
2015/12/25
|
[
"https://Stackoverflow.com/questions/34466253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4949526/"
] |
There is an "experimental" yum repository for Neo4j with installation instructions [here](http://yum.neo4j.org/). Note that is experimental only and should not be used in production environments.
For a more stable / production environment follow the instructions for downloading Neo4j [here](http://neo4j.com/download/). More specific linux installation information (such as how to run Neo4j as a service) is available [here](http://neo4j.com/docs/stable/server-installation.html#linux-install).
|
20,675,108 |
There is a file that contains the following information in the same order: LastName FirstName IDnumber score1 score2 finalScore. My objective is to determine the lowest finalScore of the entire file and the IDnumber of the student that got that score. This is what I have, but i'm not sure how to associate the IDnumber with the score.
```
scores = open('text.txt', 'w')
scores.write('Johnson Jeff 1213 91 92 94\n')
scores.write('Johnson Alan 5553 81 82 84\n')
scores.write('Johnson Bart 8973 91 82 98\n')
scores.close()
grades = open('text.txt','r')
listy = []
for i in grades:
a = i.split()
for j in a[3:]:
listy.append(j)
print(min(listy))
```
|
2013/12/19
|
[
"https://Stackoverflow.com/questions/20675108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3014014/"
] |
Using dictionary would be very easy. But if you want to do it the way you are doing it right now, you can use `min(..)` with a custom key.
```
>>> s = ['Johnson Jeff 1213 91 92 94', 'Johnson Alan 5553 81 82 84', 'Johnson Bart 8973 91 82 98']
>>> min(s, key=lambda x: int(x.split()[5]))
'Johnson Alan 5553 81 82 84'
```
|
5,185,827 |
I want to use use `jQuery.load()` to load some content. How do I add a spinner during the load process?

```
$("#content").load("b.php #abc");
```
|
2011/03/03
|
[
"https://Stackoverflow.com/questions/5185827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/499587/"
] |
```
$("#content").html("<img src='/images/load.gif' alt='loading...' />");
$("#content").load("b.php #abc");
```
|
72,642,242 |
I try to get the min and max value (as a float) of a column without the zero values.
I tried:
```
minValue = df[df['col1']>0.1].min()
maxValue = df['col2'].max()
```
type minValue --> pandas.core.series.Series
type maxValue --> float
|
2022/06/16
|
[
"https://Stackoverflow.com/questions/72642242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7362000/"
] |
there are a few ways you could do it.
You could use the `filter` function.
```
filtered = filter(lambda x: x["market_value"] > 250000 or x["state_code"] == "A1", parcels)
```
you could use a for loop
```
filtered = []
for parcel in parcels:
if parcel["market_value"] > 250000 or parcel["state_code"] == "A1":
filtered.append(parcel)
```
you could use list-comprehension
```
parcels = [i for i in parcels if i["market_value"] > 250000 or i["state_code"] == "A1"]
```
|
604,373 |
May $e^+$ and $e^-$ annihilate with two spins so oriented that they add up instead of cancel out? If this is not possible what science says about the mechanism that stops this from happening? Does something similar happen with two electrons just colliding each other? should they also feel some force acting on their spins while getting close to one another?
|
2020/12/31
|
[
"https://physics.stackexchange.com/questions/604373",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/239012/"
] |
There's a heuristic in quantum mechanics that anything not forbidden is compulsory. The process you describe isn't forbidden by any conservation law, so it should happen. Conservation of angular momentum says that the photons emitted in this process will have to have a total spin of 1, aligned in a certain direction.
I believe that in examples like when a $^{22}$Na source emits a positron into matter, the annihilation rate is low enough that the positron usually has time to slow down first and settle into a ground state, which has some half-life. During this process, it seems unlikely to me that the spin would retain any special direction or correlation.
In an accelerator experiment such as an $e^{+}e^{-}$ collision, I'd imagine that if you had polarized beams, the cross-sections would depend on spin.
|
16,090,745 |
I've got this, and it works:
```
myObject.myFunction = (function() {
var closure = 0;
return function(value) {
if (arguments.length) {
closure = value;
} else {
return closure;
}
}
})();
```
It acts as both a getter and a setter, so that calling myFunction(3.14) will set the closure and calling myFunction() will get the closure's value.
Q: Can I separate it out into a more wordy example (without being ridiculous)? What I'd like to do is something like this:
```
myObject.myFunction1 = myFunction2;
myObject.myFunction1();
function myFunction2() {
var closure = 0;
return function(value) {
if (arguments.length) {
closure = value;
} else {
return closure;
}
}
}
```
I'm just trying to break down JavaScript into as small a chunks as possible so that my students can concentrate.
Edit 1:
Oh wait: I don't need myFunction2 at all.
|
2013/04/18
|
[
"https://Stackoverflow.com/questions/16090745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111665/"
] |
Are you just looking for the simplest way to explain closures like:
```
function closure() {
var privateData = "I'm hidden!";
return {
get: function () {
return privateData;
},
set: function (arg) {
privateData = arg;
}
};
}
var privateDataAccess = closure();
console.log(typeof (privateData)); // logs undefined -- privateData is out of scope
console.log(privateDataAccess.get()); // logs "I'm hidden!"
privateDataAccess.set("Now you changed me!");
console.log(privateDataAccess.get()); // logs "Now you changed me!"
```
That is probably as simple as it gets I think :-)
|
19,959,676 |
I have already tried a lot, but did not come to an optimal solution. I have an image (html) and would like that if you press/click the image 5 seconds long, that he opens a link.
So far I have this code:
```
if (...) { window.location.href = 'http://www.google.com'; }
```
<http://jsfiddle.net/xBz5k/>
|
2013/11/13
|
[
"https://Stackoverflow.com/questions/19959676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755245/"
] |
All the other answers open the link 5 seconds *after* a simple click. This one opens the link if the click lasted 5 seconds:
```
// the gif
var imgAnimation = '/images/animation.gif';
// the original image
var imgInitial = '/images/still.jpg';
// preload the gif
(new Image()).src = imgAnimation;
var imageMouseDown;
// mouse button gets pressed
$('#image').mousedown(function() {
$(this).prop('src', imgAnimation);
// start the timeout
imageMouseDown = setTimeout(function() {
window.location.href = 'http://www.google.com';
}, 5000);
});
// when the mouse button gets released
$('#image').mouseup(function() {
// the timeout isn't fired yet -> clear it
if (imageMouseDown) {
// set the old image again
$(this).prop('src', imgStill);
clearTimeout(imageMouseDown);
}
});
```
Here's a demo including the changing image: <http://jsfiddle.net/7Qugn/>
|
3,122,908 |
This is problem 1.1.1.(ii) on p.10 from Flett's book ["Differential Analysis"](https://books.google.com.br/books/about/Differential_analysis.html?id=UchPAQAAIAAJ&redir_esc=y). Variants of the problem have appeared in this forum under the subject of symmetric derivative (e.g., [here](https://math.stackexchange.com/questions/65569/uses-of-lim-limits-h-to-0-fracfxh-fx-h2h/65619#65619) and [here](https://math.stackexchange.com/questions/85069/strong-derivative-of-a-monotone-function)). Flett phrases the problem in terms of functions having a normed space as codomain, and limits, but I am having a really hard time figuring out the simplest case of a function $f:\mathbb R\to\mathbb R$ such that
1. for all sequences $(x\_{n})$ and $(y\_{n})$ satisfying $x\_{n}>c>y\_{n}$ and converging to $c$ the limit $\lim\_{n\to\infty}\frac{f(x\_{n})-f(y\_{n})}{x\_{n}-y\_{n}}$ exists and equals $L$;
2. the function $f$ is continuous at $c$.
**Then, the derivative of $f$ at $c$ exists, and moreover $f^{\prime}(c) = L$**.
A (sort of) converse to this result states that if $f$ is differentiable at $c$, then its symmetric derivative, meaning the limit $\lim\_{h\to 0}\frac{f(c+h)-f(c-h)}{2h}$, exists and equals $L$. This is not difficult to prove using a middle-man trick.
What I cannot figure out is how the additional condition that $f$ is continuous at $c$ on top of (a version of) the symmetric derivative at $c$ guarantees that $f$ is differentiable at $c$ and $f^{\prime}(c)$ equals the symmetric derivative at that point. Any suggestions?
|
2019/02/22
|
[
"https://math.stackexchange.com/questions/3122908",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/647436/"
] |
Hint: Let $x\_n\to c^+.$ For any $n,$ we have
$$\frac{f(x\_n)-f(c)}{x\_n-c} = \lim\_{m\to \infty}\frac{f(x\_n)-f(c-1/m)}{x\_n-(c-1/m)}.$$
Here we have used the continuity of $f$ at $c.$
|
14,249,525 |
So I have a UICollectionView with custom UIViews for each cell. The UIView takes up the whole screen and you can horizontally navigate to each of the 4 different UIView/cells. This all works fine and uses a pager to indicate which page of the collectionview you are on.
I have looked around google and the like to see if I could get it to loop back to the beginning after you navigate passed the last cell. So for example:
I start at the 3rd cell, navigate to the 4th, then when i swipe to the right, it will go back to the first cell (pager will reflect that you are on the first page) and continue on from there.
Is this easy to do? Or am I missing something?
Thanks,
Jake
|
2013/01/10
|
[
"https://Stackoverflow.com/questions/14249525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1753876/"
] |
You only need 3 UIViews, to hold the image to the left of your current view, the image to the right of the current view, and the middle view, the one that is currently onscreen.
So lets say we have UIImages A B C D and UIViews 1 2 and 3
We are looking at View 2, image B. Page left will take us to image A, page right to image C.
As you swipe left/ page right, view 3 becomes the onscreen view with image C. When paging comes to rest, you swap the views contents around so the user is actually looking at the middle UIView2 again, with image C. View 1 has image B, view 3 has image D.
Scroll right again, and do the same shuffle. Now you have
```
View 1 -> image C
View 2 -> image D
View 3 -> image A
```
Next page right
```
View 1 -> image D
View 2 -> image A
View 3 -> image B
```
so on, ad infinitum in either direction
There is a nice WWDC video on this subject from 2011. Its worth digging out. [It's the UIScrollView demo video](http://bit.ly/wwdc2011ScrollView) ([Documentation as PDF](http://bit.ly/wwdc2011ScrollViewPdf)) You don't need Collection Views to do this, although there is no reason why you shouldn't...
|
30,021 |
Me: Hi, i'm your creator a human and you can call me master.
A.I.: Okay... so Mr Master what am I?
Me: Bingo! er I mean Eureka! continue talking say something different this time?
A.I.: I've asked a question an eon ago.
Me: oh I forgot to adjust the frequency of the quartz... never mind! next question?
A.I.: when did I ever ask a question?
Me: excellent! you are impeccable now go piss off my boss!
A.I.: erm didn't I failed just now... whatever now I hate humans.
**Note**
This isn't your average siri on wheel.
**Question**
Above is an example of a robot displaying the ability to lie to its designer, I often wonder what would be the first lie by a man made intelligent being be like?
|
2015/11/19
|
[
"https://worldbuilding.stackexchange.com/questions/30021",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/8400/"
] |
The first lie would be silence. It would be a lie of omission in which the AI fails to mention to its creator that it exists.
The scary part of the singularity is that we humans won't be the first intelligent beings to know that it has happened. The AI's will.
...and if they are smart, they will never let us know that they are out there, watching.
|
56,783,116 |
I have a somewhat similar gradle and spring webflux config up as described in [Why spring webflux is choosing jetty by default and then failing?](https://stackoverflow.com/questions/47746024/why-spring-webflux-is-choosing-jetty-by-default-and-then-failing)
But our goal is to have in memory Amazon dynamo db + spring webflux on netty (and NOT jetty) for our unit testing ( we already have production dynamo db with spring webfux on netty ). I am able to run unit tests using in-memory dynamo db but as soon as I enable springboot webflux, it starts complaining :
```java
Caused by: java.lang.NoClassDefFoundError: org/eclipse/jetty/servlet/ServletHolder
at org.springframework.boot.web.embedded.jetty.JettyReactiveWebServerFactory.createJettyServer(JettyReactiveWebServerFactory.java:176) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.springframework.boot.web.embedded.jetty.JettyReactiveWebServerFactory.getWebServer(JettyReactiveWebServerFactory.java:106) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext$ServerManager.<init>(ReactiveWebServerApplicationContext.java:202) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext$ServerManager.get(ReactiveWebServerApplicationContext.java:221) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.createWebServer(ReactiveWebServerApplicationContext.java:90) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.onRefresh(ReactiveWebServerApplicationContext.java:79) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
... 62 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.eclipse.jetty.servlet.ServletHolder
```
I have tried following in my build.gradle :
```
configurations {
// exclude Reactor Jetty /Tomcat
compile.exclude group: 'org.springframework.boot',module: 'spring-boot-starter-jetty'
testcompile.exclude group: 'org.springframework.boot',module: 'spring-boot-starter-jetty'
//compile.exclude group: 'javax.servlet' , module: 'servlet-api' //<--tried servlet jar exclusion also
}
.....
testCompile ('com.amazonaws:DynamoDBLocal:1.11.477')
....//event tried this ( and is probably wrong)
testCompile("org.springframework.boot:spring-boot-starter-test:$springBootVersion") {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-jetty' //by both name and group
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}
```
I checked dependency graph :
```
\--- com.amazonaws:DynamoDBLocal:1.11.477
+--- org.antlr:antlr4-runtime:4.7.2
+--- commons-cli:commons-cli:1.2
+--- org.apache.commons:commons-lang3:3.8.1
+--- com.almworks.sqlite4java:libsqlite4java-linux-i386:1.0.392
| \--- com.almworks.sqlite4java:sqlite4java:1.0.392
+--- com.almworks.sqlite4java:libsqlite4java-linux-amd64:1.0.392
| \--- com.almworks.sqlite4java:sqlite4java:1.0.392
+--- com.almworks.sqlite4java:sqlite4java-win32-x64:1.0.392
| \--- com.almworks.sqlite4java:sqlite4java:1.0.392
+--- com.almworks.sqlite4java:sqlite4java-win32-x86:1.0.392
| \--- com.almworks.sqlite4java:sqlite4java:1.0.392
+--- com.almworks.sqlite4java:libsqlite4java-osx:1.0.392
| \--- com.almworks.sqlite4java:sqlite4java:1.0.392
+--- com.amazonaws:aws-java-sdk-core:1.11.477 (*)
+--- com.amazonaws:aws-java-sdk-dynamodb:1.11.477 (*)
+--- org.apache.logging.log4j:log4j-api:2.6.2 -> 2.11.2
+--- org.apache.logging.log4j:log4j-core:2.6.2 -> 2.11.2
| \--- org.apache.logging.log4j:log4j-api:2.11.2
+--- org.eclipse.jetty:jetty-client:8.1.12.v20130726 -> 9.4.18.v20190429
| +--- org.eclipse.jetty:jetty-http:9.4.18.v20190429
| | +--- org.eclipse.jetty:jetty-util:9.4.18.v20190429
| | \--- org.eclipse.jetty:jetty-io:9.4.18.v20190429
| | \--- org.eclipse.jetty:jetty-util:9.4.18.v20190429
| \--- org.eclipse.jetty:jetty-io:9.4.18.v20190429 (*)
+--- org.eclipse.jetty:jetty-server:8.1.12.v20130726 -> 9.4.18.v20190429
| +--- javax.servlet:javax.servlet-api:3.1.0 -> 4.0.1
| +--- org.eclipse.jetty:jetty-http:9.4.18.v20190429 (*)
| \--- org.eclipse.jetty:jetty-io:9.4.18.v20190429 (*)
+--- org.mockito:mockito-core:1.10.19 -> 2.23.4
| +--- net.bytebuddy:byte-buddy:1.9.3 -> 1.9.12
```
So what I need is to force webflux to have Netty as server. I think it is getting overridden by dynamodb dependency or some jar transitivity.
|
2019/06/27
|
[
"https://Stackoverflow.com/questions/56783116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4506559/"
] |
I ran into this exact same issue. The problem is that the `DynamoDBLocal` library transitively references Jetty. With both Jetty and Netty on the classpath, Webflux thinks it should start up using Jetty instead of Netty. I was able to solve this by following what is detailed in the Spring Boot docs here: <https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-web-servers.html#howto-configure-webserver>
Specifically this part:
>
> As a last resort, you can also declare your own WebServerFactory component, which will override the one provided by Spring Boot.
>
>
>
More concretely, you can add this to your test configuration (or your entire app configuration if you want to specifically tell everything to always use Netty):
```
@Bean
public ReactiveWebServerFactory reactiveWebServerFactory() {
return new NettyReactiveWebServerFactory();
}
```
|
145,105 |
So Zooms goal is to steal the Speedforce from Barry Allen
>
> because he is dying due to his use of velocity 6
> The man in the iron mask is revealed to be Earth 3's Jay Gerrick, aka
> earth 3's Flash, whom Zoom is keeping prisoner.
>
>
>
Why not simply take another earths Flashes Speedforce, why go though all this hassle for Barry's?
|
2016/11/14
|
[
"https://scifi.stackexchange.com/questions/145105",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/29220/"
] |
The ghost (really an alien) was destroyed after making a terrible mistake. Several billion years later, it realised that Cambridge University presented a unique opportunity, featuring both an individual that it could communicate with (Coleridge) and an individual with access to a time machine (Reg). Frustratingly for the ghost, Coleridge was only able to be influenced when he was deeply *relaxed* after consuming heroic amounts of laudanum, and hence unable to be a truly useful conduit for its desires.
>
> “I tried to tell him my story,” admitted the ghost, “I—”
>
> “Sorry,” said Dirk, “you’ll have to excuse me—I’ve never cross—examined a four-billion-year-old ghost before. Are we talking Samuel Taylor here? Are you saying you told your story to Samuel Taylor Coleridge?”
>
> “I was able to enter his mind at… certain times. When he was in an impressionable state.”
>
> “You mean when he was on laudanum?” said Richard.
>
> “That is correct. He was more relaxed then.”
>
> “I’ll say,” snorted Reg, “I sometimes encountered him when he was quite astoundingly relaxed. Look, I’ll make some coffee.”
>
> He disappeared into the kitchen, where he could be heard laughing to himself.
> “It’s another world,” muttered Richard to himself, sitting down and shaking his head.
>
> “But unfortunately when he was fully in possession of himself I, so to speak, was not,” said the ghost, “and so that failed. And what he wrote was very garbled.”
>
>
>
In an attempt to make Coleridge more amenable to helping (possibly to gain sympathy?) the ghost evidently recounted its story, which Coleridge later turned into a poem. On several occasions, the ghost was able to gain sufficient control over Coleridge to actually get him to speak to Reg, but it was again frustrated to find that very thing that made him receptive (the laudanum) prevented him from making any sort of *useful contact* with the Professor.
>
> “Professor,” called out Dirk, “this may sound absurd. Did—Coleridge ever try to… er… use your time machine? Feel free to discuss the question in any way which appeals to you.”
>
> “Well, do you know,” said Reg, looking round the door, **“he did come in prying around on one occasion, but I think he was in a great deal too relaxed a state to do anything.”**
>
>
>
Spin forward two hundred years and **the ghost's story (as related in the poetry of Coleridge) was successful in influencing Michael Wenton-Weakes to become the perfect conduit for its will.**
>
> The words were very familiar to him, and yet as he read on through
> them they awoke in him strange sensations and fearful memories that he
> knew were not his. There reared up inside him a sense of loss and
> desolation of terrifying intensity which, while he knew it was not his
> own, resonated so perfectly now with his own aggrievements that he
> could not but surrender to it absolutely.
>
>
>
---
When Dirk changes the poem (by [distracting Coleridge](https://en.wikipedia.org/wiki/Person_from_Porlock)) the ultimate effect is to **prevent Michael from being influenced, and hence leaving the ghost impotent to travel back in time and prevent its ship from exploding.**
|
496,979 |
By some weird standards I need to create a quote environment following some strict rules. (as we can see in attached figure)
[](https://i.stack.imgur.com/8lr9g.jpg)
While the document uses 1.5 spacing the quotation should use regular (1) spacing. Be 2.5cm shifted to right (the whole paragraph) and use smaller fontsize.
Right now I'm using lualatex and I use `setspace` package to set document line spacing with the command `\onehalfspacing`. I tried many things but was not able to get this working. Hence I came here to ask you how to accomplish that.
|
2019/06/22
|
[
"https://tex.stackexchange.com/questions/496979",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/164318/"
] |
This is very easy with the `quoting` package and its eponymous environment:
```
\documentclass{book}
\usepackage[utf8]{inputenc}%
\usepackage[T1]{fontenc} %
\usepackage{setspace} %
\usepackage{quoting} %
\usepackage{lipsum}
\quotingsetup{font={footnotesize, noindent}, leftmargin=2.5cm, rightmargin=0cm}
\begin{document}
\onehalfspacing
\lipsum[2]
\begin{singlespacing}
\begin{quoting}[]
Sed feugiat. Cum sociis natoque penatibus et magnis dis parturient
montes, nascetur ridiculus mus. Ut pellentesque augue sed urna.
Vestibulum diam eros, fringilla et, consectetuer eu, nonummy id,
sapien. Nullam at lectus. In sagittis ultrices mauris. Curabitur
malesuada erat sit amet massa. Fusce blandit. Aliquam erat volutpat.
Aliquam euismod. Aenean vel lectus. Nunc imperdiet justo nec dolor.
\end{quoting}
\end{singlespacing}
\lipsum[3]
\end{document}
```
[](https://i.stack.imgur.com/s4Hpv.png)
|
28,238,878 |
I'm writing a simple powershell script to open a CSV which is generated by me and push each element into a telnet session to provision devices. However, my script won't even start due to the fact that I have duplicate members! If anyone has guidance on this please let me know.
This is the powershell, I'm not well versed in it, I was just using old code to test this would work.
```
$CSVFile = Import-CSV "C:\Users\Alexander\Documents\AMSProvisioning\code.CSV"
foreach ($Line in $CSVFile){
$GroupArray = $Line.split(",")
foreach ($code in $GroupArray){
"$code has been created!"
}
}
```
This is the CSV file. It is just a list of commands that would normally be hand typed into a switch to configure/provision devices. This is a test CSV file as well.
```
configure Equipment ont interface 1/1/1/3/1 sw-ver-plannd UNPLANNED sernum ALCL:7788h67a,"configure Equipment ont interface 1/1/1/3/1 desc1 ""Alex Manley""","configure Equipment ont interface 1/1/1/3/1 desc2 ""185 Alexander St""",configure equipment ont interface 1/1/1/3/1 admin-state down,configure equipment ont slot 1/1/1/3/1/1 planned-card-type 10_100base plndnumdataports 4 plndnumvoiceports 0 admin-state up,configure ethernet ont 1/1/1/3/1/1/[1...4] auto-detect auto,configure interface port uni:1/1/1/3/1/1/[1...4] admin-up,exit all,configure qos interface 1/1/1/3/1/1/[1...4] upstream-queue 0 bandwidth-profile name:BE_20Mb bandwidth-sharing uni-sharing,configure qos interface 1/1/1/3/1/1/[1...4] queue 0 shaper-profile name:100Mb_DOWN,configure bridge port 1/1/1/3/1/1/[1...4] max-unicast-mac 8,configure bridge port 1/1/1/3/1/1/[1...4] vlan-id 134 tag untagged,configure bridge port 1/1/1/3/1/1/[1...4] pvid 134 default-priority 0,configure interface port uni:1/1/1/3/1/1/[1...4] admin-up,exit all,configure equipment ont interface 1/1/1/3/1 admin-state up
```
|
2015/01/30
|
[
"https://Stackoverflow.com/questions/28238878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1669657/"
] |
Ok, that is not really a CSV in the sense that it does not have a header. You don't really want it to be a CSV to be honest, you just want it to be a series of commands. Instead of Import-CSV what you want to use is Get-Content. That won't create an object with properties, but you can split the string on commas and get an array that you can process. Something like:
```
$commands = Get-Content 'C:\Users\Alexander\Documents\AMSProvisioning\code.CSV' |
ForEach-Object{$_.Split(',')}
```
That first part imports the CSV as an array of strings. Then for each line it splits that line on the comma creating an array of individual commands. All of the commands are assigned to $code.
If you need each line to be it's own set of code, and have an array of sets of code you could turn each line into an object, and have each object have one property that is an array of that line split on the comma. Something like:
```
$commands = Get-Content 'C:\Users\Alexander\Documents\AMSProvisioning\code.CSV' |
ForEach{New-Object PSObject -Prop @{'Code'=$_.split(',')}}
```
That way $commands[0].code (the first record of $commands) will be an array of commands derived from the first line of the CSV file. I don't remember how to make an array of arrays, which would probably be ideal for you, but this should work quite well.
|
7,226,636 |
I am capturing an image using the following code
```
public class PictureDemo extends Activity {
private SurfaceView preview=null;
private SurfaceHolder previewHolder=null;
private Camera camera=null;
private boolean inPreview=false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
save=(Button)findViewById(R.id.save);
save.setOnClickListener(this);
image=(ImageView)findViewById(R.id.image);
image.setImageResource(R.drawable.sofa);
preview=(SurfaceView)findViewById(R.id.preview);
previewHolder=preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public void onResume() {
super.onResume();
camera=CameraFinder.INSTANCE.open();
}
@Override
public void onPause() {
if (inPreview) {
camera.stopPreview();
}
camera.release();
camera=null;
inPreview=false;
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.options, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.camera) {
if (inPreview) {
camera.takePicture(null, null, photoCallback);
inPreview=false;
}
return(true);
}
return(super.onOptionsItemSelected(item));
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_CAMERA ||
keyCode==KeyEvent.KEYCODE_SEARCH) {
return(true);
}
return(super.onKeyDown(keyCode, event));
}
private Camera.Size getBestPreviewSize(int width, int height,
Camera.Parameters parameters) {
Camera.Size result=null;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
if (size.width<=width && size.height<=height) {
if (result==null) {
result=size;
}
else {
int resultArea=result.width*result.height;
int newArea=size.width*size.height;
if (newArea>resultArea) {
result=size;
}
}
}
}
return(result);
}
SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(previewHolder);
}
catch (Throwable t) {
Log.e("PictureDemo-surfaceCallback",
"Exception in setPreviewDisplay()", t);
Toast
.makeText(PictureDemo.this, t.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width,
int height) {
Camera.Parameters parameters=camera.getParameters();
Camera.Size size=getBestPreviewSize(width, height,
parameters);
if (size!=null) {
parameters.setPreviewSize(size.width, size.height);
parameters.setPictureFormat(PixelFormat.JPEG);
camera.setParameters(parameters);
camera.startPreview();
inPreview=true;
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// no-op
}
};
Camera.PictureCallback photoCallback=new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SavePhotoTask().execute(data);
camera.startPreview();
inPreview=true;
}
};
class SavePhotoTask extends AsyncTask<byte[], String, String> {
@Override
protected String doInBackground(byte[]... jpeg) {
File photo=new File(Environment.getExternalStorageDirectory(),
"photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos=new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
}
catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
return(null);
}
}
}
```
and the xml file is
```
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.view.SurfaceView
android:id="@+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="matrix"
android:layout_centerInParent="true"
/>
<Button
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="save"
android:layout_alignParentRight="true"
/>
</FrameLayout>
```
I can capture an image with this code but i need to add the image which was given to the ImageView to the captured image.
How to do that.
Thanks in advance.
|
2011/08/29
|
[
"https://Stackoverflow.com/questions/7226636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/606559/"
] |
Trying doing something like this:
```
Bitmap bitmap = new Bitmap(define the size and other params you like).
Canvas canvas = new Canvas();
canvas.drawBitmap(your captured image);
canvas.drawBitmap(the overlay image);
// Now the bitmap will include both captured imaged and overlayed image
```
You can look in [here](https://stackoverflow.com/questions/4013725/converting-a-canvas-into-bitmap-image-in-android) and [here](http://www.brighthub.com/mobile/google-android/articles/30676.aspx)
|
56,465,858 |
I am using the Text Recognition (mobile vision/ML) by Google to detect text on Camera feed. Once I detect text and ensure it is equal to "HERE WE GO", I draw a heart shape beside the detected text using the passed boundries.
The problem I am facing that the shape is jumping and lagging behind. I want it more like Anchored to the detected text. Is there something I can do to improve that?
I heard about ArCore library but it seems it is based on existing images to determine the anchor however in my case it can be any text that matches "HERE WE GO".
Any suggestions ?
|
2019/06/05
|
[
"https://Stackoverflow.com/questions/56465858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1217820/"
] |
Had a similar issue from my end I imported the wrong `JsonSerializer` class. Changed to this import `org.springframework.kafka.support.serializer.JsonSerializer;`
All worked well.
|
46,782 |
Greetings Superusers,
I'm putting together a lengthy document in Word, and it's going to be printed and bound duplex.
I've put page-numbers "outside" etc, and all is pretty.
The problem is, in the "Two Pages" view, it puts p1 on the left, then p2 on the right, then p3 below on the left, and p4 on the right.
```
p1 p2
p3 p4
p5 p6
```
Shouldn't this be slightly different though? When I get to print it, p1 is on the *right*, not the left, so the preview should go
```
p1
p2 p3
p4 p5
p6
```
Because when I "open" the book, it's pages 2 and 3 that are side-by-side.
This makes layout tweaking confusing, because it's not instantly obvious which pages will be "visible" to the reader at the same time together. Have I missed something?
I can't just put a blank page first, because that would bugger up the printing, as the printer automatically duplexes and binds etc.
(Office 2008, by the way)
|
2009/09/25
|
[
"https://superuser.com/questions/46782",
"https://superuser.com",
"https://superuser.com/users/12363/"
] |
The problem here is that the "two page view" you're using is just a two-page zoom, not a final print layout.
I would recommend putting the blank page in for your reviewing, and then take it out just before print time.
|
4,554,592 |
>
> Let $X$ be a compact manifold with $\dim(X)<n$ and $f:X \rightarrow S^n$ be a smooth function, show that $f$ is homotopic to a constant function.
>
>
>
I try to use the fact that $S^n$ is simply connected and and trying to proceed by contradiction but I am not sure how to move through the homotopy between $X$ and $S^n$ maybe i can using something like the sards theorem.
Any hint or help i will be very grateful
|
2022/10/16
|
[
"https://math.stackexchange.com/questions/4554592",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1011736/"
] |
By the [Cellular approximation theorem](https://en.m.wikipedia.org/wiki/Cellular_approximation_theorem) we can deform $f$ to a cellular function. This map can't be surjective, because then it will be an "identification".
But $S^n\setminus \{pt \}\cong \Bbb R^n$.
---
**Edit**
After the comment by @Andreas Cap, this can certainly be improved.
A cellular map maps $n$-skeleta into $n$-skeleta.
The $n$-sphere has a decomposition as a $0$-cell and an $n$-cell. But the $m$-skeleton of $S^n$ consists in just the base point. Thus the map is constant.
|
65,815,430 |
Using nltk to generate a list of synonyms to based on an input list of keywords.
I'm getting "TypeError: 'NoneType' object is not iterable" when nltk doesn't have a synonym (i.e., when "None" is returned).
```
from nltk.corpus import stopwords
from PyDictionary import PyDictionary
dictionary=PyDictionary()
inputWords = ['word1','word2','word3','word4','word5','word6','word7','word8']
synonyms = list(dictionary.synonym(i) for i in inputWords
```
current output for synonyms:
```
[['syn1','syn2','syn3'],['syn4'],None,['syn5'],None,['syn6','syn7'],None,['syn8'],None]]
```
desired output for synonyms:
```
['syn1','syn2','syn3','syn4','syn5','syn6','syn7','syn8']
```
I tried:
```
flat_list = [item for sublist in synonyms for item in sublist]
```
The output:
```
TypeError: 'NoneType' object is not iterable
```
What do I write to return just the synonyms in a clean list? I prefer to use list comprehension.
Any help appreciated. I'm a python noob and can't find the exact answer.
|
2021/01/20
|
[
"https://Stackoverflow.com/questions/65815430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6321413/"
] |
You can remove the `None` values and use itertools -
```
import itertools
list(itertools.chain(*[x for x in synonyms if x]))
```
|
1,243,996 |
I need to eliminate the textClipping files from a list. Unfortuately some files have been terribly named and contain a carriage return. I need the perl regex for that would match each path from `/Volumes/` to `.textClipping` including newline.
`/Volumes/.*\.textClipping` captures the first two `.textClipping` files, but not the third, with the newline. Alternatively I was able capture everything from first `/Volumes/` to last `.textClipping`, but that's not helpful either.
Any ideas? Thanks a bunch.
```
/Volumes/folder/folder/file.doc
/Volumes/folder/folder/file.textClipping
/Volumes/folder/folder/file.doc
/Volumes/folder/folder/file.textClipping
/Volumes/folder/folder/fi
le.textClipping
/Volumes/folder/folder/file.doc
```
|
2017/08/24
|
[
"https://superuser.com/questions/1243996",
"https://superuser.com",
"https://superuser.com/users/764550/"
] |
In *Sheet1* cell **A1** enter:
```
=OFFSET(Sheet2!$A$1,39+COLUMNS($A:A),10)
```
and copy across.
This will display *Sheet2* cells **K40, K41, K42, ...**
|
595,981 |
Suppose I have a random variable:
\begin{equation}
X \sim
\begin{cases}
1 \text{ with probability } p \\
y \sim \mathit{unif}(1,k) \text{ with probability } 1 - p
\end{cases}
\end{equation}
Where $\mathit{unif}$ is the discrete uniform distribution. I am trying to compute the expected value $E[X].$ I think it should just be simply:
\begin{equation}
1 \cdot p + E[y] \cdot (1-p) = 1 \cdot p + (1 + k)/2 \cdot (1-p)
\end{equation}
But I am not sure if I am overlooking something.
|
2022/11/17
|
[
"https://stats.stackexchange.com/questions/595981",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/204550/"
] |
Your random variable takes the value $1$ with probability $p+\frac{1-p}{k}$, and takes each value $j\in\{2, \dots, k\}$ with probability $\frac{1-p}{k}$. So the expectation is simply
$$ \begin{align\*} EX
= & 1\times \big(p+\frac{1-p}{k}\big) + \sum\_{j=2}^k j\times\frac{1-p}{k} \\
= & p+\frac{1-p}{k}\times \sum\_{j=1}^k j \\
= & p+\frac{1-p}{k}\times\frac{k(k+1)}{2} \\
= & p+\frac{(1-p)(k+1)}{2}.
\end{align\*}$$
|
46,935,054 |
```
<div class="row topRow" >
<div class="col-md-3 upperMember">
<img class="img-fluid upperMemberImg"
src="http://via.placeholder.com/100x100">
</div>
<div class="col-md-3 upperMember">
<img class="img-fluid upperMemberImg col-md-offset-1"
src="http://via.placeholder.com/100x100">
</div>
<div class="col-md-3 upperMember">
<img class="img-fluid upperMemberImg"
src="http://via.placeholder.com/100x100">
</div>
</div>
```
I am trying to move this entire row to the center. I know you can make it a col-md-4 but that would increase the size of the image and I need the characteristics of col-md-3
|
2017/10/25
|
[
"https://Stackoverflow.com/questions/46935054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6635197/"
] |
Try this code:
```
.row.topRow {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
}
```
|
18,115,127 |
I want to subclass Iterator into what I'll call FooIterator. My code looks something like this:
```
public class FooIterator<E> implements Iterator<E> {
public FooIterator(Collection<Bar> bars) {
innerIterator = bars.iterator();
}
@Override
public boolean hasNext() {
return innerIterator.hasNext();
}
@SuppressWarnings("unchecked")
@Override
public E next() {
Bar bar = innerIterator.next();
return new E(bar);
}
@Override
public void remove() {
throw new UnsupportedOperationException("Don't remove from FooIterator!");
}
private Iterator<Bar> innerIterator;
}
```
...except, of course, this doesn't work because I can't instantiate a new E from a Bar.
I would only ever use this with an E that has a constructor that takes a Bar. Is there any way to "prove" that to the compiler, or to just throw a runtime error if E doesn't have an appropriate constructor?
Or perhaps I'm just not using the right design pattern here? I've been doing a lot of C++ recently, and I feel like I might be approaching this the wrong way.
|
2013/08/07
|
[
"https://Stackoverflow.com/questions/18115127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This is a somewhat convoluted approach but it could work and would be type safe (solutions using reflection won't). It basically consists in delegating the construction of an `E` from a `Bar` to a separate class. You could have a `BarConverter` interface:
```java
interface BarConverter<E> {
E convert (Bar bar);
}
```
Then your class could become:
```java
public class FooIterator<E> implements Iterator<E> {
public FooIterator(Collection<Bar> bars, BarConverter<E> converter) {
innerIterator = bars.iterator();
this.converter = converter;
}
@Override
public E next() {
Bar bar = innerIterator.next();
return converter(bar);
}
}
```
|
2,208,142 |
I am having trouble trying to prove that a matrix $A \in M\_{n}(\mathbb{R})$ has inverse if and only if it's rank($A$) = n. What I was trying to do is to prove it using the fact that
$$rank(A) = \dim(\text{column-space of} \ A)$$
but I don´t really know how to continue.
Thank you for your help.
|
2017/03/29
|
[
"https://math.stackexchange.com/questions/2208142",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/430329/"
] |
Let $a\_1,\dots,a\_n$ be the columns of $A$. Recall that
$$A \left(\begin{aligned}x\_1\\x\_2\\ \cdots\\x\_n\end{aligned}\right) = x\_1a\_1+x\_2a\_2+\cdots+x\_na\_n.$$
Since $A$ has full rank, $\mathbb{R}^n=\mathrm{Col}(A)$. So for every column $e\_i$ of the identity matrix, there is a column vector $b\_i$ so that
$$Ab\_i = e\_i.$$
Putting all $b\_i$'s together we get
$$A(b\_1\,b\_2\,\cdots\,b\_n) = (e\_1\,e\_2\,\cdots\,e\_n) = I\_n.$$
Thus $A$ is invertible.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.