qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
|---|---|---|---|---|
3,214
|
For Category theory there is a well known and quite active research mailing list <https://www.mta.ca/~cat-dist/> Do similar mailing lists or usenet groups exist for other branches of mathematics? For example in metric geometry, conformal geometry,... Or do most research related discussions now take place on MO?
|
2017/04/18
|
[
"https://meta.mathoverflow.net/questions/3214",
"https://meta.mathoverflow.net",
"https://meta.mathoverflow.net/users/54495/"
] |
Here is a list of some mailing list for specific areas of mathematics. (This is posted as a [community wiki](https://meta.mathoverflow.net/tags/community-wiki/info), if you are aware of some other mailings lists, do not hesitate to add them to the list. And also if you have some additional useful information related to some of the lists.)
* FOM -- Foundations of Mathematics - [basic info](http://www.cs.nyu.edu/mailman/listinfo/fom), [archive](http://cs.nyu.edu/pipermail/fom/). This mailing list has been mentioned quite often [in MO posts](https://www.google.com/search?q=pipermail+fom+site:mathoverflow.net) and [elsewhere](https://www.google.com/search?q=pipermail+fom), including citations in some [books](http://books.google.com/books?q=pipermail+fom) and [papers](https://scholar.google.com/scholar?hl=en&q=pipermail+fom).
* Banach -- Banach Space Theory News - [basic info](https://www.mathdept.okstate.edu/cgi-bin/mailman/listinfo/banach), [archive](https://www.mathdept.okstate.edu/pipermail/banach/)
* ALGTOP-L -- Algebraic Topology Discussion Group - [basic info](https://lists.lehigh.edu/mailman/listinfo/algtop-l), [archive](https://lists.lehigh.edu/pipermail/algtop-l/)
* Categories List (category theory) - [basic info](https://www.mta.ca/~cat-dist/), [archive until 2009](https://www.mta.ca/~cat-dist/#archives)
* ~~Real Analysis List~~ - [basic info](http://www.math.louisville.edu/~lee/rae/rafaq.html) (now very likely defunct - see [GEdgar's comment](https://meta.mathoverflow.net/questions/3214/mailing-lists-usenet-groups-for-research-math/3219?noredirect=1#comment14271_3219))
|
9,439,136
|
I have set up the code to call a remote server from Android app to a remote server. Here is the code:
```
private class DownloadWebPageTask extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... theParams)
{
Log.d( "Inner class: " , "Doing stuff in background" );
String myUrl = theParams[0];
String myEmail = theParams[1];
String myPassword = theParams[2];
Log.d( "Inner myURL: " , myUrl );
Log.d( "myEmail: " , myEmail );
Log.d( "myPass: " , myPassword );
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", myEmail ));
postParameters.add(new BasicNameValuePair("password", myPassword ));
String response = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(myUrl);
try
{
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null)
{
response += s;
}
Log.d( "After call, response: " , " " + response);
}
catch (Exception e)
{
Log.d( "Exception: " , "Yup");
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result)
{
Log.d( "Post execute: " , "In the post-execute method" );
//textView.setText(result);
if ( result != null && result == "Ok")
{
Log.d( "Post execute: " , "OKKKK :)" );
}
else
{
Log.d( "Post execute: " , "NOOOT OKKKK :)" );
}
}
```
}
This is a request to be authenticated and logged in. Right now as you can see, I am collecting a login and password from the user, but not sure how to best attach that to the request URL.
I can just do something like urlString + "?login=login&pass=pass but I was wondering whether there is a "good practice" way of doing this in the Android environment? Also, my url is not htpps - is there a way to make it secure?
Thanks!
|
2012/02/24
|
[
"https://Stackoverflow.com/questions/9439136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731255/"
] |
This is **not** secure. Your URL is passed through the internet most likely through several hops unencrypted. It is trivially simple to sniff these requests. The simplest way is to send this data in the message body using HttpPost and use HTTPS. If you must use HTTP, try [digest authentication](http://en.wikipedia.org/wiki/Digest_access_authentication) explained here: [how to use Digest authentication in android?](https://stackoverflow.com/questions/6704607/how-to-use-digest-authentication-in-android)
|
30,658,916
|
When I execute the following code, it returns non-standard characters, so how do we remove it or get original string?
```
header('Content-type: text/html; charset=utf-8');
$String = "à¸?่à¸à¸•ั้งเมื่à¸";
echo $String;
```
Output : `�?่อตั้งเมื่อ`
Need actual result : `ก่อตั้งเมื่อ`
|
2015/06/05
|
[
"https://Stackoverflow.com/questions/30658916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1979522/"
] |
Your string, `à¸?่à¸à¸•ั้งเมื่à¸` is not valid utf-8. That is why the `�` shows up - the browser does not know how to interpret it.
As others have indicated, the question mark on the third position likely is the problem.
The first three bytes of the erroneous string are `e0 b8 3f` (`3f` being the ascii code `?`). I do not know any Thai, but the byte sequence for a [THAI CHARACTER KO KAI](http://www.fileformat.info/info/unicode/char/0e01/index.htm) looks pretty similar and should be`e0 b8 81`.
|
60,118,300
|
How can I optimize the processing of strings?
|
2020/02/07
|
[
"https://Stackoverflow.com/questions/60118300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3931559/"
] |
Your problem is you are making n copies of t and concatenating them. This is a simple approach, but quite expensive - it turns what could be an O(n) solution into an O(n2) one.
Instead, just check each char of s:
```
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != t.charAt(i % t.length())) {
return -1:
}
}
```
|
30,802,667
|
I have several documents, that have a title:
1. -> "Just some Word 13 from year 2015"
2. -> "Just some Word 13 from year 2011"
3. -> "Just some Word 13 from year 2012"
4. -> "Just some Word 13 from year 2014"
5. -> "Just some Word 13 from year 2013"
When searching for 13 i'm expecting number 5 to be the first result because 13 is exists twice.
Field is multiValued="true".
My fieldtype for indexing looks like this:
```
<analyzer type="index">
<charFilter class="solr.PatternReplaceCharFilterFactory" pattern="[(")(,:;!?)]" replacement=""/>
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.ReverseStringFilterFactory"/>
<filter class="solr.EdgeNGramFilterFactory" minGramSize="2" maxGramSize="30" side="front"/>
<filter class="solr.ReverseStringFilterFactory"/>
</analyzer>
```
|
2015/06/12
|
[
"https://Stackoverflow.com/questions/30802667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153948/"
] |
It doesn't sound quite right to have one test depending on an another test to define and export a variable. Set the global variable inside `onPrepare()` using `global`:
```
onPrepare: function() {
global.caseNumber = moment().format('YYYYMMDD-HHmmss-SS');
},
```
Then, you'll have `caseNumber` as a global variable across all the tests.
|
41,202,508
|
I've tried every option explained step by step [here](https://stackoverflow.com/questions/6760115/importing-a-github-project-into-eclipse) [and here:](https://stackoverflow.com/questions/29245924/import-java-project-from-github-to-eclipse) [and here](https://stackoverflow.com/questions/8070017/how-to-import-a-git-non-eclipse-java-project-into-eclipse)
And I can't get it to work.
What I want to do is pick [this project:](https://github.com/Simmetrics/simmetrics) , however it may be done (I've tried both through maven and git), and use its code in eclipse. And what I mean by that, is that I get to the point of seeing the folders in eclipse, but I can't create packages since it's not a java project, and if I mess up the code on the files that appear, it doesn't give me a warning nor in general interacts with said code.
So I guess I'm missing some piece of knowledge and I don't know where else to look for it. **What should I do to use that project in my eclipse, and create my own code that calls and uses the classes and methods from said project?**
Thank you in advance.
|
2016/12/17
|
[
"https://Stackoverflow.com/questions/41202508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2204260/"
] |
Yes, I found the similar issue, it seems to me `react-addons-perf` only work on `react`, for `react native` project, you can use `RCTRenderingPerf` which is a built-in tool in `react native` lib. My react native version is `"react-native": "^0.45.1"`
`import PerfMonitor from 'react-native/Libraries/Performance/RCTRenderingPerf';`
Start measurements
```
PerfMonitor.toggle();
PerfMonitor.start();
```
Stop measurements and print Results
```
PerfMonitor.stop();
```
You do not need to explicitly call print method to print the results, `stop()` already covered that.
You can verify it by running:
```
...
_setIndex(idx){
PerfMonitor.toggle();
PerfMonitor.start();
this.setState({index:idx})
}
componentDidUpdate(){
PerfMonitor.stop();
}
render() {
return (
<View style={styles.container}>
<Text>Welcome to react-native {helloWorld()}</Text>
<Text>Open up App.js to start working on your app!</Text>
<Text>Changes you make will automatically reload.</Text>
<Text>Shake your phone to open the developer menu.</Text>
<Button title="click me to see profiling in console log" onPress={()=> this._setIndex(2)}/>
</View>
);
}
...
```
Make sure `Remote Debug JS` is on, then you can see the results on chrome console.
|
55,594,929
|
It is only a simple question but shouldn't a label stay inside of it's nested frame when you use sticky ? In my code it only stays in the parent frame. If it is normal do you have a solution ?
I have tried looking the documentation but I didn't find anything which could help.
```
from tkinter import *
from tkinter import ttk
root = Tk()
root.title("Tk test")
root.geometry("800x800")
frame_1 = ttk.Frame(root, relief="sunken", height="400", width="400").grid(row=0, column=0, rowspan=1, columnspan=1)
frame_2 = ttk.Frame(frame_1, relief="sunken", height="200", width="200").grid(row=0, column=0, rowspan=1, columnspan=1)
label_1 = ttk.Label(frame_2, text="Text").grid(row=0, column=0, sticky="N, E")
root.mainloop()
```
Expected result : The label stays inside of it's frame which is nested inside the parent frame.
Actual results : It only stays inside the parent frame
|
2019/04/09
|
[
"https://Stackoverflow.com/questions/55594929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10695357/"
] |
The `.grid(...)` function returns `None`. Therefore, when you do
```
frame_1 = ttk.Frame(root, relief="sunken", height="400", width="400").grid(row=0, column=0, rowspan=1, columnspan=1)
```
you assign `None` to `frame_1`. And the same goes for `frame_2` and `label_1`.
Because `frame_1 == None`, calling `ttk.Frame(frame_1, ...)` is actually the same as `ttk.Frame(None, ...)`. Therefore, you're not passing a master, which defaults to having the root window as the master. Again, the same goes for the creation of `label_1`.
The fix is to split the creation and placement of the widgets to two separate lines:
```
from tkinter import *
from tkinter import ttk
root = Tk()
root.title("Tk test")
root.geometry("800x800")
frame_1 = ttk.Frame(root, relief="sunken", height="400", width="400")
frame_1.grid(row=0, column=0, rowspan=1, columnspan=1)
frame_2 = ttk.Frame(frame_1, relief="sunken", height="200", width="200")
frame_2.grid(row=0, column=0, rowspan=1, columnspan=1)
label_1 = ttk.Label(frame_2, text="Text")
label_1.grid(row=0, column=0, sticky="N, E")
root.mainloop()
```
|
5,377,732
|
After reading [an article on REST](http://www.ibm.com/developerworks/java/library/j-grails09168/index.html) ("Restful Grails"), I have gotten the impression that it is not possible to truly conform to a REST style in a service that demands a lot of parameters. Is this so? All the examples I have seen so far seem to imply that true REST style services are "parameterless". Using parameters would be RPC-ish and not truly RESTful.
To be more specific, say we have a service that returns graph data for stock prices, and this service needs to know the start date, end date, the currency, stock name, and whatever else might be applicable. In any case, at least 4-5 parameters are needed to retrieve the information needed.
I would imagine the URL to be something like this : /stocks/YAHOO?startDate="2008-09-01"&endDate=...
("YAHOO" is here a made-up stock name).
Would this really be REST or is this more RPC-like, what the author of the aforementioned article calls "GETful" (i.e. just low ceremony rpc)?
|
2011/03/21
|
[
"https://Stackoverflow.com/questions/5377732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200987/"
] |
You can see the querystring as a filter on the resource you are GETing. Here, your resource is the stock prices of yahoo. Doing a GET on that resource give you all the available data, or the most recents. The query string filter the prices you want. Content negociation allow you to change the representation, e.g. a png graph, a csv file, and so on. To add a price, simply POST a representation (e.g. CSV) to the same resource.
The "restfulness" is not realy in the URL itself, since URIs are obscures to client, but in the way you interact with resources themselves identified by their URI
|
9,687,883
|
I have a simple spring web application that only has spring mvc and spring roo setup. For some reason on all of my old app instances, when I uploaded this sample application, it always gets a "hanging/exceeded time" error in the logs. Even in the case of basic spring mvc setup. The logs I've seen are below. I am a bit confused since the same application was working previously until today, and now even the simple deployments to google app engine are returning a 500 error. Any help would be appreciated, but I just want to see if this is an issue people are seeing with spring mvc specifically or with the latest google app engin sdk?:
```
Uncaught exception from servlet
com.google.apphosting.runtime.HardDeadlineExceededError: This request (c22ac44effde64c8) started at 2012/03/13 15:39:52.285 UTC and was still executing at 2012/03/13 15:40:54.889 UTC.
at com.google.appengine.runtime.Request.process-c22ac44effde64c8(Request.java)
at java.util.zip.ZipFile.read(Native Method)
at java.util.zip.ZipFile.access$1200(ZipFile.java:57)
at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:476)
at java.util.zip.ZipFile$1.fill(ZipFile.java:259)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at sun.misc.Resource.getBytes(Resource.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:273)
at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
at org.springframework.web.servlet.view.tiles2.SpringTilesApplicationContextFactory.createApplicationContext(SpringTilesApplicationContextFactory.java:55)
```
|
2012/03/13
|
[
"https://Stackoverflow.com/questions/9687883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1266930/"
] |
If you don't want two view controllers, just create a separate delegate for each scroll view. Make it an `NSObject` which conforms to `UIScrollViewDelegate` and create it at the same time as the scroll view.
Seems to combine the results you seek: one view controller, but encapsulated scroll view code.
|
347,170
|
Unfortunately the printer being used to print envelopes uses a LPR port which can only be attached to an old machine running Windows 98. The rest of the systems in the network are running Windows 7 and need to have the ability to send print jobs to Windows 98 print server.
Are there any alternatives? Unfortunately Linux is not an option as there are no known drivers for the printer unless this does not matter.
If there any no alternatives, what should be secured on the network and the print server so that it is not susceptible to viruses, unauthorized access, etc?
The network does not run off a domain as they only have 5 computers.
|
2011/10/16
|
[
"https://superuser.com/questions/347170",
"https://superuser.com",
"https://superuser.com/users/79947/"
] |
Get a [USB-to-parallel](http://www.google.com/search?q=usb%20to%20parallel%20adapter) adapter, it's around $7. Connect this printer with this adapter to any computer running Windows. HP LaserJet drivers are available for modern Windows versions too.

This is what one vendor says about their adapter:
>
> Add a DB25 parallel port to your desktop or laptop PC through USB. The ICUSB1284D25 6 ft USB to DB25 parallel printer adapter cable turns an available USB port on a host PC into a DB25 female parallel port - allowing you to connect a DB25 printer to the computer as if the necessary parallel port was built-on. A cost-effective and reliable solution, the USB to DB25 adapter saves the expense of replacing a parallel printer for the sake of USB capability.
>
>
>
|
2,352,890
|
If $\dim E = n$ and the normal operator $A\colon E \rightarrow E$ has $n$ distinct eigenvalues, how do I show that $A$ is self adjoint?
|
2017/07/09
|
[
"https://math.stackexchange.com/questions/2352890",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/462216/"
] |
This is asking you to prove that a normal operator with $n$ distinct realeigenvalues over a vector space of dimension $n$ is self-adjoint.
$A = EDE^\*$ Therefore $A^\* = (EDE^\*)\* = (E^\*)^\*(D^\*)E^\*= ED^\*E^\*$. $\bar{D} = D^\*$ and as $D$ is real $\bar{D} = D$. So $A^\* = EDE^\* = A$.
|
25,980,263
|
Basically im a xlst newbie and have been tasked with working on some changes to a large xls file that handles the transformation of movies metadata for the german market.
The xls file looks something like this:
```
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:str="http://exslt.org/strings" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:redirect="http://xml.apache.org/xalan/redirect" extension-element-prefixes="redirect" xmlns:xalan="http://xml.apache.org/xslt" exclude-result-prefixes="xalan str">
<xsl:output method="xml" indent="yes" xalan:indent-amount="4"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/metadata">
<xsl:variable name="featureID" select="substring(mpm_product_id, 7, string-length(mpm_product_id))"/>
<xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />
<Metadata>
<some values...>
<xsl:for-each select="genres/genre">
<Genre>
<xsl:choose>
<!-- Mappings for German Genres -->
<xsl:when test="/metadata/base/territory_code='DE'">
<xsl:choose>
<xsl:when test=".= 'Action'">Action und Abenteuer</xsl:when>
<xsl:when test=".= 'Adventure'">Action und Abenteuer</xsl:when>
<xsl:when test=".= 'Animation'">Zeichentrick</xsl:when>
<xsl:when test=".= 'Anime'">Zeichentrick</xsl:when>
<xsl:when test=".= 'Bollywood'">Bollywood</xsl:when>
<xsl:when test=".= 'Classics'">Drama > Klassiker</xsl:when>
<xsl:when test=".= 'Comedy'">Komödie</xsl:when>
<xsl:when test=".= 'Concert Film'">Musik</xsl:when>
<xsl:when test=".= 'Crime'">Kriminalfilm > Drama</xsl:when>
<xsl:when test=".= 'Drama'">Drama</xsl:when>
<xsl:when test=".= 'Fantasy'">Drama > Sci-Fi und Fantasy</xsl:when>
<xsl:when test=".= 'Foreign'">International</xsl:when>
<xsl:when test=".= 'Horror'">Kriminalfilm > Horror</xsl:when>
<xsl:when test=".= 'Independent'">Independentfilm & Arthouse</xsl:when>
<xsl:when test=".= 'Japanese Cinema'">International > Japan</xsl:when>
<xsl:when test=".= 'Jidaigeki'">International > Japan</xsl:when>
<xsl:when test=".= 'Kids & Family'">Kinderfilm > Familie</xsl:when>
<xsl:when test=".= 'Music Documentary'">Musik > Dokumentation</xsl:when>
<xsl:when test=".= 'Music Feature Film'">Musik</xsl:when>
<xsl:when test=".= 'Musicals'">Musik > Musical</xsl:when>
<xsl:when test=".= 'Mystery'">Drama > Mystery</xsl:when>
<xsl:when test=".= 'Nonfiction - Documentary'">Dokumentation</xsl:when>
<xsl:when test=".= 'Regional Indian'">International > Indien & Pakistan</xsl:when>
<xsl:when test=".= 'Romance'">Drama > Romanze</xsl:when>
<xsl:when test=".= 'Science Fiction'">Science Fiction und Fantasy</xsl:when>
<xsl:when test=".= 'Short Films'">Independentfilm & Arthouse > Experimentalfilm</xsl:when>
<xsl:when test=".= 'Special Interest'">Hobby</xsl:when>
<xsl:when test=".= 'Sports'">Sport</xsl:when>
<xsl:when test=".= 'Thrillers'">Thriller</xsl:when>
<xsl:when test=".= 'Tokusatsu'">International > Japan</xsl:when>
<xsl:when test=".= 'Urban'">Drama > Alltag</xsl:when>
<xsl:when test=".= 'Westerns'">Western</xsl:when>
<xsl:otherwise>
<xsl:value-of select="." />
</xsl:otherwise>
</xsl:choose>
</xsl:when>
</xsl:choose>
</Genre>
</xsl:for-each>
<More values...>
</Metadata>
</xsl:template>
```
Issue being when the genres are transformed we end with duplicate values for example when the input contains the elements
```
<genres>
<genre>Comedy</genre>
<genre>Adventure</genre>
<genre>Action</genre>
</genres>
```
After transformation we have
```
<Genre>Komödie</Genre>
<Genre>Action und Abenteuer</Genre>
<Genre>Action und Abenteuer</Genre>
```
I have tried looking for some solution for this but i have not reached the solution and any help would be appreciated.
Edit for clarification: What i need is to eliminate the duplicate genre elements from the output. Those elements can be not adjacent to each other and we cant run the output through a second transformation as we cant modify the code of the service that handles this.
Thanks
|
2014/09/22
|
[
"https://Stackoverflow.com/questions/25980263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4051655/"
] |
Header:
```
#define LITERAL "Hello, world"
extern char const literal[sizeof LITERAL];
```
One source file:
```
char const literal[] = LITERAL;
```
There's still no guarantee that any particular compiler/linker only make one copy of the string literal (but it does guarantee the requirement that `&literal[0]` is the same in all units).
|
63,870,080
|
I was trying to use the top level in the project and saw that it was necessary to change the module from tscofnig to esnext or system, but for some reason my ts-node's error.
And I already put the type: module I tried to use the flag: --experimental-modules but the error still does not know how to solve.
package.json:
```
{
"name": "micro-hr",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"type": "module",
"scripts": {
"commit": "git-cz",
"build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored",
"start:dev": "ts-node-dev --experimental-modules --inspect --respawn --transpile-only --ignore-watch node_modules -r tsconfig-paths/register src/index.ts",
"start:debug": "node start --debug --watch",
"start:prod": "node dist/index.ts",
"test": "jest",
"lint": "eslint --fix",
"lint2": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./ormconfig.ts",
"migration:generate": "ts-node ./node_modules/typeorm/cli.js migration:generate -n"
},
"devDependencies": {
"@babel/cli": "^7.11.5",
"@babel/core": "^7.11.5",
"@babel/node": "^7.10.5",
"@babel/preset-env": "^7.11.5",
"@babel/preset-typescript": "^7.10.4",
"@commitlint/cli": "^9.1.2",
"@commitlint/config-conventional": "^9.1.2",
"@types/bcryptjs": "^2.4.2",
"@types/cookie-parser": "^1.4.2",
"@types/cors": "^2.8.7",
"@types/express": "^4.17.8",
"@types/helmet": "^0.0.48",
"@types/jest": "^26.0.13",
"@types/node": "^14.6.4",
"@types/pino": "^6.3.0",
"@types/pino-http": "^5.0.5",
"@types/supertest": "^2.0.10",
"@typescript-eslint/eslint-plugin": "^4.0.1",
"@typescript-eslint/parser": "^4.0.1",
"babel-plugin-module-resolver": "^4.0.0",
"commitizen": "^4.2.1",
"cz-conventional-changelog": "^3.3.0",
"eslint": "^7.8.1",
"eslint-config-airbnb-base": "^14.2.0",
"eslint-config-prettier": "^6.11.0",
"eslint-config-standard": "^14.1.1",
"eslint-import-resolver-typescript": "^2.3.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"husky": "^4.2.5",
"jest": "^26.4.2",
"pino-pretty": "^4.2.0",
"prettier": "^2.1.1",
"supertest": "^4.0.2",
"ts-jest": "^26.3.0",
"ts-node": "^9.0.0",
"ts-node-dev": "^1.0.0-pre.62",
"tsconfig-paths": "^3.9.0",
"tscpaths": "^0.0.9",
"typescript": "^4.0.2"
},
"dependencies": {
"amqplib": "^0.6.0",
"assert": "^2.0.0",
"bcryptjs": "^2.4.3",
"class-transformer": "^0.3.1",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"envalid": "^6.0.2",
"express": "^4.17.1",
"extendable-error": "^0.1.7",
"helmet": "^4.1.0",
"nabbitmq": "^1.0.0",
"pg": "^8.3.3",
"pino": "^6.5.1",
"pino-http": "^5.2.0",
"reflect-metadata": "^0.1.13",
"spt-rabbit-helpers": "^1.0.6",
"tsyringe": "^4.3.0",
"typeorm": "^0.2.25"
},
"config": {
"commitizen": {
"path": "cz-conventional-changelog"
}
}
}
```
tsconfig:
```
{
"compilerOptions": {
"target": "es2020",
"module": "esnext",
"allowJs": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"strictPropertyInitialization": false,
"moduleResolution": "node",
"baseUrl": "./src",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"forceConsistentCasingInFileNames": true,
"noImplicitAny": true,
"typeRoots": ["node_modules/@types", "@types"]
},
"include": ["src", "__tests__"],
"exclude": ["node_modules"]
}
```
main:
```
import 'reflect-metadata';
import express from 'express';
import { RabbitServer } from 'spt-rabbit-helpers';
import validateEnv from 'utils/validateEnvs';
import {
RabbitMqConnectionFactory,
ConsumerFactory,
PublisherFactory,
RabbitMqConnection,
} from 'nabbitmq';
import { container, singleton } from 'tsyringe';
const factory = new RabbitMqConnectionFactory();
factory.setUri('amqp://localhost:5672');
const ConsumerConnection = await factory.newConnection();
const PublisherConnection = await factory.newConnection();
container.registerInstance('Consumer_Connection', ConsumerConnection);
container.registerInstance('Publisher_Connection', PublisherConnection);
```
|
2020/09/13
|
[
"https://Stackoverflow.com/questions/63870080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13102905/"
] |
To run ts-node (or plain node for that matter) you need to use `"module": "commonjs", "target": "ES2017"`, otherwise the `import`/`export` statements are illegally placed in an IIFE.
So I would suggest using another file called *node.tsconfig.json* with the following contents:
```json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"target": "ES2017" // For NodeJS 8 compat, see https://www.typescriptlang.org/tsconfig#target for more info
}
}
```
And then run ts-node with `--project ./node.tsconfig.json`
|
115,602
|
Context
=======
I'm working on very complex enterprise solution. We have this table that shows list of let's call them contracts. Every contract (row) can contain one or more customers (and one or more products).
Problem
=======
I need to think of these use cases:
1. People want to copy & paste customer IDs.
2. People should be able to remove all the customers at once.
3. People should still have an overview what customers were selected.
4. People should be able to browse customers and pick those they want to.
(Since we are in the able the solution needs to be compact)
My proposal
===========
[](https://i.stack.imgur.com/HLqCS.png)
- Clicking on the "CD-0005" would trigger the browse window
- **Missing** copy & paste functionality
[](https://i.stack.imgur.com/vctwb.png)
- Looks super ugly
- Hard to provide overview on all the items (having tooltip on input hover is somehow strange)
**What do you think? How can this problem be solved?**
|
2018/02/06
|
[
"https://ux.stackexchange.com/questions/115602",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/108493/"
] |
1. You can add a copy link in front of each customer ID on hover.
[](https://i.stack.imgur.com/LMt7G.jpg)
2. Add filters on table headers
3. Highlight the selected rows or make customer ID a badge when selected
4. Making customer ID badge would make it easier to identify the ones needed and switch between states.
I loved how "Clear Move" handle the tables. You can use it as inspiration.
[](https://i.stack.imgur.com/zmTlD.jpg)
|
6,887,091
|
I am a new user of git and can't figure out how to get around this. I have had some experience with SVN and am going by SVN behavior.
Any time I pull files from remote repository, and the file I have modified are also modified remotely, it needs merging. I can understand merge conflicts for complex changes, but I am seeing merge conflicts for very small (e.g. one line change in different functions) changes. As far as I remember, SVN could merge most of it automatically and will put the file in conflicted state only if automatic merge failed.
For git, it seems to be happening every time and forcing to open the git merge tool. Is there any way to automatically merge the files? Am I missing some setting that is basically putting the repository in conflicted set by default?
|
2011/07/31
|
[
"https://Stackoverflow.com/questions/6887091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/871199/"
] |
A common cause of this is differing line endings. Are you sharing a repo with someone else using a different OS? SVN does some munging of line endings. Git, on the other hand, stores files byte-for-byte exactly as they are by default. That means that when a Windows user saves a file with \r\n line endings and a Linux user saves the file with \n line feeds, every line appears changed, and if any other changes are in play, it causes conflicts everywhere. To change the way line endings are handled, use the configuration setting "core.autocrlf". In a repo where different OS's are in play, I recommend setting it to "input" for Linux users and "true" for Windows users:
```
git config [--global] core.autocrlf input
```
or
```
git config [--global] core.autocrlf true
```
Actually, I'd say just use these settings globally all the time. They'll save you some heartache. Read more about core.autocrlf on the [git-config man page](https://git-scm.com/docs/git-config), and note that if you're suffering from this problem and you turn autocrlf on with an existing repository, you may see some startling behavior, but it can be explained.
|
694,274
|
I am really confused with expressions under Lorentz transformation. I will try to showcase my confusion via an easy and very popular example:
If we have two inertial systems $S$ and $S'$, and $S'$ is moving relative to S with velocity $v$.
A point charge is in the origin of $S'$. Initially at $t=t'=0$ their origins are at the same point.
In $S'$:
We only have electric field: $\vec E'= \frac{1}{4\pi \epsilon\_0}\frac{\vec r'}{|\vec r'|^3}$
There is no magnetic field: $\vec B'=0$
We want to know the electric field and magnetic field at point $P=(0,b,0)$.
This point is in $S$ system as $\vec P=(0,b,0)$.
This point is in $S'$ system as $\vec P'=(x',b,0)$. Performing Lorentz transformation of the kind $x'=\gamma(x -vt)$. We know that $x=0$, therefore $x'=-v\gamma t$. Then $\vec P'=(-v\gamma t,b,0)$. I consider that these are the coordinates of point $\vec P'$ observed by someone in the system $S'$, but via the coordinates of the same point $\vec P$ observed by someone in the rest frame.
But we can also express the coordinates of $\vec P'=(-vt',b,0)$. Here the coordinates are directly related to the frame at motion, and no Lorentz transformation takes place.
Anyway, we perform Lorentz transformations etc and for the x component of the Electric field we have:
$$E\_x=E\_x'=\frac{1}{4\pi \epsilon\_0} \frac{-vt'}{(b^2 + v^2t'^2)^{\frac 32 }}=\frac{1}{4\pi \epsilon\_0} \frac{-v\gamma t}{(b^2 + \gamma^2v^2t^2)^{\frac 32 }}$$
Both of the above expressions are related to $E\_x'$.
When the observer is in the rest frame of the particle and no LT takes place, the expression for the electric field at $\vec P'$ is:
$$E\_x'=\frac{1}{4\pi \epsilon\_0} \frac{-vt'}{(b^2 + v^2t'^2)^{\frac 32 }}$$
Now if we want to express the x-component of the electric field, but by utilizing the coordinates from the rest frame, we would get:
$$E\_x'=\frac{1}{4\pi \epsilon\_0} \frac{-v\gamma t}{(b^2 + \gamma^2v^2t^2)^{\frac 32 }}$$
But if I want to know the expression of the x-component, described by an observer at the rest frame $S$, while taking into consideration the coordinates from the frame at motion $S'$, we need to perform the following LT: $x=\gamma(x'+vt)$ and because $x'=-vt$, I would get $x=0$, which is correct because in the rest frame the point where we want to find the electric field is $\vec P(0,b,0)$ which has a $0$ for the x component. As a result $E\_x=0$. But this is not possible since $E\_x=E\_x'$ for this case.
So what exactly I am not understanding here?
|
2022/02/13
|
[
"https://physics.stackexchange.com/questions/694274",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/275029/"
] |
The radius of the first maximum is approximately $$\frac{\lambda l}{d}\sim\frac{0.5\cdot 10^{-6}m\cdot0.3 m}{0.2\cdot 10^{-3}m}\sim 1mm.$$ As "The 'cloud' is about 8cm in radius", you are probably looking for the rings in wrong places. It is possible that even minimums of the "ring" diffraction picture look very bright (except for narrow areas).
|
6,666
|
My wife doesn't work anymore and she has a 401(k) of about $80,000 from an old job. I have been kicking around the idea of taking that money out or rolling into an IRA so that I can have better access to this money. Given the interest rates I want to purchase a new home and would like to leverage this money as a down payment if it makes sense. Thanks for the help.
|
2011/03/04
|
[
"https://money.stackexchange.com/questions/6666",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/-1/"
] |
Unless that 401K has very low [expense ratios](http://www.investopedia.com/terms/e/expenseratio.asp) on its funds, you should roll it into an IRA and choose funds with low expense ratios.
After rolling it over you should *not* take the 10% penalty and use it to purchase a home. Unless you use that home as an income property, it is unlikely to provide you more than a 1% inflation-adjusted rate of return given historical data. The S&P 500 is about 4% adjusted for inflation. And that money currently in your 401(k) is for your retirement - your future. Don't borrow against your future. Let compound interest do its work on that money.
The value of a house is in the rent you aren't paying to live somewhere and there are a lot of costs to consider. That doesn't mean don't buy. It just means buy wisely.
If you are currently maxing out your 401(k), you may consider cutting back to save for your down payment. Other than that I wouldn't touch retirement money unless it was a dire financial emergency.
|
13,629,483
|
I have a list of list, such as
```
T =[[0.10113], [0.56325], [0.02563], [0.09602], [0.06406], [0.04807]]
```
I would like to find the total sum of these numbers.
I am new to python programming, when I try a simple `int(T[1])` conversion, I get error
```
TypeError: int() argument must be a string or a number, not 'list'
```
I appreciate any input.
|
2012/11/29
|
[
"https://Stackoverflow.com/questions/13629483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1863596/"
] |
easy:
```
sum(x[0] for x in T)
```
You're done :)
---
Of course, you could use
```
import itertools
sum(itertools.chain.from_iterable(T))
```
too. This would work if your sublists had more than 1 element each.
|
42,569
|
From random Internet sites, we can see many examples of the grammar structures:
>
> [verb] + 在了
>
>
>
>
> 手机**忘在了**出租车上。
>
> 我**站在了**舞台上。
>
> 因为人不在,快递员就**放在了**门口。
>
> 小男孩被父亲故意**丢在了**超市。
>
> 闺蜜和男友**睡在了**一起。
>
> (Google the quotes surrounded by quotation marks to see the source(s).)
>
>
>
I think I get the gist from these examples. It looks like adding 在 modifies a verb, e.g., 忘 = "to forget" turns into 忘在 = "to forget at". The 了 is the [completion 了](https://resources.allsetlearning.com/chinese/grammar/Expressing_completion_with_%22le%22), added after the modified verb 忘在了 (so we don't write 忘了在 [or do we?]). 在了 doesn't seem to be used in the same way without a preceding verb (but we can say 不在了 or 没在了 to mean "not here", sometimes as a euphemism for being dead).
However, there may be a better way to understand this. I'm wondering if there is a more rigorous treatment available. I didn't find a reference from Google, not at the Chinese Grammar Wiki.
**Question**: How does one understand the [verb] + 在了 grammar structure?
|
2021/01/10
|
[
"https://chinese.stackexchange.com/questions/42569",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/8099/"
] |
在了 is very common, even colloquially, but it'd be better to see it as separate 在 and 了.
The usage of 了 and its position in a sentence is complex. In the example sentence
>
> 手机忘在了出租车上,
>
>
>
1. 忘 here can be understood as a [labile verb](https://en.wikipedia.org/wiki/Labile_verb) (perhaps?), meaning "be forgotten".
2. 在 is a **结果补语 (complement of result)**. Accroding to 刘月华(Liu Yuehua) et al.'s 《实用现代汉语语法》(*Practical Modern Chinese Grammar*, I'll refer to it as Gr from now on), the function of 在 is to "表示通过动作使人或事物处于某个处所,后边一定要有处所宾语" (convey the idea that something or someone is placed in some position via an action, and must be followed by an object of location).
3. 出租车上 is the **处所宾语 (object of location)** of 在. The object 出租车, or taxi, usually can't convey the idea of location on its own, but can do so when compounded with the adverb of position 上.
4. 了 is a **动态助词 (aspect particle)**. According to Gr, it's a bit complex; for a verb like 忘 in the sense of "to leave something at some place", 了 means the action has happened and has ended.
I think your problem here can boil down to *where should the article 了 be in this sentence?*
According to Gr, "如果谓语动词后有结果补语,“了”位于结果补语后:动词+结果补语+“了”+宾语" (**if there is a complement of result after the verb, then 了 is placed after the complement of result: verb + complement of result + 了 particle + object**). So,
手机(Subject)忘(Verb)在(Complement)了(Particle)出租车上(Object)。
This rule can explain the first four sentences you provided. I think the fifth one is the same, but I'm unsure for now.
Also, please note that in every sentence you provided, 了 can be placed at the very end. This kind of 了 is called a 语气助词 (Modal particle), and the meanings of some sentences will change when you move 了 to the end, and some will not change very much. However, this is a much more complex grammar mischief of Chinese and I don't consider myself capable of talking about it.
Hope this helps.
|
18,667,032
|
I found this answer here regarding graphic design:
<https://graphicdesign.stackexchange.com/questions/265/font-face-loaded-on-windows-look-really-bad-which-fonts-are-you-using-that-rend>
This is exactly what my fonts are doing, but I'm trying to find out if there's a way to prevent this using html or css or anything web-based.
I'm using "platin" as my font. Do I just need to find a different font?
Any other thoughts on the topic?
|
2013/09/06
|
[
"https://Stackoverflow.com/questions/18667032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2666084/"
] |
An answer from [this similar question](https://stackoverflow.com/questions/11225654/xcode-how-to-connect-xib-to-viewcontroller-class/18003928#18003928):
"Here's a more step-by-step way to associate your new UIViewController and .xib.
Select File's Owner under Placeholders on the left pane of IB. In the Property Inspector(right pane of IB), select the third tab and edit "Class" under "Custom Class" to be the name of your new UIViewController subclass.
Then ctrl-click or right-click on File's Owner in the left pane and draw a line to your top level View in the Objects portion of the left pane. Select the 'view' outlet and you're done.
You should now be able to set up other outlets and actions. You're ready to instantiate your view controller in code and use initWithNibName and your nib name to load it."
|
21,211,502
|
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates.
Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below.
```
public class Test {
public static void main (String[] args) {
int sum = 0;
for (int k = 1; k < 10; k += 2)
{
sum += k;
System.out.print(sum + " ");
}
}
}
```
The output the program puts out is 1 4 9 16 25
Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3?
It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about.
My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around.
Overall my question is, how is sum equal to 1 when k is actually equal to 3.
|
2014/01/19
|
[
"https://Stackoverflow.com/questions/21211502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2966385/"
] |
The sections of the for loop are run at different times.
1. The first section is run once at the start to initialize the variables.
2. The second is run each time around the loop at the START of the loop to say whether to exit or not.
3. The final section is run each time around the loop at the END of the loop.
All sections are optional and can just be left blank if you want.
You can also depict a for loop as a while loop:
```
for (A;B;C) {
D;
}
```
is the same as:
```
A;
while (B) {
D;
C;
}
```
|
39,903,986
|
I have a categorical index of wind directions in a pandas dataframe.
```
print (self.Groups.index)
CategoricalIndex([22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5],
categories=[22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5],
ordered=True, name='Dir', dtype='category')
```
I am trying to use this index to plot a wind rose eg.
```
ax.bar(self.Groups.index,self.Groups['wind_speed'])
```
but I need to convert the index to radians for it to properly display on a polar plot.
Is there a way to convert the the Categorical index to a float?
|
2016/10/06
|
[
"https://Stackoverflow.com/questions/39903986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5683778/"
] |
Use `astype` to perform the conversion:
```
self.Groups.index = self.Groups.index.astype('float')
```
|
26,337,469
|
So that is the question:
how to revert to specific commit in history while saving current work to another branch?
I've tried checking out to another branch and then `git reset --hard commit_hash` but the other branch was reverted too and i don't want this.
|
2014/10/13
|
[
"https://Stackoverflow.com/questions/26337469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1491475/"
] |
That seems to happen because you are using `mysqldump` 5.5 or prior with a MySQL 5.6 database. The `SET OPTION` syntax was removed (see discussion in [this bug report](http://bugs.mysql.com/bug.php?id=66765)), causing this tool to stop working.
You will need to update your version of `mysqldump`. More info about it in [this other bug report](http://bugs.mysql.com/bug.php?id=67507).
|
52,773,492
|
I have the following data set:
```
column1
HL111
PG3939HL11
HL339PG
RC--HL--PG
```
I am attempting to write a function that does the following:
1. Loop through each row of column1
2. Pull only the alphabet and put into an array
3. If the array has "HL" in it, remove it from the array UNLESS HL is the only word in the array.
4. Take the first word in the array and output results.
So for the above example, my array (step2) would look like this:
```
[HL]
[PG,HL]
[HL,PG]
[RC,HL,PG]
```
and my desired final output (step4) would look like this:
```
desired_column
HL
PG
PG
RC
```
I have the code for step 2, and it seems to work fine
```
df['array_column'] = (df.column1.str.extractall('([A-Z]+)')
.unstack()
.values.tolist())
```
But I don't know how to get from here to my final output (step4).
|
2018/10/12
|
[
"https://Stackoverflow.com/questions/52773492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6365890/"
] |
You may achieve what you need by replacing all non-letters first, then extracting pairs of letters and then applying some custom logic to extract the necessary value from the array:
```
>>> df['array_column'].str.replace('[^A-Z]+', '').str.findall('([A-Z]{2})').apply(lambda d: [''] if len(d) == 0 else d).apply(lambda x: 'HL' if len(x) == 1 and x[0] == 'HL' else [m for m in x if m != 'HL'][0])
0 HL
1 PG
2 PG
3 RC
Name: array_column, dtype: object
>>>
```
**Details**
* `.replace('[^A-Z]+', '')` - remove all chars other the uppercase letters
* `.str.findall('([A-Z]{2})')` - extract pairs of letters
* `.apply(lambda d: [''] if len(d) == 0 else d)` will add an empty item if there is no regex match in the previous step
* `.apply(lambda x: 'HL' if len(x) == 1 and x[0] == 'HL' else [m for m in x if m != 'HL'][0])` - custom logic: if the list length is 1 and it is equal to `HL`, keep it, else remove all `HL` and get the first element
|
40,810,736
|
I'm trying to get different audio files to play depending on what "region" of my `Processing` sketch is clicked. I'm having issues with the `soundFile` to get even just one file playing when clicking the first region.
I have imported the `sound library` but I must have a syntax or directory error. This is the message I keep getting:
```
Error: Soundfile doesn't exist. Pleae check path
Could not run the sketch (Target VM failed to initialize).
For more information, read revisions.txt and Help → Troubleshooting.
```
Firstly, is it possible to load 5 different sound files as conditions of `if` statements?
Code here:
```
PImage img; // Declare variable "a" of type PImage
import processing.sound.*;
SoundFile file;
void setup() {
size(1475, 995);
// The image file must be in the data folder of the current sketch
// to load successfully
img = loadImage("PaceTaker.jpg"); // Load the image into the program
}
void draw() {
// Displays the image at its actual size at point (0,0)
image(img, 0, 0);
}
void mousePressed() {
if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) {
// Load a soundfile from the /data folder of the sketch and play it back
file = new SoundFile(this, "Heartbeatreg.mp3");
file.play();
stroke(0);
}
else if (mouseX>410 && mouseX<584 && mouseY>696 && mouseY<714) {
println("yikes2");
stroke(0);
}
else if (mouseX>659 && mouseX<837 && mouseY>696 && mouseY<714) {
println("yikes3");
stroke(0);
}
else if (mouseX>928 && mouseX<1065 && mouseY>696 && mouseY<714) {
println("yikes4");
stroke(0);
}
else if (mouseX>1123 && mouseX<1397 && mouseY>696 && mouseY<714) {
println("yikes5");
stroke(0);
}
else {
println("hello");
}
}
```
|
2016/11/25
|
[
"https://Stackoverflow.com/questions/40810736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7186847/"
] |
I have had this issue a few times now. I'm unsure what causes it, but i've found that you can fix it by selecting `"Restore to defaults"` in the `Toggle device toolbar` menu.
[](https://i.stack.imgur.com/WSPye.png)
|
10,875,055
|
Do I put it in each model, right before, `multisearchable :against => [ ... ]` or should this be in a separate file? Thanks.
|
2012/06/04
|
[
"https://Stackoverflow.com/questions/10875055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156125/"
] |
I had similar questions about how to implement PgSearch.multisearch\_options.
This is what worked for me. Hopefully it will help someone else out.
I created the Initializer `config/initializers/pg_search.rb`
```
PgSearch.multisearch_options = {
:using => {
:tsearch => {
:dictionary => "english"
}
}
}
```
In my `application.rb` file I uncommented this line: `config.active_record.schema_format = :sql`
Then created a migration called `rails g migration add_trigram_extension` adding the below to the migration file
```
def up
execute "create extension pg_trgm"
end
def down
execute "drop extension pg_trgm"
end
```
Then run `bundle exec rake db:migrate`
Restart the server
Now full text search with Stemming is working.
p.s. this worked using (PostgreSQL) 9.1.4
|
71,616,876
|
I am trying to do this that strips "['" or "']" in the string.
For Example, if we have ['Customer Name'] it should be "Customer Name"
```
select regexp_replace("['Customers NY']","\\['|\\']","") as customername;
```
>
> I am getting this error--
> SQL compilation error: error line 1 at position 22 invalid identifier "['Customers NY']"
>
>
>
|
2022/03/25
|
[
"https://Stackoverflow.com/questions/71616876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18408875/"
] |
I managed to make it using *positions*. I assume this would give a better understanding on how to make these kind of shapes.
```css
#cont {
background: -webkit-linear-gradient(green -50%, #fff);
width: 300px;
height: 300px;
border-radius: 100%;
padding: 10px;
position: relative;
top: 0;
left: 0;
}
#box {
background: #fff;
width: 320px;
height: 320px;
border-radius: 100%;
position: absolute;
top: 2%;
left: 0.1%;
}
```
```html
<div id="cont">
<div id="box"></div>
<div id="box2"></div>
</div>
```
|
19,786,196
|
First of all, sorry for bad english.
Well, I need to change the color property of all parragraphs, using javascript, here's my html&JS code:
```
<body>
<p>Parragraph one</p>
<p>Parragraph two</p>
<button onclick="CE()">change style</button>
</body>
for (var j=0;j<document.styleSheets[0].cssRules.length;j++) {
if(document.styleSheets[0].cssRules[j].selectorText='p')
document.styleSheets[0].cssRules[j].style.color="#FF0000";
}
```
And this is my CSS code:
```
p{
color: green;
font-size: 20px;
font-weight: bold;
font-family: arial;
}
```
I tried to change it with this too: `document.styleSheets[0].cssRules[0].style.backgroundColor="#FF0000"`;
(trying to change the background color, just to see if it works, but only works on Mozilla Firefox)
|
2013/11/05
|
[
"https://Stackoverflow.com/questions/19786196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2382353/"
] |
here you go [http://jsfiddle.net/6KfHy/1/]
```
var baseWidth = 90;
var stepWidth = 4;
var baseHeight = 20;
var growHeightPerStep = 1;
function changeHeight() {
var windowW = $(window).width();
var diffWidth = windowW - baseWidth;
var diffHeight = parseInt(diffWidth / 4, 10);
$('.grow').css('height', baseHeight + diffHeight + 'px');
}
changeHeight();
$(window).resize(function() {
changeHeight();
});
```
|
38,291
|

Why does the object not go inward, into the circle if the acceleration is inward? I think its because the velocity to outward? So they sort of cancel each other out? But if the speed is kept constant and the acceleration is inward, won't the object eventially move inward?
Also, what keeps the direction of acceleration always point inward?
|
2012/09/25
|
[
"https://physics.stackexchange.com/questions/38291",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/12035/"
] |
I suspect Luboš's answer may be a bit complex for you so I'll attempt a simpler explanation (if I'm wrong just ignore this answer).
When you say "I think its because the velocity to outward" you're getting close. To show what's going on I've zoomed in on the diagram you posted in your question.

Let's start at the moment where the velocity of the object is $u$. The thing you need to remember is that *velocity* is a vector so it has both magnitude and direction. Acceleration may be a change in the magnitude or a change in direction or both. In the case of circular motion it's the direction of the velocity that is changing not it's magnitude.
To see this look at the vector $v$, which is the velocity of the particle after some short time. So the velocity has changed from $u$ to $v$. To get the size of the change we need to find what vector has to be added to $u$ to give $v$. At the top of the diagram I've put the two vectors $u$ and $v$ with their starting point together, so you can see that the vector needed to change $u$ to $v$ is the small vector $a$, and you can see it points downwards. If I move $a$ to the starting point of $u$ on the circle you can see that $a$ points towards the centre of the circle.
The vector $a$ is of course the acceleration (well it's the acceleration times the short time interval between $u$ and $v$) and that's why the acceleration points towards the centre of the circle.
If you didn't have any acceleration the object would move in a straight line so it would just move away at a tangent to the circle. The effect of the acceleration $a$ is to bend the trajectory of the object so it stays on the circle.
Finally, you ask "what keeps the direction of acceleration always point inward". You've mixed up cause and effect. It isn't that there's some magical property of circular motion that causes the acceleration to be central. It's that if in some system the acceleration is always central the object will move in a circle (or strictly speaking in a conic section, but let's not complicate matters).
For example suppose I tie a stone to a string and start whirling it round my head. The force causing the acceleration is provided by the string, and obviously the string always runs from the stone to the centre because my hand is at the centre. It's because the force caused by the string is always central that the stone moves in a circle.
|
10,943
|
I'm doing a total kitchen renovation with solid hardwood flooring. Do I go hardwood all the way under the cabinets to the wall or stop just past the toe kick and finish the rest with ply of the same thickness?
|
2011/12/27
|
[
"https://diy.stackexchange.com/questions/10943",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/4711/"
] |
You can do either, but in my opinion it's better to use plywood as the base because:
* it's a lot cheaper than hardwood flooring.
* if you need to replace the hardwood flooring at some point in the future, it will be a lot easier to remove just the hardwoods: if you run planks under the cabinets, you'll have to cut them off where they go under the toe kick which will be a lot trickier with the cabinets in place.
|
29,145,564
|
I have created two classes, StepsCell and WeightCell
```
import UIKit
class StepsCell {
let name = "Steps"
let count = 2000
}
import UIKit
class WeightCell {
let name = "Weight"
let kiloWeight = 90
}
```
In my VC I attempt to create an array, cellArray, to hold the objects.
```
import UIKit
class TableViewController: UIViewController {
var stepsCell = StepsCell()
var weightCell = WeightCell()
override func viewDidLoad() {
super.viewDidLoad()
var cellArray = [stepsCell, weightCell]
println(StepsCell().name)
println(stepsCell.name)
println(cellArray[0].name)
}
```
but when I index into the array :
```
println(cellArray[0].name)
```
I get nil.. Why? How can I create an array that "holds" these classes and that I can index into to get the various variables (and functions to be added later). I thought this would be a super simple thing but I can't find any answers for this. Any ideas?
|
2015/03/19
|
[
"https://Stackoverflow.com/questions/29145564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4051036/"
] |
The problem is that you create an array with mixed types. Because of this, the compiler doesn't know the type of the object returned by `cellArray[0]`. It infers that this object must be of type `AnyObject`. Apparently this has a property named `name`, which returns nil.
The solution is to either cast it `println((cellArray[0] as StepsCell).name)`, or use a common protocol or superclass:
```
protocol Nameable {
var name: String { get }
}
class StepsCell: Nameable {
let name = "Steps"
let count = 2000
}
class WeightCell: Nameable {
let name = "Weight"
let kiloWeight = 90
}
var stepsCell = StepsCell()
var weightCell = WeightCell()
var cellArray: [Nameable] = [stepsCell, weightCell]
println(StepsCell().name)
println(stepsCell.name)
println(cellArray[0].name)
```
|
21,517,685
|
I'm making an application to scan multiple page pdf files. I have a `PDFView` and a `PDFThumbnailView` that are linked. The first time a scan is completed, I create a new `PDFDocument` and set it to `PDFView`. Then whenever another scan is completed I add a `PDFPage` to `[pdfView document]`.
Now the problem is whenever a page is added, neither the `PDFView` or `PDFThumbnailView` update to show the new document with the extra page. That is until I zoom in or out, then they both update to show the document with the new page.
The temporary solution I have now (zoom in and then autoscale) is certainly not the best one. Take for example when you have already zoomed in on the document, and you scan a new page, the view will then autoscale. I tried `[pdfView setNeedsDisplay:YES]` before but that doesn't seem to work.
This is the method where the scan arrives as `NSData`:
```
- (void)scannerDevice:(ICScannerDevice *)scanner didScanToURL:(NSURL *)url data:(NSData *)data {
//Hide the progress bar
[progressIndicator stopAnimation:nil];
//Create a pdf page from the data
NSImage *image = [[NSImage alloc] initWithData:data];
PDFPage *page = [[PDFPage alloc] initWithImage:image];
//If the pdf view has a document
if ([pdfView document]) {
//Set the page number and add it to the document
[page setValue:[NSString stringWithFormat:@"%d", [[pdfView document] pageCount] + 1] forKey:@"label"];
[[pdfView document] insertPage:page atIndex:[[pdfView document] pageCount]];
} else {
//Create a new document and add the page
[page setValue:@"1" forKey:@"label"];
PDFDocument *document = [[PDFDocument alloc] init];
[document insertPage:page atIndex:0];
[pdfView setDocument:document];
}
//Force a redraw for the pdf view so the pages are shown properly
[pdfView zoomIn:self];
[pdfView setAutoScales:YES];
}
```
Does anyone know of a way where I can add a `PDFPage` and have the `PDFView` update without messing with the zoom state of the `PDFView`?
|
2014/02/02
|
[
"https://Stackoverflow.com/questions/21517685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1640293/"
] |
You need to manually call:
```
- (void)layoutDocumentView
```
I imagine the reason that this is not called manually is to allow coalescing of multiple changes into one update.
This is documented:
>
> The PDFView actually contains several subviews, such as the document
> view (where the PDF is actually drawn) and a “matte view” (which may
> appear as a gray area around the PDF content, depending on the
> scaling). Changes to the PDF content may require changes to these
> inner views, so you must call this method explicitly if you use PDF
> Kit utility classes to add or remove a page, rotate a page, or perform
> other operations affecting visible layout.
>
>
> This method is called automatically from PDFView methods that affect
> the visible layout (such as setDocument:, setDisplayBox: or zoomIn:).
>
>
>
|
46,435,623
|
Hi the custom policy gets called with the client id of the B2C app
<https://login.microsoftonline.com/TENANT/oauth2/v2.0/authorize?p=B2C_1A_POLICY&client_id=THE-CLIENT-ID-I-WANT>
How can I access this in the policy, i thought this would be hard coded to the client\_id claim but I dont think it is
Its only returned as default as the aud claim but again I dont see that in the custom policy
Thanks
|
2017/09/26
|
[
"https://Stackoverflow.com/questions/46435623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1197563/"
] |
Ok its a bit of a work around but I tried with a standard UserJourneyContextProvider technical profile and this didnt work
so to get the client id as a claim I did the following
Create an orchestration step
```
<OrchestrationStep Order="2" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange
Id="ClientIdFromOIDC-JC"
TechnicalProfileReferenceId="Get-ClientID-FromOIDC"/>
</ClaimsExchanges>
</OrchestrationStep>
```
Then create a RESTFUL technical profile which will call a Function App passing the OIDC with the {OIDC:ClientID}
```
<TechnicalProfile Id="Get-ClientID-FromOIDC">
<DisplayName>Get-ClientID-FromOIDC</DisplayName>
<Protocol Name="Proprietary"
Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="AuthenticationType">None</Item>
<Item Key="ServiceUrl">--FUNCTION APP URL--</Item>
<Item Key="SendClaimsIn">QueryString</Item>
</Metadata>
<InputClaims>
<InputClaim
ClaimTypeReferenceId="client_id"
PartnerClaimType="client_id"
DefaultValue="{OIDC:ClientId}" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="client_id" />
</OutputClaims>
</TechnicalProfile>
```
And then finally create a function app which accepts the client id from the querystring and returns it with the correct format for B2C to identify
using System.Net;
using System.Net.Http.Formatting;
```
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req,
TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
// parse query parameter
string client_id = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "client_id", true) == 0)
.Value;
return req.CreateResponse<ResponseContent>(
HttpStatusCode.OK, new ResponseContent
{
version = "1.0.0",
status = (int) HttpStatusCode.OK,
client_id = client_id
},
new JsonMediaTypeFormatter(), "application/json");
}
class ResponseContent {
public string version;
public int status;
public string client_id;
}
```
You will now get the B2C application client\_id as a claim in the claim bag so you can do what you want with it now
|
71,096,453
|
I want to convert a certain list of strings into separated lists inside another list, which will contain strings and floats.
I've tried to use the `append` method to get the result, but I'm having trouble on making the nested list. Is there a way to get only the last line of my `output` as the result? This is my code:
```
def func(L):
n = []
lists = [i.split(',') for i in L]
for xlist in lists:
xlist[1:] = [float(item) for item in xlist[1:]]
n.append(xlist)
print(n)
if __name__ == '__main__':
func(['PersonX, 10, 92, 70', 'PersonY, 60, 70', 'PersonZ, 98.5, 1100, 95.5, 38'])
OUTPUT: [['PersonX', 10.0, 92.0, 70.0]]
[['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0]]
[['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]]
EXPECTED OUTPUT: [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]]
```
Thanks in advance for any help.
|
2022/02/12
|
[
"https://Stackoverflow.com/questions/71096453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I actually recently made a little helper function for exactly this. The idea
is to use `group_modify()` to take the group data, and
`bind_rows()` the summary statistics calculated with `summarise()`.
This is what it looks like in code:
```r
add_summary_rows <- function(.data, ...) {
group_modify(.data, function(x, y) bind_rows(x, summarise(x, ...)))
}
```
And here’s how that would work with your data:
```r
library(dplyr, warn.conflicts = FALSE)
df <- data.frame(
test_id = c(1, 1, 1, 1, 1, 1, 1, 1),
test_nr = c(1, 1, 1, 1, 2, 2, 2, 2),
region = c("A", "B", "C", "D", "A", "B", "C", "D"),
test_value = c(3, 1, 1, 2, 4, 2, 4, 1)
)
df %>%
group_by(test_id, test_nr) %>%
add_summary_rows(
region = "MEAN",
test_value = mean(test_value)
)
#> # A tibble: 10 x 4
#> # Groups: test_id, test_nr [2]
#> test_id test_nr region test_value
#> <dbl> <dbl> <chr> <dbl>
#> 1 1 1 A 3
#> 2 1 1 B 1
#> 3 1 1 C 1
#> 4 1 1 D 2
#> 5 1 1 MEAN 1.75
#> 6 1 2 A 4
#> 7 1 2 B 2
#> 8 1 2 C 4
#> 9 1 2 D 1
#> 10 1 2 MEAN 2.75
```
|
312,921
|
My PC (CentOS)has one ethernet card 1, linked to the internal company network for internet surfing etc., and another ethernet card 2, linked with an embedded device for programming.
Each time, when I restart PC, I have ethernet card 1 active and ready (listed as "Eth0" by ifconfig command), and ethernet card 2 inactive (listed as "\_\_tmp1835522531" by ifconfig command), waiting for configuration with some local ip address.
my question is:
why it is listed as "\_\_tmp1835522531"? Is it possible to make it listed as "Eth1", when PC restarts? How to do that?
|
2011/09/19
|
[
"https://serverfault.com/questions/312921",
"https://serverfault.com",
"https://serverfault.com/users/95115/"
] |
try looking in /etc/udev/rules.d/70-persistent-net.rules and match the mac address for the \_tmp interface to an entry there (or make an entry if needed), then reboot.
|
59,439,204
|
I've seen some usage of `self.destroy()` within classes but I couldn't get it working with what I wanted it to do.
I have the class `resultsPage` that shows results obtained on another page. I have made the `displayResults(pageNo)` function to show these when `resultsPage` is visible. The problem arises with the back and next buttons which are made to go between pages of results. All widgets are created on top of each other but I want to remove them all then create the new ones. I added `self.destroy()` to try and fix this but it didn't work.
I'm not sure if it's to do with the placement of where I'm defining my functions but I have had a play around with where they're defined and it hasn't changed the error message.
This is a simplified example of my code:
```
class resultsPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
def onShowFrame(self, event):
def displayResults(pageNo):
self.destroy()
#Create widgets related to pageNo
#Create back and next buttons e.g.
back = tk.Button(self, text="<=",
command=lambda: displayResults(pageNo - 1))
displayResults(1)
```
The error I get is: `_tkinter.TclError: bad window path name ".!frame.!previewresultspage"`
If it helps, I can post my full code but I thought I'd generalise it so it's more helpful to others.
|
2019/12/21
|
[
"https://Stackoverflow.com/questions/59439204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11204185/"
] |
The problem comes from the line:
```
tempArray = finalValues[-1]
```
You don't create a copy of the previous list, but only a new name to refer to it. After that, all changes you make to `tempArray` are actually changes to this list, and when you finally do:
```
finalValues.append(tempArray)
```
you just add another reference to this same list in `finalValues`.
In the end, `finalValues` contains 4 references to the same list, which you can access with `finalValues[0]`, `finalValues[1]`...
What you need is to create a new list by copying the previous one. One way to do it is to use a slice:
```
tempArray = finalValues[-1][:]
```
You can find other ways to close or copy a list in [this question](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list)
And so, the complete code gives the expected output:
```
Last array of final: [1, 2, 3, 4]
Temp Array: [1, 2, 3, 4]
Final Values: [[1, 2, 3, 4], [2, 3, 4, 1]]
Last array of final: [2, 3, 4, 1]
Temp Array: [2, 3, 4, 1]
Final Values: [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2]]
Last array of final: [3, 4, 1, 2]
Temp Array: [3, 4, 1, 2]
Final Values: [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]]
[[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]]
```
|
55,489
|
Many Israeli banks let their customers give them post-dated checks, which they will hang on to, for an extra fee, and deposit at the deposit date.
Does this option exist in other countries as well (such as the US, India, or the UK)? If who, what is this service called?
Thank you.
|
2015/11/02
|
[
"https://money.stackexchange.com/questions/55489",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/22835/"
] |
In India Post Dated Check [PDC's] are provided by almost all banks to Corporate Customers. This facility is not provided to individual retail customers.
|
20,572,423
|
I have a PNG file which is a one-pixel-wide, 283-pixel-tall gradient image, which I need to stretch across the background of an ImageView, stretching only horizontally. I attempted to set the asset as a background to an ImageView like this:
```
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/gradient_tile"
android:layout_gravity="bottom|center"
android:scaleType="matrix"/>
```
but that just creates a one-pixel line in the middle of the parent view.
Is there a way to do this, or do I need to request a wider image, and use a 9-patch?
Thanks in advance.
UPDATE:
I ended up having to set minimum height properties in the XML as follows:
```
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="119dp"
android:background="@drawable/gradient_tile_drawable"
android:id="@+id/tiledGradientBackground"
android:layout_gravity="bottom|center"
android:scaleType="matrix"/>
```
...and then set minimumWidth to the width of the parent view in code. Not sure why this solved it, but it did...
```
int width = holder.container.getResolvedWidth();
holder.tiledGradientBackground.setMinimumWidth(width);
```
|
2013/12/13
|
[
"https://Stackoverflow.com/questions/20572423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239318/"
] |
Because you're doing nothing with that function in the parameter. You can do this:
```
function mySecondFunction(func)
{
alert("Second Function");
func();
}
```
|
24,779,055
|
<http://fiddle.jshell.net/hutber/uAczq/> Is the easiest way to explain it.
```
/html
<div title="1%">
1%
<div class="background rating_90"></div>
</div>
//css
.rating {
display: block;
width: 100%;
height: 18px;
line-height: 18px;
border: 1px solid #7F7F7F;
position: relative;
text-align: center;
border-radius: 3px;
}
.rating .background.rating_90 {
width: 90%;
}
.rating .background {
height: 100%;
position: absolute;
top: 0;
left: 0;
content: "";
background-color: #75890C;
border-right: 1px solid #7F7F7F;
}
```
Currently, the text inside the will not be visible, instead `.background` sits in front of the text.
I don't want to add another element inside of the parent `div`
|
2014/07/16
|
[
"https://Stackoverflow.com/questions/24779055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240363/"
] |
Firstly, you do not need the `content` property as this is not a pseudo element.
However, you need to set the z-index of the bg div
[**JSfiddle Demo**](http://fiddle.jshell.net/uAczq/1/)
**CSS (extract)**
```
.rating .background {
z-index:-1; /* add this */
}
```
|
3,963,664
|
**Problem:** Let $g\_t(x)=\frac{1}{\sqrt{2\pi}} e^{ \frac{- (x-t)^2}{2}}$ be the Gaussian function centered at $t\in \mathbb R$. Let $I$ be a subset of $\mathbb R$. Consider the "convolution operator"
\begin{align}
\mathcal A: L^1(I) & \longrightarrow L^2(I)\\
f & \longmapsto \left(x\longmapsto \int\_{I} g\_t(x)f(t) dt \right).
\end{align}
How can I prove (or disprove) that the operator is well-defined and injective?
---
**My attempts:** Here are some of my attempts to prove the well-defined property.
* I have tried to use Cauchy inequality but with no success:
\begin{align}
\int\_{I} \left( \int\_{I} g\_t(x)f(t)dt\right)^2 dx \leq \int\_{I} \int\_{I} g\_t^2(x)dx dt \int\_{I}f^2(t)dt.
\end{align}
as the right-hand-side may be infinite as $f$ does not belong to $L^2(I)$.
* I have tried to use the boundedness of Gaussian function but nothing better. We have
\begin{align}
\int\_{I} \left( \int\_{I} g\_t(x)f(t)dt\right)^2 dx \leq
M \left( \int\_{I} f(t)dt \right)^2 \int\_I dx.
\end{align}
and the right-hand-side may be infinite as $I$ is unbounded.
|
2020/12/27
|
[
"https://math.stackexchange.com/questions/3963664",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/818617/"
] |
I'm going to unclutter the situation and leave out some constants. If it works in the simplified case, you can throw constants at it later.
Suppose $f\in L^1(\mathbb R)$ and $g(t) = e^{-t^2}.$ For $x\in \mathbb R,$ define
$$(g\*f)(x) = \int\_{\mathbb R}g(x-t)f(t)\,dt.$$
That is certainly well defined for any $x,$ since $g\in L^\infty.$ To show $g\*f\in L^2,$ note
$$|g\*f(x)|^2 \le (\int\_{\mathbb R}g(x-t)|f(t)|\,dt)^2$$ $$ = \|f\|\_1^2(\int\_{\mathbb R}(g(x-t)(|f(t)|/\|f\|\_1)\,dt)^2.$$
Use Jensen to see the last expression is bounded above by
$$\|f\|\_1^2\int\_{\mathbb R}(g(x-t))^2(|f(t)|/\|f\|\_1)\,dt.$$
Thus, using Fubini, we have
$$\int |g\*f(x)|^2\,dx \le \|f\|\_1^2 \int g(x)^2\,dx.$$
This proves $\|g\*f\|\_2 \le \|f\|\_1\|g\|\_2.$ Thus $f\to g\*f$ is a bounded linear operator from $L^1$ to $L^2.$
For injectivity, I'll use some Fourier analysis. Let $F$ denote the Fourier transform. Then $F$ is an isometry on $L^2,$ and is injective on $L^1.$ Thus $g\*f$ is the zero function iff $F(g\*f)$ is the zero function. Now
$$F(g\*f)(x) =F(g)(x)\cdot F(f)(x).$$
And as is well known, $F(g)>0$ everywhere. (In fact for the Gaussian $g,$ $F(g)$ is essentially $g,$ meaning $F(g)(x)= ag(bx)$ for some nonzero constants $a,b.$) Thus $F(g\*f)=0$ iff $F(f)=0.$ And the later happens iff $f=0.$ It follow that $f\to g\*f$ is injective.
|
32,107,344
|
Can some one explain what is the difference between these two code blocks? Why would we ever need the first type when second one is more concise.
First
```
var Utility;
(function (Utility) {
var Func = (function () {
function Func(param1, param2) {
var self = this;
this.Owner = param2;
}
return Func;
})();
Utility.Func = Func;
})(Utility || (Utility = {}));
```
Second:
```
var Utility;
(function (Utility) {
Utility.Func = function (param1, param2) {
var self = this;
this.Owner = param2;
}
})(Utility || (Utility = {}));
```
context: First version was code generated by typescript compiler and I am trying to understand why did it generate the first instead of a simpler second.
|
2015/08/19
|
[
"https://Stackoverflow.com/questions/32107344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322933/"
] |
The only difference between the code blocks is that the first has a function scope around the code that creates the `Func` function. The only reason to do that would be to create a scope where you can declare variables that would not be available in the outer scope:
```
var Utility;
(function (Utility) {
var Func = (function () {
var x; // a variable in the inner scope
function Func(param1, param2) {
var self = this;
this.Owner = param2;
}
return Func;
})();
// the variable x is not reachable from code here
Utility.Func = Func;
})(Utility || (Utility = {}));
```
|
68,454,237
|
I'm trying to retrieve some data from a dummy function declared in an Oracle DB.
The function was created like this in SQL Developer:
```sql
create or replace NONEDITIONABLE FUNCTION hello
RETURN varchar2 is
BEGIN
return 'Voici les caractères accentués : àéôï etc...' || chr(10) || 'ça marche ?';
END;
```
My Java application is executed in NetBeans at the moment and goes like this:
```java
try(Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:OraDoc", "sys as sysdba", "MyPasswd123")) {
CallableStatement cs = connection.prepareCall("{? = call hello}");
cs.registerOutParameter(1, Types.NVARCHAR);
cs.execute();
byte[] bytes = cs.getBytes(1);
logger.info(Hex.encodeHexString(bytes));
logger.info(new String(bytes, StandardCharsets.UTF_8));
logger.info(new String(bytes, StandardCharsets.UTF_16));
logger.info(new String(bytes, StandardCharsets.ISO_8859_1));
logger.info(new String(bytes, StandardCharsets.US_ASCII));
} catch(SQLException e) {
logger.error(e.getMessage(), e);
return;
}
```
The output looks like this:
```none
2021-07-20 13:24:36 INFO Main:119 - 0056006f0069006300690020006c00650073002000630061007200610063007400e800720065007300200061006300630065006e0074007500e900730020003a002000e000e900f400ef0020006500740063002e002e002e000a00e700610020006d006100720063006800650020003f
2021-07-20 13:24:36 INFO Main:121 - Voici les caract?res accentu?s : ???? etc...
?a marche ?
2021-07-20 13:24:36 INFO Main:122 - Voici les caract?res accentu?s : ???? etc...
?a marche ?
2021-07-20 13:24:36 INFO Main:123 - Voici les caract?res accentu?s : ???? etc...
?a marche ?
2021-07-20 13:24:36 INFO Main:124 - Voici les caract?res accentu?s : ???? etc...
?a ma
```
Using the same connection, I ran two different queries to try to understand this issue:
```sql
SELECT * FROM v$nls_parameters WHERE parameter LIKE '%CHARACTERSET';
SELECT * FROM nls_session_parameters;
```
which yield the following (truncated):
```none
2021-07-20 13:24:36 INFO Main:51 - PARAMETER -> NLS_CHARACTERSET
2021-07-20 13:24:36 INFO Main:51 - VALUE -> AL32UTF8
2021-07-20 13:24:36 INFO Main:51 - CON_ID -> 0
2021-07-20 13:24:36 INFO Main:51 - PARAMETER -> NLS_NCHAR_CHARACTERSET
2021-07-20 13:24:36 INFO Main:51 - VALUE -> AL16UTF16
2021-07-20 13:24:36 INFO Main:51 - CON_ID -> 0
2021-07-20 13:24:36 INFO Main:55 - ==============================================================
2021-07-20 13:24:36 INFO Main:63 - PARAMETER -> NLS_LANGUAGE
2021-07-20 13:24:36 INFO Main:63 - VALUE -> AMERICAN
2021-07-20 13:24:36 INFO Main:63 - PARAMETER -> NLS_TERRITORY
2021-07-20 13:24:36 INFO Main:63 - VALUE -> AMERICA
```
I've tried different things like:
* adding "?useUnicode=true&characterEncoding=utf-8" at the end of the connection string like I do when I connect to a MySQL database
* changing the NLS\_LANG to NLS\_LANG=AMERICAN\_AMERICA.UTF8 per [How to setup the NLS\_LANG Properly for UNIX](https://www.oracle.com/database/technologies/faq-nls-lang.html)
* using NVARCHAR instead of VARCHAR when registering the outParameter
* adding the parameter -Doracle.jdbc.defaultNChar=true
But it's not improving.
For reference, this is my only two dependencies in that project (related to Oracle):
```xml
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc11</artifactId>
<version>21.1.0.0</version>
</dependency>
<dependency>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>orai18n</artifactId>
<version>19.3.0.0</version>
</dependency>
```
* I've removed the NLS\_LANG environment variable (thanks @Wernfried Domscheit)
* I've switched back to VARCHAR instead of NVARCHAR when registering the out parameter a
* I am using getString() (I was using getBytes() to try to see whether I was receiving ? characters or if it was a display issue.
* I've tried to create the string with UTF\_16BE charset
Still, the result stays the same:
```java
try(Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:OraDoc?useUnicode=true&characterEncoding=utf-8", "sys as sysdba", "MyPasswd123")) {
CallableStatement cs = connection.prepareCall("{? = call hello}");
cs.registerOutParameter(1, Types.VARCHAR);
cs.execute();
logger.info(cs.getString(1));
} catch(SQLException e) {
logger.error(e.getMessage(), e);
return;
}
```
```none
2021-07-20 17:00:20 INFO Main:43 - Voici les caract?res accentu?s : ???? etc...
```
What am I missing?
|
2021/07/20
|
[
"https://Stackoverflow.com/questions/68454237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/894876/"
] |
Well, I also raised a defect to spring-data-redis repository on GitHub for the same but the defect got closed by one of the maintainers of this repository without even posting any proper solution. He just gave a reference to an existing issue that was even closed without posting any solution. Here is the link to that issue.
<https://github.com/spring-projects/spring-data-redis/issues/2130>
Hence, while doing some research, I came across a solution that I am sharing here which worked in my case.
The solution is not to use the default CRUD repository methods implemented by Spring Boot, instead, write your own repository class having methods with your criteria to store and fetch the data from the Redis cache. That's it, now you should be able to store/fetch the data using the repository methods across your project.
I am posting an example below for reference.
**Custom Repository Interface**
```
package com.test.cache.repository;
import java.io.IOException;
import java.util.Map;
import com.test.cache.entity.OTPValidationLogCache;
public interface OTPValidationLogCacheRepository {
void save(OTPValidationLogCache customer);
OTPValidationLogCache find(Long id);
Map<?,?> findAll() throws IOException;
void update(OTPValidationLogCache customer);
void delete(Long id);
}
```
**Custom Repository Interface Implementation**
```
package com.test.cache.repository;
import java.io.IOException;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.ScanOptions.ScanOptionsBuilder;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.test.cache.entity.OTPValidationLogCache;
import com.test.configuration.AppConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
@Repository
public class OTPValidationLogCacheRepositoryImpl implements OTPValidationLogCacheRepository {
private String key;
private RedisTemplate redisTemplate;
private HashOperations hashOperations;
private ObjectMapper objMapper;
@Autowired
public OTPValidationLogCacheRepositoryImpl(RedisTemplate redisTemplate, ObjectMapper objmapper) {
this.redisTemplate = redisTemplate;
this.objMapper = objmapper;
}
@PostConstruct
private void init() {
hashOperations = redisTemplate.opsForHash();
}
@Override
public void save(OTPValidationLogCache otpvalCache) {
hashOperations.put(key.concat(otpvalCache.getId().toString()), otpvalCache.getId(), otpvalCache);
setExpiryTime(key.concat(String.valueOf(otpvalCache.getId())), AppConfig.getUserBanDurationInSeconds());
}
@Override
public OTPValidationLogCache find(Long id) {
return (OTPValidationLogCache) hashOperations.get(key.concat(String.valueOf(id)), id);
}
@Override
public Map findAll() throws IOException {
Map<Integer, OTPValidationLogCache> values = Maps.newHashMap();
Cursor c = hashOperations.scan(OTPValidationLogCache.class, new ScanOptionsBuilder().match(key.concat("*")).build());
AtomicInteger count = new AtomicInteger(1);
c.forEachRemaining(element ->
{
values.put(count.getAndIncrement(), objMapper.convertValue(element, OTPValidationLogCache.class));
}
);
c.close();
return values;
}
@Override
public void update(OTPValidationLogCache customer) {
hashOperations.put(key, customer.getId(), customer);
}
@Override
public void delete(Long id) {
hashOperations.delete(key, id);
}
private void setExpiryTime(String key, Long timeout)
{
redisTemplate.expire(key, Duration.ofSeconds(timeout));
}
public synchronized void setKey(String key)
{
this.key = key;
}
}
```
Hope this helps others who may encounter this issue in the future.
Also, there is one more alternative available for this issue, that is switching to a different library provider such as Redisson, however, I have not tried it yet, so if you want, you may try and check.
|
30,697
|
I am trying to implement an algorithm where given an image with several objects on a plane table, desired is the output of segmentation masks for each object. Unlike in CNN's, the objective here is to detect objects in an unfamiliar environment. What are the best approaches to this problem? Also, are there any implementation examples available online?
Edit: I am sorry, question may have been a bit misleading. What I meant by "unfamiliar environment" is that objects may be unknown to the algorithm. The algorithm shouldn't need to understand what the object is, but should only detect the object. How should I approach this problem?
|
2018/04/23
|
[
"https://datascience.stackexchange.com/questions/30697",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/50956/"
] |
Fast answear
============
[Mean Shift LSH](https://github.com/beckgael/Mean-Shift-LSH) which is an upgrade in **$O(n)$** of the famous Mean Shift algorithm in $O(n^2)$ well know for its image segmentation ability
Some explanations
=================
If you desire a true **unsupervised** approach to segment images, use **clustering algorithms**. The fact is that there is a lot of algorithms with different **time complexity** and **specificity**. Take the most famous one, the $K$-Means, it is in $O(n)$ so pretty fast but you have to specify how many cluster you want which is not what you intend by exploring an unknown image without any information about how many shapes are presents in it. Moreover even if you suppose that you know how many shape are present, we may suppose that there shapes are random which is another point where the $K$-Means fail because it is design to find elliptic clusters and **NOT** random shape ones.
At the opposite we have the Mean Shift that is able to find **automatically** the number of cluster -- which is useful when you don't know what you're looking for -- with **random shapes**.
Of course you replace the $K$ parameter of $K$-Means by others Mean Shift parameters which can be tricky to fine tuned but it doesn't exist a tool that allow you to do magic if you're not exercising to do magic.
An advice to image segmentation clustering
==========================================
Transform your color space from RGB to LUV which is better for euclidean distance.
$K$-Means vs Mean Shift LSH time complexity
===========================================
* Mean Shift : $O(\alpha.n)$
* K-Means : $O(\beta.n)$
* $\alpha \gt \beta$
Mean Shift LSH is slower but it fits better with your needs. It stay still linear and is also **scalable** with the mentioned implementation.
PS : My profile picture is an application of the Mean Shift LSH on myself if it can help to figure out how it works.
|
7,570,496
|
I'm trying to get the document object of an iframe, but none of the examples I've googled seem to help. My code looks like this:
```
<html>
<head>
<script>
function myFunc(){
alert("I'm getting this far");
var doc=document.getElementById("frame").document;
alert("document is undefined: "+doc);
}
</script>
</head>
<body>
<iframe src="http://www.google.com/ncr" id="frame" width="100%" height="100%" onload="myFync()"></iframe>
</body>
</html>
```
I have tested that I am able to obtain the iframe object, but .document doesn't work, neither does .contentDocument and I think I've tested some other options too, but all of them return undefined, even examples that are supposed to have worked but they don't work for me. So I already have the iframe object, now all I want is it's document object. I have tested this on Firefox and Chrome to no avail.
|
2011/09/27
|
[
"https://Stackoverflow.com/questions/7570496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/821562/"
] |
Try the following
```
var doc=document.getElementById("frame").contentDocument;
// Earlier versions of IE or IE8+ where !DOCTYPE is not specified
var doc=document.getElementById("frame").contentWindow.document;
```
Note: AndyE pointed out that `contentWindow` is supported by all major browsers so this may be the best way to go.
* <http://help.dottoro.com/ljctglqj.php>
Note2: In this sample you won't be able to access the document via any means. The reason is you can't access the document of an iframe with a different origin because it violates the "Same Origin" security policy
* <http://javascript.info/tutorial/same-origin-security-policy>
|
52,784,794
|
I'm working through TestDome.com and ran into this question.
>
> Implement the removeProperty function which takes an object and
> property name, and does the following:
>
>
> If the object obj has a property prop, the function removes the
> property from the object and returns true; in all other cases it
> returns false.
>
>
>
My solution was this:
```
function removeProperty(obj, prop) {
if (obj[prop]) {
delete obj[prop];
return true;
} else {
return false;
}
}
```
The test says that this doesn't work and their solution is:
```
function removeProperty(obj, prop) {
if (prop in obj) {
delete obj[prop];
return true;
} else {
return false;
}
}
```
For the life of me I can't figure out why my solution is wrong.
Edit: further examples.
```
const a = { b: 'c'};
if(a['b']) {console.log(true);} //true
if('b' in a) {console.log(true);} //true
```
|
2018/10/12
|
[
"https://Stackoverflow.com/questions/52784794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3792201/"
] |
The difference is the following:
```js
obj = {
prop: 1
};
// retrieves the property from the object
console.log(obj['prop']); // 1
// checks if prop is in obj object
console.log('prop' in obj); // true
```
In the case of an if statement, both will evaluate to true. However, if the value retrieved from `obj['prop']` is coerced to `false` the `if` block would not run. For example:
```js
obj = {
prop: 0
};
// 0 convert to false so
if (obj['prop']) {
console.log('executed 1');
}
// prop is a property of obj so
// 'prop' in obj will evaluate to true
if ('prop' in obj) {
console.log('executed 2');
}
```
|
13,676,616
|
I made a implementation of the KMP algorithm's fail table.
```
kmp s = b
where a = listArray (0,length s-1) s
b = 0:list 0 (tail s)
list _ [] = []
list n (x:xs)
| x==a!n = (n+1):list (n+1) xs
| n > 0 = list (b!!(n-1)) (x:xs)
| otherwise = 0:list 0 xs
```
`b` is a list, and `b!!(n-1)` in the last line is slow, therefore I wish to speed it up and did the following.
```
kmp s = b
where a = listArray (0,length s-1) s
t = listArray (0,length s-1) b
b = 0:list 0 (tail s)
list _ [] = []
list n (x:xs)
| x==a!n = (n+1):list (n+1) xs
| n > 0 = list (t!(n-1)) (x:xs)
| otherwise = 0:list 0 xs
```
Note the only difference is to replace `b!!` by `t!` and declares `t` to be the array generated from `b`.
For the same input, the original code have the correct output, but the new one just outputs `<<loop>>`.
How can one fix this problem?
|
2012/12/03
|
[
"https://Stackoverflow.com/questions/13676616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/303863/"
] |
Your problem is that the list `b` needs the array `t` to determine its structure (length). But the array `t` needs the length of the list before it exists:
```
listArray :: Ix i => (i,i) -> [e] -> Array i e
listArray (l,u) es = runST (ST $ \s1# ->
case safeRangeSize (l,u) of { n@(I# n#) ->
case newArray# n# arrEleBottom s1# of { (# s2#, marr# #) ->
let fillFromList i# xs s3# | i# ==# n# = s3#
| otherwise = case xs of
[] -> s3#
y:ys -> case writeArray# marr# i# y s3# of { s4# ->
fillFromList (i# +# 1#) ys s4# } in
case fillFromList 0# es s2# of { s3# ->
done l u n marr# s3# }}})
```
As you can see, first a raw array of appropriate size is allocated, then it is filled with `arrEleBottom` (which is an `error` call with message undefined array element), then the list is traversed and the list elements are written to the array (the list elements can refer to array values without problem). Then, finally, the array is frozen. Before the array is frozen, it cannot be accessed from outside the filling code (it's basically an `ST s` computation).
The simplest way to fix it is IMO to use a mutable array in an `ST s` monad,
```
kmp s = elems b
where
l = length s - 1
a = listArray (0, l) s
b = runSTArray $ do
t <- newArray_ (0,l)
writeArray t 0 0
let fill _ _ [] = return t
fill i n (x:xs)
| x == a!n = do
writeArray t i (n+1)
fill (i+1) (n+1) xs
| n > 0 = do
k <- readArray t (n-1)
fill i k (x:xs)
| otherwise = do
writeArray t i 0
fill (i+1) 0 xs
fill 1 0 (tail s)
```
is a very direct (and a bit inefficient) translation of the code.
|
35,214,094
|
I tried setting the following:
set ftp:initial-prot ""
set ftp:ssl-force true
set ftp:ssl-protect-data true
set ftp:ssl-auth TLS
and am on RHEL4 trying to lftp to a 2010 Windows server but I am getting
Fatal error: gnutls\_handshake: A TLS packet with unexpected length was received.
Can you please let me know what is that am missing now?
|
2016/02/05
|
[
"https://Stackoverflow.com/questions/35214094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249798/"
] |
Let does not create local "variables", it gives names to values, and does not let you change them after giving them the name. So introducing a let is more like defining a local constant.
First I'll just add another item into the `loop` expression to store the value so far. Each time through the loop we will update this to incorporate the new information. This pattern is very common. I also needed to add a new argument to the function to hold the initial state (reduce as a concept needs this)
```
user> (defn new-reduce [function initial-value coll]
(loop [i 0
answer-so-far initial-value]
(if (< i (count coll))
(recur (inc i) (function answer-so-far (get coll i)))
answer-so-far)))
user> (new-reduce + 0 [1 2 3])
6
```
This moves the "global variable" into a name that is local to the loop expression can be updated once per loop at the time you jump back up to the top. Once it reaches the end of the loop it will return the answer thus far as the return value of the function rather than recurring again. Building your own reduce function is a great way to build understanding on how to use reduce effectively.
There is a function that introduces true local variables, though it is very nearly never used in Clojure code. It's only really used in the runtime bootstap code. If you are really curious read up on binding very carefully.
|
52,023,130
|
What i'm trying to do is to read big file 5.6GB have approximately 600Million lines and the second is 16MB have 2M lines.
I want to check the duplicate lines in these two files.
```
$wordlist = array_unique(array_filter(file('small.txt', FILE_IGNORE_NEW_LINES)));
$duplicate = array();
if($file = fopen('big.txt', 'r')){
while(!feof($file)){
$lines = rtrim(fgets($file));
if(in_array($lines, $wordlist)){
echo $lines." : exists.\n";
}
}
fclose($file);
}
```
But this take forever to finish ( its been running from 6 hours and didn't finish yet :/ ).
My question is. Is there a better way to search in huge files fast?
|
2018/08/26
|
[
"https://Stackoverflow.com/questions/52023130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8966922/"
] |
You won't need to call `array_filter()` or `array_unique()` if you are going to call `array_flip()` -- it will eliminate the duplicates for you because you can't have duplicate keys in the same level of an array.
Furthermore:
1. `array_unique()` is stated to be slower than `array_flip()` (and there are times when it is slower than two `array_flip()`s)
2. `array_filter()` has a bad reputation for killing falsey/empty/null/zero-ish data, so I will caution you not to use its default behavior.
3. `array_flip()` sets up the very speedy `isset()` check. `isset()` will likely outperform `array_key_exists()` because `isset()` doesn't check for `null` values.
4. I am adding the `FILE_SKIP_EMPTY_LINES` flag to `file()` call so that your lookup array is potentially smaller.
5. Calling `rtrim()` of every line of your big file, may be causing some drag too. Do you know if you have consistently identical newline characters on both files? It would spare you six hundred millions calls of `rtrim()` if you can safely remove the `FILE_IGNORE_NEW_LINES` flag from the `file()` call. Alternatively, if you *know* the newlines (e.g. `\n`? or `\r\n`?) that trail the big.txt lines, you can append specific newline(s) to the `$lookup` keys -- this means preparing the smaller file's data versus every line of the big file.
Untested Code:
```
$lookup = array_flip(file('small.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
if($file = fopen('big.txt', 'r')){
while(!feof($file)){
$line = rtrim(fgets($file));
if (isset($lookup[$line])) {
echo "$lines : exists.\n";
}
}
fclose($file);
}
```
|
71,621,056
|
I have an app that I need to clean up some resources before it shuts down. I've got it handling the event using:
`AppDomain.CurrentDomain.ProcessExit += OnProcessExit;`
```
private static async void OnProcessExit(object? sender, EventArgs e)
{
Console.WriteLine("We");
Thread.Sleep(1000);
Console.WriteLine("Are");
Thread.Sleep(1000);
Console.WriteLine("Closing");
}
```
But the event never gets fired? At least I don't see it, it instantly closes. I've tried this in an external and internal console and neither seem to catch it.
Using Linux Ubuntu 20.10
|
2022/03/25
|
[
"https://Stackoverflow.com/questions/71621056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18571693/"
] |
While you might see it as overkill in the beginning, I can recommend wrapping your console app in .NET Generic Host. This enables you to easily handle resource initialisation and cleanup, it also encapsulates logging and DI and nested services if available. The console app becomes easy to startup in an integration test, install as a Windows service (e.g. via Topshelf) or just keep running as a console app.
<https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host>
To get started you can run in command prompt
```
dotnet new worker
```
Then in Worker.cs you can override the StopAsync
```
public override async Task StopAsync(CancellationToken cancellationToken)
{
await Task.Delay(1000);
_logger.LogInformation("Ended!");
}
```
Running with `dotnet run` you will see logging each second, and when you Ctrl+C you will see "Ended!" after 1 second - here you do any resource cleanup needed.
|
51,915,320
|
`var string = "3y4jd424jfm`
Ideally, I'd want it to be `["3","y","4","j","d","4","24","j","f","m"]`
but when I split: `string.split("")`, the `2` and the `4` in `24` are separated. How can I account for double digits?
Edit: Here is the question I was trying to solve from a coding practice:
*Using the JavaScript language, have the function EvenPairs(str) take the str parameter being passed and determine if a pair of adjacent even numbers exists anywhere in the string. If a pair exists, return the string true, otherwise return false. For example: if str is "f178svg3k19k46" then there are two even numbers at the end of the string, "46" so your program should return the string true. Another example: if str is "7r5gg812" then the pair is "812" (8 and 12) so your program should return the string true.*
|
2018/08/19
|
[
"https://Stackoverflow.com/questions/51915320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10245232/"
] |
You could take a staged approach by
* getting only numbers of the string in an array
* filer by length of the string,
* check if two of the digits are even
```js
function even(n) {
return !(n % 2);
}
function checkEvenPair(string) {
return string
.match(/\d+/g)
.filter(s => s.length > 1)
.some(s =>
[...s].some((c => v => even(v) && !--c)(2))
);
}
console.log(checkEvenPair('2f35fq1p97y931')); // false
console.log(checkEvenPair('3y4jd424jfm')); // true 4 2
console.log(checkEvenPair('f178svg3k19k46')); // true 4 6
console.log(checkEvenPair('7r5gg812')); // true 8 12
console.log(checkEvenPair('2f35fq1p97y92321')); // true (9)2 32
```
A regular expression solution by taking only even numbers for matching.
```js
function checkEvenPair(string) {
return /[02468]\d*[02468]/.test(string);
}
console.log(checkEvenPair('2f35fq1p97y931')); // false
console.log(checkEvenPair('3y4jd424jfm')); // true
console.log(checkEvenPair('f178svg3k19k46')); // true
console.log(checkEvenPair('7r5gg812')); // true
console.log(checkEvenPair('2f35fq1p97y92321')); // true
```
|
968,806
|
How can xkb or some other tool be used to permanently bind Caps Lock to `ctrl`+`b` while in terminal?
(This is to make `Caps Lock` the default prefix key for tmux. It could also be mapped to a specific key if that's too difficult, e.g. a function key, which could then be made the tmux prefix instead.)
|
2017/10/24
|
[
"https://askubuntu.com/questions/968806",
"https://askubuntu.com",
"https://askubuntu.com/users/40428/"
] |
XKB will be appropriate for Xwindows or Wayland GUIs. It will not affect virtual consoles, but GUI terminal emulators will be fine. For XKB background I'll point you to [some (overview, system vs user)](https://askubuntu.com/a/896297/669043) .. [other (custom options)](https://superuser.com/a/1168603/685512) .. [answers (custom rules)](https://unix.stackexchange.com/a/355404/222377).
The following will allow you to add a new option like `caps:myf13` to an existing XKB layout with whatever tools you'd normally use (`setxkbmap`, `localectl` settings, GNOME panel, etc).
---
### Defining the option
Existing XKB capslock options are listed in `/usr/share/X11/xkb/rules/evdev.lst`. Looking at the corresponding options in the `.../rules/evdev` file, you can see these options are all loaded from the file `.../symbols/capslock`. All of them are modifier keys, which probably aren't the best example, but `caps:backspace` might be a good comparison. Looking at the file, we find the stanza defining this option:
```
hidden partial modifier_keys
xkb_symbols "backspace" {
key <CAPS> { [ BackSpace ] };
};
```
`grep`'ing through the other symbol files, we can see that the F13 symbol is simply `F13`. The new option stanza might look like this:
```
hidden partial modifier_keys
xkb_symbols "myf13" {
key <CAPS> { [ F13 ] };
};
```
As you can see, we only changed the name of the option and the symbol assigned to the key.
---
### Hooking it up
The only thing left to do is hook up the new stanza. On a basic Xwindows system, using commandline tools like `setxkbmap` and `xkbcomp`, a [custom user location](https://askubuntu.com/a/896298/669043) will do fine; for GNOME, KDE or a Wayland system you'll need to make your changes in the system XKB database.
As an example for system changes (you will need `sudo` access to create or edit these files):
* Place the custom stanza in a new symbol file, eg `/usr/share/X11/xkb/symbols/mycaps`.
* Add this to `/usr/share/X11/xkb/rules/evdev` just below the line for `caps:backspace`:
```
caps:myf13 = +mycaps(myf13)
```
* ... add to `/usr/share/X11/xkb/rules/evdev.lst`:
```
caps:myf13 Caps Lock is F13
```
* ... add to `/usr/share/X11/xkb/rules/evdev.xml`:
```
<option>
<configItem>
<name>caps:myf13</name>
<description>Caps Lock is F13</description>
</configItem>
</option>
```
* Finally, make backups of your `.../rules/evdev*` files, or create a patch file. Your changes will be overwritten whenever the `xkb-data` package is updated. If you saved your modification stanza into the `.../symbols/capslock` file, it will need to be backed up as well.
Once these changes are made, you should be able to set this option as if it were any other XKB option. You may need to restart any GNOME/KDE session for control panels to pick up the changes, but tools like `setxkbmap` should find it immediately: `setxkbmap -option caps:myf13`
|
5,216,370
|
So my problem is simple, the data i am initalizing in my constructor is not saving at all.
basically I have pin pointed to this one point. I have a constructor in a class
```
strSet::strSet(std::string s){
std::vector<std::string> strVector;
strVector.push_back(s);
}
```
and in my main file i have
```
else if(command == "s"){
cout << "Declare (to be singleton). Give set element:";
cin >> input >> single_element;
vector_info temp;
temp.name = input;
strSet set(single_element);
set.output();
temp.vector = set;
list.push_back(temp);
}
```
when my constructor is called and i check the length of my vector the answer is appropriate, but then when i check the length of my vector in output, it resets to 0?
can anyone help me, much appreciated!!!!!!!
EDIT
this is my .h file
```
class strSet
{
private:
std::vector<std::string> strVector;
// This is initially empty (when constructed)
bool isSorted () const;
public:
strSet (); // Create empty set
strSet (std::string s); // Create singleton set
void nullify (); // Make a set be empty
bool isNull () const;
int SIZE() const;
void output() const;
bool isMember (std::string s) const;
strSet operator + (const strSet& rtSide); // Union
strSet operator * (const strSet& rtSide); // Intersection
strSet operator - (const strSet& rtSide); // Set subtraction
strSet& operator = (const strSet& rtSide); // Assignment
}; // End of strSet class
```
|
2011/03/07
|
[
"https://Stackoverflow.com/questions/5216370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647682/"
] |
```
strSet::strSet(std::string s){
std::vector<std::string> strVector; //line 1
strVector.push_back(s); //line 2
}
```
This is your constructor, and here you're storing the value in the local vector which gets destroyed on returning from the constructor. How do you expect your data to be saved in strSet?
I believe you need to know the basic of C++ and class, by reading an introductory C++ book yourself. So please get a book and read it first; here is a list of really good books:
[The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)
EDIT:
If you've declared `strVector` as class member, then you need to remove the `line 1`. Then it will work.
|
37,414,994
|
I am looking for a way to stop a higher-level function after evaluating part of its input sequence.
Consider a situation when you look for the first index in a sequence that satisfies a certain condition. For example, let's say we are looking for the first position in an array `a` of `Int`s where the sum of two consecutive values is above 100.
You can do it with a loop, like this:
```
func firstAbove100(a:[Int]) -> Int? {
if a.count < 2 {
return nil
}
for i in 0..<a.count-1 {
if a[i]+a[i+1] > 100 {
return i
}
}
return nil
}
```
The looping stops as soon as the position of interest is discovered.
We can rewrite this code using `reduce` as follows:
```
func firstAbove100(a:[Int]) -> Int? {
if a.count < 2 {
return nil
}
return (0..<a.count-1).reduce(nil) { prev, i in
prev ?? (a[i]+a[i+1] > 100 ? i : nil)
}
}
```
However, the disadvantage of this approach is that `reduce` goes all the way up to `a.count-2` even if it finds a match at the very first index. The result is going to be the same, but it would be nice to cut the unnecessary work.
Is there a way to make `reduce` stop trying further matches, or perhaps a different function that lets you stop after finding the first match?
|
2016/05/24
|
[
"https://Stackoverflow.com/questions/37414994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335858/"
] |
The issue with your code lies in `readingTheFile()`:
This is the return-statement:
```
return null;
```
Which - Captain Obvious here - returns `null`. Thus `secret` is `null` and the `IllegalArgumentException` is thrown.
If you absolutely want to stick to the `BufferedReader`-solution, this should solve the problem:
```
byte[] readingTheFile(){
byte[] result = null;
try(BufferedReader br = new BufferedReader(new FileReader(path))){
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null)
sb.append(line).append(System.getProperty("line.separator"));
result = sb.toString().getBytes();
}catch(IOException e){
e.printStackTrace();
}
return result;
```
}
Some general advice:
`BufferedReader` isn't built for the purpose of reading a file `byte` for `byte` anyways. E.g. `'\n'` will be ignored, since you're reading line-wise. This may cause you to corrupt data while loading. Next problem: you're only closing the `FileReader` in `readingTheFile()`, but not the `BufferedReader`. **Always** close the ToplevelReader, not the underlying one. By using `try-with-resources`, you're saving yourself quite some work and the danger of leaving the `FileReader` open, if something is coded improperly.
If you want to read the bytes from a file, use `FileReader` instead. That'll allow you to load the entire file as `byte[]`:
```
byte[] readingTheFile(){
byte[] result = new byte[new File(path).length()];
try(FileReader fr = new FileReader(path)){
fr.read(result , result.length);
}catch(IOException e){
e.printStackTrace();
}
return result;
}
```
Or alternatively and even simpler: use `java.nio`
```
byte[] readingTheFile(){
try{
return Files.readAllBytes(FileSystem.getDefault().getPath(path));
}catch(IOException e){
e.printStackTrace();
return null;
}
}
```
|
45,714,606
|
Usually the question is for the main thread to wait for child thread which I can use `await` on the `Task`.
But I have a situation where the child thread must wait for some method in the main thread to complete before continuing. How to make this communication possible?
```
public void MainThread()
{
Task t = Task.Run(ChildThread); //not using await because we want to continue doing work that must be only on the main thread
WorkA();
WorkB();
???
WorkC();
}
public async Task ChildThread()
{
WorkD();
???
Need_WorkB_ToBeCompletedBeforeThisOne();
}
```
`WorkA` `WorkB` `WorkC` are all necessary to be on the main thread. All of them would be issue indirectly from the child thread in my real code because child thread need them done but could not do it because of thread restriction.
I have a way for my child thread to tell main thread to do work already (so I simplify the code to what you see here, as soon as the task start the work will immediately follows) but I need some way for the issuer (child thread) to know about the progress of those commands.
PS. Thanks to answers from this thread I have created `CoroutineHost` for Unity, which you are able to `await` the `yield IEnumerator` method that you can issue to your main thread to do from any of your child threads : <https://github.com/5argon/E7Unity/tree/master/CoroutineHost>
|
2017/08/16
|
[
"https://Stackoverflow.com/questions/45714606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/862147/"
] |
You're looking for a "signal". Since the child is asynchronous and the signal is used only one time, a `TaskCompletionSource<T>` would work nicely:
```
public void MainThread()
{
var tcs = new TaskCompletionSource<object>(); // Create the signal
Task t = Task.Run(() => ChildThread(tcs.Task)); // Pass the "receiver" end to ChildThread
WorkA();
WorkB();
tcs.SetResult(null); // Send the signal
WorkC();
}
public async Task ChildThread(Task workBCompleted)
{
WorkD();
await workBCompleted; // (asynchronously) wait for the signal to be sent
Need_WorkB_ToBeCompletedBeforeThisOne();
}
```
See recipe 11.4 "Async Signals" in [my book](https://stephencleary.com/book/) for more information. If you need a "signal" that can become set and unset multiple times, then you should use [`AsyncManualResetEvent`](https://github.com/StephenCleary/AsyncEx).
|
65,477,564
|
In `opentelemetery-api` version `0.8.0`, we used to set a new `SpanContext` in current `Context` via following code:
```scala
TracingContextUtils.currentContextWith(DefaultSpan.create(newSpanCtx))
```
However, in version `0.13.1`, both - `TracingContextUtils` and `DefaultSpan` are removed. Then how can I set a new `SpanContext` in the current `Context`?
|
2020/12/28
|
[
"https://Stackoverflow.com/questions/65477564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3620633/"
] |
From [opentelemetry-java](https://github.com/open-telemetry/opentelemetry-java) version [0.10.0 release notes](https://github.com/open-telemetry/opentelemetry-java/releases/tag/v0.10.0):
>
> * `TracingContextUtils` and `BaggageUtils` were removed from the public API. Instead, use the appropriate static methods on the `Span` and `Baggage` classes, or use methods on the `Context` itself.
> * `DefaultSpan` was removed from the public API. Instead, use `Span.wrap(spanContext)` if you need a non-functional span that propagates the trace context.
>
>
>
You can try something like:
```scala
val newSpanCtx: SpanContext = null
val span: Span = Span.wrap(newSpanCtx)
Context.current().`with`(span).makeCurrent()
```
|
37,651,258
|
I try to make WebApp using php & R . this is my php code:
```
exec("/usr/bin/Rscript /home/bella/Downloads/htdocs/laut/script.r $N");
$nocache = rand();
echo("<img src='tmp.png?$nocache' />");
```
And this is my script.r code:
```
slices <- c(10, 12,4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
png(filename="tmp.png", width=600, height=600)
pie(slices, labels = lbls, main="Pie Chart of Countries")
dev.off()
```
Everything work fine.
Then, i change slices data and store it in csv. I change script.r code:
```
setwd("/home/bella/Downloads/DATA")
slices<-read.csv("country.csv",header=T,sep=";",dec=",")
lbls <- c("US", "UK", "Australia", "Germany", "France")
png(filename="tmp.png", width=600, height=600)
pie(as.matrix(slices), labels = lbls, main="Pie Chart of Countries")
dev.off()
```
I run it, but tmp.png file not updated.
It seem that my R code "`setwd`" and "`read.csv`" didn't run.
(i try both script in R and running well)
Why this happen? How to get data from csv file using R script in php?
|
2016/06/06
|
[
"https://Stackoverflow.com/questions/37651258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6428913/"
] |
>
> Note: If you want to convert a callback API to promises see [this question](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises).
>
>
>
Let's start with something that should be said from the get go. An executor is *not* required in order to design promises. It is *entirely* possible to design a promises implementation that does something like:
```
let {promise, resolve, reject} = Promise.get();
```
If you promise not to tell anyone, I'll even let you in on a little secret - this API even exists from a previous iteration of the spec and in fact even still works in Chrome:
```
let {promise, resolve, reject} = Promise.defer();
```
However, it is being removed.
### So, why do I need to pass an executor?
I [just answered your other question](https://stackoverflow.com/questions/37651780/why-does-the-promise-constructor-need-an-executor) about why an executor is an interesting design. It's throw-safe and it lets you take care of interesting things.
### Can I still get the resolve, reject functions? I need those
In my experience, most of the times I *needed* resolve/reject I didn't *actually* need them. That said - I did in fact actually *need* them a couple of times.
The specifiers recognized this and for this reason the executor function *is always run synchronously*. You can get the `.defer` interface it just isn't the default:
```
function defer() {
let resolve, reject, promise = new Promise((res, rej) => {
[resolve, reject] = [res, rej];
});
return {resolve, reject, promise};
}
```
Again, this is *typically* not something you want to do but it is *entirely possible* that you have a justifiable use case which is why it's not the default but completely possible.
### Your actual code
I would start with implementing things like timeout and a request as primitives and then compose functions and chain promises:
```
function delay(ms) {
return new Promise(r => setTimeout(r, ms));
}
function timeout(promise, ms) {
return Promise.race([
promise,
delay(ms).then(x => { throw new Error("timeout"); })
]);
}
function ajax(url) { // note browsers do this natively with `fetch` today
return new Promise((resolve, reject) => { // handle errors!
makeAjaxRequest(url, (result) => {
// if(result.isFailure) reject(...);
if(result.status >= 400) reject(new Error(result.status));
else resolve(result.data);
});
});
}
```
Now when we promisified *the lowest level API surface* we can write the above code quite declaratively:
```
function getDetails (someHash) {
var ajax = makeAjaxRequest("http://somewebsite.com/" + someHash);
return timeout(ajax, 500);
}
```
|
444,871
|
Using a stand alone Windows Server 2012 Standard edition (no Active Directory),
I succeded to add a new rule to allow sql server connection, by entering the .exe file
When I edited the rule property to specify the port number, text zones for ports are greyed and no way to write in them.
Is there a new feature in Windows Server 2012 that by default disables port numbers editing ?
Any advices please ?
|
2012/11/02
|
[
"https://serverfault.com/questions/444871",
"https://serverfault.com",
"https://serverfault.com/users/140342/"
] |
I actually found something that so far does what I asked for, sharing here so anyone who runs into this issue can try out this solution:
```
sudo setfacl -Rdm g:groupnamehere:rwx /base/path/members/
sudo setfacl -Rm g:groupnamehere:rwx /base/path/members/
```
**R** is recursive, which means everything under that directory will have the rule applied to it.
**d** is default, which means for all future items created under that directory, have these rules apply by default.
**m** is needed to add/modify rules.
The first command, is for new items (hence the d), the second command, is for old/existing items under the folder. Hope this helps someone out as this stuff is a bit complicated and not very intuitive.
|
20,749,660
|
Using a Perl regex, I need to match a series of eight digits, for example, 12345678, but only if they are not all the same. 00000000 and 99999999 are typical patterns that should not match. I'm trying to weed out obviously invalid values from existing database records.
I've got this:
```
my ($match) = /(\d{8})/;
```
But I can't quite get the backref arranged right.
|
2013/12/23
|
[
"https://Stackoverflow.com/questions/20749660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321898/"
] |
How about:
```
^(\d)(?!\1{7})\d{7}$
```
This will match 8 digit number that haven't 8 same digit.
**Sample code:**
```
my $re = qr/^(\d)(?!\1{7})\d{7}$/;
while(<DATA>) {
chomp;
say (/$re/ ? "OK : $_" : "KO : $_");
}
__DATA__
12345678
12345123
123456
11111111
```
**Output:**
```
OK : 12345678
OK : 12345123
KO : 123456
KO : 11111111
```
**Explanation:**
```
The regular expression:
(?-imsx:^(\d)(?!\1{7})\d{7}$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
\d digits (0-9)
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
\1{7} what was matched by capture \1 (7 times)
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
\d{7} digits (0-9) (7 times)
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
```
|
731,220
|
So I have this big file of fix length lines. I want to do a find and replace on a character line position.
Example:
```
xxxxxxx 010109 xxxxxx xxxxx
xxxxxxx 010309 xxxxxx xxxxx
xxxxxxx 021506 xxxxxx xxxxx
xxxxxxx 041187 xxxxxx xxxxx
```
So in this case I would want to find any value starting on position 13 through position 18 and replace it with 010107.
Can anyone give help me out on how to formulate the regex for this?
Much appreciated.
|
2009/04/08
|
[
"https://Stackoverflow.com/questions/731220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88737/"
] |
**Edited: after testing, Notepad++ doesn't support the {n} method of defining an exact number of chars**
This works, tested on your data:
Find:
```
^(............)......
```
Replace:
```
\1010107
```
|
3,115,810
|
I would like to use the libical library in my project, but I have never used an external library before. I have downloaded the libical files, but I am pretty much stuck there. I do not how how, or even if, I need to build/extract them and then how to get them into Xcode. Any help would be greatly appreciated. Thank you.
|
2010/06/25
|
[
"https://Stackoverflow.com/questions/3115810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172131/"
] |
If this a pre-built library then you can just drag it into your Xcode project (or use `Project` => `Add to Project…`) in the same way that you would for source/header files.
If it's not pre-built then you'll need to build it for whatever environments and architecture you want to target. If it comes with an Xcode project then this is easy. If it's just the usual open source type of distribution then you usually do something like this:
```
$ ./configure
$ ./make
$ sudo ./make install
```
That will typically put the built library(ies) and header(s) into somewhere like `/usr/local/lib` and `/usr/local/include`. In your main Xcode project you can then just add these header(s) and library(ies) to your project.
Note that if you're cross-compiling, e.g. for iPhone, then you'll need to add some flags to the `./configure` command so that you target the correct architecture, e.g. `./configure -build=arm-apple-darwin9.0.0d1`.
Note also that it's usually a good idea to check [MacPorts](http://www.macports.org/) to see if they have already fixed up a given open source project for Mac OS X - this can save you a lot of work.
See also [this blog about building and using libical on iPhone](http://ingvar.blog.linpro.no/2008/08/18/how-i-made-the-iphone-sync-my-calendar-over-air/).
|
41,522,744
|
Trying to bundle the following file with Webpack fails with
>
> ERROR in ./~/pg/lib/native/index.js Module not found: Error: Cannot
> resolve module 'pg-native' in
> .../node\_modules/pg/lib/native
> @ ./~/pg/lib/native/index.js 9:13-33
>
>
>
I tried several `ignore` statements in the *.babelrc* but didnt get it running...
The test-file i want to bundle: *handler.js*
```
const Client = require('pg').Client;
console.log("done");
```
*webpack.config.js*
```
module.exports = {
entry: './handler.js',
target: 'node',
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: __dirname,
exclude: /node_modules/,
}]
}
};
```
*.babelrc*
```
{
"plugins": ["transform-runtime"],
"presets": ["es2015", "stage-1"]
}
```
*package.json*
```
"dependencies": {
"postgraphql": "^2.4.0",
"babel-runtime": "6.11.6"
},
"devDependencies": {
"babel-core": "^6.13.2",
"babel-loader": "^6.2.4",
"babel-plugin-transform-runtime": "^6.12.0",
"babel-preset-es2015": "^6.13.2",
"babel-preset-stage-0": "^6.5.0",
"babel-polyfill": "6.13.0",
"serverless-webpack": "^1.0.0-rc.3",
"webpack": "^1.13.1"
}
```
Somewhat related github-issues:
* <https://github.com/brianc/node-postgres/issues/1187>
* <https://github.com/serverless/serverless-runtime-babel/issues/8>
|
2017/01/07
|
[
"https://Stackoverflow.com/questions/41522744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3301344/"
] |
This is indeed an old thread, but one that helped me nonetheless.
The solution provided by Steve Schafer [1](https://stackoverflow.com/a/59652739/2822888) is good, but not the simplest.
Instead, the one provided by Marco Lüthy [2](https://github.com/brianc/node-postgres/issues/838#issuecomment-405646013) in the linked issue is probably the easiest to set up because it is pure configuration, without even the need for a dummy file to be created.
It consists of modifying your Webpack config `plugins` array as follows:
```js
const webpack = require('webpack');
const webpackConfig = {
...
resolve: { ... },
plugins: [
new webpack.IgnorePlugin(/^pg-native$/)
// Or, for WebPack 4+:
new webpack.IgnorePlugin({ resourceRegExp: /^pg-native$/ })
],
output: { ... },
...
}
```
Updated to include a change suggested in the comments.
|
14,977,697
|
I want to read data from one column of datagridview. My datagridview contains many columns but I want to read all cells but only from one column. I read all columns using this code:
```
foreach (DataGridViewColumn col in dataGridView1.Columns)
col.Name.ToString();
```
But I want to read all cell from particular column.
|
2013/02/20
|
[
"https://Stackoverflow.com/questions/14977697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865258/"
] |
Try this
```
string data = string.Empty;
int indexOfYourColumn = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
data = row.Cells[indexOfYourColumn].Value;
```
|
54,187,563
|
Any suggestions on how to convert the [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations) format `PnYnMnDTnHnMnS` (ex: P1W, P5D, P3D) to number of days?
I'm trying to set the text of a button in a way that the days of free trial are displayed to the user.
Google provides the billing information in the ISO 8601 duration format through the key "freeTrialPeriod", but I need it in numbers the user can actually read.
The current minimum API level of the app is 18, so the Duration and Period classes from Java 8 won't help, since they are meant for APIs equal or greater than 26.
I have set the following method as a workaround, but it doesn't look like the best solution:
```
private String getTrialPeriodMessage() {
String period = "";
try {
period = subsInfoObjects.get(SUBS_PRODUCT_ID).getString("freeTrialPeriod");
} catch (Exception e) {
e.printStackTrace();
}
switch (period) {
case "P1W":
period = "7";
break;
case "P2W":
period = "14";
break;
case "P3W":
period = "21";
break;
case "P4W":
period = "28";
break;
case "P7D":
period = "7";
break;
case "P6D":
period = "6";
break;
case "P5D":
period = "5";
break;
case "P4D":
period = "4";
break;
case "P3D":
period = "3";
break;
case "P2D":
period = "2";
break;
case "P1D":
period = "1";
}
return getString(R.string.continue_with_free_trial, period);
}
```
Any suggestions on how to improve it?
Thanks!
|
2019/01/14
|
[
"https://Stackoverflow.com/questions/54187563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10567570/"
] |
java.time and ThreeTenABP
-------------------------
This exists. Consider not reinventing the wheel.
```
import org.threeten.bp.Period;
public class FormatPeriod {
public static void main(String[] args) {
String freeTrialString = "P3W";
Period freeTrial = Period.parse(freeTrialString);
String formattedPeriod = "" + freeTrial.getDays() + " days";
System.out.println(formattedPeriod);
}
}
```
This program outputs
>
> 21 days
>
>
>
You will want to add a check that the years and months are 0, or print them out too if they aren’t. Use the `getYears` and `getMonths` methods of the `Period` class.
As you can see, weeks are automatically converted to days. The `Period` class doesn’t represent weeks internally, only years, months and days. All of your example strings are supported. You can parse `P1Y` (1 year), `P1Y6M`(1 year 6 months), `P1Y2M14D` (1 year 2 months 14 days), even `P1Y5D`, `P2M`, `P1M15D`, `P35D` and of course `P3W`, etc.
Question: Can I use java.time on Android?
-----------------------------------------
Yes, java.time works nicely on older and newer Android devices. It just requires at least **Java 6**.
* In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. In this case import from `java.time` rather than `org.threeten.bp`.
* In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
* On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from `org.threeten.bp` with subpackages.
Links
-----
* [Oracle tutorial: Date Time](https://docs.oracle.com/javase/tutorial/datetime/) explaining how to use `java.time`. [Section *Period and Duration*](https://docs.oracle.com/javase/tutorial/datetime/iso/period.html).
* [Java Specification Request (JSR) 310](https://jcp.org/en/jsr/detail?id=310), where `java.time` was first described.
* [ThreeTen Backport project](http://www.threeten.org/threetenbp/), the backport of `java.time` to Java 6 and 7 (ThreeTen for JSR-310).
* [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP), Android edition of ThreeTen Backport
* [Question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project), with a very thorough explanation.
* [Wikipedia article: ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)
|
18,819,048
|
I have a static double variable in a static class. When I create a specific class, I use the double variable as one of the args of the constructor. What would be the easiest way of manipulating field of the object by changing the variable in static class.
Code for clarity:
```
public static class Vars
{
public static double Double1 = 5.0;
}
public class ClassFoo
{
public double Field1;
public ClassFoo(double number)
{
Field1 = number;
}
}
class Program
{
static void Main(string[] args)
{
ClassFoo Foo = new ClassFoo(Vars.Double1);
Console.WriteLine(Foo.Field1 + " " + Vars.Double1); //5 5
Vars.Double1 = 0.0;
Console.WriteLine(Foo.Field1 + " " + Vars.Double1); //5 0
//Foo.Field1 need to be a reference to Vars.Double1
}
}
```
EDIT that goes beyond the question (no more answers needed, other solution found):
I change some values (fields) very often (at runtime, or at least i would like to change them at runtime) to look for one that is right for me. Implementing:
```
if(KeyDown)
variable++;
if(OtherKeyDown)
variable--;
```
Wasn't convenient enough. I just checked Visual Studio Debugger. It's not good (fast) enough. Have to pause, change and run code code again. Method i presented would be good if changed static variable would change field of the object.
|
2013/09/16
|
[
"https://Stackoverflow.com/questions/18819048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679437/"
] |
In short: no, you can't do this... at least, not seamlessly.
As noted, this is generally considered to be A Bad Idea™. There is no reference encapsulation for value types, and no simple way to implement a seamless wrapper class to do it because you can't overload the assignment operators. You can use the techniques from the `Nullable<T>` type to get part-way there, but no further.
The big stumbling block is the assignment operator. For the `Nullable` type this is fine. Since it is non-referencing (new values are distinct), an implicit conversion operator is sufficient. For a referencing type you need to be able to overload the assignment operator to ensure that assignment changes the contained data instead of replacing the wrapper instance.
About the closest you can get to full reference is something like this:
```
public class Refable<T> where T : struct
{
public T Value { get; set; }
public Refable(T initial = default(T))
{
Value = initial;
}
public static implicit operator T(Refable<T> self)
{
return self.Value;
}
}
```
This will hold a value of the specific type, will automatically convert to that type where applicable (`Refable<double>` will implicitly convert to `double` when required for instance), but all assignments must be done by referencing the `Value` property.
Example usage:
```
Refable<double> rd1 = new Refable<double>(1.5);
Refable<double> rd2 = d1;
// get initial value
double d1 = rd1;
// set value to 2.5 via second reference
rd2.Value = 2.5;
// get current value
double d2 = rd1;
// Output should be: 1.5, 2.5
Console.WriteLine("{0}, {1}", d1, d2);
```
|
13,433,844
|
I've been doing C# with XNA for a year or so now, and I'm pretty comfortable with 2D games. But after some reading, I'm worried about XNA's future since it isn't supported in Windows 8 and stuff like that.
So I've been considering switching to Unity 3D? What are the benefits of Unity over XNA/C# and it is worth the move? if not, why?
I'm also open to suggestions of other languages and engines.
I'm currently going through school and considering game development as a career, so I would like something which won't die in a year or so (as far as we can tell) and will give me skills I need. Also consider that I have previous programming knowledge with C#.
Thanks, David.
|
2012/11/17
|
[
"https://Stackoverflow.com/questions/13433844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1739071/"
] |
**XNA**
XNA still works on Windows 8. The issue is that they are not supporting XNA based games in Windows 8 Modern UI. XNA still works for Windows 8 desktop games. The terminology is extremely confusing.
XNA will either get a serious overhaul when the new XBox console is released or something brand new will be designed.
**Language**
If you want to create games for Windows 8 Modern UI, such as Cut The Rope, etc, you'll need to use C++. The last time I saw C++ was the only supported language that could interop with DirectX and Windows 8 mode. All the other features of Windows 8 are available with C#.
**Unity3d**
If you want to make video games you should pick Unity3d, or an equivalent gaming engine and framework. The problem a lot of video games creators get into is trying to design yet another game engine. This has been done to the point of them becoming commodities. Focus on the game, not the engine.
Unity3d knowledge will be far more value than creating simple games with XNA. You should still understand 3D theory though.
|
11,000,975
|
I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java.
We declare a serialVersionUid as follows.
```
private static final long serialVersionUID = 1L;
```
If a static variable was not serialized then, we often face an exception during the de-serialization process.
```
java.io.InvalidClassException
```
in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class.
To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning.
Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.
|
2012/06/12
|
[
"https://Stackoverflow.com/questions/11000975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/792580/"
] |
serialVersionUID is a **special** static variable used by the serialization and deserialization process, to verify that a local class is compatible with the class used to serialize an object. It's not just a static variable as others, which are definitely not serialized.
When an object of a class is first serialized, a class descriptor containing among other things the class name and serial version UID is written to the stream. When this is deserialized, the JVM checks if the serial version UID read from the stream is the same as the one of the local class. If they're not, it doesn't even try to deserialize the object, because it knows the classes are incompatible.
|
68,317
|
I am trying to figure out head-internal relative clauses. A paper I looked at presented two versions of the same sentence, one with the head word (りんご) outside the relative clause:
>
> [皿の上にあった]**りんご**をくすねた。
>
>
>
And one version where it is inside the relative clause:
>
> [**りんご**が皿の上にあった]のをくすねた。
>
>
>
Do these two sentences mean exactly the same thing, or are there differences in nuance? When are head-internal relative clauses usually used in Japanese?
|
2019/05/17
|
[
"https://japanese.stackexchange.com/questions/68317",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/33409/"
] |
They are slightly different, if not much. The former sounds saying a fact relatively objectively.
On the other hand, the latter rather means "although an apple was on the plate, s/he stole it" and it sounds somehow accusive in the sense that it should have been there. In grammar for old Japanese, a similar form is considered a conjunction.
>
> When are head-internal relative clauses usually used in Japanese?
>
>
>
I forgot to answer to this part. Speaking of this usage of を, not specifically to "head-internal relative clause", I personally use it like a weaker version of のに in the point of paradoxical sense, mostly in the form of "…、それをさぁ~、…。". So, I think I've been using it to some degree. I personally am used to the form of HIRC with を too. But I'm not sure other native speakers share that sense.
|
29,511,677
|
I have a table which consisting of the following columns:
```
id name value
serial text text
```
And I need to remove a row with the least `id` value and `name = 'SUPPORT_EMAIL'`. How can I do that in the most optimal way? I tried:
```
DELETE FROM propertie
WHERE name = 'SUPPORT_EMAIL'
HAVING id = MIN(id)
GROUP BY name ;
```
and
```
DELETE FROM propertie
WHERE name = 'SUPPORT_EMAIL'
GROUP BY name
HAVING id = MIN(id) ;
```
But it didn't work. Of course, I can write
```
DELETE FROM propertie
WHERE id = (SELECT id
FROM propertie
WHERE name = 'SUPPORT_EMAIL' and id = (SELECT MIN(id)
FROM propertie
WHERE name = 'SUPPORT_EMAIL')
)
```
but it seems quite wierd to me.
|
2015/04/08
|
[
"https://Stackoverflow.com/questions/29511677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3663882/"
] |
Have you published the view? I'm going to guess that the SDK is running in production mode, so document retrieval will work as the document exists but for views it won't be looking in the development views as your screenshot above shows.
|
44,877,715
|
why do we need self referential object in javascript.
example
```
let a = {};
a.self = a;
```
now a property self is referring to itself and become circular object.
in nodejs when we use routing library like hapi.
the request object which we receive is circular
|
2017/07/03
|
[
"https://Stackoverflow.com/questions/44877715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5949299/"
] |
The problem came from ***malloc(total\_courses + sizeof(course\_collection))***
You only allocate array of pointer of course\_collection.
You need allocate memory for whole the *struct Course*
It should be **malloc(total\_courses \* sizeof(struct Course))**
|
38,796,482
|
Does it simply mean that I have a parameter in my 'model\_params' variable that is not in this line?
```
params.require(...).permit(...)
```
I can't find offending parameter. Is there a way to accept all parameters?
|
2016/08/05
|
[
"https://Stackoverflow.com/questions/38796482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344643/"
] |
A space is a [descendant combinator](https://www.w3.org/TR/css3-selectors/#descendant-combinators). It targets descendants, but the div is not a descendant of the button, it is a sibling.
You need to use the [adjacent sibling combinator](https://www.w3.org/TR/css3-selectors/#adjacent-sibling-combinators) instead: a plus sign.
You also need to target the links (which are descendants of `.dropcontent` so you should use a descendant combinator there) since it is those which you have set `display: none` on and not the div.
```
.dropbutton:hover + .dropcontent a {
```
|
44,105,977
|
This is what I have:
```
class encoded
{
public static void main(String[] args)
{
String s1 = "hello";
char[] ch = s1.toCharArray();
for(int i=0;i<ch.length;i++)
{
char c = (char) (((i - 'a' + 1) % 26) + 'a');
System.out.print(c);
}
}
}
```
So far I've converted the string to an array, and I've worked out how to shift, but now I'm stuck.
What I want is for the code to start at `ch[0]`, read the character, shift it one to the right (`h` to `i`) and then do the same for each character in the array until it reaches the end.
Right now, my code outputs `opqrs`. I want it to output `ifmmp`. If I replace the `int i = 0` in the `for` loop with `int i = ch[0]`, it does start at `i`, but then it just inputs `ijklmno...`
I want it to read `h`, output as `i`, read `e`, output as `f`, and so on until it reaches the end of the array.
|
2017/05/22
|
[
"https://Stackoverflow.com/questions/44105977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8046403/"
] |
You are using the loop index `i` instead of the `i`th character in your loop, which means the output of your code does not depend the input `String` (well, except for the length of the output, which is the same as the length of the input).
Change
```
char c = (char) (((i - 'a' + 1) % 26) + 'a');
```
to
```
char c = (char) (((ch[i] - 'a' + 1) % 26) + 'a');
```
|
40,428,510
|
I have a directory "FolderName" with 10,000 new files every day. Almost a half of those files are named as follows:
```
filename_yyyy-mm-dd_hh:mm
```
while the other half are named:
```
filename_yyyy-mm-dd hh:mm
```
(with space instead of underscore)
The script I'd like to set up should do the following:
Rename only the files containing a space in their name, skipping files that need no processing.
I cannot find a way to make the script efficient, I need to really skip the good half, my script tries to mv any file, and it's quite long and inefficient. Any good idea for a better design?
Thanks everybody
|
2016/11/04
|
[
"https://Stackoverflow.com/questions/40428510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5233499/"
] |
Check out the [`rename`](http://search.cpan.org/~rmbarker/File-Rename-0.06/rename.PL) utility, a Perl script designed just for this, it's powerful and fast.
```
rename -n ' ' _ *\ *
```
Or:
```
find /path/to/dir -type f -name '* *' -exec rename -n ' ' _ {} \;
```
The `-n` flag is for dry run, to print what works happen without actually renaming anything. If the output looks good, remove the flag and rerun.
|
25,440,573
|
i have created Lead Management System. i have created to type of user category as given below
1. user - Normal user of System who can see only his/her data while logged in system
2. admin - treating as manager login in which manager can see all data of user which has been register under his/her name
Function:-
i have created on function in which im checking weather logged in user is 'logged\_in\_as' as admin or user. Coder give below
```
function logged_in_as() {
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `user` WHERE `user_type` = 'admin'"), 0) == 1) ? true : false;
}
```
Query :-
Now by using this function i am trying to pull out the data according to query given below.
```
if(logged_in_as() === false) {
$sql = mysql_query("SELECT * FROM `lead_table` WHERE `created_by` = $session_user_id");
} else {
$sql = mysql_query("SELECT * FROM `lead_table`");
}
$hotelcount = mysql_num_rows($sql);
if($hotelcount > 0) {
while($row = mysql_fetch_array($sql)) {
$id = $row['customer_id'];
$pic = $row['client_name'];
$country = $row['city'];
$destination = $row['contact_person'];
$price = $row['email_id'];
$mobile = $row['mobile'];
$lead_id = $row['lead_id'];
$dynamiclist .= '<tbody>
<tr class="yahoo">
<td>' . $id . '</td>
<td>' . $pic . '</td>
<td class="hidden-phone">' . $country . '</td>
<td class="hidden-phone">' . $destination . '</td>
<td class="hidden-phone">'. $price . '</td>
<td>'. $mobile .'</td>
<td>Trident</td>
<td><a href="edit.php?mode=update&lead_id='. $lead_id .'">Edit</a> / <a href="updatelead.php?lead_id='. $lead_id .'">Update</a></td>
</tr>
</tbody>';
}
} else {
$dynamiclist = 'We Do Not Have Any Hotel Listed in This City';
}
```
Error:-
When i am logged in as 'user' query is returning only the data which has been entered by the user but when i am logged in as admin query is not returning any data which has been entered by register user under that admin.
Please Help !!!
|
2014/08/22
|
[
"https://Stackoverflow.com/questions/25440573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3270076/"
] |
Check whether logged\_in\_as() returns the proper bool value. Maybe u have a bug in that function and it always returns false.
Since it is false, it will return all the leads entered by that user (i.e. admin), and since admin has not entered any data, it shows blank.
This is only a guess. It should work otherwise, your code is apparently OK.
Let me know what returns by the logged\_in\_as() function for further support.
|
42,014,274
|
Haven't seen a solution similar enough to this yet...
I have two files each containing a list of file names. There are overlap in the contents of the files but file A contain some file names that are not in file B. Also, the file extensions are different in files A and B. That is:
```
A B
------------ --------------
file-1-2.txt file-1-2.png
file-2-3.txt file-3-4.png
file-3-4.txt
...
```
How do I combine the two files, comma-delimited, into one ignoring lines that don't match?
That is:
```
C
------------
file-1-2.txt,file-1-2.png
file-3-4.txt,file-3-4.png
```
I believe some usage of `awk` similar to the following will work:
```
awk 'FNR==NR{NOT SURE} {print $1,$2}' fileA fileB
```
Thanks in advance!
|
2017/02/02
|
[
"https://Stackoverflow.com/questions/42014274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3741624/"
] |
This pure bash solution should work and handle dots, backslashes, dashes, and other special characters in either file.
```
mapfile -t arr_a < A
mapfile -t arr_b < B
for a in "${arr_a[@]}"; do for b in "${arr_b[@]}"; do
[[ ${a%.*} == "${b%.*}" ]] && printf '%s,%s\n' "$a" "$b" && break
done; done
```
First, we read the contents of the files into arrays, one line per item, using `mapfile`. 1 Then, for each line in `A`, we compare to each line in `B`.
To compare only the portion before the extension, we use the shell parameter expansion `${var%pattern}`, which removes the shortest match of the glob `.*`2 from the end of the filenames.
1The -t option strips the trailing newline from the array items.
2The `.` here is literal, removing a period and everything after.
|
8,797,791
|
I'm trying to run a simple `test\spec` but getting an error. Error is only happening when the tests fail.
```
begin
require 'rubygems'
require 'test/spec'
rescue LoadError
puts "==> you need test/spec to run tests. {sudo gem install test-spec}"
end
context "Foo" do
specify "should bar" do
"ttes".should.equal "tes"
end
end
```
>
> 1) Error: test\_spec {Foo} 001 should bar: NoMethodError:
> undefined method `ascii_compatible?' for #<Encoding:US-ASCII>
> person.rb:11:in`block (2 levels) in '
>
>
>
|
2012/01/10
|
[
"https://Stackoverflow.com/questions/8797791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44286/"
] |
I can only guess, but there is something very strange going on here. Are you mixing Ruby versions or something? Are you using a gem that's not compatible with your version of Ruby? Every encoding instance should respond to [`ascii_compatible?`](http://apidock.com/ruby/Encoding/ascii_compatible%3F) in Ruby 1.9, so maybe you are using 1.8 (as you seem to be on Windows, this seems likely).
Also, a full stack trace will be of great help (you can catch the exception with `begin`/`rescue` and call [`backtrace`](http://apidock.com/ruby/Exception/backtrace) on it. That way you will find out which exact line of the `test-spec` module fails.
Also, *test-spec* doesn't seem to be a very actively developed Gem. Maybe an option is to use [*RSpec*](https://www.relishapp.com/rspec) instead, a more widely used tool with the same purpose.
|
48,073,506
|
I did a lot of research on the web, but did not find a documentation of the composer error log. In the discussions I found, nobody had an explanation that was consistent with the error log. For example:
* [[Support] Need explanation for "Conclusion: don't install ..."](https://github.com/composer/composer/issues/2702)
* [Why composer says "Conclusion: don't install" when (seemingly) no obstacles are present?](https://stackoverflow.com/q/45009772)
I know, what composer does and can resolve issues on my own, but I often have to consult packagist.org for this. Despite being quite (and unnecessarily) verbose, the composer log only gives me some hints. It does not really point out the concrete problems.
Does anyone know of a complete documentation or how to explain the reasoning behind the logs, maybe taking the above ones as an example?
|
2018/01/03
|
[
"https://Stackoverflow.com/questions/48073506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486218/"
] |
Documentation of Composer can be found at [getcomposer.org/doc](https://getcomposer.org/doc/), especially [Troubleshooting](https://getcomposer.org/doc/articles/troubleshooting.md) section. Usually the dependency problems comes from misconfiguration of your `composer.json` and understanding Composer logs comes with experience or learning on trial and error. Documenting every possible errors out of hundreds can become quickly outdated. If you believe some specific error isn't clear enough, you can always raise a [new suggestion](https://github.com/composer/composer/issues) at the [Composer's GitHub page](https://github.com/composer/composer).
As suggested in linked [GitHub issue](https://github.com/composer/composer/issues/2702), "Conclusion: don't install" message it could be related to requirements defined in [`minimum-stability`](https://getcomposer.org/doc/04-schema.md#minimum-stability). Another [linked question](https://stackoverflow.com/q/45009772/55075) could be related to Composer's bug as reported at [GH-7215](https://github.com/composer/composer/issues/7215).
### Errors
Here is a small guide explaining the common Composer's errors:
* >
> **Can only install one** of: org/package[x.y.z, X.Y.Z].
>
>
>
If you see this messages, that could be the main cause of the dependency issue. It basically means that based on the Composer's dependency calculation both of these versions are required, but only one major version can be installed (you cannot have both x.y.z and X.Y.Z, unless you split your configuration for different folders). To see `why` these packages are required, use the `composer why`/`depends` command and adjust the dependencies accordingly.
See: [How to resolve a "Can only install one of:" conflict?](https://stackoverflow.com/q/36611550/55075) & [How to solve two packages requirements conflicts when running composer install?](https://stackoverflow.com/q/21052831/55075)
* >
> Installation request for org/package2 (**locked at** vX.Y.Z)
>
>
>
This message means that there was an installation request for org/package, however, it is locked at X.Y.Z. If the requested version is not compatible with the locked version (like a different major version), you cannot install both. This message often comes along with already mentioned "Can only install one" one. So, whenever you see "locked at", that means Composer reads your installed package version from the `composer.lock` file. To troubleshoot, you can use `composer why`/`depends` command to find why the package was requested and adjust the compatibility, otherwise, you may try to remove `composer.lock` file and start from scratch (ideally from the empty folder).
See: [Installation failed for laravel/lumen-installer: guzzlehttp/guzzle locked at 6.3.0](https://stackoverflow.com/q/48427886/55075)
* >
> org/package1 vx.y.z **conflicts** with org/package2[vX.Y.Z].
>
>
>
It is a similar issue as above where two packages are conflicting and you need to solve the dependency manually. Reading the whole context of the message may give you some more clues. Checking the dependency tree may also help (`composer show -t`).
* >
> conflict with your requirements or **`minimum-stability`**
>
>
>
This message means as it reads, so you should check the required version and/or your `minimum-stability` settings.
This can be caused by a package being marked as non-stable and your requirements being "stable only. See: [But these conflict with your requirements or minimum-stability](https://stackoverflow.com/q/40453388/55075)
Or because of conflicts with other installed packages. See: [How to identify what is preventing Composer from installing latest version of a package?](https://stackoverflow.com/q/45386572/1426539).
For any other errors, check out the official **[Composer's Troubleshooting page](https://getcomposer.org/doc/articles/troubleshooting.md)**.
### Troubleshooting
Here are more suggestions how to troubleshoot the Composer dependency issues in general:
* Add `-v`/`-vv`/`-vvv` parameter to your command for more verbose output.
* Run `composer diagnose` to check for common errors to help debugging problems.
* If you seeing "locked at x.y.z" messages, it relates to packages locked in your `composer.lock`.
* Test your `composer.json` on the empty folder.
* Keep your `composer.json` to minimum.
* Run `composer show -t` to see your current dependency tree.
* Run `composer show -a org/package x.y.z` to check the details about the package.
* Feel free to ask a new question at *Stack Overflow*.
To fully debug Composer's dependency problem, you can:
* Analyse or modify the source code (e.g. [`DependencyResolver/Problem.php`](https://github.com/composer/composer/blob/master/src/Composer/DependencyResolver/Problem.php)).
* Run Composer under [XDebug](https://xdebug.org/), either by the breakpoint or generating a full or partial trace file.
---
Useful threads explaining common errors:
* [How to resolve a "Can only install one of:" conflict?](https://stackoverflow.com/q/36611550/55075)
* [composer.json fails to resolve installable set of package](https://stackoverflow.com/q/16672993/55075)
* [Discover latest versions of Composer packages when dependencies are locked](https://stackoverflow.com/q/30277015/55075)
* [When trying to install php-jwt facing trouble with auth0](https://stackoverflow.com/q/42532831/55075)
* [Reference - Composer error "Your PHP version does not satisfy requirements" after upgrading PHP](https://stackoverflow.com/q/66368196/)
* [How to identify what is preventing Composer from installing latest version of a package?](https://stackoverflow.com/q/45386572/1426539)
|
35,661,088
|
I am new to bootstrap and I am attempting to learn the basics. However, I have put a color background for the div and it is only appears when I have resize the browser. Here is my code:
```
<html>
<body>
<div id="header">
<div class="col-md-8"><img src="images/logo.png"></div>
<div class="col-md-4">
<br />
<br />
<p>
<a href="#">HOME</a>
<a href="#">SERVICES</a>
<a href="#">NEWS</a>
<a href="#">CAREERS</a>
<a href="#">CONTACT</a>
</p>
</div>
</div>
</body>
</html>
.container {
margin:0px;
padding:0px;
}
#header{
background-color:#e4e4e4;
}
```
Thank you in advance.
|
2016/02/26
|
[
"https://Stackoverflow.com/questions/35661088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5335546/"
] |
You might want to try something like this. You will have to replace the hard coded elements...
```js
var fruits = ["Apple", "Banana"];
var tempString = "Pie,Dumpling,Cider";
var tempArray = new Array();
tempArray.push(tempString);
tempString = "Bread,Republic";
tempArray.push(tempString);
var output = {};
for (var i = 0; i < fruits.length; i++)
{
var members = tempArray[i].split(",");
var temp = {};
for(var k = 0; k < members.length; k++)
{
temp[("" + k)] = members[k];
}
output[("" + fruits[i])] = temp;
}
console.log(output);
//Different ways to access the objects
console.log(output.Apple);
console.log(output["Apple"]);
console.log(output.Banana[0]);
console.log(output["Banana"]["0"]);
```
[](https://i.stack.imgur.com/zS7gB.png)
|
40,378
|
I am performing 10-folds cross-validation to evaluate the performances of a series of models (variable selection + regression) with R. I created manually the folds with this [code](https://stats.stackexchange.com/questions/61090/how-to-split-a-data-set-to-do-10-fold-cross-validation).
At the moment I'm performing first variable selection, then hyperparameters tuning through cv, and finally testing the performance with RMSE and MAE for all the models, but I have a doubt.
Is it correct to "use" the same fold for all the models? Or should I do a separate cv for each model?
|
2018/10/29
|
[
"https://datascience.stackexchange.com/questions/40378",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/56923/"
] |
I recommend trying both (more than once), and exploring any differences. In my experience, using the same set of folds for all models or using a new set of folds for each model doesn't make any material difference. Post if you find different!
Regarding "I'm performing first variable selection, then hyperparameters tuning through cv", maybe watch <https://www.youtube.com/watch?reload=9&v=S06JpVoNaA0> to be sure you are not introducing any bias.
|
26,231,939
|
I am learning Laravel as my first framework, I saw, they have own syntax for create forms eg:
Laravel Inputs:
```
{{ Form::text('email', '', array('placeholder' => 'Email')) }}
{{ Form::password('password', array('placeholder' => 'Password')) }}
{{ Form::submit('Login', array('class' => 'btn btn-success')) }}
```
HTML Inputs:
```
<input type="text" name="email" placeholder="Email"/>
<input type="password" name="password" placeholder="Password"/>
<input type="submit" name="submit" value="Login" class="btn btn-success"/>
```
what are the advantages, I can get, if i use Laravel syntax for create forms? thank you
|
2014/10/07
|
[
"https://Stackoverflow.com/questions/26231939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3099298/"
] |
There are many advantages of using the Laravel syntax.
1. The Laravel Form automatically adds CSRF protection .
2. You can autofill form easily using the Form::model() instead of the plain PHP.
3. Your code remains clean and consistent and is not filled with a mix of HTML and PHP
4. It gives extensibility i.e others can dynamically insert form elements.
This is useful only if you are building a software for others to use.
|
908,077
|
I'm looking at the PayPal `IPN docs`, and it says the `datetime` stamps of their strings are formatted as:
```
HH:MM:SS DD Mmm YY, YYYY PST
```
So year is specified twice?
Once in double digits, and another with 4 digits?
This looks bizarre.
|
2009/05/25
|
[
"https://Stackoverflow.com/questions/908077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73398/"
] |
This seems to be a bug in the documentation. The actual format should be "HH:MM:SS Mmm DD, YYYY PST" (e.g. "08:30:06 Apr 19, 2017 PDT")
|
63,770,877
|
I am working on SQL Server and I have two tables TableMaster and TableValidator. They both share 5 columns but no IDs. I need to find in TableValidator all those records that are not on the TableMaster to eventually insert them into TableMaster. If the values of all those 5 columns are identical on both then that is the same record.
For example:
TableMaster
```
JobCode | Location | Code1 | Code2 | Code3 | Other column...
>100333 USA A112 TR 0057
100987 TAR A112 TR 0098
>220999 PUR R100 LK 0098
...
```
TableValidator
```
JobCode | Location | Code1 | Code2 | Code3 | Other column...
100333 USA A100 NS 0057
100987 TAR A112 TR 0098
>220999 PUR R100 LK 0098
220999 PUR R100 LK 1009
220999 PUR R100 LK 3305
>100333 USA A112 TR 0057
...
```
As you can see in this tables only two records are identical. I need to identify those on TableValidator that are not on the TableMaster in order to insert them back into TableMaster.
|
2020/09/07
|
[
"https://Stackoverflow.com/questions/63770877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6273079/"
] |
You can simply use `NOT EXISTS()` as
```
INSERT INTO MasterTable (JobCode, Location, Code1, Code2, Code3)
SELECT JobCode, Location, Code1, Code2, Code3
FROM ValidatorTable VT
WHERE NOT EXISTS(
SELECT 1
FROM MasterTable MT
WHERE VT.JobCode = MT.JobCode
AND VT.Location = MT.Location
AND VT.Code1 = MT.Code1
AND VT.Code2 = MT.Code2
AND VT.Code3 = MT.Code3
);
```
Here is a `[db-fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=cd10b487e1916af8a0ae344ff5a699c0)`
|
1,736,287
|
With Windows Presentation Foundation, if I have an HWND, how can I capture it's window as an image that I can manipulate and display?
|
2009/11/15
|
[
"https://Stackoverflow.com/questions/1736287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76322/"
] |
You can:
1. `CreateBitmap()` to create a hBitmap
2. Call `GetDC()` on the hWnd
3. `BitBlt()` the contents to the hBitmap
4. `ReleaseDC()`
5. Call `Imaging.CreateBitmapSourceFromHBitmap()` to create a managed `BitmapSource`
6. `DeleteObject()` on the hBitmap
7. Use the `BitmapSource` as desired
Steps 1-4 and 6 use the Win32 API (GDI to be precise), Steps 5 and 7 are done using WPF
|
399,464
|
I'm often creating PDF files from web pages in MacOS X (10.6) and very often I have the problem that the automatically proposed file name (based on the name of the web page) contains many special characters.
So I wonder: is there an easy way (apple script, shell script, OS X service) which takes a string (like this file name) and converts it by
* removing all spaces and other special characters (also those which might be allowed in OS X, but forbidden in Windows or Linux!! as I'm often transferring files to our PC)
* maybe starting each word (after a removed space) with an uppercase letter
* ... what else could be important?
I'm using Quicksilver, so maybe it could be possible to create a command which makes it possible to replace the current text selection (in the file save as... dialog) by a converted string.
|
2012/03/11
|
[
"https://superuser.com/questions/399464",
"https://superuser.com",
"https://superuser.com/users/92184/"
] |
You can create an Automator service to do this in all applications that support services (which is almost all of them).
---
Open Automator and select to create a *Service* that receives *selected text* in *any application* and check *Output replaces selected text*.
Add a single *Run Shell Script* action from the library, and paste the following script code:
```
sed 's|[^a-zA-Z0-9]||g'
```
This specific script, a simple `sed` substitution will remove all non alpha-numeric characters from the file name. It uses `a-zA-Z0-9` as a whitelist of allowed characters, add to it as desired.
You can do other actions as well, and chain them together. For example, `tr [A-Z] [a-z]` will lowercase everything, and `sed 's|[^a-zA-Z0-9]||g' | tr [A-Z] [a-z]` will combine the two.
Save as e.g. *Sanitize Filename*, and optionally assign a keyboard shortcut in *System Preferences » Keyboard » Keyboard Shortcuts » Services*. You should be able to invoke services using Quicksilver as well, just type their name.
---
Whenever you're in a *Save as…* or similar dialog, select the suggested file name (it's selected by default):

Invoke the service *Program Menu » Services » Sanitize Filename* (or use the keyboard shortcut you invoked). It will pipe the file name through the script, and use its output to replace the selection.

---
For title-casing and removing bad characters (I also keep underscore, dot and hyphen in), the following script code seems to mostly work for me:
```
perl -ane 'foreach $wrd(@F){print ucfirst($wrd)." ";}' | sed 's|[^a-zA-Z0-9_.-]||g'
```

|
155,161
|
I noticed that there are a list of Platforms/Vendors for which a CVE can be applied for.
What happens if I find a CVE for a proprietary platform (that is commercially available), is there a way to get a CVE assigned for it?
|
2017/03/28
|
[
"https://security.stackexchange.com/questions/155161",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/12253/"
] |
Different vendors require different steps to be taken in order to get a CVE ID assigned for vulnerabilities.
If you check [the MITRE CVE ID Request page here](https://cve.mitre.org/cve/request_id.html) then you can follow the instructions to request an ID after locating the correct CVE Numbering Authority.
If the vendor is not specifically mentioned in any of the tables and a relevant CNA is not listed then you have to contact MITRE directly to request a CVE ID by [filling out the form here](https://cveform.mitre.org/).
|
2,382,723
|
I have been looking at the definition of a 'branch' of a complex function. The typical definition I am getting is as follows:
>
> ...branches $f\_1(z)$, $f\_2(z)$, $...$ of $f(z)$ each defined as a single-valued continuous function throughout its range of definition. Each branch assumes one set of the function values of $f(z)$. (Korn & Korn, 2013; pg 193)
>
>
>
(a similar definition is given [here](http://mathworld.wolfram.com/Branch.html))
The problem with these definition is that there is an ambiguity of what we call a branch, and by these definitions we should have an infinite number. e.g. we could have a branch defined for $0\le \theta \lt 2\pi$ and another for $0.001\le \theta \lt 2\pi+0.001$.
My question is; is their a name for the set of branches $f\_i$ such that they don't overlap in this way?
|
2017/08/04
|
[
"https://math.stackexchange.com/questions/2382723",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/203397/"
] |
Let $f:U\to \mathbb C$ and $g:V\to\mathbb C$ be analytic on connected open sets $U,V$. They are branches of the same function if there is a sequence of open connected subsets, $U=W\_1,W\_2,\dots,V=W\_n$ and analytic functions $f\_i:W\_i\to \mathbb C$ such that $f\_1=f,f\_n=g$ and $W\_{i}\cap W\_{i+1}$ is non-empty, and $f\_{i}(x)=f\_{i+1}(x)$ for all $x\in W\_{i}\cap W\_{i+1}$.
So, it can be seen as the transitive closure of the relationship on analytic functions $f,g$ defined by:
>
> $fRg$ iff $\mathrm{domain }(f) \cap\mathrm{domain}(g)\neq \emptyset$ and $f(x)=g(x)$ for all $x\in \mathrm{domain }(f) \cap\mathrm{domain}(g)$.
>
>
>
You can use this set to define something called the Riemann manifold of a function, $f$.
Given analytic $f$, we take $X$ to be the set of all pairs $(g,x)$ where $g$ is a branch of $f$ and $x\in\mathrm{domain}(g)$. We define a relationship $(g\_1,x)\sim (g\_2,y)$ if $x=y$ and $g\_1(z)=g\_2(z)$ for all $x$ where both are defined.
Then $M=X/\sim$ is the Riemann manifold of $f$.
Then there is a natural map $M\to\mathbb C$ defined as $(g,x)\mapsto x$, and the function $(g,x)\mapsto g(x)$ which is the "lift" of $f$ from $\mathbb C$ to $M$.
|
43,853,743
|
I need to sum all digits in a given string. So for I've got this
```
public static void main(String[] args) {
Scanner odczyt = new Scanner(System.in);
System.out.println("Input string");
String ciag = odczyt.nextLine();
int suma = 0;
for (int i = 0; i < ciag.length(); i++) {
if (Character.isDigit(ciag.charAt(i))) {
suma += ciag.charAt(i);
}
}
System.out.println(suma);
}
```
When I input:
>
> "Ala got 3 apples and 1 orange"
>
>
>
the output is 100 instead of 4. What should I change to make it count only digits?
|
2017/05/08
|
[
"https://Stackoverflow.com/questions/43853743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7981922/"
] |
The problem occurs here:
```
suma += ciag.charAt(i);
```
you're adding the character code rather than the digit itself.
change it to this:
```
suma += Integer.parseInt(ciag.charAt(i)+"");
```
|
18,286,184
|
I've run into a problem in my application's code and I would like to know the best way to handle it: I have a function that applies 5 values on callback and I would like to know the best way to use it.
Here is my function code :
```
var someFunc = function(callback) {
var http = require('http');
var id;
var url = 'http://somesite.com/json';
// First request to get an array of 5 elements
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var jsonResult = JSON.parse(body);
// 5 requests with a value from each of the 5 elements
for (var i=0;i<5;i++)
{
(function(idx) {
gameId = jsonResult.gameList[idx].id;
url = 'http://somesite.com' + id + '/token';
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
jsonRes = JSON.parse(body);
callback.apply(null, [idx, jsonRes.interestScore]);
});
}).on('error', function(e) {
console.log("Got error: ", e);
});
})(i);
}
});
}).on('error', function(e) {
console.log("Got error: ", e);
});
};
exports.someFunc = someFunc;
```
When I call the function to retrieve the 5 values I do it like this :
```
exports.featured = function(req, res){
getSome.someFunc(function callback(result) {
var variables = {};
var variableName = result;
variables[variableName] = jsonRes.interestScore;
res.render('featured', { score0: variables[0], score1: variables[1], score2: variables[2], score3: variables[3], score4: variables[4] });
});
};
```
Unfortunately 'res.render' is called after the function retrieved only 1 value, so I want to know how to do it proprely, or make a proper callback.
Thanks.
|
2013/08/17
|
[
"https://Stackoverflow.com/questions/18286184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2663041/"
] |
The first problem which I'm seeing is that you are assigning listener for the *end* event five times. You should do that only once. You can collect the result five times and after that call the callback. Here is an example which uses request module:
```
var request = require('request');
var makeRequests = function(callback) {
var result = [],
done = 0;
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
// read the body here
var searchFor = [
'nodejs', // 1
'http request', // 2
'npm', // 3
'express', // 4
'javascript' // 5
];
for(var i=0; keyword = searchFor[i]; i++) {
request('https://www.google.bg/search?q=' + keyword, function (error, response, body) {
if (!error && response.statusCode == 200) {
result.push(body);
++done;
if(done == searchFor.length) {
callback(result);
}
}
});
}
}
});
}
makeRequests(function(result) {
console.log("result=" + result.length);
})
```
|
65,340,738
|
I am creating an Input Dialog using kivymd. Whenever I try to fetch the text from the text field, it doesn't output the text, rather it seems like the text is not there. (the dialog just pops up ok and the buttons are working fine).
part of the kivy code
=====================
```
<Content>
MDTextField:
id: pin
pos_hint: {"center_x": 0.5, "center_y": 0.5}
color_mode: 'custom'
line_color_focus: [0,0,1,1]
```
part of the python code
=======================
```py
class Content(FloatLayout):
pass
class MenuScreen(Screen):
def __init__(self, **kwargs):
super(MenuScreen, self).__init__(**kwargs)
def show_confirmation_dialog(self):
# if not self.dialog:
self.dialog = MDDialog(
title="Enter Pin",
type="custom",
content_cls=Content(),
buttons=[
MDFlatButton(
text="cancel",on_release=self.callback
),
MDRaisedButton(
text="[b]ok[/b]",
on_release=self.ok,
markup=True,
),
],
size_hint_x=0.7,
auto_dismiss=False,
)
self.dialog.open()
def callback(self, *args):
self.dialog.dismiss()
def ok(self, *args):
pin = Content().ids.pin.text
if pin == "":
toast("enter pin")
else:
toast(f"pin is {pin}")
```
|
2020/12/17
|
[
"https://Stackoverflow.com/questions/65340738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14284845/"
] |
Go to your Canvas and change the **Render Mode** from **Screen Space-Overlay** to **Screen Space-Camera**. I think that should fix your problem.
|
13,714,517
|
I'm not the best at php coding, just learning it. But i was wondering why I keep getting a variable passed to each() is not an array or object warning. I know there is a similar thread that I had used for this code but that post was not resolved so I am hoping it can be the error is one line 46 where it states -
>
> while(list($key,$val) = each($\_POST['checkbox'])) {
>
>
>
the whole code is
```
<?php
$host = 'localhost'; // Host name
$username = 'root'; // Mysql username
$password = ''; // Mysql password
$db_name = 'forms'; // Database name
$tbl_name = 'members'; // Table name
// Connect to server and select databse.
mysql_connect($host, $username, $password) or die('cannot connect');
mysql_select_db($db_name) or die('cannot select DB');
$sql = 'SELECT * FROM `'.$tbl_name.'`';
$result = mysql_query($sql);?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td>
</tr>
<?php while ($rows = mysql_fetch_array($result)): ?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="need_delete[<? echo $rows['id']; ?>]" type="checkbox" id="checkbox[<? echo $rows['id']; ?>]" value="<? echo $rows['id']; ?>"></td>
<td bgcolor="#FFFFFF"><? echo $rows['Member ID']; ?></td>
<td bgcolor="#FFFFFF"><? echo htmlspecialchars($rows['firstname']); ?></td>
<td bgcolor="#FFFFFF"><? echo htmlspecialchars($rows['lastname']); ?></td>
</tr>
<?php endwhile; ?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
<?php
// Check if delete button active, start this
if ($_POST['delete']) {
$i = 0;
while(list($key,$val) = each($_POST['checkbox'])) {
$sql = "DELETE FROM $tbl_name WHERE id= '$val'";
mysql_query($sql);
$i += mysql_affected_rows();
}
if($i > 0){
echo '<meta http-equiv="refresh" content="0;URL=delete_member3.php">';
}
}
mysql_close();
?>
</table>
</form>
</td>
</tr>
```
Please help me resolve this.
|
2012/12/05
|
[
"https://Stackoverflow.com/questions/13714517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874551/"
] |
`Reducer` is apparently typed as `<A, B, C, D>`. Just because A and C happen to be provided by the same type doesn't make it impossible (and should work in C# as far as I know).
Edit: to clarify -- you can have a method with more than one parameter of the same type: `public void foo(String a, String b)`. One wouldn't say this was ambiguous. Generic types are parameters on the class, and can be used in a similar fashion. Think of a `Map<String, String>` -- you may have one String that represents an ID pointing to another String as a username.
|
3,207,385
|
I came across this question in one of the linear algebra textbooks:
Proof the linear independence of the following set $\{f\_i ∣ i\in\mathbb{N}\}$, such that $f\_i : \mathbb{N}\to\mathbb{Q}$ defined as follows:
For $n\in\mathbb{N}$, $$f\_i (n) =
\begin{cases}
-n & \text{for }n \geq i \\
0 & \text{for }n < i \end{cases} $$
What would be an appropriate approach to check the independence of this infinite set? I thought long about it but was unable to come up with anything.
Any help would be appreciated.
Thanks!
|
2019/04/29
|
[
"https://math.stackexchange.com/questions/3207385",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/669697/"
] |
View each function as an infinite vector
$$v\_i = \left( \begin{array}{c} f\_i (1)\\ f\_i (2) \\ f\_i (3)\\ \vdots \end{array}\right) = \left( \begin{array}{c} 0\\0\\\vdots\\0\\-i\\ -i-1\\-i-2\\\vdots\end{array}\right)$$
in $\prod\_{n\in\mathbb{N}}\mathbb{N} $, and show that the $v\_i $ are linearly independent (this is more natural way to view it in my opinion). For example, for $i=5$, $v\_i = (0,0,0,0,-5,-6,-7,...)$
Then to check linear Independence, we check that the following is true only when all coefficients $a\_i $ are zero:
$$ \sum\_{i\geq 1} a\_i v\_i = \left( \begin{array}{c}
-a\_1 \\
-2(a\_1 + a\_2) \\
-3 (a\_1 + a\_2 + a\_3) \\
\vdots
\end{array}\right)
=
\left( \begin{array}{c} 0 \\ 0 \\ 0 \\ \vdots \end{array}\right)$$
But that's clear, since if we solve for the first entry we get $a\_1 = 0$. Substituting that into the next entry we get $a\_2 = 0$. Continuing to infinity, we see that $$ a\_i = 0 \qquad \mbox{ for all } i\geq 1$$
|
60,617,513
|
The company I work for wants a file uploader. The file uploader not only has to upload files, but it also has to prevent certain files from being uploaded. The company contracted another company to build this site. I am a Mobile Developer learning Angular. How do I prevent certain files from being uploaded?
Here is a copy of the HTML file.
```html
<div [hidden]="documentation.get('uploadMethod').value !== 'upload'">
<div ng2FileDrop [uploader]="uploader">
<span [hidden]="uploader.queue.length > 0 || (documentation.controls['fileUpload'].errors?.required && documentation.controls['fileUpload'].touched)">Drag Files Here</span><br>
<table>
<tbody>
<tr *ngFor="let item of uploader.queue">
<td>{{item.file.name}}</td>
<td>
{{item.file.size / 1024 >= 1000 ? (item.file.size / 1024 / 1024).toFixed(2) : (item.file.size / 1024).toFixed(2)}}
{{item.file.size / 1000 >= 1000 ? 'mb' : 'kb'}}</td>
<td>
<button mat-raised-button (click)="removeItem(item)">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<button mat-button (click)="saveDocumentation()">Upload all</button>
<button mat-button (click)="removeAll()">Remove all</button>
<div
[hidden]="uploader.progress < 1 || !(uploader.progress <= 100 && uploader.progress >= 0)">
<div>{{uploader.progress}}</div>
</div>
</div>
</div>
```
|
2020/03/10
|
[
"https://Stackoverflow.com/questions/60617513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951977/"
] |
You need to use the accept attribute of HTML element. You will pass a string of comma separated file types.
```
<input type="file" id="profile_pic" name="profile_pic"
accept=".jpg, .jpeg, .png">
```
Use this for the accept attribute guide - <https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept>
And for ngng2FileDrop (Credit goes to Z. Bagley)
```
<div ng2FileDrop [uploader]="uploader"
[ng2FileDropSupportedFileTypes]="supportedFileTypes">
</div>
```
where supportedFileTypes is an array of file types.
Documentation link - <https://github.com/leewinder/ng2-file-drop>
|
56,542,236
|
Here is my problem. I've built the following `ListView`
```
<ListView Grid.Row="1" x:Name="messageList" BorderThickness="0"
ItemsSource="{Binding MySource}"
HorizontalContentAlignment="Stretch">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="5*"/>
</Grid.ColumnDefinitions>
<WrapPanel Grid.Row="0" Grid.Column="0">
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Received.SenderId}"
/>
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Received.DeliverDate}"
/>
</WrapPanel>
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Received.MsgText}"
Grid.Row="1" Grid.Column="0"
TextWrapping="WrapWithOverflow">
</TextBlock>
<WrapPanel Grid.Row="0" Grid.Column="1">
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Sent.SenderId}"
/>
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Sent.DeliverDate}"
/>
</WrapPanel>
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Sent.MsgText}"
Grid.Row="1" Grid.Column="1"
TextWrapping="WrapWithOverflow">
</TextBlock>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
```
For each element of `MySource` only 1 between Received and Sent will be not null. The `ListView`is working as i expect, placing the element on the left or the right of the screen, but the `TextBlock` that contain the `MsgText` get all the available space (so the whole row) if the message is too long. How can i limit it to stay only in one half of the parent Grid and make the text overflow eventually?
**EDIT**: I added an image showing my problem. The 4th message should overflow, but it doesn't
[](https://i.stack.imgur.com/wLqO7.jpg)
|
2019/06/11
|
[
"https://Stackoverflow.com/questions/56542236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6474054/"
] |
It took me few minutes to produce [mcve](https://stackoverflow.com/help/minimal-reproducible-example), but the missing part of the puzzle is this:
```
<Grid MaxWidth="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}">
```
That would limit maximum width of all `Grid`s (each item has one) and let wrapping happens. Otherwise `Grid` is [asking](https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/layout#measuring-and-arranging-children) for a width to fit whole item in one line and `ListView` is ok with it, but then you will see horizontal scrollbar (the most hated control by users including me).
---
MCVE:
```
public partial class MainWindow : Window
{
public class Item
{
public string Received { get; set; }
public string Sent { get; set; }
}
public List<Item> Items { get; }
public MainWindow()
{
InitializeComponent();
Items = new List<Item>
{
new Item { Received = "1111 111 11 111 11 1" },
new Item { Received = "2222 2 22 2 2 222222222 2 222222 22222222 222222222222 2" },
new Item { Sent = "333333333 3333333 333 33333 3 3 33 333333333 3333" },
new Item { Received = "444444444444444 444 44444444444444 44 4 44444444444444444 4 4 4444444444 4 444 444444444444" },
};
DataContext = this;
}
}
```
Screenshot:
[](https://i.stack.imgur.com/LeZkl.png)
Xaml:
```
<ListView ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid MaxWidth="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Received}"
TextWrapping="WrapWithOverflow" />
<TextBlock Grid.Column="1"
Text="{Binding Sent}"
TextWrapping="WrapWithOverflow" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment"
Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
```
|
6,008,304
|
I am using lua to administrate a firewall server and want to obfuscate sensible variables such as login data. I have tried luac but the variable content is still easily readable. Is there any way to encrypt/decrypt these sensible data?
|
2011/05/15
|
[
"https://Stackoverflow.com/questions/6008304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752297/"
] |
I'm assuming you have a lua script which contains both the commands to send as well as any "secret data", and you want to be able to run this script without having to type in anything interactively.
If so, the script itself must be able to decrypt your secret data in order to use it - and if an attacker can read the script, he can do the same steps to decrypt your data (or run it in a debugger or similar). Thus, it is impossible to **really** hide the secret data in your script. Use your systems file permissions to ensure nobody but you and the process that executes it can read the script.
That said, if you do not want to hinder real attackers, but only want to avoid casual lookers reading the password, any encoding scheme will do - from simple Rot13 over Base64 to hex-encoding. But you should be conscious that this is not a security measure.
|
14,814,658
|
I have a string:
`The disk 'virtual memory' also known as 'Virtual Memory' has exceeded the maximum utilization threshold of 95 Percent.`
I need to search every time in this string word `The disk` and if found then I need to extract only phrase in `'*' also known as '*'` and put it in a variable `MONITOR`
In other words I want to search and put the value to
```
MONITOR="'virtual memory' also known as Virtual Memory'"
```
How can I do it using `awk`?
|
2013/02/11
|
[
"https://Stackoverflow.com/questions/14814658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2061705/"
] |
Here's a snippet that does what you describe. You should put it in `$(...)` to assign it to the $MONITOR variable:
```
$ awk '/The disk '\''.*'\'' also known as '\''.*'\'' has exceeded/ {gsub(/The disk /,"");gsub(/ has exceeded.*$/,"");print}' input.txt
```
The two problems with awk in this case is
* it doesn't have submatch extraction on its regexes (which is why my solution uses `gsub()` in the body to get rid of the first and last part of the line.
* To use the quotes in your awk regex in a shell script you need the `'\''` sequence to scape it (more info [here](https://stackoverflow.com/questions/9899001/how-to-escape-single-quote-in-awk-inside-printf))
|
46,523,857
|
[](https://i.stack.imgur.com/fmk8w.jpg)
I open the `Message-Fragment` from `Activity-A` and then open the `Camera-Fragment` from `Message-Fragment`. Now current fragment is `Camera-Fragment` and i have media-slider on it. Now I have two options, one is `ImagePreview-Fragment` that is opened if I click the image item on media-slider. Other is `VideoPreview-Activity` that is opened if click the video item on media-slider. So there is one condition of clicking video-item. If I click the video-item on media-slider and video size is bigger than 10 MB, I open the `VideoTrim-Activity` and when trim is completed i call the `VideoPreview-Activity`.
I'm sending a media from `VideoPreview-Activity` or `ImagePreview-Fragment`. So when I send the media I want to return back to the `Message-Fragment` with data.
How can I return back to `Message-Fragment` from `VideoPreview-Activity` (opened from Camera-Fragment) and `VideoPreview-Activity` (opened from `VideoTrim-Activity`). Also if you can help me about how to return back from `ImagePreview-Fragment` to `Message-Fragment` I would be much appreciated. These are seperated questions. Hope you can help.
I open the fragments with adding to backstack `addToBackStack(fragmentTag)`.
Edited : VideoPreview-Fragment must be VideoPreview-Activity
and VidoTrim-Fragment must be VideoTrim-Activity. these are the activities. like you see on the image.
|
2017/10/02
|
[
"https://Stackoverflow.com/questions/46523857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3583237/"
] |
If I understand everything correctly I think I have a solution. I will ignore all other aspects of the navigation and just focus on the fact you want to go from `VideoPreviewActivity` to the `MainActivity` and adjust the fragment stack, and that this is being triggered from a done button (or something similar) but NOT the back button.
The simple way would be to use the activity result functions `startActivityForResult` which would allow you to use a `onActivityResult` function in the main activity to pass the information back. However you may potentially navigate to the `VideoPreviewActivity` via the `VideoTrimActivity` so you would have to pass this information back through two activities which would be a bit messy.
So my proposed solution has a few steps.
Instead of calling `finish()` on the `VideoPreviewActivity` fire an intent to create the `MainActivity`
```
Intent intent = new Intent(context, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra()//Add your return data here
startActivity(intent)
```
Instead of starting a new `MainActivity` this will return you to the previous one and finish all the activities sat above it in the task task.
Add this function to the `MainActivity`.
```
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
```
Then in the `onStart` function you can check your intent to see if there is data in there returned from `VideoPreview` and remove the fragments you no longer need.
```
if (getIntent().hasExtra(YOUR_DATA)) {
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
getSupportFragmentManager(). popBackStackImmediate("MESSAGE_TAG", 0);
}
```
Where "MESSAGE\_TAG" is the tag used in the `ft.addToBackStack("MESSAGE_TAG")` call.
This will clear all of the fragments with an `addToBackStack` in the transaction. The `MessageFragment` will start its lifecycle calls again and you can access the data from
```
getActivity().getIntent()
```
|
59,065
|
First of all I just started doing barre chords after learning ordinary non-barre chords. Problem is they don't sound so well, so my question is, will training with hand grippers help me achieve this? Because I've been applying equal pressure and they still sound a bit off, only a bit off.
|
2017/07/09
|
[
"https://music.stackexchange.com/questions/59065",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/42610/"
] |
It turns out that strength is not what is needed to improve your ability to finger barre chords, or any chords. It's mostly about precise placement and using the minimum amount of force to hold it down.
It's not necessarily that equal pressure is correct. You just need the right amount of pressure for each fret and string.
|
6,359,617
|
As part of a project, I need to analyse string which may contain a reference to PHP in the following manner:
`[php]functionName(args1, args2)[/php]`
The function name is not always the same, and I would like to replace everything in the above example (including the pseudo-tags) with another value.
Can anyone suggest a Regular Expression to effectively match the pattern `[php]anything[/php]`.
Sorry if this is a basic question, but I suck at Regular Expressions!
|
2011/06/15
|
[
"https://Stackoverflow.com/questions/6359617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] |
I think `"\[php\](.*?)\[\/php\]"` would do the trick.
Edit: you may or may not need the double quotes-- not sure how you're ultimately using the regex string.
|
48,118,038
|
I am trying to create a simple drag race animation. The car image moves across the page upon the click of a button until each reaches a certain position. The code below works with individual clicks moving the car a random distance each click, but I want one click to repeat the movement in a loop. I have tried putting it in a while loop referencing the value of x, but it doesn't work. Any ideas.
```html
<html>
<head>
<meta charset="utf-8">
<title>Race Car</title>
</head>
<body>
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.png"></div>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
//Get car position coordinates
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
var race = function() {
var delay = 1000;
setTimeout(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
top: y
});
x = $("#car").offset().left;
}, delay);
};
</script>
</body>
</html>
```
|
2018/01/05
|
[
"https://Stackoverflow.com/questions/48118038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9178525/"
] |
You're looking for [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval).
`setTimeout` runs your function once after x milliseconds.
`setInterval` runs your function every x milliseconds.
Be sure to store your interval in a variable you can access (`var timer = setInterval(fn, ms)`) and then clear it when you want to stop the interval (`clearInterval(timer)`).
|
66,862,650
|
I found some code that uses a decorator as an instance variable in a class...
I tried to replicate this in plain Javascript, but it doesn't work.
This is the Typescript:
```
export function ObservableProperty() {
return (obj: Observable, key: string) => {
let storedValue = obj[key];
Object.defineProperty(obj, key, {
get: function () {
return storedValue;
},
set: function (value) {
if (storedValue === value) {
return;
}
storedValue = value;
this.notify({
eventName: Observable.propertyChangeEvent,
propertyName: key,
object: this,
value
});
},
enumerable: true,
configurable: true
});
};
}
```
Then, in the class:
```
export class MyClass extends Observable {
@ObservableProperty() public theBoolValue: boolean;
…
```
I tried all sorts of ways to instantiate my JS-variable - always get errors…
Like:
```
@ObservableProperty
this.theBoolValue = false;
```
Is this even possible?
|
2021/03/29
|
[
"https://Stackoverflow.com/questions/66862650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/424706/"
] |
Decorators are a TypeScript thing, not a JavaScript thing ([yet](https://github.com/tc39/proposal-decorators))
Looking at the [TypeScript Docs](https://www.typescriptlang.org/docs/handbook/decorators.html), you can take their example (or even your example for that matter), and throw it in their Playground to get a the JavaScript equivalent.
[For example](https://www.typescriptlang.org/play?ssl=19&ssc=2&pln=1&pc=1#code/GYVwdgxgLglg9mABMGAnAzlAFASkQbwChFEIF04AbAUwDpK4BzLAIhQ2xwC5kBDaOKgCeiagDdelELyjUAJixwBuYolTUoIVElCRYCRFii9UjDT15ghAGkQAHVHDvVUUIQGlqQnplQwwjLZy1OgQfnZQgjwACo7OrkIAIiFhMBGCeEQkJGRgFDT0TKzsmLg8EJI0CsqqAL4qtYSEutDwSOjUuXK4BKq5%20XQMzCwdXWV8AsKiElIy8ooqJOqa2sjgrQZGJmZQFla2Dk4ubp7eiL7%20gYjBoeGRqDFxx0kpdxm92aTkVINFI50IbrcUiVeY1Ej1QiNQgQSi8dDoRAAUQAHrwALZ2GgAYThCI%20iAAAiVOKpCaNAbhVOiNAALOBAgiNWpAA), here is the TypeScript example:
```
function first() {
console.log("first(): factory evaluated");
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("first(): called");
};
}
function second() {
console.log("second(): factory evaluated");
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("second(): called");
};
}
class ExampleClass {
@first()
@second()
method() {}
}
```
And that boils down to this in JavaScript:
```
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
function first() {
console.log("first(): factory evaluated");
return function (target, propertyKey, descriptor) {
console.log("first(): called");
};
}
function second() {
console.log("second(): factory evaluated");
return function (target, propertyKey, descriptor) {
console.log("second(): called");
};
}
class ExampleClass {
method() { }
}
__decorate([
first(),
second(),
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], ExampleClass.prototype, "method", null);
```
|
55,618,061
|
I do not understand why after clicking the link "undefined" is shown. Does anyone know why?
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks[i])">Link</p>';
}
function test(n){
alert(n);
}
```
|
2019/04/10
|
[
"https://Stackoverflow.com/questions/55618061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11341802/"
] |
Because your code in the click handler is
```
test(allBlocks[i])
```
It would appear your code is at global scope, which is the only reason it's not throwing an error. When the click occurs, `i` has the value `allBlocks.length`, which is beyond the end of the array. Accessing an array entry that isn't there results in `undefined`.
The minimum change is to use string concatenation to put the value of `i` in the click handler rather than `i`:
```
document.body.innerHTML += '<p id="" onclick="test(allBlocks[' + i + '])">Link</p>';
```
However, rather than doing that, I'd suggest modern event handling via `addEventListener`:
```
for (let i = 0; i < allBlocks.length; i++) {
// ^^^---- Note
const p = document.createElement("p");
p.textContent = "Link";
p.addEventListener("click", test.bind(null, allBlocks[i]));
document.body.appendChild(p);
}
```
---
Side note: `element.innerHTML += ...` is never a good idea. It forces the browser to loop through the entire contents of `element`, building up an HTML string for the DOM structure it contains, and then pass that string to the JavaScript layer; then the JavaScript layer has to add to the string and pass it back to the browser; then the browser has to parse the HTML, creating a bunch of new, replacement elements, wipe out the contents of `element`, and replace it with those new elements. Other than being a lot of unnecessary work, it also destroys any event handlers on the elements, any state information, etc.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.