id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
8,889,302
What is the meaning of a question mark in bash variable parameter expansion as in ${var?}?
<p>What is the meaning of a bash variable used like this:</p> <pre><code> ${Server?} </code></pre>
8,889,350
4
0
null
2012-01-17 03:23:36.943 UTC
11
2019-10-29 16:27:25.817 UTC
2018-10-17 18:12:07.73 UTC
null
6,862,601
null
612,418
null
1
62
bash|variables|syntax
20,509
<p>It works almost the same as (from the <code>bash</code> manpage):</p> <blockquote> <p><strong><code>${parameter:?word}</code></strong> <br> <code>Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.</code></p> </blockquote> <p>That particular variant checks to ensure the variable exists (is both defined and not null). If so, it uses it. If not, it outputs the error message specified by <code>word</code> (or a suitable one if there is no <code>word</code>) and terminates the script.</p> <p>The actual difference between that and the non-colon version can be found in the <code>bash</code> manpage above the section quoted:</p> <blockquote> <p>When not performing substring expansion, using the forms documented below, <code>bash</code> tests for a parameter that is unset or null. <strong>Omitting the colon results in a test only for a parameter that is unset.</strong></p> </blockquote> <p>In other words, the section above can be modified to read (basically taking out the "null" bits):</p> <blockquote> <p><strong><code>${parameter?word}</code></strong> <br> <code>Display Error if Unset. If parameter is unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.</code></p> </blockquote> <p>The difference is illustrated thus:</p> <pre><code>pax&gt; unset xyzzy ; export plugh= pax&gt; echo ${xyzzy:?no} bash: xyzzy: no pax&gt; echo ${plugh:?no} bash: plugh: no pax&gt; echo ${xyzzy?no} bash: xyzzy: no pax&gt; echo ${plugh?no} pax&gt; _ </code></pre> <p>There, you can see that while both unset <em>and</em> null variable result in an error with <code>:?</code>, only the unset one errors with <code>?</code>.</p>
8,592,921
How to return HTTP 204 in a Rails controller
<p>This seems to be basic but I'm a Ruby/Rails beginner. I need to simply return HTTP 204 in a controller. Would </p> <pre><code>respond_to do |format| format.html end </code></pre> <p>return a 204?</p>
11,485,810
3
0
null
2011-12-21 16:16:29.94 UTC
8
2018-07-06 03:58:12.51 UTC
2018-04-25 11:23:48.587 UTC
null
2,423,164
null
1,098,917
null
1
69
ruby-on-rails|ruby
37,321
<pre><code>head :no_content </code></pre> <p>Tested with Rails 3.2.x, 4.x. It causes the controller method to respond with the 204 No Content HTTP status code. </p> <p>An example of using this inside a controller method named <code>foobar</code>:</p> <pre><code>def foobar head :no_content end </code></pre>
30,485,151
Python pandas: exclude rows below a certain frequency count
<p>So I have a pandas DataFrame that looks like this:</p> <pre><code>r vals positions 1.2 1 1.8 2 2.3 1 1.8 1 2.1 3 2.0 3 1.9 1 ... ... </code></pre> <p>I would like the filter out all rows by position that do not appear at least 20 times. I have seen something like this</p> <pre><code>g=df.groupby('positions') g.filter(lambda x: len(x) &gt; 20) </code></pre> <p>but this does not seem to work and I do not understand how to get the original dataframe back from this. Thanks in advance for the help.</p>
30,485,620
4
0
null
2015-05-27 14:15:31.783 UTC
14
2021-05-24 08:35:46.877 UTC
2015-05-27 14:46:35.137 UTC
null
704,848
null
1,628,702
null
1
22
python|pandas|filter|dataframe
24,523
<p>On your limited dataset the following works:</p> <pre><code>In [125]: df.groupby('positions')['r vals'].filter(lambda x: len(x) &gt;= 3) Out[125]: 0 1.2 2 2.3 3 1.8 6 1.9 Name: r vals, dtype: float64 </code></pre> <p>You can assign the result of this filter and use this with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html#pandas.Series.isin" rel="noreferrer"><code>isin</code></a> to filter your orig df:</p> <pre><code>In [129]: filtered = df.groupby('positions')['r vals'].filter(lambda x: len(x) &gt;= 3) df[df['r vals'].isin(filtered)] Out[129]: r vals positions 0 1.2 1 1 1.8 2 2 2.3 1 3 1.8 1 6 1.9 1 </code></pre> <p>You just need to change <code>3</code> to <code>20</code> in your case</p> <p>Another approach would be to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html#pandas.Series.value_counts" rel="noreferrer"><code>value_counts</code></a> to create an aggregate series, we can then use this to filter your df:</p> <pre><code>In [136]: counts = df['positions'].value_counts() counts Out[136]: 1 4 3 2 2 1 dtype: int64 In [137]: counts[counts &gt; 3] Out[137]: 1 4 dtype: int64 In [135]: df[df['positions'].isin(counts[counts &gt; 3].index)] Out[135]: r vals positions 0 1.2 1 2 2.3 1 3 1.8 1 6 1.9 1 </code></pre> <p><strong>EDIT</strong></p> <p>If you want to filter the groupby object on the dataframe rather than a Series then you can call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html#pandas.DataFrame.filter" rel="noreferrer"><code>filter</code></a> on the groupby object directly:</p> <pre><code>In [139]: filtered = df.groupby('positions').filter(lambda x: len(x) &gt;= 3) filtered Out[139]: r vals positions 0 1.2 1 2 2.3 1 3 1.8 1 6 1.9 1 </code></pre>
30,748,480
Swift - Get device's WIFI IP Address
<p>I need to get IP Address of iOS device in Swift. This is not a duplicate of other questions about this! I need to get only WiFi IP address, if there is no wifi ip address - I need to handle it. There are a few questions about it on Stack Overflow, but there are only functions that return ip addresses. For example (from <a href="https://stackoverflow.com/questions/25626117/how-to-get-ip-address-in-swift/25627545#25627545">How to get Ip address in swift</a>):</p> <pre><code>func getIFAddresses() -&gt; [String] { var addresses = [String]() // Get list of all interfaces on the local machine: var ifaddr : UnsafeMutablePointer&lt;ifaddrs&gt; = nil if getifaddrs(&amp;ifaddr) == 0 { // For each interface ... for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next) { let flags = Int32(ptr.memory.ifa_flags) var addr = ptr.memory.ifa_addr.memory // Check for running IPv4, IPv6 interfaces. Skip the loopback interface. if (flags &amp; (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) { if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) { // Convert interface address to a human readable string: var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0) if (getnameinfo(&amp;addr, socklen_t(addr.sa_len), &amp;hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) == 0) { if let address = String.fromCString(hostname) { addresses.append(address) } } } } } freeifaddrs(ifaddr) } return addresses } </code></pre> <p>Here I get 2 values - address from mobile internet(I think) and WiFi address I need. Is there any other way to get ONLY WiFi IP Address?</p>
30,754,194
17
0
null
2015-06-10 06:16:12.917 UTC
51
2021-08-20 04:22:38.197 UTC
2018-09-10 10:39:01.873 UTC
null
129,202
null
2,938,258
null
1
83
ios|swift|network-programming
105,971
<p>According to several SO threads (e.g. <a href="https://stackoverflow.com/questions/14334076/what-exactly-means-ios-networking-interface-name-whats-pdp-ip-whats-ap">What exactly means iOS networking interface name? what&#39;s pdp_ip ? what&#39;s ap?</a>), the WiFi interface on an iOS device always has then name "en0".</p> <p>Your code (which seems to be what I answered at <a href="https://stackoverflow.com/questions/25626117/how-to-get-ip-address-in-swift">How to get Ip address in swift</a> :) retrieves a list of the IP addresses of <em>all</em> running network interfaces. It can easily be modified to return only the IP address of the "en0" interface, and actually that is what I <em>originally</em> had answered at that thread (and this is just a Swift translation of the answer to <a href="https://stackoverflow.com/questions/6807788/how-to-get-ip-address-of-iphone-programatically">how to get ip address of iphone programmatically</a>):</p> <pre><code>// Return IP address of WiFi interface (en0) as a String, or `nil` func getWiFiAddress() -&gt; String? { var address : String? // Get list of all interfaces on the local machine: var ifaddr : UnsafeMutablePointer&lt;ifaddrs&gt; = nil if getifaddrs(&amp;ifaddr) == 0 { // For each interface ... var ptr = ifaddr while ptr != nil { defer { ptr = ptr.memory.ifa_next } let interface = ptr.memory // Check for IPv4 or IPv6 interface: let addrFamily = interface.ifa_addr.memory.sa_family if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) { // Check interface name: if let name = String.fromCString(interface.ifa_name) where name == "en0" { // Convert interface address to a human readable string: var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0) getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.memory.sa_len), &amp;hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) address = String.fromCString(hostname) } } } freeifaddrs(ifaddr) } return address } </code></pre> <p>Usage:</p> <pre><code>if let addr = getWiFiAddress() { print(addr) } else { print("No WiFi address") } </code></pre> <hr> <p><strong>Update for Swift 3:</strong> In addition to adopting the code to the <a href="https://github.com/apple/swift-evolution" rel="noreferrer">many changes in Swift 3</a>, iterating over all interfaces can now use the new generalized <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0094-sequence-function.md" rel="noreferrer"><code>sequence()</code></a> function:</p> <p>Do <strong>NOT</strong> forget to add <code>#include &lt;ifaddrs.h&gt;</code> in your bridging header</p> <pre><code>// Return IP address of WiFi interface (en0) as a String, or `nil` func getWiFiAddress() -&gt; String? { var address : String? // Get list of all interfaces on the local machine: var ifaddr : UnsafeMutablePointer&lt;ifaddrs&gt;? guard getifaddrs(&amp;ifaddr) == 0 else { return nil } guard let firstAddr = ifaddr else { return nil } // For each interface ... for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) { let interface = ifptr.pointee // Check for IPv4 or IPv6 interface: let addrFamily = interface.ifa_addr.pointee.sa_family if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) { // Check interface name: let name = String(cString: interface.ifa_name) if name == "en0" { // Convert interface address to a human readable string: var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len), &amp;hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) address = String(cString: hostname) } } } freeifaddrs(ifaddr) return address } </code></pre> <hr> <p><strong>For those of you who came looking for more than the WIFI IP you could modify this code a little</strong></p> <pre><code>func getAddress(for network: Network) -&gt; String? { var address: String? // Get list of all interfaces on the local machine: var ifaddr: UnsafeMutablePointer&lt;ifaddrs&gt;? guard getifaddrs(&amp;ifaddr) == 0 else { return nil } guard let firstAddr = ifaddr else { return nil } // For each interface ... for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) { let interface = ifptr.pointee // Check for IPv4 or IPv6 interface: let addrFamily = interface.ifa_addr.pointee.sa_family if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) { // Check interface name: let name = String(cString: interface.ifa_name) if name == network.rawValue { // Convert interface address to a human readable string: var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len), &amp;hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) address = String(cString: hostname) } } } freeifaddrs(ifaddr) return address } </code></pre> <pre><code>enum Network: String { case wifi = "en0" case cellular = "pdp_ip0" //... case ipv4 = "ipv4" //... case ipv6 = "ipv6" } </code></pre> <p>Then we have access to the cellular IP as well.</p> <p><code>guard let wifiIp = getAddress(for: .wifi) else { return }</code></p> <p><strong>&amp;</strong></p> <p><code>guard let cellularIp = getAddress(for: .cellular) else { return }</code></p>
43,556,212
Failed form propType: You provided a `value` prop to a form field without an `onChange` handler
<p>When I load my react app I get this error in the console.</p> <blockquote> <p>Warning: Failed form propType: You provided a <code>value</code> prop to a form field without an <code>onChange</code> handler. This will render a read-only field. If the field should be mutable use <code>defaultValue</code>. Otherwise, set either <code>onChange</code> or <code>readOnly</code>. Check the render method of <code>AppFrame</code>.</p> </blockquote> <p>My AppFrame component is below:</p> <pre><code>class AppFrame extends Component { render() { return ( &lt;div&gt; &lt;header className="navbar navbar-fixed-top navbar-shadow"&gt; &lt;div className="navbar-branding"&gt; &lt;a className="navbar-brand" href="dashboard"&gt; &lt;b&gt;Shire&lt;/b&gt;Soldiers &lt;/a&gt; &lt;/div&gt; &lt;form className="navbar-form navbar-left navbar-search alt" role="search"&gt; &lt;div className="form-group"&gt; &lt;input type="text" className="form-control" placeholder="Search..." value="Search..."/&gt; &lt;/div&gt; &lt;/form&gt; &lt;ul className="nav navbar-nav navbar-right"&gt; &lt;li className="dropdown menu-merge"&gt; &lt;span className="caret caret-tp hidden-xs"&gt;&lt;/span&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/header&gt; &lt;aside id="sidebar_left" className="nano nano-light affix"&gt; &lt;div className="sidebar-left-content nano-content"&gt; &lt;ul className="nav sidebar-menu"&gt; &lt;li className="sidebar-label pt20"&gt;Menu&lt;/li&gt; &lt;li className="sidebar-label"&gt; &lt;IndexLink to="/" activeClassName="active"&gt;Dashboard&lt;/IndexLink&gt; &lt;/li&gt; &lt;li className="sidebar-label"&gt; &lt;Link to="/fixtures" activeClassName="active"&gt;Fixtures&lt;/Link&gt; &lt;/li&gt; &lt;li className="sidebar-label"&gt; &lt;Link to="/players" activeClassName="active"&gt;Players&lt;/Link&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/aside&gt; &lt;section id="content_wrapper"&gt; &lt;section id="content" className="table-layout animated fadeIn"&gt; {this.props.children} &lt;/section&gt; &lt;/section&gt; &lt;/div&gt; ) } } export default AppFrame; </code></pre> <p>I am struggling to work out what I am actually doing wrong here. The application starts up and works but I am trying to remove all console warning/errors.</p>
72,252,485
5
0
null
2017-04-22 06:50:27.613 UTC
13
2022-06-13 15:15:02.557 UTC
null
null
null
null
7,304,216
null
1
119
javascript|jquery|forms|reactjs
161,963
<h3>Try this,</h3> <pre><code>const [email, SetEmail] = useState(&quot;&quot;); </code></pre> <pre><code>&lt;Form.Control onChange={e =&gt; SetEmail(e.target.value)} type=&quot;email&quot; name=&quot;email&quot; value={email || &quot;&quot;} /&gt; </code></pre>
504,431
T-Sql How to return a table from a storedproc in another stored proc
<p>I would like to do the following. Basically have a stored procedure call another stored procedure that returns a table. How is this done? </p> <pre><code> ALTER PROC [GETSomeStuff] AS BEGIN @table = exec CB_GetLedgerView @accountId, @fromDate, @toDate, @pageSize, @pageNumber, @filter, @status, @sortExpression, @sortOrder, @virtualCount OUTPUT Select * from @table --Do some other stuff here END </code></pre>
504,449
3
0
null
2009-02-02 19:00:25.63 UTC
5
2013-06-25 18:32:34.66 UTC
null
null
null
Arron
16,628
null
1
15
tsql|stored-procedures
44,581
<p>The target of a stored procedure has to be a temp or actual table so you can </p> <pre><code> Insert into #table exec CB_GetLedgerView @accountId, @fromDate, @toDate, @pageSize, @pageNumber, @filter, @status, @sortExpression, @sortOrder, @virtualCount OUTPUT </code></pre> <p>If the output result set of the stored procedure does not match the ordinal positions and count of the rows in the target table, specify a column list. </p>
276,543
How to run a console application with command line parameters in Visual C++ 6.0?
<p>I've got a console application that compiles and executes fine with Visual C++ 6.0, except that it will then only get as far as telling me about missing command line parameters. There doesn't seem to be anywhere obvious to enter these. How do I run or debug it with command line parameters?</p>
276,547
3
0
null
2008-11-09 22:02:15.56 UTC
3
2013-01-17 10:06:22.8 UTC
2008-11-09 22:16:50.68 UTC
Martin York
14,065
Rob Kam
25,093
null
1
31
c++|command-line|parameters|visual-c++-6
42,321
<p>I assume you're talking about setting the command line parameters for running in the IDE.</p> <p>Open the Project/Settings property page and go to the Debug tab.</p> <p>There's a "Program arguments" field you can put them into.</p>
41,683,195
Access Control Allow Origin issue in Angular 2
<p>I have a problem with getting data from my node.js server.</p> <p>The client side is:</p> <pre><code> public getTestLines() : Observable&lt;TestLine[]&gt; { let headers = new Headers({ 'Access-Control-Allow-Origin': '*' }); let options = new RequestOptions({ headers: headers }); return this.http.get('http://localhost:3003/get_testlines', options) .map((res:Response) =&gt; res.json()) .catch((error:any) =&gt; Observable.throw(error.json().error || 'Server error')); } </code></pre> <p>in server side I also set the headers:</p> <pre><code>resp.setHeader('Access-Control-Allow-Origin','*') resp.send(JSON.stringify(results)) </code></pre> <p>But I get an error</p> <blockquote> <p>"XMLHttpRequest cannot load <a href="http://localhost:3003/get_testlines" rel="noreferrer">http://localhost:3003/get_testlines</a>. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<a href="http://localhost:3000" rel="noreferrer">http://localhost:3000</a>' is therefore not allowed access."</p> </blockquote> <p>How can I fix it? When I remove headers it says that this header is required. </p>
41,684,356
5
2
null
2017-01-16 18:52:55.647 UTC
1
2019-09-23 14:11:00.42 UTC
2017-01-17 10:20:34.88 UTC
null
4,927,984
null
7,235,292
null
1
10
html|angular|http-headers
51,127
<p><code>Access-Control-Allow-Origin</code> is a <strong>response</strong> header, not a request header.</p> <p>You need to have it appear on the response, not the request.</p> <p>You have attempted to put it on the response:</p> <blockquote> <pre><code>resp.setHeader('Access-Control-Allow-Origin','*') </code></pre> </blockquote> <p>… but it hasn't worked.</p> <p>This is probably because you haven't put it on the response to the right request. The error message says:</p> <blockquote> <p>Response to <strong>preflight request</strong> doesn't pass access control check</p> </blockquote> <p>You have done <em>something</em> to make the request preflighted. This means that before the browser makes the GET request you are trying to make, it is making an OPTIONS request.</p> <p>This is, presumably, being handled by a different piece of code on your server so the line <code>resp.setHeader('Access-Control-Allow-Origin','*')</code> isn't being hit. </p> <p>One thing that causes a preflighted request to be made is the addition of request headers (other than a small number of exceptions). Adding <code>Access-Control-Allow-Origin</code> to the <em>request</em> will trigger a preflighted request, so the first thing to do to try to fix the problem is to <strong>remove <code>Access-Control-Allow-Origin</code> from the request</strong>.</p> <p>If that fails, then you need to set up your server so it can respond to the OPTIONS request as well as the GET request.</p>
28,619,113
Start a new Activity from Fragment
<p>Using Android Studio, I have my MainActiviy class with a Placeholder fragment. This fragment has buttons, but one has to load an Activity. How does one do this? I was told to try something like the below, but the new Intent does not work.</p> <pre><code>Button button = (Button) rootView.findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.class, AnotherActivity.class); startActivity(intent); } }); </code></pre>
28,619,264
7
1
null
2015-02-19 23:36:05.597 UTC
10
2019-08-08 12:23:38.587 UTC
2017-02-22 02:38:18.647 UTC
null
4,758,255
null
4,586,140
null
1
18
android|android-activity
69,769
<p>If you have a look at the <a href="http://developer.android.com/training/basics/firstapp/starting-activity.html" rel="noreferrer">documentation</a> you can see that to start an activity you'll want to use the following code</p> <pre><code>Intent intent = new Intent(getActivity(), AnotherActivity.class); startActivity(intent); </code></pre> <p>Currently you're using <code>MainActivity.class</code> in a place that requires a context object. If you're currently in an activity, just passing <code>this</code> is enough. A fragment can get the activity via the <code>getActivity()</code> function.</p> <p>Your full code above should look like this</p> <pre><code>Button button = (Button) rootView.findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), AnotherActivity.class); startActivity(intent); } }); </code></pre>
24,427,009
Is there a cleaner way of getting the last N characters of every line?
<p>To simplify the discussion, let <code>N = 3</code>.</p> <p>My current approach to extracting the last three characters of every line in a file or stream is to use <code>sed</code> to capture the last three characters in a group and replace the entire line with that group. </p> <pre><code>sed 's/^.*\(.\{3\}\)/\1/' </code></pre> <p>It works but it seems excessively verbose, especially when we compare to a method for getting the <em>first</em> three characters in a line.</p> <pre><code>cut -c -3 </code></pre> <p><strong>Is there a cleaner way to extract the last N characters in every line?</strong> </p>
24,427,087
4
0
null
2014-06-26 09:32:41.343 UTC
8
2014-11-25 20:05:34.567 UTC
2014-06-26 09:38:41.513 UTC
null
391,161
null
391,161
null
1
18
bash|command-line|awk|sed|cut
42,147
<p>It's very simple with <code>grep -o '...$'</code>:</p> <pre><code>cat /etc/passwd | grep -o '...$' ash /sh /sh /sh ync /sh /sh /sh </code></pre> <p>Or better yer:</p> <pre><code>N=3; grep -o ".\{$N\}$" &lt;/etc/passwd ash /sh /sh /sh ync /sh /sh </code></pre> <p>That way you can adjust your <code>N</code> for whatever value you like.</p>
42,606,091
Change another module state from one module in Vuex
<p>I have two modules in my vuex store.</p> <pre><code>var store = new Vuex.Store({ modules: { loading: loading posts: posts } }); </code></pre> <p>In the module <code>loading</code>, I have a property <code>saving</code> which can be set either <code>true</code> or <code>false</code> and also have a mutation function named <code>TOGGLE_SAVING</code> to set this property.</p> <p>In the module <code>posts</code>, before and after fetching posts, I want to change the property <code>saving</code>. I am doing it by calling <code>commit('TOGGLE_SAVING')</code> from one of the actions in the <code>posts</code> module.</p> <pre><code>var getPosts = function (context) { context.commit(TOGGLE_LOADING); }; </code></pre> <p>When it tried to commit, I got following error in the console</p> <pre><code>[vuex] unknown local mutation type: TOGGLE_LOADING, global type: posts/TOGGLE_LOADING </code></pre> <p>How can I mutate state in another module using <code>commit</code>?</p>
42,606,829
4
1
null
2017-03-05 08:21:35.927 UTC
18
2022-04-21 15:33:35.943 UTC
2022-04-21 15:33:35.943 UTC
null
3,518,515
null
1,154,350
null
1
112
vue.js|vuejs2|vuex
61,438
<p>Try it with following parameters as suggested <a href="https://vuex.vuejs.org/en/modules.html" rel="noreferrer">here</a>;</p> <pre><code>commit('TOGGLE_LOADING', null, { root: true }) </code></pre> <p>If you have <code>namespaced</code> set to true (in Nuxt that's the default when in modules mode), this becomes:</p> <pre><code>commit('loading/TOGGLE_LOADING', null, { root: true }) </code></pre>
5,616,684
Recursive Fibonacci in Assembly
<p>I'm attempting to implement a recursive Fibonacci program in Assembly. However, my program crashes, with an unhandled exception, and I can't seem to pick out the problem. I don't doubt that it involves my improper use of the stack, but I can't seem to point out where...</p> <pre><code>.386 .model Flat public Fibonacci include iosmacros.inc ;includes macros for outputting to the screen .code Fibonacci proc MOV EAX, [EBP+8] CMP EAX, 1 JA Recurse MOV ECX, 1 JMP exit Recurse: DEC EAX MOV EDX, EAX PUSH EAX CALL Fibonacci ADD ESP, 4 MOV EBX, ECX DEC EDX PUSH EDX CALL Fibonacci ADD ECX, EBX exit: ret Fibonacci endp .data end </code></pre> <p>Also, I've pushed the number that I'm using to get the Fibonacci value to the stack in an external procedure. Any ideas where the problem might lie?</p>
5,616,829
3
0
null
2011-04-11 04:15:35.653 UTC
2
2018-05-24 04:05:24.433 UTC
null
null
null
null
386,869
null
1
8
assembly|fibonacci
53,710
<p>When you perform a <code>call</code>, the address of the next operation is pushed to the stack as a return value. When creating a function, it is often customary to create a "stack frame". This frame can be used to print the call stack, as well as an offset for local variables and arguments. The frame is created through two operations at the beginning of the function:</p> <pre><code>push ebp mov ebp, esp </code></pre> <p>At the end of the function, the call stack is removed using <code>leave</code>, which is equivalent to the reverse of those 2 operations. When using a stack frame, value of <code>esp</code> is stored into <code>ebp</code>, making it point to a location on the stack called the frame's base. Since, above this address, there are the old value of <code>ebp</code> and the return address, you would normally get the first argument using <code>[ebp+8]</code>. However, you did not set up a stack frame. This means that the old value of <code>ebp</code> was not pushed to the stack, and the current value of <code>ebp</code> cannot be used to get arguments because you don't know where it is. Therefore, you should get your argument using <code>[esp+4]</code>.</p> <p>Also, it is customary that return values are placed in <code>eax</code> and <code>ebx</code> be preserved for the caller. Your code does not follow either of these conventions. Also, technically functions aren't required to preserved <code>ecx</code> or <code>edx</code>, so normally you should push them to the stack before calling another function if you want them preserved. With this code, <code>edx</code> and <code>ebx</code> would be overwritten if called with a value greater than 2, causing an invalid result.</p> <p>Here is a full listing which includes all of the fixes I have mentioned. I did not create a stack frame as it is not necessary and your code didn't.</p> <pre><code>.386 .model Flat public Fibonacci include iosmacros.inc ;includes macros for outputting to the screen .code Fibonacci proc MOV EAX, [ESP+4] CMP EAX, 1 JA Recurse MOV EAX, 1 ; return value in eax JMP exit Recurse: PUSH EBX ; preserve value of ebx DEC EAX PUSH EAX CALL Fibonacci MOV EBX, EAX ; ebx is preserved by callee, so it is safe to use DEC [ESP] ; decrement the value already on the stack CALL Fibonacci ADD EAX, EBX ; return value in eax ADD ESP, 4 ; remove value from stack POP EBX ; restore old value of ebx exit: ret Fibonacci endp </code></pre>
6,118,814
is there anywhere where I could start MobileSubstrate tweaks programming?
<p>After a search here on the forum I found a question like that, and it redirected me to a tutorial which gave em some basic instructions on manipulating SpringBoard with CapitainHook.</p> <p>To start I'd like to do it with normal %hooks only. Any hint where I could start?</p>
11,553,722
3
0
null
2011-05-25 02:11:14.003 UTC
51
2012-07-19 11:50:26.887 UTC
2011-05-25 02:24:20.833 UTC
null
639,668
null
768,779
null
1
30
objective-c|cocoa-touch|ios|jailbreak
19,711
<p>So, since I (hope I) am far away from a noob with MobileSubstrate programming now, and saw this question as quite popular, I decided to create an answer covering everything you need to know about the subject hopefully briefly.</p> <p>This little introduction is meant for whoever <strong>has a minimal knowledge on Objective-C</strong> and knows what he is doing.</p> <p><strong>NOTE</strong>: I will refer to the theos install path as <code>$THEOS</code>. This could be <code>~/theos</code>, <code>/var/theos</code>, <code>/usr/theos</code>... Yeah.</p> <p>The most popular way of creating MobileSubstrate extensions, also known as <em>tweaks</em>, is using <a href="http://howett.net" rel="noreferrer">Dustin Howett</a>'s <strong><a href="http://iphonedevwiki.net/index.php/Theos" rel="noreferrer">theos build suite</a></strong>. Details follow:</p> <h2>What is theos?</h2> <p>So, we should start with what theos is <strong>not</strong>:</p> <ul> <li>The Operating System</li> <li>A Greek God</li> <li>A compiler</li> </ul> <p>And of course, what theos <strong>doesn't do</strong>:</p> <ul> <li>Teaches you how to code.</li> <li>Creates tweaks without having you to think</li> <li>Sets up a whole building environment and/or installs the iOS SDK.</li> </ul> <p>Theos is <strong>a cross-platform suite of development tools for managing, developing, and deploying iOS software without the use of Xcode</strong>, featuring:</p> <ul> <li><p><strong><a href="http://uv.howett.net/ipf.html" rel="noreferrer">A robust build system driven by GNU Make</a></strong>, which makes its Makefiles easily deployable through everywhere with theos installed too.</p></li> <li><p><strong><a href="http://iphonedevwiki.net/index.php/Jailbreak_Development_Tools#NIC_.28New_Instance_Creator.29" rel="noreferrer">NIC</a></strong>, a project templating system which creates ready-to-build empty projects for varying purposes.</p></li> <li><p><strong><a href="http://iphonedevwiki.net/index.php/Logos" rel="noreferrer">Logos</a></strong>, a built-in preprocessor-based library of directives designed to make MobileSubstrate extension development easy and with optimal code generation.</p></li> <li><p><strong>Automated packaging</strong>: Theos is capable of directly creating DEB packages for distribution in Cydia, the most popular mean of package distribution in the jailbreak scene.</p></li> </ul> <h2>How to install theos?</h2> <ul> <li>On <strong>OSX</strong>: Have the iOS SDK installed and follow <a href="http://iphonedevwiki.net/index.php/Theos/Getting_Started#On_Mac_OS_X_or_Linux" rel="noreferrer">these instructions</a>.</li> <li>On <strong>iOS</strong>: Install the <em>BigBoss Recommended Tools</em> package from Cydia and run <code>installtheos3</code>.</li> <li>On <strong>Linux</strong>: Find a mean to have the toolchain installed, and follow <a href="http://iphonedevwiki.net/index.php/Theos/Getting_Started#On_Mac_OS_X_or_Linux" rel="noreferrer">these instructions</a>.</li> <li>On <strong>Windows</strong>: Nothing is impossible, but if you actually manage to do so, please let me know. :P</li> </ul> <h2>How to use theos?</h2> <p>This is a <strong>very</strong> asked question and too vague. Since theos is a whole suite of development tools, it doesn't make sense to ask <em>How to use it</em>, but more specifically, to ask <em>How to create software using theos</em>.</p> <p>First of all, always have the <a href="http://uv.howett.net/ipf.html" rel="noreferrer">Theos Makefile Reference</a> in hand. It covers the basics of creating a theos Makefile, and that includes <strong>solving your linking issues adding a framework or private framework to the project</strong>.</p> <p>Now, you can either create your own Makefile from scratch, create your little theos clone/symlink and start coding, but theos makes this step easier. You can just use <code>nic.pl</code>.</p> <p>A very simple example of running NIC to create something can be found <a href="http://iphonedevwiki.net/index.php/Theos/Getting_Started#NIC_Example" rel="noreferrer">here</a>. It's very straight-forward and sets you up right-away for programming.</p> <p>Now, here's where we start getting back to topic.</p> <h2>Creating a tweak with theos</h2> <p>First of all, <strong>do not</strong> run NIC when inside <code>$THEOS/bin</code>. NIC will create the project directory exactly where you're running it from, and it avoids any project being created in <code>$THEOS/bin</code>. Therefore, you'll end up with a simple error which can be avoided by creating the project directory somewhere decent.</p> <p>Run <code>$THEOS/bin/nic.pl</code> and choose the <code>iphone/tweak</code> template. You will be prompted by simple information which you may well know well how to answer, except for the last field: <code>MobileSubstrate bundle filter</code>.</p> <p>Since a big part of MobileSubstrate is not just the <strong>hooker</strong> (the library which switches original methods/functions with yours), but also the <strong>loader</strong> (the part which gets your hooking to be inserted into certain processes), you have to supply this basic information for the Loader to know where to load your tweak. This field is but the <em>bundle identifier for the application where this project will be inserted</em>.</p> <p><code>com.apple.springboard</code>, the default option is the bundle identifier for SpringBoard, the application which is:</p> <ul> <li>The iOS Homescreen</li> <li>The launcher/displayer of common applications</li> <li>The iOS Status Bar</li> <li>Handler of some high-level essential background processes</li> </ul> <p>Therefore, there's where many tweaks take place, altering behavior from something as trivial as app launching to something like how the whole homescreen UI looks like.</p> <h2>Programming a tweak with Logos</h2> <p>Now, the directory generated by NIC will contain:</p> <ul> <li>The Theos <code>Makefile</code>, where you'll change information related to compiling</li> <li>The <code>control</code> file, where you'll change packaging-related information</li> <li>A symbolic link (or shortcut) to <code>$THEOS</code> named <code>theos/</code></li> <li>The main code file, defaulted as <code>Tweak.xm</code>. It is already added to the Makefile for compiling, so you can start coding right-away with it!</li> </ul> <h2>On knowing what to do</h2> <p>Now, you don't have SpringBoard's source code laying around, and you can't guess what methods to hook from nowhere. Therefore, you need a <em>SpringBoard header set</em>. For that, you need to use a tool named <code>class-dump-z</code> and run it into the <code>SpringBoard</code> binary (which is inside the iOS filesystem) to obtain header files including all class declarations and its methods inside the application.</p> <p>From that (a deal of guessing and logging a method call is involved) you can start messing around with what you want in a tweak.</p> <p>Of course, if you are not hooking SpringBoard you can use <code>class-dump-z</code> as you would in other binaries, such as <code>UIKit</code>, <code>MobileSafari</code>, etc.</p> <p>Note that for when reversing <strong>App Store apps</strong>, they'll be encrypted. You'll need to decrypt those (I am unfortunately not allowed to tell you how-to), and then just run <code>class-dump-z</code> on them.</p> <h2>On obtaining private headers</h2> <p>Stuff like preference bundles require the headers for private frameworks, in that case the <code>Preferences</code> framework's headers. Else you'll get endless missing declaration errors (as I guess you could assume).</p> <p>Getting them has the same logic applied the previous step. Run <code>class-dump-z</code> on, at this case, the <code>Preferences</code> binary and throw the headers at your <code>INCLUDEPATH</code>. The <code>INCLUDEPATH</code> is where the compiler will go looking for headers you include like <code>#include &lt;stdio.h&gt;</code>. Yes, <code>stdio.h</code> is inside one of the directories which build a compiler's <code>INCLUDEPATH</code>!</p> <p>When compiling with a theos Makefile, <code>$THEOS/include</code> counts as part of your <code>INCLUDEPATH</code>, which means, you can just throw your dumped headers over there and include them later.</p> <p>(Note that class-dumped headers aren't always perfect, so you're likely to have a couple of header-related compilation errors which can be easily fixed with something like removing a <code>#import</code> directive or changing it, or adding a couple of declarations.)</p> <h2>Code tips</h2> <ul> <li>You can't link against SpringBoard, so whenever you require a class from SpringBoard you have to use either the Logos <code>%c</code> directive or the <code>objc_getClass</code> function, as defined at <code>&lt;objc/runtime.h&gt;</code> to get it. Example: <code>[%c(SBUIController) sharedInstance]</code>, <code>[objc_getClass("SBUIController") sharedInstance]</code>.</li> <li>When not knowing what a method does or how something works in SpringBoard, try disassembling it with <em>IDA</em> or others. I use <em>IDA Demo</em> (&lt;- noob!) for my disassembling.</li> <li>Looking at example code is <em>amazingly helpful</em> for both learning and figuring out how something works inside SpringBoard or others (again..). Great people at GitHub to have a projects looked at are <em>rpetrich</em>, <em>chpwn</em>, <em>DHowett</em>, <em>EvilPenguin</em>, and of course way more.</li> <li>To also find about how SpringBoard and other works (...), have a look at a class's article at the <a href="http://iphonedevwiki.net" rel="noreferrer">iPhone Dev Wiki</a>!</li> </ul> <h2>Epilogue</h2> <p>Wait, where's the good part? Where do I learn about coding in <code>Tweak.xm</code>?</p> <p>Well, the original question was actually <em>How to start MobileSubstrate tweaks programming?</em>. You're all setup, hopefully with all headers placed, ready to type in <code>make</code> and see your project magically compiled with theos.</p> <p>All you need to do is now to actually dig into your headers or your disassembly and go hooking, calling, etc.!</p> <p><a href="http://iphonedevwiki.net/index.php/Logos" rel="noreferrer">Logos Reference</a> contains exactly how to hook and use other features of Logos, and the <a href="http://iphonedevwiki.net/index.php/MobileSubstrate" rel="noreferrer">MobileSubstrate article on the devwiki</a> is also a great read.</p> <p>Good luck. And in case there is any doubt, don't hesitate joining the <code>irc.saurik.com #theos</code> IRC channel. It's a great way to discuss theos-related topics and ask questions. I'm mostly there, along with other greatly smart people ;)</p>
6,211,575
Proper way (move semantics) to return a std::vector from function calling in C++11
<p>I want to fill std::vector (or some other STL container):</p> <pre><code>class Foo { public: Foo(int _n, const Bar &amp;_m); private: std::vector&lt;Foo&gt; fooes_; } </code></pre> <p><em>1.Good looking ctor, expensive performance</em></p> <pre><code>std::vector&lt;Foo&gt; get_vector(int _n, const Bar &amp;_m) { std::vector&lt;Foo&gt; ret; ... // filling ret depending from arguments return ret; } Foo::Foo(int _n, const Bar &amp;_m) : fooes_(get_vector(_n, _m) {} </code></pre> <p><em>2. Better performance, worse looking ctor</em></p> <pre><code>void fill_vector(int _n, const Bar &amp;_m, std::vector&lt;Foo&gt; &amp;_ret) { ... // filling ret depending from arguments } Foo::Foo(int _n, const Bar &amp;_m) { fill_vector(_n, _m, fooes_); } </code></pre> <p>Is it possible to rewrite <code>get_vector</code> function from 1st example with C++0x (move semantics features and so on) to avoid redundant copying and constructor calls?</p>
6,211,604
3
3
null
2011-06-02 07:14:47.33 UTC
2
2012-10-11 12:18:05.427 UTC
2012-10-11 12:18:05.427 UTC
null
723,845
null
723,845
null
1
33
c++|stl|c++11|move-semantics|return-value-optimization
20,400
<p>If you're using a C++0x-compatible compiler and standard library, you get better performance from the first example <strong>without doing anything</strong>. The return value of <code>get_vector(_n, _m)</code> is a temporary, and the move constructor for <code>std::vector</code> (a constructor taking an rvalue reference) will automatically be called with no further work on your part.</p> <p>In general, non-library writers won't need to use rvalue references directly; you'll just reap a decent chunk of the benefits automatically.</p>
5,816,417
How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?
<p>Consider the following JPQL query:</p> <pre><code>SELECT foo FROM Foo foo INNER JOIN FETCH foo.bar bar WHERE bar.baz = :baz </code></pre> <p>I'm trying to translate this into a Criteria query. This is as far as I have gotten:</p> <pre><code>CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery&lt;Foo&gt; cq = cb.createQuery(Foo.class); Root&lt;Foo&gt; r = cq.from(Foo.class); Fetch&lt;Foo, Bar&gt; fetch = r.fetch(Foo_.bar, JoinType.INNER); Join&lt;Foo, Bar&gt; join = r.join(Foo_.bar, JoinType.INNER); cq.where(cb.equal(join.get(Bar_.baz), value); </code></pre> <p>The obvious problem here is that I am doing the same join twice, because <code>Fetch&lt;Foo, Bar&gt;</code> doesn't seem to have a method to get a <code>Path</code>. Is there any way to avoid having to join twice? Or do I have to stick with good old JPQL with a query as simple as that?</p>
5,819,631
3
3
null
2011-04-28 09:23:47.89 UTC
34
2022-01-19 17:34:27.723 UTC
2020-11-17 17:39:58.37 UTC
null
2,387,977
null
531,232
null
1
65
java|jpa|criteria|jpa-2.0
130,289
<p>In JPQL the same is actually true in the spec. The JPA spec does not allow an alias to be given to a fetch join. The issue is that you can easily shoot yourself in the foot with this by restricting the context of the join fetch. It is safer to join twice.</p> <p>This is normally more an issue with ToMany than ToOnes. For example, </p> <pre><code>Select e from Employee e join fetch e.phones p where p.areaCode = '613' </code></pre> <p>This will <strong>incorrectly</strong> return all Employees that contain numbers in the '613' area code but will left out phone numbers of other areas in the returned list. This means that an employee that had a phone in the 613 and 416 area codes will loose the 416 phone number, so the object will be corrupted.</p> <p>Granted, if you know what you are doing, the extra join is not desirable, some JPA providers may allow aliasing the join fetch, and may allow casting the Criteria Fetch to a Join.</p>
6,263,453
Retrieve client ip address in mysql
<p>I'm trying to get with a simple SQL statement the IP address of the client. I do not want to use PHP or other techniques. Only pure SQL. When I use </p> <pre><code>SELECT USER(); </code></pre> <p>I get</p> <pre><code>[email protected] </code></pre> <p>When I use </p> <pre><code>SELECT CURRENT_USER(); </code></pre> <p>I get</p> <pre><code>dbouser@% </code></pre> <p>But how do I get the plain IP? Thanks a lot in advance.</p>
6,263,482
4
0
null
2011-06-07 09:47:18.84 UTC
8
2017-01-14 02:42:59.21 UTC
null
null
null
null
787,191
null
1
27
mysql|sql
48,806
<p>You will only get the IP address of the client process communicating with MySQL. Assuming this is what you want:</p> <pre><code>select host from information_schema.processlist WHERE ID=connection_id(); </code></pre> <p>Will give you the host name (or IP address if name resolution is not enabled, which it is usually not) connecting to the mysql server on the current connection.</p>
6,152,231
Is there a Ruby library/gem that will generate a URL based on a set of parameters?
<p>Rails' URL generation mechanism (most of which routes through <code>polymorphic_url</code> at some point) allows for the passing of a hash that gets serialized into a query string at least for GET requests. What's the best way to get that sort of functionality, but on top of any base path?</p> <p>For instance, I'd like to have something like the following:</p> <pre><code>generate_url('http://www.google.com/', :q =&gt; 'hello world') # =&gt; 'http://www.google.com/?q=hello+world' </code></pre> <p>I could certainly write my own that strictly suits my application's requirements, but if there existed some canonical library to take care of it, I'd rather use that :).</p>
6,152,484
4
0
null
2011-05-27 12:27:38.523 UTC
3
2020-12-21 22:26:09.58 UTC
null
null
null
null
203,137
null
1
29
ruby-on-rails|ruby|gem
18,678
<p>Yes, in Ruby's standard library you'll find a whole module of classes for working with URI's. There's one for HTTP. You can call <code>#build</code> with some arguments, much like you showed.</p> <p><a href="http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/classes/URI/HTTP.html#M009497" rel="noreferrer">http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/classes/URI/HTTP.html#M009497</a></p> <p>For the query string itself, just use Rails' Hash addition <code>#to_query</code>. i.e.</p> <pre><code>uri = URI::HTTP.build(:host =&gt; "www.google.com", :query =&gt; { :q =&gt; "test" }.to_query) </code></pre>
2,150,138
How to parse milliseconds?
<p>How do I use <code>strptime</code> or any other functions to parse time stamps with milliseconds in R?</p> <pre><code>time[1] # [1] "2010-01-15 13:55:23.975" strptime(time[1], format="%Y-%m-%d %H:%M:%S.%f") # [1] NA strptime(time[1], format="%Y-%m-%d %H:%M:%S") # [1] "2010-01-15 13:55:23"` </code></pre>
2,150,179
2
0
null
2010-01-27 20:48:38.73 UTC
19
2022-08-04 14:52:40.453 UTC
2017-07-29 06:35:40.387 UTC
null
3,576,984
null
220,120
null
1
90
r|datetime|time-series|strptime
51,026
<p>Courtesy of the <code>?strptime</code> help file (with the example changed to your value):</p> <pre><code>&gt; z &lt;- strptime(&quot;2010-01-15 13:55:23.975&quot;, &quot;%Y-%m-%d %H:%M:%OS&quot;) &gt; z # prints without fractional seconds [1] &quot;2010-01-15 13:55:23 UTC&quot; &gt; op &lt;- options(digits.secs=3) &gt; z [1] &quot;2010-01-15 13:55:23.975 UTC&quot; &gt; options(op) #reset options </code></pre>
29,058,229
Download Xcode simulator directly
<p>I have downloaded Xcode 6.2 today which replaced previous Xcode 6.1 now to use simulator 7.1 &amp; 8.1 it asks to download both simulators , but for some reason after trying 4-5 times it shows network issues in downloading or request time out (note: in n/w diagnostic after it shows net is working properly)</p> <p>so is there any direct link from where i can download the simulator package directly or somewhere at least it shows progress in percentage/size instead just a bar </p> <p>if it's not possible i have read about copying the older simulator to new Xcode so how can i place the old simulator(7.1 &amp; 8.1) in Xcode 6.2 that it works directly without downloading again </p>
29,111,012
9
1
null
2015-03-15 07:20:59.617 UTC
54
2022-08-09 12:45:25.52 UTC
2018-06-04 15:14:42.277 UTC
null
5,638,630
null
4,557,505
null
1
88
ios|xcode|ios-simulator|simulator|xcode-6.2
114,247
<p>Clicking on Download in Xcode didn't do anything - the progress bar did not progress (does that make it a regress bar?).</p> <p>This is what worked for me:</p> <ol> <li><p>Open Xcode, open preferences, go to the Components section.</p> </li> <li><p>Open the Console App, clear the console.</p> </li> <li><p>Go back to the Xcode preferences. Start the simulator download, then cancel it.</p> </li> <li><p>Now in the Console, you will see something about the cancellation with the download URL.</p> </li> <li><p>Copy the URL from the Console. Then in Terminal in some suitable scratch folder, download it:</p> <blockquote> <p><code>curl [the url you copied] -O</code> (the letter O, not a zero)</p> </blockquote> </li> <li><p>Finally, copy this file to ~/Library/Caches/com.apple.dt.Xcode/Downloads<br /> Remove all *.dvtdownloadableindex files (maybe it doesn't matter, but I removed them).</p> </li> <li><p>In Xcode, in the Downloads section, start the Simulator download again, it should find the file you downloaded and install it.</p> </li> </ol> <p>How easy was that! Only 7 steps, hah!</p>
28,867,975
Unable to Sign In to iTunes Connect: "Your Apple ID isn't enabled for iTunes Connect"
<p>I am a member of my company's development team, with the role of Admin. I can access the Member Center of the team at <a href="https://developer.apple.com/" rel="nofollow noreferrer">https://developer.apple.com/</a></p> <p>However, when I I attempt to sign in at <a href="https://itunesconnect.apple.com" rel="nofollow noreferrer">https://itunesconnect.apple.com</a> I am presented with the following error message:</p> <p><img src="https://i.stack.imgur.com/EsW8h.png" alt="Your Apple ID isn&#39;t enabled for iTunes Connect"></p> <p><a href="https://i.stack.imgur.com/wTltZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wTltZ.png" alt="Your Apple ID isn&#39;t enabled for iTunes Connect"></a></p> <blockquote> <p>Your Apple ID isn't enabled for iTunes Connect. Learn More</p> </blockquote> <p>I am an admin on the development team. When I visit <code>Developer &gt; Member Center &gt; People</code> I do not see any permissions related to iTunes Connect.</p> <p>How do I gain access to my team's iTunes Connect portal?</p>
28,867,976
9
2
null
2015-03-05 00:40:14.813 UTC
11
2022-07-28 18:51:15.06 UTC
2019-10-31 21:02:05.827 UTC
null
1,265,393
null
1,265,393
null
1
46
app-store-connect|iphone-developer-program
65,078
<p>It is not enough to be a member of the Apple Developer Account / Member Center team.</p> <p>The account must <strong>also</strong> be added as an iTunes Connect User.</p> <p>From an <strong>existing iTunes Connect admin account</strong>, add the new user to iTunes Connect:</p> <p><code>iTunes Connect &gt; Users and Roles &gt; "+" &gt; Add iTunes Connect User</code></p> <p><img src="https://i.stack.imgur.com/MvF86.png" alt="Users and Roles"></p>
5,695,240
PHP: Regex to ignore escaped quotes within quotes
<p>I looked through related questions before posting this and I couldn't modify any relevant answers to work with my method (not good at regex).</p> <p>Basically, here are my existing lines:</p> <pre><code>$code = preg_replace_callback( '/"(.*?)"/', array( &amp;$this, '_getPHPString' ), $code ); $code = preg_replace_callback( "#'(.*?)'#", array( &amp;$this, '_getPHPString' ), $code ); </code></pre> <p>They both match strings contained between <code>''</code> and <code>""</code>. I need the regex to ignore escaped quotes contained between themselves. So data between <code>''</code> will ignore <code>\'</code> and data between <code>""</code> will ignore <code>\"</code>.</p> <p>Any help would be greatly appreciated.</p>
5,696,141
6
3
null
2011-04-17 17:48:07.98 UTC
20
2021-01-30 08:50:08.193 UTC
2013-10-24 01:10:35.47 UTC
null
15,168
null
711,416
null
1
35
php|regex
21,154
<p>For most strings, you need to allow escaped <em>anything</em> (not just escaped quotes). e.g. you most likely need to allow escaped characters like <code>"\n"</code> and <code>"\t"</code> and of course, the escaped-escape: <code>"\\"</code>.</p> <p>This is a frequently asked question, and one which was solved (and optimized) long ago. Jeffrey Friedl covers this question in depth (as an example) in his classic work: <a href="https://rads.stackoverflow.com/amzn/click/com/0596528124" rel="noreferrer" rel="nofollow noreferrer" title="Best book on Regex - ever!">Mastering Regular Expressions (3rd Edition)</a>. Here is the regex you are looking for:</p> <h2>Good:</h2> <p><code>"([^"\\]|\\.)*"</code><br> Version 1: Works correctly but is not terribly efficient.</p> <h2>Better:</h2> <p><code>"([^"\\]++|\\.)*"</code> or <code>"((?&gt;[^"\\]+)|\\.)*"</code><br> Version 2: More efficient if you have possessive quantifiers or atomic groups (See: sin's correct answer which uses the atomic group method).</p> <h2>Best:</h2> <p><code>"[^"\\]*(?:\\.[^"\\]*)*"</code><br> Version 3: More efficient still. Implements Friedl's: <em>"unrolling-the-loop"</em> technique. Does not require possessive or atomic groups (i.e. this can be used in Javascript and other less-featured regex engines.)</p> <p>Here are the recommended regexes in PHP syntax for both double and single quoted sub-strings:</p> <pre><code>$re_dq = '/"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"/s'; $re_sq = "/'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'/s"; </code></pre>
6,184,691
if statement for throwing Exception?
<p>Hi I wanted to ask because I'm not sure if is it propriete using of Exception:</p> <pre><code>public int Method(int a, int b) { if(a&lt;b) throw new ArgumentException("the first argument cannot be less than the second"); //do stuff... } </code></pre> <p>can I throw Exception after if statement? or should I always use try - catch when it goes with the exceptions?</p>
6,184,712
7
0
null
2011-05-31 08:11:02.317 UTC
2
2021-10-15 06:59:35.717 UTC
null
null
null
null
422,235
null
1
23
c#|exception|exception-handling
40,888
<p>That is perfectly valid. That is exactly what exceptions are used for, to check for "Exceptions" in your logic, things that weren't suppose to be.</p> <p>The idea behind catching an exception is that when you pass data somewhere and process it, you might not always know if the result will be valid, that is when you want to catch.</p> <p>Regarding your method, you don't want to catch inside <code>Method</code> but infact when you call it, here's an example:</p> <pre><code>try { var a = 10; var b = 100; var result = Method(a, b); } catch(ArgumentException ex) { // Report this back to the user interface in a nice way } </code></pre> <p>In the above case, a is less than b so you can except to get an exception here, and you can handle it accordingly.</p>
5,625,524
How to Close a program using python?
<p>Is there a way that python can close a windows application (example: Firefox) ?</p> <p>I know how to start an app, but now I need to know how to close one.</p>
10,457,565
7
5
null
2011-04-11 18:09:13.777 UTC
11
2022-08-10 18:24:05.787 UTC
2020-06-18 16:05:27.67 UTC
null
6,451,573
null
514,584
null
1
29
python
97,457
<pre><code># I have used subprocess comands for a while # this program will try to close a firefox window every ten secounds import subprocess import time # creating a forever loop while 1 : subprocess.call(&quot;TASKKILL /F /IM firefox.exe&quot;, shell=True) time.sleep(10) </code></pre>
5,753,680
Change CSS of class in Javascript?
<p>I've got a class with the display set to <code>none</code> I'd like to in Javascript now set it to <code>inline</code> I'm aware I can do this with an <code>id</code> with <code>getElementById</code> but what's the cleanest way to do it with a class?</p>
5,753,733
8
2
null
2011-04-22 08:33:28.45 UTC
6
2021-05-01 11:50:40.43 UTC
2019-04-02 06:54:01.623 UTC
null
860,099
null
358,438
null
1
35
javascript|css
104,346
<p>You <strong>can</strong> do that — actually change style rules related to a class — using the <code>styleSheets</code> array (<a href="https://developer.mozilla.org/en-US/docs/Web/API/StyleSheetList" rel="nofollow noreferrer">MDN link</a>), but frankly you're probably better off (as changelog said) having a separate style that defines the <code>display: none</code> and then removing that style from elements when you want them no longer hidden.</p>
5,757,555
How do I trigger the success callback on a model.save()?
<pre><code>this.model.save({ success: function(model, response){ console.log('success'); }, error: function(){ console.log('error'); } }) </code></pre> <p>The model is correctly posted to the server which handles the save, but the success callback is not fired. Do I need to send something back from the server ?</p>
5,759,860
8
4
null
2011-04-22 16:25:12.733 UTC
21
2015-07-02 16:58:54.177 UTC
2011-04-22 16:28:11.567 UTC
null
560,648
null
565,299
null
1
107
backbone.js
70,182
<p>The first argument of save is the attributes to save on the model:</p> <pre><code>this.model.save( {att1 : "value"}, {success :handler1, error: handler2}); </code></pre>
5,631,618
How to fix "Configuration system failed to initialize/Root element is missing" error when loading config file?
<p>I got this error in my c# windows application: "Configuration system failed to initialize". </p> <p>It was working fine. Suddenly I got this exception. It shows inner exception detail as "Root element is missing". (C:\Users\company\AppData\Local\Clickbase_Corp_Sverige_AB\TouchStation.vshost.exe_Url_no1nets4fg3oy2p2q2pnwgulbvczlv33\1.1.0.12\user.config)"}.This happens when I try to get values from Settings.cs class.</p> <p>In program.cs file the below code is written</p> <pre><code>if (Properties.Settings.Default.CallUpgrade) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.CallUpgrade = false; Properties.Settings.Default.Save(); } </code></pre> <p>And calls settings.cs class where the below code throws above exception</p> <pre><code> [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("True")] public bool CallUpgrade { get { return ((bool)(this["CallUpgrade"])); } set { this["CallUpgrade"] = value; } } </code></pre> <p>The below is my entire app.config</p> <pre class="lang-xml prettyprint-override"><code>&lt;configuration&gt; &lt;configSections&gt; &lt;sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"&gt; &lt;section name="TouchStation.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /&gt; &lt;section name="TouchStation.TouchStation" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /&gt; &lt;/sectionGroup&gt; &lt;sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"&gt; &lt;section name="TouchStation.TouchStation" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /&gt; &lt;/sectionGroup&gt; &lt;section name="SitesInfo" type="TouchServer.SitesInfoSectionHandler,TouchServerLib" /&gt; &lt;/configSections&gt; &lt;appSettings&gt; &lt;add key="WebRoot" value="webroot" /&gt; &lt;add key="TempDir" value="temp" /&gt; &lt;add key="ServerPort" value="9338" /&gt; &lt;add key="ClientSettingsProvider.ServiceUri" value="" /&gt; &lt;/appSettings&gt; &lt;userSettings&gt; &lt;TouchStation.Properties.Settings&gt; &lt;setting name="Site" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="StationID" serializeAs="String"&gt; &lt;value&gt;0&lt;/value&gt; &lt;/setting&gt; &lt;setting name="Location" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="ShutdownTime" serializeAs="String"&gt; &lt;value&gt;0000&lt;/value&gt; &lt;/setting&gt; &lt;setting name="ReportStatusEvery" serializeAs="String"&gt; &lt;value&gt;0&lt;/value&gt; &lt;/setting&gt; &lt;setting name="SynchronizeEvery" serializeAs="String"&gt; &lt;value&gt;10&lt;/value&gt; &lt;/setting&gt; &lt;setting name="DefaultUsername" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="DefaultPassword" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="WatchdogTimeout" serializeAs="String"&gt; &lt;value&gt;60&lt;/value&gt; &lt;/setting&gt; &lt;setting name="RebootOnTimeout" serializeAs="String"&gt; &lt;value&gt;False&lt;/value&gt; &lt;/setting&gt; &lt;setting name="AnonymousLogin" serializeAs="String"&gt; &lt;value&gt;True&lt;/value&gt; &lt;/setting&gt; &lt;setting name="RefID" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="AutoStart" serializeAs="String"&gt; &lt;value&gt;False&lt;/value&gt; &lt;/setting&gt; &lt;setting name="DemoMode" serializeAs="String"&gt; &lt;value&gt;True&lt;/value&gt; &lt;/setting&gt; &lt;setting name="UnlockPassword" serializeAs="String"&gt; &lt;value&gt;needle&lt;/value&gt; &lt;/setting&gt; &lt;setting name="SynchronizerUsername" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="SynchronizerPassword" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="RunClientApplications" serializeAs="String"&gt; &lt;value&gt;False&lt;/value&gt; &lt;/setting&gt; &lt;setting name="MapID" serializeAs="String"&gt; &lt;value&gt;0&lt;/value&gt; &lt;/setting&gt; &lt;setting name="ServerName" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="CallUpgrade" serializeAs="String"&gt; &lt;value&gt;True&lt;/value&gt; &lt;/setting&gt; &lt;setting name="ServerPort" serializeAs="String"&gt; &lt;value&gt;9338&lt;/value&gt; &lt;/setting&gt; &lt;/TouchStation.Properties.Settings&gt; &lt;TouchStation.TouchStation&gt; &lt;setting name="ServerURL" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="Site" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="StationID" serializeAs="String"&gt; &lt;value&gt;0&lt;/value&gt; &lt;/setting&gt; &lt;setting name="Location" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="ShutdownTime" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="ReportStatusEvery" serializeAs="String"&gt; &lt;value&gt;0&lt;/value&gt; &lt;/setting&gt; &lt;setting name="SynchronizeEvery" serializeAs="String"&gt; &lt;value&gt;0&lt;/value&gt; &lt;/setting&gt; &lt;setting name="HideMouse" serializeAs="String"&gt; &lt;value&gt;False&lt;/value&gt; &lt;/setting&gt; &lt;setting name="HideDesktopOnStart" serializeAs="String"&gt; &lt;value&gt;False&lt;/value&gt; &lt;/setting&gt; &lt;setting name="DefaultUsername" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="DefaultPassword" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;setting name="LogServerPort" serializeAs="String"&gt; &lt;value&gt;9050&lt;/value&gt; &lt;/setting&gt; &lt;setting name="WatchdogTimeout" serializeAs="String"&gt; &lt;value&gt;60&lt;/value&gt; &lt;/setting&gt; &lt;setting name="RebootOnTimeout" serializeAs="String"&gt; &lt;value&gt;False&lt;/value&gt; &lt;/setting&gt; &lt;setting name="AnonymousLogin" serializeAs="String"&gt; &lt;value&gt;True&lt;/value&gt; &lt;/setting&gt; &lt;setting name="RefID" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;/TouchStation.TouchStation&gt; &lt;/userSettings&gt; &lt;applicationSettings&gt; &lt;TouchStation.TouchStation&gt; &lt;setting name="ClientSettingsURL" serializeAs="String"&gt; &lt;value /&gt; &lt;/setting&gt; &lt;/TouchStation.TouchStation&gt; &lt;/applicationSettings&gt; &lt;SitesInfo&gt; &lt;sites&gt; &lt;site Name="Local" FullName="Local Site" DatabaseConnectionString="Data\local.db" /&gt; &lt;/sites&gt; &lt;/SitesInfo&gt; &lt;system.web&gt; &lt;membership defaultProvider="ClientAuthenticationMembershipProvider"&gt; &lt;providers&gt; &lt;add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" /&gt; &lt;/providers&gt; &lt;/membership&gt; &lt;roleManager defaultProvider="ClientRoleProvider" enabled="true"&gt; &lt;providers&gt; &lt;add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" /&gt; &lt;/providers&gt; &lt;/roleManager&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>can anyone help me in this?</p> <p>Thank You.</p> <p>Regards,</p> <p>jennie</p>
5,631,775
12
3
null
2011-04-12 07:10:51.583 UTC
2
2022-06-14 02:30:28.17 UTC
2011-04-12 08:59:02.677 UTC
null
447,356
null
703,526
null
1
15
c#|config
54,367
<p>The cause of the <code>XmlException</code> entitled Root element is missing means the XML document (The config file here) you're trying to load is not formatted properly, more exactly it's missing the root node.</p> <p>Each XML file must have a root element / node which encloses all the other elements.</p> <p>Your file must look like the following:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" &gt; &lt;/sectionGroup&gt; &lt;/configSections&gt; &lt;userSettings&gt; &lt;WindowsFormsApplication.Properties.Settings&gt; &lt;/WindowsFormsApplication.Properties.Settings&gt; &lt;/userSettings&gt; &lt;/configuration&gt; </code></pre>
44,173,624
How to apply NLTK word_tokenize library on a Pandas dataframe for Twitter data?
<p>This is the Code that I am using for semantic analysis of twitter:-</p> <pre><code>import pandas as pd import datetime import numpy as np import re from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.porter import PorterStemmer df=pd.read_csv('twitDB.csv',header=None, sep=',',error_bad_lines=False,encoding='utf-8') hula=df[[0,1,2,3]] hula=hula.fillna(0) hula['tweet'] = hula[0].astype(str) +hula[1].astype(str)+hula[2].astype(str)+hula[3].astype(str) hula["tweet"]=hula.tweet.str.lower() ho=hula["tweet"] ho = ho.replace('\s+', ' ', regex=True) ho=ho.replace('\.+', '.', regex=True) special_char_list = [':', ';', '?', '}', ')', '{', '('] for special_char in special_char_list: ho=ho.replace(special_char, '') print(ho) ho = ho.replace('((www\.[\s]+)|(https?://[^\s]+))','URL',regex=True) ho =ho.replace(r'#([^\s]+)', r'\1', regex=True) ho =ho.replace('\'"',regex=True) lem = WordNetLemmatizer() stem = PorterStemmer() fg=stem.stem(a) eng_stopwords = stopwords.words('english') ho = ho.to_frame(name=None) a=ho.to_string(buf=None, columns=None, col_space=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=False, index_names=True, justify=None, line_width=None, max_rows=None, max_cols=None, show_dimensions=False) wordList = word_tokenize(fg) wordList = [word for word in wordList if word not in eng_stopwords] print (wordList) </code></pre> <p>Input i.e. a :-</p> <pre><code> tweet 0 1495596971.6034188::automotive auto ebc greens... 1 1495596972.330948::new free stock photo of cit... </code></pre> <p>getting output ( wordList) in this format:-</p> <pre><code>tweet 0 1495596971.6034188 : :automotive auto </code></pre> <p>I want the output of a row in a row format only. How can I do it? If you have a better code for semantic analysis of twitter please share it with me.</p>
44,174,565
1
0
null
2017-05-25 06:21:49.383 UTC
12
2020-08-22 03:06:13.1 UTC
2018-10-19 18:58:35.077 UTC
null
8,047,559
null
8,047,559
null
1
13
python|pandas|twitter|nltk|tokenize
37,100
<p>In short:</p> <pre><code>df['Text'].apply(word_tokenize) </code></pre> <p>Or if you want to add another column to store the tokenized list of strings:</p> <pre><code>df['tokenized_text'] = df['Text'].apply(word_tokenize) </code></pre> <p>There are tokenizers written specifically for twitter text, see <a href="http://www.nltk.org/api/nltk.tokenize.html#module-nltk.tokenize.casual" rel="noreferrer">http://www.nltk.org/api/nltk.tokenize.html#module-nltk.tokenize.casual</a> </p> <p>To use <code>nltk.tokenize.TweetTokenizer</code>:</p> <pre><code>from nltk.tokenize import TweetTokenizer tt = TweetTokenizer() df['Text'].apply(tt.tokenize) </code></pre> <p>Similar to:</p> <ul> <li><p><a href="https://stackoverflow.com/questions/41674573/how-to-apply-pos-tag-sents-to-pandas-dataframe-efficiently">How to apply pos_tag_sents() to pandas dataframe efficiently</a></p></li> <li><p><a href="https://stackoverflow.com/questions/33098040/how-to-use-word-tokenize-in-data-frame">how to use word_tokenize in data frame</a></p></li> <li><p><a href="https://stackoverflow.com/questions/41674573/how-to-apply-pos-tag-sents-to-pandas-dataframe-efficiently">How to apply pos_tag_sents() to pandas dataframe efficiently</a> </p></li> <li><p><a href="https://stackoverflow.com/questions/38119954/tokenizing-words-into-a-new-column-in-a-pandas-dataframe">Tokenizing words into a new column in a pandas dataframe</a></p></li> <li><p><a href="https://stackoverflow.com/questions/43922145/run-nltk-sent-tokenize-through-pandas-dataframe">Run nltk sent_tokenize through Pandas dataframe</a></p></li> <li><p><a href="https://stackoverflow.com/questions/34784004/python-text-processing-nltk-and-pandas">Python text processing: NLTK and pandas</a></p></li> </ul>
49,648,270
how to define index in angular material table
<p>how should I define an index variable when angular material table is used as ngFor is not used in this table. </p> <p>I did search for it in the documentation but index is not mentioned any where in it. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;mat-table #table [dataSource]="dataSource"&gt; &lt;!--- Note that these columns can be defined in any order. The actual rendered columns are set as a property on the row definition" --&gt; &lt;!-- Position Column --&gt; &lt;ng-container matColumnDef="position"&gt; &lt;mat-header-cell *matHeaderCellDef&gt; No. &lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef="let element"&gt; {{element.position}} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;!-- Name Column --&gt; &lt;ng-container matColumnDef="name"&gt; &lt;mat-header-cell *matHeaderCellDef&gt; Name &lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef="let element"&gt; {{element.name}} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;!-- Weight Column --&gt; &lt;ng-container matColumnDef="weight"&gt; &lt;mat-header-cell *matHeaderCellDef&gt; Weight &lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef="let element"&gt; {{element.weight}} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;!-- Symbol Column --&gt; &lt;ng-container matColumnDef="symbol"&gt; &lt;mat-header-cell *matHeaderCellDef&gt; Symbol &lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef="let element"&gt; {{element.symbol}} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;mat-header-row *matHeaderRowDef="displayedColumns"&gt;&lt;/mat-header-row&gt; &lt;mat-row *matRowDef="let row; columns: displayedColumns;"&gt;&lt;/mat-row&gt; &lt;/mat-table&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>where and how do i define an index variable for the array that I used in this table, so that I can bind the index value in my table itself.</p>
49,648,620
9
2
null
2018-04-04 10:05:10.06 UTC
11
2021-12-31 13:02:31.43 UTC
2021-01-11 08:43:49.4 UTC
null
7,436,489
null
8,483,823
null
1
85
javascript|angular|typescript|angular-material2
103,591
<p>Can you add <code>index</code> to <code>let element; let i = index;&quot;</code> as you'd do with <code>*ngFor</code>?</p> <pre class="lang-xml prettyprint-override"><code>&lt;mat-row *matRowDef=&quot;let row; columns: displayedColumns; let i = index&quot;&gt;&lt;/mat-row&gt; </code></pre> <p>Or like so:</p> <pre class="lang-xml prettyprint-override"><code>&lt;ng-container matColumnDef=&quot;index&quot;&gt; &lt;mat-header-cell *matHeaderCellDef&gt; Index &lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef=&quot;let element; let i = index;&quot;&gt;{{i}}&lt;/mat-cell&gt; &lt;/ng-container&gt; </code></pre> <p>Working Example: <a href="https://stackblitz.com/edit/angular-acdxje?file=app/table-basic-example.html" rel="noreferrer">https://stackblitz.com/edit/angular-acdxje?file=app/table-basic-example.html</a></p>
41,068,599
How do I set the animation color of a LinearProgressIndicator?
<p>The <a href="https://docs.flutter.io/flutter/material/LinearProgressIndicator-class.html" rel="noreferrer">LinearProgressIndicator documentation</a> helpfully displays the existence of a valueColor property and even mentions &quot;To specify a constant color use: new AlwaysStoppedAnimation(color).&quot;, but if I try to set the color I get an error that LinearProgressIndicator has no instance setter for valueColor and the constructor for the class only accepts a key and a numerical value for the progress amount.</p> <p>If I want a LinearProgressIndicator with a custom color do I need to create my own class? Is there really no way to specify this?</p>
41,069,053
5
0
null
2016-12-09 20:44:44.327 UTC
2
2022-09-24 22:35:54.563 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
3,134,918
null
1
40
flutter
26,964
<p>Looks like it's controlled from the Theme's accent color: <a href="https://github.com/flutter/flutter/blob/b670ce4bcc49bbab745221eae24fcebcbc9dba7c/packages/flutter/lib/src/material/progress_indicator.dart#L61" rel="noreferrer">https://github.com/flutter/flutter/blob/b670ce4bcc49bbab745221eae24fcebcbc9dba7c/packages/flutter/lib/src/material/progress_indicator.dart#L61</a></p> <p>Wrap the relevant subtree in a modified Theme setting the accentColor to whatever you might like.</p>
40,836,208
Set maximum value (upper bound) in pandas DataFrame
<p>I'm trying to set a maximum value of a pandas DataFrame column. For example:</p> <pre><code>my_dict = {'a':[10,12,15,17,19,20]} df = pd.DataFrame(my_dict) df['a'].set_max(15) </code></pre> <p>would yield:</p> <pre><code> a 0 10 1 12 2 15 3 15 4 15 5 15 </code></pre> <p>But it doesn't. </p> <p>There are a million solutions to <em>find</em> the maximum value, but nothing to <em>set</em> the maximum value... at least that I can find. </p> <p>I could iterate through the list, but I suspect there is a faster way to do it with pandas. My lists will be significantly longer and thus I would expect iteration to take relatively longer amount of time. Also, I'd like whatever solution to be able to handle <code>NaN</code>.</p>
40,836,266
3
0
null
2016-11-28 02:11:08.86 UTC
4
2019-06-04 19:44:31.023 UTC
2019-01-03 13:45:46.043 UTC
null
4,909,087
null
6,163,621
null
1
29
python|pandas|dataframe|max
40,276
<p>I suppose you can do:</p> <pre><code>maxVal = 15 df['a'].where(df['a'] &lt;= maxVal, maxVal) # where replace values with other when the # condition is not satisfied #0 10 #1 12 #2 15 #3 15 #4 15 #5 15 #Name: a, dtype: int64 </code></pre> <p>Or:</p> <pre><code>df['a'][df['a'] &gt;= maxVal] = maxVal </code></pre>
38,393,343
How to use ansible 'expect' module for multiple different responses?
<p>Here I am trying to test my bash script where it is prompting four times.</p> <pre><code>#!/bin/bash date &gt;/opt/prompt.txt read -p "enter one: " one echo $one echo $one &gt;&gt;/opt/prompt.txt read -p "enter two: " two echo $two echo $two &gt;&gt;/opt/prompt.txt read -p "enter three: " three echo $three echo $three &gt;&gt;/opt/prompt.txt read -p "enter password: " password echo $password echo $password &gt;&gt;/opt/prompt.txt </code></pre> <p>for this script I wrote the code below, and it is working fine</p> <pre><code>- hosts: "{{ hosts }}" tasks: - name: Test Script expect: command: sc.sh responses: enter one: 'one' enter two: 'two' enter three: 'three' enter password: 'pass' echo: yes </code></pre> <p>But if I am doing the same for <code>mysql_secure_installation</code> command it not working</p> <pre><code>- hosts: "{{ hosts }}" tasks: - name: mysql_secure_installation Command Test expect: command: mysql_secure_installation responses: 'Enter current password for root (enter for none):': "\n" 'Set root password? [Y/n]:': 'y' 'New password:': '123456' 'Re-enter new password:': '123456' 'Remove anonymous users? [Y/n]:': 'y' 'Disallow root login remotely? [Y/n]:': 'y' 'Remove test database and access to it? [Y/n]:': 'y' 'Reload privilege tables now? [Y/n]:': 'y' echo: yes </code></pre> <p>and its trackback is here:</p> <pre><code>PLAY [S1] ********************************************************************** TASK [setup] ******************************************************************* ok: [S1] TASK [mysql_secure_installation Command Test] ********************************** fatal: [S1]: FAILED! =&gt; {"changed": true, "cmd": "mysql_secure_installation", "delta": "0:00:30.139266", "end": "2016-07-15 15:36:32.549415", "failed": true, "rc": 1, "start": "2016-07-15 15:36:02.410149", "stdout": "\r\n\r\n\r\n\r\nNOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL\r\n SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!\r\n\r\n\r\nIn order to log into MySQL to secure it, we'll need the current\r\npassword for the root user. If you've just installed MySQL, and\r\nyou haven't set the root password yet, the password will be blank,\r\nso you should just press enter here.\r\n\r\nEnter current password for root (enter for none): ", "stdout_lines": ["", "", "", "", "NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL", " SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!", "", "", "In order to log into MySQL to secure it, we'll need the current", "password for the root user. If you've just installed MySQL, and", "you haven't set the root password yet, the password will be blank,", "so you should just press enter here.", "", "Enter current password for root (enter for none): "]} NO MORE HOSTS LEFT ************************************************************* to retry, use: --limit @/home/jackson/AnsibleWorkSpace/AnsibleTest/example1.retry PLAY RECAP ********************************************************************* S1 : ok=1 changed=0 unreachable=0 failed=1 </code></pre> <p>I have also tried blank <code>''</code> instead of <code>"\n"</code> for the first answer but it is not working either. I also visited Ansible <a href="http://docs.ansible.com/ansible/expect_module.html" rel="noreferrer"><code>expect</code></a> doc but they show only very simple example and explanation. I am also trying regex match for multiple different responses but it is also not working.<br> Please do not recommend me to use mysql module of Ansible, because here my purpose is to learn this module for future use.</p>
39,458,575
1
0
null
2016-07-15 10:04:40.157 UTC
3
2019-10-04 18:59:37.053 UTC
2019-10-04 18:59:37.053 UTC
null
2,123,530
null
5,433,567
null
1
21
python|python-2.7|ansible|ansible-2.x
42,590
<p>The reason is that the questions are interpreted as regexps. Hence you must escape characters with a special meaning in regular expressions, such as -()[]\?*. et cetara.</p> <p>Hence:</p> <pre><code>'Enter current password for root (enter for none):' </code></pre> <p>should instead be:</p> <pre><code>'Enter current password for root \(enter for none\):' </code></pre> <p>Good luck!</p>
35,154,717
Is dependency-reduced-pom.xml automatically used instead of pom.xml?
<p>Is <code>dependency-reduced-pom.xml</code> created by <a href="http://maven.apache.org/plugins/maven-shade-plugin/" rel="noreferrer">Maven shade plugin</a> <strong>automatically</strong> used in projects that depends on the uberjar (instead of the ordinary <code>pom.xml</code>)?</p> <p>Asking this after reading a number of dependency-reduced-pom.xml related questions and haven't found the answer yet:</p> <p><a href="https://stackoverflow.com/questions/11314182/maven-shade-plugin-adding-dependency-reduced-pom-xml-to-base-directory">Maven shade plugin adding dependency-reduced-pom.xml to base directory</a></p> <p><a href="https://stackoverflow.com/questions/22904573/what-is-the-purpose-of-dependency-reduced-pom-xml-generated-by-the-shade-plugin">What is the purpose of dependency-reduced-pom.xml generated by the shade plugin?</a></p> <p><a href="https://stackoverflow.com/questions/26500735/what-is-dependency-reduced-pom-xml-file-which-created-when-calling-maven-packa">What is `dependency-reduced-pom.xml` file which created when calling maven package command?</a></p>
35,155,294
1
0
null
2016-02-02 13:22:55.687 UTC
5
2021-01-11 16:46:43.187 UTC
2021-01-11 16:46:43.187 UTC
null
6,156,700
null
2,811,258
null
1
36
maven|maven-3|maven-shade-plugin
14,516
<p>The <code>dependency-reduced-pom.xml</code> is generated at build time into <code>${basedir}</code> of the project. This file is a temporary file that is only used for packaging into the shaded jar. Quoting the documentation of the <a href="https://maven.apache.org/plugins/maven-shade-plugin/shade-mojo.html#createDependencyReducedPom"><code>createDependencyReducedPom</code></a> attribute:</p> <blockquote> <p>Flag whether to generate a simplified POM for the shaded artifact. If set to <code>true</code>, dependencies that have been included into the uber JAR will be removed from the <code>&lt;dependencies&gt;</code> section of the generated POM. The reduced POM will be named <code>dependency-reduced-pom.xml</code> and is <strong>stored into the same directory as the shaded artifact</strong>. Unless you also specify <code>dependencyReducedPomLocation</code>, the plugin will create a <strong>temporary file</strong> named <code>dependency-reduced-pom.xml</code> in the project basedir.</p> </blockquote> <p>To make it clear, after the <code>maven-shade-plugin</code> has run:</p> <ul> <li>your initial POM will be left unchanged;</li> <li>a temporary file that you can completely ignore named <code>dependency-reduced-pom.xml</code> will have been generated inside the root folder (<a href="https://maven.apache.org/plugins/maven-shade-plugin/shade-mojo.html#dependencyReducedPomLocation">this is considered an open issue with this plugin</a>);</li> <li>the shaded artifact will contain your initial POM unchanged inside the <code>META-INF</code> directory and not the reduced POM (this is not really important but better mention it - there was an issue about this that was closed automatically: <a href="https://issues.apache.org/jira/browse/MSHADE-36">MSHADE-36</a>);</li> <li>the POM that will be deployed is the reduced POM;</li> <li>the shaded artifact will be by default the main artifact of the project.</li> </ul>
27,580,267
How to make all interactions before using glmnet
<p>I have an x-matrix of 8 columns. I want to run <code>glmnet</code> to do a lasso regression. I know I need to call:</p> <pre><code>glmnet(x, y, family = "binomial", ...). </code></pre> <p>However, how do I get <code>x</code> to consider all one way interactions as well? Do I have to manually remake the data frame: if so, is there an easier way? I suppose I was hoping to do something using an R formula.</p>
27,583,931
2
0
null
2014-12-19 23:58:24.177 UTC
12
2020-02-25 22:44:58.46 UTC
2017-01-31 06:58:11.533 UTC
null
202,229
user1357015
1,357,015
null
1
21
r|formula|interaction|glmnet
10,425
<p>Yes, there is a convenient way for that. Two steps in it are important.</p> <pre><code>library(glmnet) # Sample data data &lt;- data.frame(matrix(rnorm(9 * 10), ncol = 9)) names(data) &lt;- c(paste0("x", 1:8), "y") # First step: using .*. for all interactions f &lt;- as.formula(y ~ .*.) y &lt;- data$y # Second step: using model.matrix to take advantage of f x &lt;- model.matrix(f, data)[, -1] glmnet(x, y) </code></pre>
43,770,579
how to change the color in geom_point or lines in ggplot
<p>I have a data like this</p> <pre><code>data&lt;- structure(list(sample = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("A", "B"), class = "factor"), y = c(0.99999652, 0.99626012, 0.94070452, 0.37332406, 0.57810894, 0.37673758, 0.22784684, 0.35358141, 0.21253558, 0.17715703, 0.99999652, 0.86403956, 0.64054516, 0.18448824, 0.40362691, 0.10791682, 0.06985696, 0.07384465, 0.0433271, 0.02875159), time = c(100L, 150L, 170L, 180L, 190L, 220L, 260L, 270L, 300L, 375L, 100L, 150L, 170L, 180L, 190L, 220L, 260L, 270L, 300L, 375L), x = c(0.9999965, 0.9981008, 0.9940164, 1.0842966, 0.9412978, 1.0627907, 0.9135079, 1.1982235, 0.9194105, 0.9361713, 0.9999965, 1.0494051, 0.9526752, 1.1594711, 0.9827104, 1.0223711, 1.1419197, 1.0328598, 0.6015229, 0.3745817)), .Names = c("sample", "y", "time", "x"), class = "data.frame", row.names = c(NA, -20L)) </code></pre> <p>I am interested in plotting it with a costumed color like black and red</p> <p>I can plot it with two random different color like this but the problem is that </p> <pre><code>ggplot() + geom_point(data = data, aes(x = time, y = y, color = sample),size=4) </code></pre> <p>if I want to assign the first one (A) to black and the (B) to red. how can I do that? </p>
43,770,608
2
0
null
2017-05-03 21:50:00.107 UTC
1
2017-05-03 22:14:14.573 UTC
null
null
null
null
5,919,561
null
1
10
r|ggplot2
54,295
<p>You could use <code>scale_color_manual</code>:</p> <pre><code>ggplot() + geom_point(data = data, aes(x = time, y = y, color = sample),size=4) + scale_color_manual(values = c("A" = "black", "B" = "red")) </code></pre> <p><a href="https://i.stack.imgur.com/3m6bP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3m6bP.png" alt="enter image description here"></a></p> <hr> <p>Per OP's comment, to get lines with the same color as the points you could do:</p> <pre><code>ggplot(data = data, aes(x = time, y = y, color = sample)) + geom_point(size=4) + geom_line(aes(group = sample)) + scale_color_manual(values = c("A" = "black", "B" = "red")) </code></pre> <p><a href="https://i.stack.imgur.com/hUHhp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hUHhp.png" alt="enter image description here"></a></p>
49,660,399
Is it possible to create and handle a custom Event in a Customized UserForm?
<p>I have a <code>UserForm</code> to which I added a property with the adequate Let and Get statements. I would like to have an event fire when the property changes. Event, <code>RaiseEvent</code> and Routine have been stated, all in the <code>UserForm</code> module. However, I can't find a way to assign the routine to the event.</p> <p>For what I know, this is different from the usual Custom Events in Class Modules situation, because it is not declared in a Class Module whose Class I can instantiate in a regular module. All my searches provided examples to Custom Events in Class Modules or Built-In Events in UserForms, but no material on Custom Events in UserForms.</p> <p>This actually made me wonder if it is at all possible to create Custom Events in UserForms and Private Subs to handle those Events. So is it possible to do it? And if so, what am I missing? How can I make <code>Private Sub UFStatus_StatusChange()</code> handle the event?</p> <p>Any help would be apreciated!</p> <p>So far, the code goes, all in the UserForm module:</p> <pre><code>Public Event StatusChange (old_status As Long, current_status As Long) Dim old_status As Long Private current_status As Long Public Property Let UFStatus (RHS As Long) old_status = current_status current_status = RHS RaiseEvent StatusChange(old_status, current_status) End Property Private Sub UFStatus_StatusChange() MsgBox("Status changed from " &amp; old_status &amp; "to " &amp; current_status) End Sub </code></pre>
49,661,053
1
0
null
2018-04-04 21:03:44.463 UTC
16
2018-04-14 22:31:13.92 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
7,350,537
null
1
7
vba|excel
3,537
<p>Yes, but you need to understand how VBA/COM events work first.</p> <h3>A bit of background...</h3> <p>Notice the dropdowns/comboboxes at the top of the VBE's code panes? The leftmost one is listing all available <em>interfaces</em> and <em>event providers</em> - the rightmost one is listing the available <em>members</em> and <em>events</em> exposed by whatever is selected in the leftmost dropdown.</p> <p>So when you handle the <code>Click</code> event of some <code>OkButton</code> in the code-behind of <code>UserForm1</code>, the handler stub might look like this:</p> <pre><code>Private Sub OkButton_Click() End Sub </code></pre> <p>The signature is constructed in a very particular way, always in the same manner, regardless of whether you're implementing an interface or handling an event:</p> <pre><code>Private Sub [Provider]_[MemberName]([Args]) </code></pre> <p>That underscore matters. Whatever you do, <strong>DO NOT</strong> name an event (or interface member) with an identifier that contains an underscore. In the case of an event, you'll hit a compile error:</p> <blockquote> <p>Compile error: Invalid event name</p> </blockquote> <p>In the case of an interface, you'll also get a compile error, with the VBE complaining that interface members aren't implemented.</p> <p>This is why everything is <code>PascalCase</code> and not <code>Upper_Snake_Case</code> in VB. Stick to the convention, avoid underscores in public member names.</p> <p>If you're not sure what interfaces are and why I'm mentioning them in a post about events, lookup the <code>Implements</code> keyword, know that interfaces and events are very intimately related and work in a very similar fashion, and keep reading ;-)</p> <hr> <h3>The Provider</h3> <p>Any <em>class</em> can define events. A <code>UserForm</code> being a class, it can absolutely define events, yes. You define events exactly how you've done, using the <code>Event</code> keyword:</p> <pre><code>Public Event SomethingHappened(ByVal SomeArg As Long) </code></pre> <p>The class that defines the event is an event <em>provider</em> - it is the only class that is allowed to <em>raise</em> the events it defines.</p> <p>You raise events using the <code>RaiseEvent</code> keyword, and provide the arguments:</p> <pre><code>Private Sub OnSomethingHappened() RaiseEvent SomethingHappened(42) End Sub </code></pre> <p>When and why you raise events is entirely up to your imagination.</p> <hr> <h3>The Client</h3> <p>Consider the <code>Click</code> event of a <code>CommandButton</code> on a <code>UserForm</code>: the <code>CommandButton</code> class probably has a method that listens for Win32 messages involving the mouse, and when it decides to handle a left-button click, it raises its <code>Click</code> event, and <em>something something</em> and poof the <code>OkButton_Click</code> procedure runs. Right?</p> <p>The part MSForms is automagically doing for you, is that when you add a <code>CommandButton</code> on the form, and name it <code>OkButton</code>, well this <code>OkButton</code> identifier essentially becomes a public field on the form, as if you had added a public, module-level variable:</p> <pre><code>Public OkButton As MSForms.CommandButton </code></pre> <p>Except, it actually looks like this:</p> <pre><code>Public WithEvents OkButton As MSForms.CommandButton </code></pre> <p>That <code>WithEvents</code> keyword makes the <code>OkButton</code> available in the left-side dropdown - <code>OkButton</code> becomes an <em>event provider</em>, and its <code>Click</code> event can be handled... in the form's code-behind.</p> <p>The <code>CommandButton</code> class doesn't know or care about a handler for its <code>Click</code> event: the event provider is the <code>OkButton</code> object, and the <em>client</em> is the <code>UserForm1</code> class you're implementing the handlers in.</p> <p>In other words, the event provider, and the client, are two completely separate classes.</p> <hr> <p>The catch is that <code>WithEvents</code> is only legal in a class module.</p> <p>You can make your <code>UserForm1</code> an <em>event provider</em>, but it cannot handle its own events.</p> <p>Declare the events in your <code>UserForm1</code> code-behind, and make sure you specify <code>ByVal</code> parameters for parameters that are meant to be read-only at the handler site - use <code>ByRef</code> when the handler can modify the value, e.g. for some <code>Cancel As Boolean</code> parameter that you can read when the handler returns:</p> <pre><code>Public Event StatusChange(ByVal oldStatus As Long, ByVal newStatus As Long) </code></pre> <p>Now add a class module, call it <code>MyPresenter</code>:</p> <pre><code>Option Explicit Private WithEvents MyView As UserForm1 Private Sub Class_Initialize() Set MyView = New UserForm1 End Sub Private Sub Class_Terminate() Set MyView = Nothing End Sub Public Sub ShowDialog() MyView.Show End Sub </code></pre> <p>Select <code>MyView</code> from the leftmost dropdown; the rightmost dropdown should contain the <code>StatusChange</code> event - and selecting it should create a handler stub:</p> <pre><code>Private Sub MyView_StatusChange(ByVal oldStatus As Long, ByVal newStatus As Long) MsgBox "Status changed from " &amp; oldStatus &amp; " to " &amp; newStatus &amp; "!" End Sub </code></pre> <p>Now, in the standard/procedural module where you were normally showing your form, instantiate that presenter class instead:</p> <pre><code>Public Sub Macro1() With New MyPresenter .ShowDialog End With End Sub </code></pre>
44,129,108
How to get path from file upload input in angular 4
<p>I want to upload an image and create a preview of it in angular 4. <br> The template is given below:<br></p> <pre><code>&lt;div&gt; &lt;input type="file" (onchange)="handleUpload($event)"&gt; &lt;img [src]="Logo" &gt; &lt;/div </code></pre> <p>I want to call a function <code>handleUpload()</code> whenever a file is chosen. This function sets the value of the variable <code>Logo</code> to the path of the file chosen. I am not able to get the path because the function <code>handleUpload($event)</code> is not called. <br>The component class is given below:<br></p> <pre><code> export class App { Logo:string; handleUpload(e):void{ this.Logo = e.target.value; } constructor() { } } </code></pre> <p>I don't understand what is wrong with my code. <a href="https://plnkr.co/edit/ZroQeV?p=preview" rel="noreferrer"><strong>Demo</strong></a></p>
44,129,206
3
0
null
2017-05-23 08:02:38.043 UTC
1
2021-12-17 06:24:37.437 UTC
null
null
null
null
4,645,774
null
1
5
angular|typescript
46,339
<p>In angular you write javascript events without the "on" suffix.</p> <p>Change:</p> <pre><code>&lt;input type="file" (onchange)="handleUpload($event)"&gt; </code></pre> <p>To:</p> <pre><code>&lt;input type="file" (change)="handleUpload($event)"&gt; </code></pre>
37,556,972
HIVE - date_format( your_date_column, '%Y-%m-%d %H' )
<p>I'm trying to achieve the MySQL equivalent of <code>date_format( your_date_column, '%Y-%m-%d %H' ) as my_date</code> in Hive. I've tried a few options from <a href="http://www.folkstalk.com/2011/11/date-functions-in-hive.html" rel="nofollow">Hive date formatting</a> but can't get the format right. I haven't found anything that has helped me yet.</p> <p>Could I please request someone who may have already bumped into this situation or knows how to do it please?</p>
37,558,015
4
0
null
2016-05-31 22:57:13.62 UTC
1
2019-04-16 19:20:01.213 UTC
2016-06-01 00:51:43.367 UTC
null
3,222,797
null
5,366,075
null
1
1
hive
38,268
<p>I worked around this by using <code>concat(substr(your_date_column,1,13), ':00')</code></p> <p>In case the date column has a reserved keyword such as <code>timestamp</code> as in my case, this works - concat(substr(`timestamp`,1,13), ':00')</p>
49,189,402
auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'
<p>In my Django project I have a <code>user_manage</code> app.</p> <p>I create a model named <code>UserManage</code> in my <code>user_manage</code> app's model.py:</p> <pre><code>from django.db import models from django.contrib.auth.models import AbstractUser class UserManage(AbstractUser): username = models.CharField(max_length=12) </code></pre> <p>Then I run:</p> <pre><code>$ python3 manage.py makemigrations </code></pre> <p>There comes the error:</p> <pre><code>ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'UserManage.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'UserManage.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'UserManage.user_permissions'. users_management.UserManage.groups: (fields.E304) Reverse accessor for 'UserManage.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'UserManage.groups' or 'User.groups'. users_management.UserManage.user_permissions: (fields.E304) Reverse accessor for 'UserManage.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'UserManage.user_permissions' or 'User.user_permissions'. </code></pre>
49,189,522
8
1
null
2018-03-09 08:21:16.76 UTC
24
2022-04-27 04:10:12.673 UTC
null
null
null
null
6,523,163
null
1
129
python|django
93,643
<p>Add the following to <code>settings.py</code>: </p> <pre><code>AUTH_USER_MODEL = "users_management.UserManage" </code></pre> <p>More generally,</p> <pre><code>AUTH_USER_MODEL = 'YourAppName.YourClassName' </code></pre> <ul> <li><em>YourAppName</em>: This is the name of the app that will have the User Model</li> <li><em>YourClassName</em>: This is the name of the class used inside the <strong>models.py</strong> file</li> </ul>
27,440,953
std::unique_ptr for C functions that need free
<p>Think to a C function that return something that must be <code>free</code>d, for example the POSIX's <code>strdup()</code>. I want to use that function in C++11 and avoid any chance of leaks, is this a correct way?</p> <pre><code>#include &lt;memory&gt; #include &lt;iostream&gt; #include &lt;string.h&gt; int main() { char const* t { "Hi stackoverflow!" }; std::unique_ptr&lt;char, void(*)(void*)&gt; t_copy { strdup(t), std::free }; std::cout &lt;&lt; t_copy.get() &lt;&lt; " &lt;- this is the copy!" &lt;&lt;std::endl; } </code></pre> <p>Assuming it makes sense, it is possible to use a similar pattern with non-pointers? For example for the POSIX's function <code>open</code> that returns an <code>int</code>?</p>
27,441,139
5
2
null
2014-12-12 09:51:59.183 UTC
11
2022-09-23 20:03:57.253 UTC
2014-12-12 09:58:28.883 UTC
user3920237
null
null
1,876,111
null
1
60
c++|c++11
17,191
<p>What you have is extremely likely to work in practice, but not strictly correct. You can make it even more likely to work as follows:</p> <pre><code>std::unique_ptr&lt;char, decltype(std::free) *&gt; t_copy { strdup(t), std::free }; </code></pre> <p>The reason is that the function type of <code>std::free</code> is not guaranteed to be <code>void(void*)</code>. It is guaranteed to be callable when passed a <code>void*</code>, and in that case to return <code>void</code>, but there are at least two function types that match that specification: one with C linkage, and one with C++ linkage. Most compilers pay no attention to that, but for correctness, you should avoid making assumptions about it.</p> <p>However, even then, this is not strictly correct. As pointed out by @PeterSom in the comments, C++ allows implementations to e.g. make <code>std::free</code> an overloaded function, in which case both your and my use of <code>std::free</code> would be ambiguous. This is not a specific permission granted for <code>std::free</code>, it's a permission granted for pretty much any standard library function. To avoid this problem, a custom function or functor (as in his answer) is required.</p> <blockquote> <p>Assuming it makes sense, it is possible to use a similar pattern with non-pointers?</p> </blockquote> <p>Not with <code>unique_ptr</code>, which is really specific to pointers. But you could create your own class, similar to <code>unique_ptr</code>, but without making assumptions about the object being wrapped.</p>
42,497,479
Uncaught ReferenceError: exports is not defined in filed generated by Typescript
<p>I'm trying to get started with Typescript for Electron development. After wrestling with getting typing for node and jquery, I finally got my .ts file error free.</p> <p>The problem is now that when I run my app, I get this error:</p> <pre><code>index.js:2 Uncaught ReferenceError: exports is not defined </code></pre> <p>These are the first two lines in index.js:</p> <pre><code>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); </code></pre> <p>I don't know that that line does. Typescript added it when compiling. My app works fine if I remove it.</p> <p>How do I get rid of this error?</p> <p>Oh and here's my tsconfig, if that's relevant.</p> <pre><code>{ "compilerOptions": { "target": "es6", "module": "commonjs", "moduleResolution": "node", "isolatedModules": false, "jsx": "react", "experimentalDecorators": true, "emitDecoratorMetadata": true, "declaration": false, "noImplicitAny": false, "noImplicitUseStrict": false, "removeComments": true, "noLib": false, "preserveConstEnums": true, "suppressImplicitAnyIndexErrors": true }, "exclude": [ "node_modules", "typings/browser", "typings/browser.d.ts" ], "compileOnSave": true, "buildOnSave": false, "atom": { "rewriteTsconfig": false } } </code></pre>
42,510,255
9
1
null
2017-02-27 23:11:16.497 UTC
10
2021-06-01 22:49:19.253 UTC
null
null
null
null
3,667,074
null
1
53
javascript|typescript
104,301
<p>There is an issue with the new version of typescript 2.2.1, try using the older version 2.1.6, that solved the exact same issue which you have for me.</p> <p>Version 2.2.1 on compiling adds this line <code>Object.defineProperty(exports, "__esModule", { value: true });</code> while the older 2.1.6 does not.</p>
9,560,709
Adding a registry key in windows with quotes needed in the data using a batch script
<p>Little Willis here. I am trying to using a batch script to edit an existing registry key that is used when double clicking a .jar file. The issue is that the data that I'm trying to enter contains quotes but I also need quotes for it to be considered a string. </p> <p>Example:</p> <pre><code>reg add "HKEY_LOCAL_MACHINE\Software\Classes\jarfile\shell\open\command" /v "" /t REG_EXPAND_SZ /d "C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %* /f </code></pre> <p>When I run that in a batch script the cmd window prints out "Error: Too many command line parameters"</p> <p>So to make this simple. I want to add a registry key with "C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %* as the data including the quotations and the %1 and %* exactly as they are not converted to any actual statement or string.</p> <p>EDIT:</p> <p>The registry is normally added using using this command line string:</p> <pre><code>ftype jarfile="C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %* </code></pre> <p>it works fine in the command line, but just as the code given below when I used this in a batch script the "%1" and %* don't appear.</p>
9,560,889
4
0
null
2012-03-05 01:45:06.027 UTC
7
2019-05-19 15:31:09.053 UTC
2012-03-05 03:03:55.553 UTC
null
1,248,873
null
1,248,873
null
1
13
windows|batch-file|double-quotes|registrykey
42,643
<p>Use backslashes to escape the inner quotes, i.e.:</p> <pre><code>reg add "HKEY_LOCAL_MACHINE\Software\Classes\jarfile\shell\open\command" /v "" /t REG_EXPAND_SZ /d "\"C:\Program Files\Java\jre7\bin\javaw.exe\" -jar \"%1\" %*" /f </code></pre>
9,562,761
Is filemerge still available after Xcode 4.3 installation?
<p>Where can I find <code>filemerge</code> after Xcode is upgraded to 4.3?</p>
9,562,898
2
0
null
2012-03-05 06:57:58.293 UTC
8
2014-04-22 09:24:13.017 UTC
null
null
null
null
88,597
null
1
41
xcode|xcode4|osx-lion
14,467
<p>In Xcode, choose this menu item: Xcode -> Open Developer Tool -> FileMerge. The app itself is here:</p> <pre><code>/Applications/Xcode.app/Contents/Applications/FileMerge.app </code></pre> <p>On the command line, use <code>opendiff</code>. You must have the command line tools installed -- go to Xcode, Preferences, Downloads tab, and install Command Line Tools if you haven't already.</p>
30,054,911
How to determine the version of Gradle?
<p>How can I know which version of Gradle I am using in my Android Studio? Please guide. </p> <p>I want to make sure I am using Gradle version 2.2.1.</p>
30,055,088
13
3
null
2015-05-05 13:51:22.503 UTC
21
2022-08-22 15:37:12.53 UTC
2015-05-05 13:58:32.4 UTC
null
1,253,844
user379888
null
null
1
203
android|gradle
310,395
<p><strong>Option 1- From Studio</strong></p> <p>In Android Studio, go to File > Project Structure. Then select the "project" tab on the left.</p> <p>Your Gradle version will be displayed here.</p> <p><strong>Option 2- gradle-wrapper.properties</strong></p> <p>If you are using the Gradle wrapper, then your project will have a <code>gradle/wrapper/gradle-wrapper.properties</code> folder. </p> <p>This file should contain a line like this: </p> <pre><code>distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip </code></pre> <p>This determines which version of Gradle you are using. In this case, <code>gradle-2.2.1-all.zip</code> means I am using Gradle 2.2.1.</p> <p><strong>Option 3- Local Gradle distribution</strong></p> <p>If you are using a version of Gradle installed on your system instead of the wrapper, you can run <code>gradle --version</code> to check.</p>
47,384,952
Directive to disable Cut, Copy and Paste function for textbox using Angular2
<p>I am using Angular2 to restrict the copy and paste in textbox. But how do i write a custom directive, so that it will be easy to apply for all the text fields.</p> <p>Below is the working code to restrict the copy and paste functionality.</p> <pre><code>&lt;ion-input formControlName="confirmpass" type="tel" (cut)="$event.preventDefault()" (copy)="$event.preventDefault()" (paste)="$event.preventDefault()"&gt;&lt;/ion-input&gt; </code></pre>
47,385,485
3
2
null
2017-11-20 04:09:36.147 UTC
7
2022-04-25 15:45:14.24 UTC
2017-11-20 05:28:31.09 UTC
null
5,621,827
null
4,376,984
null
1
18
angular|ionic2
38,742
<p>You can use a <a href="https://angular.io/api/core/HostListener" rel="noreferrer">HostListener</a> in your directive to catch <a href="https://developer.mozilla.org/en-US/docs/Web/Events/cut" rel="noreferrer">cut</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/Events/paste" rel="noreferrer">paste</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/Events/copy" rel="noreferrer">copy</a> events and then use <code>preventDefault()</code>. Here's an example</p> <pre><code>import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[appBlockCopyPaste]' }) export class BlockCopyPasteDirective { constructor() { } @HostListener('paste', ['$event']) blockPaste(e: KeyboardEvent) { e.preventDefault(); } @HostListener('copy', ['$event']) blockCopy(e: KeyboardEvent) { e.preventDefault(); } @HostListener('cut', ['$event']) blockCut(e: KeyboardEvent) { e.preventDefault(); } } </code></pre> <p>Use directive like so</p> <pre><code>&lt;ion-input appBlockCopyPaste formControlName="confirmpass" type="tel"&gt;&lt;/ion-input&gt; </code></pre> <p><a href="https://stackblitz.com/edit/angular-u4jcam?file=app%2Fblock-copy-paste.directive.ts" rel="noreferrer">Working demo</a></p>
10,653,549
IIS 7.5 and images not being cached
<p>I cannot get the image files to cache. I have tried everything that I have found on this site and others and still cannot get them to cache.</p> <p>Web config setting that I have tried</p> <pre><code> &lt;staticContent&gt; &lt;clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1.00:00:00" /&gt; &lt;/staticContent&gt; &lt;httpProtocol allowKeepAlive="true" /&gt; &lt;caching enabled="true" enableKernelCache="true"&gt; &lt;profiles&gt; &lt;add extension=".png" policy="CacheUntilChange" /&gt; &lt;add extension=".jpg" policy="CacheForTimePeriod" duration="12:00:00" /&gt; &lt;/profiles&gt; &lt;/caching&gt; </code></pre> <p>Here is the response headers for 1 of the images</p> <pre><code> Key Value Response HTTP/1.1 200 OK Cache-Control no-cache Content-Type image/png Last-Modified Thu, 16 Dec 2004 18:33:28 GMT Accept-Ranges bytes ETag "a1ca4bc9de3c41:0" Server Microsoft-IIS/7.5 X-Powered-By ASP.NET Date Fri, 18 May 2012 13:21:21 GMT Content-Length 775 </code></pre>
10,687,548
2
1
null
2012-05-18 13:28:02.09 UTC
11
2018-05-29 21:54:25.843 UTC
2012-07-04 19:49:18.13 UTC
null
225,647
null
1,167,466
null
1
21
iis|caching|iis-7.5|browser-cache
29,227
<p>The following should cause the browsers to cache your images:</p> <pre><code>&lt;staticContent&gt; &lt;clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1.00:00:00" /&gt; &lt;/staticContent&gt; &lt;httpProtocol&gt; &lt;customHeaders&gt; &lt;add name="Cache-Control" value="public" /&gt; &lt;/customHeaders&gt; &lt;/httpProtocol&gt; </code></pre> <p>The <code>&lt;caching&gt;...&lt;/caching&gt;</code> block is for server-side caching, not client side caching.</p>
10,633,564
How does one change the language of the command line interface of Git?
<p>I’d like to change the language of git (to English) in my Linux installation without changing the language for other programs and couldn’t find the settings. How to do it?</p>
10,872,202
8
1
null
2012-05-17 10:03:49.42 UTC
24
2022-08-07 13:27:35.97 UTC
2019-01-18 10:02:51.647 UTC
null
905,686
null
905,686
null
1
137
bash|git|localization|environment-variables|locale
71,229
<p>Add these lines to your <code>~/.bashrc</code>, <code>~/.bash_profile</code> or <code>~/.zprofile</code> to force git to display all messages in English:</p> <pre><code># Set Git language to English #alias git='LANG=en_US git' alias git='LANG=en_GB git' </code></pre> <p>The alias needs to override <code>LC_ALL</code> on some systems, when the environment variable <code>LC_ALL</code> is set, which has precedence over <code>LANG</code>. See the <a href="http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html" rel="noreferrer">UNIX Specification - Environment Variables</a> for further explanation.</p> <pre><code># Set Git language to English #alias git='LC_ALL=en_US git' alias git='LC_ALL=en_GB git' </code></pre> <p>In case you added these lines to <code>~/.bashrc</code> the alias will be defined when a new interactive shell gets started. In case you added it to <code>~/.bash_profile</code> the alias will be applied when logging in.</p>
7,605,328
Batch how to set FINDSTR result to a variable and disable findstr print to console
<p>My batch program </p> <pre><code>FINDSTR /C:"Result Comparison failure" %tmp_result_file% </code></pre> <p>I want to do the folloiwng , set the result of the above command to a variable. If found, set the first line to varible or set the all found line to a varible is OK for me. </p> <p>also the above commmand will print the findstr command to console even @echo off. is there any method to disable the print. </p> <p>thanks a lot </p> <hr> <p>part of my script, what i do is run command on every line in sourcefile and put the run result into a tmp file, then use find str to find the failed string to check the run result. </p> <pre><code>for /f %%a in (%source_file%) do ( echo run %%a &gt;&gt; %output_file% call %run_script_command% %%a &gt; %tmp_result_file% 2&gt;&amp;1 ::notepad %tmp_result_file% for /f %%i in ('FINDSTR /C:"Result Comparison failure" %tmp_result_file%') do echo %%ixxx echo xx ) </code></pre> <p>very strange , the result is: </p> <pre> xx Resultxxx xx </pre> <p>the background is that i have two items in <code>%source_file%</code>, so the out for run 2 times.<br> for the first one, the FINDSTR can not find anything, so print <code>xxx</code><br> for the second one, it find one in findstr , but only print "<code>Result</code>" instead of "<code>Result Comparison failure</code>", also the xx is print before it in result. Very Strange!</p>
7,607,120
2
0
null
2011-09-30 02:15:54.86 UTC
1
2020-04-27 08:56:55.293 UTC
2011-09-30 04:28:50.67 UTC
null
310,574
null
778,659
null
1
12
batch-file
76,065
<p>The first problem is because you just take the first token from FOR. To solve it, you have two solutions, either to echo the complete line where the string is found...</p> <pre><code>for /f "tokens=*" %%i in ('FINDSTR /C:"Result Comparison Failure" %tmp_result_file%') do echo %%i </code></pre> <p>or echo the three tokens found</p> <pre><code>for /f %%i in ('FINDSTR /C:"Result Comparison Failure" %tmp_result_file%') do echo %%i %%j %%k </code></pre> <p>the second problem, the xx echoed two times is because you run two times the command. The first xx is the one from the first run, the second one is from the second run. If you want to prevent the second one, you need to use some additional logic. For example, setting a variable and then checking it. Warning, setting a variable in a loop requires enabling delayed expansion and using the !xx! syntax (see HELP SET for a detailed explanation)</p> <pre><code>setlocal enabledelayedexpansion ... set result= for /f "tokens=*" %%i in ('FINDSTR /C:"Result Comparison Failure" %tmp_result_file%') do ( set result=%%i ) if "!result!"=="" ( echo !result! ) else ( echo xx ) </code></pre>
7,527,118
Search in many-to-many relationship with Doctrine2
<p>This is probably an easy one but I can't figure it out nor find an answer.</p> <p>I have a simple Article and ArticleTag Entities with many to many relationship. How can I get all articles with a certain tag (or tags)?</p> <p>My following tries:</p> <pre><code>$qb = $repository-&gt;createQueryBuilder('a') // ... -&gt;andWhere('a.tags = :tag') -&gt;setParameter('tag', 'mytag') // ... </code></pre> <p>or</p> <pre><code> -&gt;andWhere(':tag in a.tags') -&gt;setParameter('tag', 'mytag') </code></pre> <p>...didn't work. Thanks!</p>
7,598,827
2
4
null
2011-09-23 09:48:04.057 UTC
10
2011-09-29 14:27:00.397 UTC
null
null
null
null
523,100
null
1
15
php|many-to-many|doctrine-orm|symfony
7,215
<p>And the winner is ... <em>drumroll, please</em> ...</p> <pre><code>$qb = $repository-&gt;createQueryBuilder('a') // ... -&gt;andWhere(':tag MEMBER OF a.tags'); -&gt;setParameter('tag', $tag); // ... </code></pre> <p>Thanks to everyone who has taken the time to read and think about my question!</p>
31,387,653
What is the fastest way to clear a SQL table?
<p>I have a table with about 300,000 rows and 30 columns. How can I quickly clear it out? If I do a <code>DROP FROM MyTable</code> query, it takes a long time to run. I'm trying the following stored procedure to basically make a copy of the table with no data, drop the original table, and rename the new table as the original:</p> <pre><code>USE [myDatabase] GO SET ANSI_NULLS_ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[ClearTheTable] AS BEGIN SET NOCOUNT ON; SELECT * INTO tempMyTable FROM MyTable WHERE 1 = 0; DROP TABLE MyTable EXEC sp_rename tempMyTable, MyTable; END </code></pre> <p>This took nearly 7 minutes to run. Is there a faster way to do it? I don't need any logging, rollback or anything of that nature. </p> <p>If it matters, I'm calling the stored procedure from a C# app. I guess I could write some code to recreate the table from scratch after doing a <code>DROP TABLE</code>, but I didn't want to have to recompile the app any time a column is added or changed.</p> <p>Thanks!</p> <p><strong>EDIT</strong></p> <p>Here's my updated stored procedure: </p> <pre><code>USE [myDatabase] GO SET ANSI_NULLS_ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[ClearTheTable] AS BEGIN SET NOCOUNT ON; ALTER DATABASE myDatabase SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE TRUNCATE TABLE MyTable ALTER DATABASE myDatabase SET MULTI_USER END </code></pre>
31,387,807
1
3
null
2015-07-13 15:39:19.63 UTC
2
2015-07-14 08:03:13.257 UTC
2015-07-13 19:43:54.133 UTC
null
1,783,592
null
1,783,592
null
1
13
sql-server|stored-procedures
43,679
<p>Best way to clear a table is with <a href="https://msdn.microsoft.com/en-us/library/ms177570.aspx" rel="noreferrer">TRUNCATE</a>.</p> <p>Since you are creating and droping ill assume you have no constraints.</p> <pre><code>TRUNCATE TABLE &lt;target table&gt; </code></pre> <p>Some advantages:</p> <blockquote> <ul> <li>Less transaction log space is used.</li> </ul> <p>The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log. </p> <ul> <li>Fewer locks are typically used.</li> </ul> <p>When the DELETE statement is executed using a row lock, each row in the table is locked for deletion. TRUNCATE TABLE always locks the table (including a schema (SCH-M) lock) and page but not each row. </p> <ul> <li>Without exception, zero pages are left in the table.</li> </ul> <p>After a DELETE statement is executed, the table can still contain empty pages. For example, empty pages in a heap cannot be deallocated without at least an exclusive (LCK_M_X) table lock. If the delete operation does not use a table lock, the table (heap) will contain many empty pages. For indexes, the delete operation can leave empty pages behind, although these pages will be deallocated quickly by a background cleanup process.</p> </blockquote>
31,489,386
How do I declare a variable of enum type in Kotlin?
<p>Following <a href="https://kotlinlang.org/docs/reference/enum-classes.html" rel="noreferrer">the documentation</a>, I created an enum class:</p> <pre><code>enum class BitCount public constructor(val value : Int) { x32(32), x64(64) } </code></pre> <p>Then, I'm trying to declare a variable in some function:</p> <pre><code>val bitCount : BitCount = BitCount(32) </code></pre> <p>But there is a compilation error:</p> <blockquote> <p>Error:(18, 29) Kotlin: Enum types cannot be instantiated</p> </blockquote> <p>How do I declare a variable of BitCount type and initialize it from an <code>Int</code>?</p>
34,625,163
3
4
null
2015-07-18 08:41:38.62 UTC
7
2022-03-12 05:14:41.44 UTC
2020-10-28 00:24:27.097 UTC
null
1,402,846
null
779,822
null
1
35
enums|kotlin
33,578
<p>As stated in other answers, you can reference any value of the <code>enum</code> that exists by name, but not construct a new one. That does not prevent you from doing something similar to what you were trying...</p> <pre class="lang-kotlin prettyprint-override"><code>// wrong, it is a sealed hierarchy, you cannot create random instances val bitCount : BitCount = BitCount(32) // correct (assuming you add the code below) val bitCount = BitCount.from(32) </code></pre> <p>If you were wanting to find the instance of the <code>enum</code> based on the numeric value <code>32</code> then you could scan the values in the following way. Create the <code>enum</code> with a <code>companion object</code> and a <code>from()</code> function:</p> <pre class="lang-kotlin prettyprint-override"><code>enum class BitCount(val value : Int) { x16(16), x32(32), x64(64); companion object { fun from(findValue: Int): BitCount = BitCount.values().first { it.value == findValue } } } </code></pre> <p>Then call the function to get a matching existing instance:</p> <pre class="lang-kotlin prettyprint-override"><code>val bits = BitCount.from(32) // results in BitCount.x32 </code></pre> <p>Nice and pretty. Alternatively in this case you could create the name of the <code>enum</code> value from the number since you have a predictable relationship between the two, then use <code>BitCount.valueOf()</code>. Here is the new <code>from()</code> function within the companion object.</p> <pre class="lang-kotlin prettyprint-override"><code>fun from(findValue: Int): BitCount = BitCount.valueOf(&quot;x$findValue&quot;) </code></pre>
37,616,521
How can I connect to SQLServer running on VirtualBox from my host Macbook
<p>I want to run SQLServer on my Mac but I can't do it natively. How can I host a SQLServer with <a href="https://www.virtualbox.org" rel="nofollow noreferrer">VirtualBox</a> and connect to it from my MacBook for local development?</p>
37,616,522
1
2
null
2016-06-03 14:05:21.693 UTC
31
2022-08-25 08:00:22.12 UTC
2022-08-25 08:00:22.12 UTC
null
4,751,173
null
2,282,538
null
1
45
sql-server|macos|virtualbox
40,220
<ol> <li>Download <a href="https://www.virtualbox.org" rel="noreferrer">VirtualBox</a></li> <li>Download a Windows 10 ISO from <a href="https://www.microsoft.com/software-download/windows10ISO" rel="noreferrer">here</a></li> <li>Create a new Windows 10 VM with VirtualBox. When it asks for the "Virtual Optical Disk File", point it to the ISO download from Step 2:</li> </ol> <p><a href="https://i.stack.imgur.com/epWdq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/epWdq.png" alt="enter image description here"></a></p> <ol start="4"> <li>Continue with the Windows 10 setup</li> <li>In the Windows VM, download and install SQL Server (I used <a href="https://www.microsoft.com/download/details.aspx?id=52679" rel="noreferrer">Express</a>)</li> <li>When the SQL Server installation finishes, install the tool (SSMS) which we will need later</li> </ol> <p><a href="https://i.stack.imgur.com/xbJ8V.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xbJ8V.png" alt="enter image description here"></a></p> <ol start="7"> <li>With SSMS, create a new database (I called mine <code>testdatabase</code>) </li> </ol> <p><a href="https://i.stack.imgur.com/Yy5a4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Yy5a4.png" alt="enter image description here"></a></p> <p>8.1. Create a new Login: right click on <code>Security &gt; New &gt; Login...</code> Be sure to select the <code>SQL Server authentication</code> option.</p> <p><a href="https://i.stack.imgur.com/XFKbA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XFKbA.png" alt="enter image description here"></a></p> <p>8.2. In the <code>Server Roles</code> tab, select the <code>sysadmin</code> option: <a href="https://i.stack.imgur.com/fuYsF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fuYsF.png" alt="enter image description here"></a></p> <p>8.3. In the <code>User Mapping</code> tab, map the login to the database, and check all assign the role memberships:</p> <p><a href="https://i.stack.imgur.com/akl9G.png" rel="noreferrer"><img src="https://i.stack.imgur.com/akl9G.png" alt="enter image description here"></a></p> <ol start="9"> <li>Open the server properties (right click the root level object). Go to the <code>Security</code> tab, and switch the <code>Server Authentication mode</code> to <code>SQL Server and Windows Authentication mode</code>:</li> </ol> <p><a href="https://i.stack.imgur.com/5tOwj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5tOwj.png" alt="enter image description here"></a></p> <ol start="10"> <li>Open the Windows Services program, and find the <code>SQL Server Browser</code>. Open its properties and change the <code>Startup type</code> to automatic:</li> </ol> <p><a href="https://i.stack.imgur.com/IiCiQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IiCiQ.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/VstYf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VstYf.png" alt="enter image description here"></a></p> <p>11.1. Open the Sql Server Configuration Manager program. Navigate to the <code>Protocols</code> under the <code>SQL Server Network Configuration</code> and Enable the <code>TCP/IP</code> option: </p> <p><a href="https://i.stack.imgur.com/5JLKw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5JLKw.png" alt="enter image description here"></a></p> <p>11.2. Open the <code>TCP/IP</code> properties switch to the <code>IP Addresses tab</code>. Make a note of the <code>IP Address</code> field under <code>IP2</code> (you will need this later):</p> <p><a href="https://i.stack.imgur.com/A6Ki4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/A6Ki4.png" alt="enter image description here"></a></p> <p>11.3. Set the <code>TCP Port</code> under <code>IPALL</code> to <code>1433</code>:</p> <p><a href="https://i.stack.imgur.com/zkjoF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zkjoF.png" alt="enter image description here"></a></p> <ol start="12"> <li><p>Configure the Firewall on the Windows VirtualBox to allow 1433 to be unblocked (I just disabled the whole firewall, probably not the best option.) <strong><em>edit:</em></strong> <em>another user has kindly added the steps for adding a firewall rule to the end of this post</em>.</p></li> <li><p>In your Macbook's VirtualBox app, open the settings for the Windows VM and go to the <code>Network</code> tab. Set the <code>Attached to</code> dropdown to <code>NAT</code>, then click <code>Port Forwarding</code>. Add a rule to forward the VM's 1433 port to your localhost's 1433 port. The <code>Guest IP</code> will be the IP from Step 11.2:</p></li> </ol> <p><a href="https://i.stack.imgur.com/HKXZc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HKXZc.png" alt="enter image description here"></a></p> <hr> <p>You should now be able to connect to your SQLServer from your macbook with a connection string something like this:</p> <p><code>jdbc:sqlserver://127.0.0.1;databaseName=testdatabase</code></p> <hr> <p><em>Steps to open a port in the Windows firewall for TCP access</em></p> <ol> <li>On the <strong>Start menu</strong>, click <strong>Run</strong>, type <strong>WF.msc</strong>, and then click OK.</li> <li>In the <strong>Windows Firewall with Advanced Security</strong>, in the left pane, right-click <strong>Inbound Rules</strong>, and then click <strong>New Rule</strong> in the action pane (upper right corner).</li> <li>In the <strong>Rule Type</strong> dialog box, select <strong>Port</strong>, and then click Next.</li> <li>In the <strong>Protocol and Ports</strong> dialog box, select <strong>TCP</strong>. Select <strong>Specific local ports</strong>, and then type the port number of the instance of the Database Engine, In my case we are using the default which is <strong>1433</strong>. Click Next.</li> <li>In the <strong>Action</strong> dialog box, select <strong>Allow the connection</strong>, and then click Next.</li> <li>In the <strong>Profile</strong> dialog box, I am going to Leave Domain turned on and turn private and public off. Then click Next.</li> <li>In the <strong>Name</strong> dialog box, type "Allow SQL 1433 Inbound" and for a description I am putting in the same. Then click Finish.</li> </ol>
35,649,045
Integration test with IOptions<> in .NET Core
<p>I pass <code>IOption&lt;T&gt;</code> to my <code>CommandBus</code> so I can get the settings from my <code>ServiceBusSetting</code> class. I want to do an integration test of my Bus. I do not want to resolve it just use <code>new QueueCommandBus</code> and need to pass <code>IOptions</code> to it. </p> <pre><code>var services = new ServiceCollection().AddOptions(); services.Configure&lt;ServiceBusAppSettings&gt;(Configuration.GetSection("ServiceBus")); var options = services.BuildServiceProvider().GetService&lt;IOptions&lt;ServiceBusAppSettings&gt;&gt;(); ////Act var commandBus = new QueueCommandBus(options); </code></pre> <p>This works fine, but feels very complex code to get the <code>IOptions&lt;T&gt;</code> from my <code>appsetting.json</code> in my test project. </p> <p>Any clue if this is the only way or is there a better way? </p>
41,990,001
1
1
null
2016-02-26 10:18:45.287 UTC
8
2017-02-01 21:23:03.81 UTC
2016-02-26 11:52:30.49 UTC
null
455,493
null
2,530,473
null
1
16
asp.net-mvc|integration-testing|asp.net-core
9,049
<p>You don't need to create the <code>ServiceCollection</code> or <code>IServiceProvider</code>. The <code>IConfiguration</code> interface has a <code>Bind()</code> method, or from .NET Core 1.1 onwards, <code>Get&lt;T&gt;</code> which you can use to get the strongly-typed object directly:</p> <pre><code>var config = Configuration.GetSection("ServiceBus"); // .NET Core 1.0 var options = new ServiceBusAppSettings(); config.Bind(options); // .NET Core 1.1 var options = config.Get&lt;ServiceBusAppSettings&gt;(); </code></pre> <p>I like to add these as static methods to my <code>AppSettings</code> strongly-typed object, to make it convenient to load them from JSON in both my web app and from unit tests.</p> <p><strong>AppSettings.cs:</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; namespace My.Namespace { public class AppSettings { public class ServiceBusAppSettings { public string Setting1; public int Setting2; } public class ApiSettings { public bool FormatJson { get; set; } } public class MySqlSettings { public string User { get; set; } public string Password { get; set; } public string Host { get; set; } public string Database { get; set; } public int Port { get; set; } = 3306; public string GetConnectionString() { return $"Server={Host};Database={Database};Port={Port};Uid={User};Pwd={Password}"; } } public ServiceBusAppSettings ServiceBus { get; set; } = new ServiceBusAppSettings(); public ApiSettings Api { get; set; } = new ApiSettings(); public MySqlSettings MySql { get; set; } = new MySqlSettings(); // Static load helper methods. These could also be moved to a factory class. public static IConfigurationRoot GetConfiguration(string dir) { return GetConfiguration(dir, null); } public static IConfigurationRoot GetConfiguration(string dir, string environmentName) { if (string.IsNullOrEmpty(environmentName)) environmentName = "Development"; var builder = new ConfigurationBuilder() .SetBasePath(dir) .AddJsonFile("appsettings.json", true, true) .AddJsonFile($"appsettings.{environmentName}.json", true) .AddEnvironmentVariables(); return builder.Build(); } public static AppSettings GetSettings(string dir) { return GetSettings(dir, null); } public static AppSettings GetSettings(string dir, string environmentName) { var config = GetConfiguration(dir, environmentName); return GetSettings(config); } public static AppSettings GetSettings(IConfiguration config) { return config.Get&lt;AppSettings&gt;(); } } } </code></pre> <p><strong>ASP.NET Core <code>Startup.cs</code>:</strong> (Getting the strongly-typed settings object is often helpful at this stage, when configuring the other services...)</p> <pre><code>public class Startup { public Startup(IHostingEnvironment env) { Configuration = AppSettings.GetConfiguration(env.ContentRootPath, env.EnvironmentName); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Configure the service collection. services.AddOptions(); services.Configure&lt;AppSettings&gt;(Configuration); // It can also be handy to get the AppSettings object here. var settings = AppSettings.GetSettings(Configuration); // Add framework services. services.AddMvc() .AddJsonOptions(options =&gt; { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); // Pretty-print JSON in Development options.SerializerSettings.Formatting = settings.Api.FormatJson ? Formatting.Indented : Formatting.None; }); // Store DB connection info in AppSettings too... var conn = settings.MySql.GetConnectionString(); services.AddDbContext&lt;MyDbContext&gt;(opt =&gt; opt.UseMySql(conn)); } } </code></pre> <p><strong>In Test Class:</strong></p> <pre><code>var testDir = AppContext.BaseDirectory; var settings = AppSettings.GetSettings(testDir, "Test"); //Act var commandBus = new QueueCommandBus(settings); </code></pre>
3,340,051
What does the output of git pull actually mean?
<p>I'm trying to gain a more thorough understanding of git.</p> <p>Can someone give me a simple line-by-line explanation of what basic git <code>pull</code> output means? Example: </p> <pre><code>remote: Counting objects: 11, done. remote: Compressing objects: 100% (5/5), done. remote: Total 7 (delta 2), reused 0 (delta 0) Unpacking objects: 100% (7/7), done. From ssh://my.remote.host.com/~/git/myproject * branch master -&gt; FETCH_HEAD Updating 9d447d2..f74fb21 Fast forward app/controllers/myproject_controller.rb | 13 +++++++++++++ 1 files changed, 13 insertions(+), 0 deletions(-) </code></pre>
3,340,304
1
0
null
2010-07-27 00:59:58.37 UTC
11
2014-09-28 12:07:02.587 UTC
null
null
null
null
402,851
null
1
46
git
9,356
<p>Under the hood, <code>git pull</code> is <code>git fetch</code> followed by <code>git merge</code>. Here's the fetch portion:</p> <pre><code>remote: Counting objects: 11, done. remote: Compressing objects: 100% (5/5), done. remote: Total 7 (delta 2), reused 0 (delta 0) </code></pre> <p>At this point, you've told the remote what you want. It finds all the objects it needs to give you (counting them in the process, I believe), compresses them for faster transfer over the network, and then reports what it's sending you. Objects may be blobs, trees, commits, or tags - see for example the <a href="http://git-scm.com/book/en/Git-Internals-Git-Objects" rel="noreferrer">git book</a> for more information.</p> <pre><code>Unpacking objects: 100% (7/7), done. </code></pre> <p>You receive the pack (set of compressed objects) and unpack it.</p> <pre><code>From ssh://my.remote.host.com/~/git/myproject * branch master -&gt; FETCH_HEAD </code></pre> <p>You've fetched the branch 'master' from the given remote; the ref FETCH_HEAD now points to it. Now we move on to the merge - precisely, git will merge FETCH_HEAD (the remote's master branch) into your current branch (presumably master).</p> <pre><code>Updating 9d447d2..f74fb21 Fast forward </code></pre> <p>It turns out that you haven't diverged from the remote's master branch, so the merge is a fast-forward (a trivial merge where it simply moves you forward in the history). Git notes the original position of your master branch (9d447d2) and the new position (f74fb21) it's been fast-forwarded to. If you had diverged from the remote's master branch, you'd see the output of a recursive merge here - <code>Merge made by recursive</code>, possibly along with some <code>Auto-merged &lt;file&gt;</code> and (oh no!) merge conflicts!</p> <pre><code> app/controllers/myproject_controller.rb | 13 +++++++++++++ 1 files changed, 13 insertions(+), 0 deletions(-) </code></pre> <p>Finally, it shows you the diffstat between the original and post-merge position of your master branch; this is basically what you'd get from <code>git diff --stat master@{1} master</code>.</p>
3,357,953
default a column with empty string
<p>Is there a way, via a SQL statement, to ensure a column's default value is an empty string <code>''</code> instead of <code>NULL</code>?</p>
3,357,962
1
0
null
2010-07-28 22:08:29.493 UTC
4
2010-07-28 22:14:25.063 UTC
2010-07-28 22:14:25.063 UTC
null
23,199
null
441,664
null
1
49
sql|mysql|default-constraint
71,189
<p>Yes - use a DEFAULT constraint:</p> <pre><code>DROP TABLE IF EXISTS `example`.`test`; CREATE TABLE `example`.`test` ( `string_test` varchar(45) NOT NULL DEFAULT '' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; </code></pre>
20,911,283
Why do programming contests want answers modulo some large prime?
<p>I have been testing the waters of competitive programming and I have already seen this statement mentioned a lot of times:</p> <blockquote> <p>Print the result modulo 10<sup>9</sup> + 7</p> </blockquote> <p>Now I can figure out that this is some way of preventing overflow of digits when dealing with very large numbers. But how and why does it work? I would be grateful if someone could explain the mathematical reasoning behind this.</p>
20,912,351
1
3
null
2014-01-03 19:29:44.867 UTC
11
2015-01-21 18:09:53.983 UTC
2015-01-21 18:09:53.983 UTC
null
100,297
null
1,691,530
null
1
25
math|primes|modulus
3,526
<p>Many contest questions ask you to compute some very, very large number (say, the number of permutations of an 150-element sequence containing some large number of duplicates). Many programming languages don't natively support arbitrary-precision arithmetic, so in the interest of fairness it makes sense for those contests not to ask you for the exact value. The challenge, then, is the following: how can the contest site know when you have the right answer given that you can't exactly compute it?</p> <p>One initially appealing option would be to just ask for the answer modulo some large power of two (say, 2<sup>32</sup> or 2<sup>64</sup>) so that competitors working in languages like C or C++ could just use <code>uint32_t</code> or <code>uint64_t</code>s to do all the computations, letting overflows occur normally, and then submit the results. However, this isn't particularly desirable. Suppose, for example, that the question is the following:</p> <blockquote> <p>Compute 10,000!</p> </blockquote> <p>This number is staggeringly huge and is way too big to fit into a 32-bit or 64-bit unsigned integer. However, if you just want to get the answer modulo 2<sup>32</sup> or 2<sup>64</sup>, you could just use this program:</p> <pre><code>#include &lt;stdio.h&gt; int main() { puts("0"); } </code></pre> <p>The reason for this is that 10,000! is the product of at least 5,000 even numbers, so one of its factors is 2<sup>5,000</sup>. Therefore, if you just want the answer modulo 2<sup>32</sup> or 2<sup>64</sup>, you don't actually have to compute it at all. You can just say that the result is 0 mod 2<sup>32</sup> or 2<sup>64</sup>.</p> <p>The problem here is that working modulo 2<sup>32</sup> or 2<sup>64</sup> is troublesome if the resulting answer is cleanly divisible by either of those numbers. However, if we work modulo a large <em>prime</em> number, then this trick wouldn't work. As an example, the number 7,897,987 is prime. If you try to compute 10,000! mod 7,897,987, then you can't just say "the answer is 0" because none of the numbers multiplied together in 10,000! are divisors of 7,897,987. You'd actually have to do some work to figure out what this number is modulo that large prime. More generally, working modulo a large prime usually requires you to compute the actual answer modulo that large prime, rather than using number-theoretic tricks to skip all the work entirely.</p> <p>So why work modulo 1,000,000,007? This number happens to be prime (so it's good to use as a modulus) and it's less than 2<sup>31</sup> - 1, the largest possible value you can fit in a signed 32-bit integer. The signedness is nice here because in some languages (like Java) there are no unsigned integer types and the default integer type is a 32-bit signed integer. This means that you can work modulo 1,000,000,007 without risking an integer overflow.</p> <p>To summarize:</p> <ul> <li>Working modulo a large prime makes it likely that if your program produces the correct output, it actually did some calculation and did so correctly.</li> <li>Working modulo 1,000,000,007 allows a large number of languages to use their built-in integer types to store and calculate the result.</li> </ul> <p>Hope this helps!</p>
40,844,903
How can I run a Python script in HTML?
<p>Currently I have some Python files which connect to an <a href="https://en.wikipedia.org/wiki/SQLite" rel="nofollow noreferrer">SQLite</a> database for user inputs and then perform some calculations which set the output of the program. I'm new to Python web programming and I want to know: What is the best method to use Python on the web?</p> <p>Example: I want to run my Python files when the user clicks a button on the web page. Is it possible?</p> <p>I started with <a href="https://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow noreferrer">Django</a>. But it needs some time for the learning. And I also saw something called <a href="https://en.wikipedia.org/wiki/Common_Gateway_Interface" rel="nofollow noreferrer">CGI</a> scripts. Which option should I use?</p>
40,845,057
8
2
null
2016-11-28 12:56:24.993 UTC
12
2022-05-29 16:54:29.323 UTC
2022-05-29 16:28:55.97 UTC
null
63,550
null
6,193,415
null
1
27
python|html|web
157,358
<p>It probably would depend on what you want to do. I personally use CGI and it might be simpler if your inputs from the web page are simple, and it takes less time to learn. Here are some resources for it:</p> <ul> <li><em><a href="https://docs.python.org/2/library/cgi.html" rel="nofollow noreferrer">cgi — Common Gateway Interface support</a></em></li> <li><em><a href="https://www.tutorialspoint.com/python/python_cgi_programming.htm" rel="nofollow noreferrer">Python - CGI Programming</a></em></li> </ul> <p>However, you may still have to do some configuring to allow it to run the program instead of displaying it.</p> <p>Here's a tutorial on that: <em><a href="http://httpd.apache.org/docs/current/howto/cgi.html" rel="nofollow noreferrer">Apache Tutorial: Dynamic Content with CGI</a></em></p>
18,384,883
Why is Google's TrueTime API hard to duplicate?
<p>I'm not sure why the press in general says that Google's TrueTime API is hard to replicate (Wired, Slashdot, etc).</p> <p>I can understand how it would be a tough thing to get the low error intervals that Google is achieving, but I don't see how the API itself would be very difficult.</p> <p>For example, I whipped up a hacked together version. Here's the interval.</p> <pre><code> typedef struct TT_interval { struct timeval earliest; struct timeval latest; } TT_interval; </code></pre> <p>Here's the now function.</p> <pre><code> int TT_now(TT_interval* interval) { struct ntptimeval tv; struct timeval delta; struct timeval* earliest_p = &amp;(interval-&gt;earliest); struct timeval* latest_p = &amp;(interval-&gt;latest); struct timeval* now_p = &amp;(tv.time); struct timeval* delta_p = &amp;delta; timerclear(&amp;delta); timerclear(&amp;interval-&gt;earliest); timerclear(&amp;interval-&gt;latest); if(ntp_gettime(&amp;tv) == 0) { tv.maxerror = tv.maxerror &gt; 0 ? tv.maxerror : -(tv.maxerror); delta.tv_sec = delta.tv_sec + (tv.maxerror / 1000); delta.tv_usec = delta.tv_usec + ((tv.maxerror % 1000) * 1000); if(delta.tv_usec &gt; 1000000) { delta.tv_usec -= 1000000; delta.tv_sec++; } timeradd(now_p, delta_p, latest_p); timersub(now_p, delta_p, earliest_p); } else { printf("error on ntp_gettime. %s\n", strerror(errno)); return ERROR; } return SUCCESS; } </code></pre> <p>Finally, here's the before and after functions (which are wrappers around the now function and could use a bit of DRY refactoring).</p> <pre><code> int TT_before(TT_interval* interval, bool* success) { struct timeval* latest_p; struct timeval* earliest_p; TT_interval now; if(TT_now(&amp;now) != SUCCESS) { return ERROR; } latest_p = &amp;(interval-&gt;latest); earliest_p = &amp;(now.earliest); if(timercmp(latest_p, earliest_p, &lt;) != 0) { *success = true; return SUCCESS; } else { *success = false; return SUCCESS; } return ERROR; } int TT_after(TT_interval* interval, bool* success) { struct timeval* latest_p; struct timeval* earliest_p; TT_interval now; if(TT_now(&amp;now) != SUCCESS) { return ERROR; } earliest_p = &amp;(interval-&gt;latest); latest_p = &amp;(now.earliest); if(timercmp(latest_p, earliest_p, &lt;) != 0) { *success = true; return SUCCESS; } else { *success = false; return SUCCESS; } return ERROR; } </code></pre> <p>I seem to be getting interval errors of around 5,000us to 350,000us (using a public NTPd). This is a far cry from Google's numbers, but you need to start somewhere.</p> <p>Other than lackluster performance, is there a major flaw in this design that would prevent something like Spanner from being built on top?</p>
18,492,024
1
0
null
2013-08-22 15:32:43.763 UTC
12
2018-12-19 02:55:31.81 UTC
2018-12-19 02:55:31.81 UTC
null
9,146,820
null
107,728
null
1
34
c|time|google-cloud-platform|distributed-computing|google-cloud-spanner
12,796
<p>The challenge in implementing a TrueTime API lies in the <em>guarantees</em> you must provide. Namely, the absolute time must <strong>never</strong> be outside the TrueTime interval on any server in the system. If this can happen, then absolute ordering of events is lost, as are most of the guarantees of Spanner.</p> <p>The <a href="http://static.googleusercontent.com/external_content/untrusted_dlcp/research.google.com/en/us/archive/spanner-osdi2012.pdf" rel="noreferrer">Spanner paper</a> achieves this by a combination of means (section 3):</p> <ol> <li>Multiple time servers, with disparate sources (GPS, atomic clocks), including time servers from other datacenters.</li> <li>Marzullo’s algorithm to detect liars and multiplex the various trusted time sources into an update of the local machine clock.</li> <li>An assumed clock drift of 200us/s at spanservers, applied between clock synchronizations.</li> <li>Kicking machines from the system that exhibit measured local clock drift > threshold (threshold &lt;&lt; 200us/s by necessity).</li> </ol> <p>Now, you <em>can</em> achieve this with simpler means - NTP and an assumed error interval of 10 minutes would trivially do. But as noted in the question, there are performance implications to this. Read-write transactions (4.2.1) must wait on commit, with an expected wait time of 2*errorAverage - 20 minutes in this example. Similarly, read-only transactions (4.2.2) at time "now" - rather than a time in the past - must wait for safetime to advance far enough; at least 10 minutes in this example. So to have a high performance system, you need to minimize the error intervals as far as possible, <em>without</em> losing your guarantees, which is where the complexity arises.</p> <p>I'm not sure how ntp_adjtime is being called in your system - it's possible it's already being set using multiple untrusted and uncorrelated time sources, in which case you're most of the way there already. If you can also ensure that the maxerror value is guaranteed to be advancing faster than the possible clock drift of your system, you should be good to go. Most of the performance of Spanner, without your own personal atomic clock :).</p>
28,023,606
Extend GridView ActionColumn with additional icon
<p>I'm building a webapp with Yii2 framework that will provide users (logged in) the capability to download pre-uploaded files by administrators.</p> <p>I've created the action <code>actionDownload</code> in the specific controller that call the <code>sendFile()</code> method.</p> <p>How can I create a button that call the specific action <code>actionDownload</code> on click in a GridView (the list of documents)?</p>
28,028,556
3
2
null
2015-01-19 11:28:21.983 UTC
9
2017-09-19 12:11:35.807 UTC
2015-01-24 17:23:40.853 UTC
null
1,387,346
null
1,662,191
null
1
24
gridview|yii2
28,485
<p>Extend declaration of <a href="http://www.yiiframework.com/doc-2.0/yii-grid-actioncolumn.html#$template-detail" rel="noreferrer">template</a> and <a href="http://www.yiiframework.com/doc-2.0/yii-grid-actioncolumn.html#$buttons-detail" rel="noreferrer">buttons</a> like this:</p> <pre><code>[ 'class' =&gt; 'yii\grid\ActionColumn', 'template' =&gt; '{download} {view} {update} {delete}', 'buttons' =&gt; [ 'download' =&gt; function ($url) { return Html::a( '&lt;span class="glyphicon glyphicon-arrow-down"&gt;&lt;/span&gt;', $url, [ 'title' =&gt; 'Download', 'data-pjax' =&gt; '0', ] ); }, ], ], </code></pre> <p>The download icon with the url will be added to existing set of icons. You can see for example how default icons are rendered <a href="https://github.com/yiisoft/yii2/blob/master/framework/grid/ActionColumn.php#L104" rel="noreferrer">here</a>.</p> <p>In common case you don't even have to build link manually, it will be constructed based on the button name and model primary key, for example <code>/download?id=1</code>.</p> <p>In case you want different url special property exists, it's called <a href="http://www.yiiframework.com/doc-2.0/yii-grid-actioncolumn.html#$urlCreator-detail" rel="noreferrer">$urlCreator</a>, but you can also change it right in the button rendering closure, for example:</p> <pre><code>'download' =&gt; function ($url, $model) { return Html::a( '&lt;span class="glyphicon glyphicon-arrow-download"&gt;&lt;/span&gt;', ['another-controller/anotner-action', 'id' =&gt; $model-&gt;id], [ 'title' =&gt; 'Download', 'data-pjax' =&gt; '0', ] ); }, </code></pre>
1,803,043
How do I display an arrow positioned at a specific angle in MATLAB?
<p>I am working in MATLAB and I'm stuck on a very simple problem: I've got an object defined by its position <code>(x,y)</code> and <code>theta</code> (an angle, in degrees). I would like to plot the point and add an arrow, starting from the point and pointing toward the direction defined by the angle. It actually doesn't even have to be an arrow, anything graphically showing the value of the angle will do!</p> <p>Here's a picture showing the kind of thing I'm trying to draw:</p> <p><em>removed dead ImageShack link</em></p>
1,804,725
3
0
null
2009-11-26 11:03:55.403 UTC
4
2017-08-08 20:07:16.437 UTC
2015-08-18 08:42:35.173 UTC
null
4,374,739
null
217,903
null
1
13
matlab|plot|angle
47,230
<p>The quiver() plotting function plots arrows like this. Take your theta value and convert it to (x,y) cartesian coordinates representing the vector you want to plot as an arrow and use those as the (u,v) parameters to quiver().</p> <pre><code>theta = pi/9; r = 3; % magnitude (length) of arrow to plot x = 4; y = 5; u = r * cos(theta); % convert polar (theta,r) to cartesian v = r * sin(theta); h = quiver(x,y,u,v); set(gca, 'XLim', [1 10], 'YLim', [1 10]); </code></pre> <p>Take a look through online the Matlab documentation to see other plot types; there's a lot, including several radial plots. They're in the MATLAB > Functions > Graphics > Specialized Plotting section. Do "doc quiver" at the command line and browse around.</p>
8,781,240
A way to restrict Git branch access?
<p>I have four branches in my git repository, which is managed using GitHub:</p> <ul> <li>Production</li> <li>Staging</li> <li>Master</li> <li>[person's name]-development</li> </ul> <p>Is there a way to restrict write access to only a single branch ([person's name]-development)? How would I do this? </p> <p>For reference, a similar question: <a href="https://stackoverflow.com/questions/4114417/how-to-write-a-git-hook-to-restrict-writing-to-branch">How to write a git hook to restrict writing to branch?</a>. </p>
8,781,450
9
1
null
2012-01-08 20:54:13.387 UTC
12
2017-12-05 03:48:16.23 UTC
2017-05-23 12:02:56.39 UTC
null
-1
null
651,174
null
1
72
git|github
76,231
<p>When using GitHub, your best option would be for each developer to have their own fork of the master repository. Everybody pushes to their own repository and somebody with push access to the master repository handles pulling from each developer's repository. This is how most open source projects work.</p> <p>If using your own Git server, it should be possible to use hooks to prevent users from pushing to wrong branches.</p>
716,049
What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?
<p>I was deploying an ASP.NET MVC application last night, and found out that it is less work to deploy with IIS7 set to integrated mode. My question is what is the difference? And what are the implications of using one or the other?</p>
716,067
4
3
null
2009-04-03 23:10:49.42 UTC
141
2017-02-21 00:49:40.393 UTC
2016-08-09 17:12:35.39 UTC
Mehrdad
2,411,320
Jon Erickson
1,950
null
1
517
asp.net|asp.net-mvc|iis|iis-7|integrated-pipeline-mode
306,593
<p>Classic mode (the only mode in IIS6 and below) is a mode where IIS only works with ISAPI extensions and ISAPI filters directly. In fact, in this mode, ASP.NET is just an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). IIS just treats ASP.NET as an external plugin implemented in ISAPI and works with it like a black box (and only when it's needs to give out the request to ASP.NET). In this mode, ASP.NET is not much different from PHP or other technologies for IIS.</p> <p>Integrated mode, on the other hand, is a new mode in IIS7 where IIS pipeline is tightly integrated (i.e. is just the same) as ASP.NET request pipeline. ASP.NET can see every request it wants to and manipulate things along the way. ASP.NET is no longer treated as an external plugin. It's completely blended and integrated in IIS. In this mode, ASP.NET <code>HttpModule</code>s basically have nearly as much power as an ISAPI filter would have had and ASP.NET <code>HttpHandler</code>s can have nearly equivalent capability as an ISAPI extension could have. In this mode, ASP.NET is basically a part of IIS.</p>
472,179
How to read the header with pycurl
<p>How do I read the response headers returned from a PyCurl request?</p>
472,243
4
0
null
2009-01-23 07:21:48.353 UTC
10
2014-02-14 18:13:56.087 UTC
null
null
null
sverrejoh
473
null
1
25
python|curl|pycurl
17,262
<p>There are several solutions (by default, they are dropped). Here is an example using the option HEADERFUNCTION which lets you indicate a function to handle them.</p> <p>Other solutions are options WRITEHEADER (not compatible with WRITEFUNCTION) or setting HEADER to True so that they are transmitted with the body.</p> <pre><code>#!/usr/bin/python import pycurl import sys class Storage: def __init__(self): self.contents = '' self.line = 0 def store(self, buf): self.line = self.line + 1 self.contents = "%s%i: %s" % (self.contents, self.line, buf) def __str__(self): return self.contents retrieved_body = Storage() retrieved_headers = Storage() c = pycurl.Curl() c.setopt(c.URL, 'http://www.demaziere.fr/eve/') c.setopt(c.WRITEFUNCTION, retrieved_body.store) c.setopt(c.HEADERFUNCTION, retrieved_headers.store) c.perform() c.close() print retrieved_headers print retrieved_body </code></pre>
335,104
Is there a program to decompile Delphi?
<p>Someone just sent me a decompile of a program into C. It was a very good decompile, producing nice, mostly readabe C code (if you overlook the fact that none of the variables or functions had a human-readable name) that mostly looked like it would actually compile.</p> <p>There was one big problem, though. I happen to know that the program he was decompiling was written in Delphi, which is full of concepts that are difficult to translate into C. But I was really impressed by the decompiler's output, and it made me wonder. Is there anything that can do that for Delphi?</p> <p>The best decompiling tool I've seen for Delphi is DeDe. It can do a lot of things, but it doesn't even try to produce Object Pascal code as its output, and it hasn't been updated since Delphi 6. Is there anything better out there?</p>
335,122
4
3
null
2008-12-02 19:17:42.557 UTC
12
2020-07-03 21:38:53.773 UTC
2008-12-02 19:40:55.27 UTC
Tim Farley
4,425
Mason Wheeler
32,914
null
1
30
delphi|reverse-engineering|decompiling
118,463
<p>I don't think there are any machine code decompilers that produce Pascal code. Most "Delphi decompilers" parse form and RTTI data, but do not actually decompile the machine code. I can only recommend using something like DeDe (or <a href="http://delphi.about.com/od/devutilities/a/decompiling_3.htm" rel="noreferrer">similar software</a>) to extract symbol information in combination with a C decompiler, then translate the decompiled C code to Delphi (there are many source code converters out there).</p>
40,028,035
Remove Last Two Characters in a String
<p>Is there a quick way to remove the last two characters in a String in Swift? I see there is a simple way to remove the last character as clearly noted <a href="https://stackoverflow.com/questions/24122288/remove-last-character-from-string-swift-language">here</a>. Do you know how to remove the last two characters? Thanks!</p>
40,028,338
5
1
null
2016-10-13 18:07:49.413 UTC
14
2020-03-26 22:55:20.897 UTC
2020-03-26 22:55:20.897 UTC
null
6,110,783
null
6,110,783
null
1
72
ios|swift|string|swift3
56,190
<p>update: <strong>Xcode 9 • Swift 4 or later</strong></p> <p>String now conforms to RangeReplaceableCollection so you can use collection method dropLast straight in the String and therefore an extension it is not necessary anymore. The only difference is that it returns a Substring. If you need a String you need to initialize a new one from it:</p> <pre><code>let string = "0123456789" let substring1 = string.dropLast(2) // "01234567" let substring2 = substring1.dropLast() // "0123456" let result = String(substring2.dropLast()) // "012345" </code></pre> <hr> <p>We can also extend <code>LosslessStringConvertible</code> to add trailing syntax which I think improves readability:</p> <pre><code>extension LosslessStringConvertible { var string: String { .init(self) } } </code></pre> <hr> <p><strong>Usage:</strong></p> <pre><code>let result = substring.dropLast().string </code></pre>
22,081,140
How to execute parent directive before child directive?
<p>I'm looking to write two angular directives, a parent and a child directive, to create sortable and cloneable widgets. The intended markup is:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="widget-container" data-sortable-widgets&gt; &lt;section class="widget" data-cloneable-widget&gt;&lt;/section&gt; &lt;div&gt; </code></pre> <p>However, the child directive seems to execute before the parent, before a certain element is available (its added by the parent):</p> <pre class="lang-js prettyprint-override"><code>function SortableWidgetsDirective() { return { priority: 200, restrict: 'A', link: function ($scope, element, attrs) { element.find(".widget header").append($("&lt;div class='widget-controls'&gt;&lt;/div&gt;")); element.sortable({ }); } }; } function CloneableWidgetDirective() { return { priority: 100, restrict: 'A', link: function ($scope, element, attrs) { // This directive wrongfully executes first so widget-controls is no available element.find("header .widget-controls").append($("&lt;div class='clone-handle'&gt;&lt;/div&gt;")); } }; } </code></pre> <p>As you can see i tried setting priority but I think because they're on different elements, it does not work.</p> <p>How can I make the parent execute first?</p>
22,081,483
1
0
null
2014-02-27 21:43:48.98 UTC
10
2015-11-06 15:47:03.573 UTC
2014-09-08 23:50:43.567 UTC
null
439,427
null
1,267,778
null
1
23
javascript|angularjs|angularjs-directive
10,233
<h2>Reasoning</h2> <p><code>postLink()</code> is executed in reverse order, which means the child directive's <code>postLink()</code> will be called before the parent's (i.e. depth first). For some reason, this is the default behavior (<code>link()</code> actually refers to <code>postLink()</code>). Luckily we also have <code>preLink()</code>, which works the other way around - we can utilize that to our benefit.</p> <p>To illustrate this - the following snippet of code:</p> <pre class="lang-js prettyprint-override"><code>app.directive('parent', function($log) { return { restrict: 'E', compile: function compile(tElement, tAttrs, transclude) { return { pre: function preLink(scope, iElement, iAttrs, controller) { $log.info('parent pre'); }, post: function postLink(scope, iElement, iAttrs, controller) { $log.info('parent post'); } } } }; }); app.directive('child', function($log) { return { restrict: 'E', compile: function compile(tElement, tAttrs, transclude) { return { pre: function preLink(scope, iElement, iAttrs, controller) { $log.info('child pre'); }, post: function postLink(scope, iElement, iAttrs, controller) { $log.info('child post'); } } } }; }); </code></pre> <p>&hellip; will output the following:</p> <pre class="lang-none prettyprint-override"><code>&gt; parent pre &gt; child pre &gt; child post &gt; parent post </code></pre> <p>See it <a href="http://plnkr.co/edit/jDQkwSKrVRKEyJH7qejp?p=preview" rel="noreferrer"><kbd>live on plunker</kbd></a>.</p> <h2>Solution</h2> <p>If we want the parent directive's logic to be performed before the child's, we will explicitly use <code>preLink()</code>:</p> <pre class="lang-js prettyprint-override"><code>function SortableWidgetsDirective() { return { restrict: 'A', compile: function compile(tElement, tAttrs, transclude) { return { pre: function preLink(scope, iElement, iAttrs, controller) { iElement.find(".widget header").append($("&lt;div class='widget-controls'&gt;&lt;/div&gt;")); iElement.sortable({}); }, post: angular.noop } } }; } function CloneableWidgetDirective() { return { restrict: 'A', compile: function compile(tElement, tAttrs, transclude) { return { pre: function preLink(scope, iElement, iAttrs, controller) { iElement.find("header .widget-controls").append($("&lt;div class='clone-handle'&gt;&lt;/div&gt;")); }, post: angular.noop } } }; } </code></pre> <h2>References</h2> <ul> <li><a href="http://docs.angularjs.org/api/ng/service/$compile" rel="noreferrer"><code>$compile</code></a> service on the AngularJS docs.</li> </ul> <hr> <h2>Post Scriptum</h2> <ul> <li><p>You are correct, by the way - <code>priority</code> is meant for use with directives that share the same element.</p></li> <li><p><code>angular.noop</code> is just an empty method that returns nothing. If you still want to use the <code>postLink()</code> functions, just place the function declaration instead, as you would normally do, i.e.:</p> <pre><code>post: function postLink(scope, iElement, iAttrs, controller) { ... } </code></pre></li> <li><p>Be ware of the use of <code>templateUrl</code>, as <em>&ldquo; Because the template loading is asynchronous the compilation/linking is suspended until the template is loaded &rdquo;</em> <sup><a href="http://docs.angularjs.org/api/ng/service/$compile#-templateurl-" rel="noreferrer">[source]</a></sup>. As a result, the order of execution will be disrupted. You can remedy this by including the template inlined in the <code>template</code> property instead.</p></li> </ul>
30,684,581
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
<p>I'm getting error when runtime my project.</p> <pre><code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.olympic/com.prima.olympic.ProductDetail}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference </code></pre> <p>This is full log :</p> <pre><code>06-06 23:12:45.561: E/AndroidRuntime(17135): FATAL EXCEPTION: main 06-06 23:12:45.561: E/AndroidRuntime(17135): Process: com.example.olympic, PID: 17135 06-06 23:12:45.561: E/AndroidRuntime(17135): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.olympic/com.prima.olympic.ProductDetail}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference 06-06 23:12:45.561: E/AndroidRuntime(17135): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693) 06-06 23:12:45.561: E/AndroidRuntime(17135): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758) 06-06 23:12:45.561: E/AndroidRuntime(17135): at android.app.ActivityThread.access$900(ActivityThread.java:177) 06-06 23:12:45.561: E/AndroidRuntime(17135): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448) 06-06 23:12:45.561: E/AndroidRuntime(17135): at android.os.Handler.dispatchMessage(Handler.java:102) 06-06 23:12:45.561: E/AndroidRuntime(17135): at android.os.Looper.loop(Looper.java:145) 06-06 23:12:45.561: E/AndroidRuntime(17135): at android.app.ActivityThread.main(ActivityThread.java:5942) 06-06 23:12:45.561: E/AndroidRuntime(17135): at java.lang.reflect.Method.invoke(Native Method) 06-06 23:12:45.561: E/AndroidRuntime(17135): at java.lang.reflect.Method.invoke(Method.java:372) 06-06 23:12:45.561: E/AndroidRuntime(17135): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389) 06-06 23:12:45.561: E/AndroidRuntime(17135): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184) 06-06 23:12:45.561: E/AndroidRuntime(17135): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference 06-06 23:12:45.561: E/AndroidRuntime(17135): at com.prima.olympic.ProductDetail.onCreate(ProductDetail.java:85) 06-06 23:12:45.561: E/AndroidRuntime(17135): at android.app.Activity.performCreate(Activity.java:6289) 06-06 23:12:45.561: E/AndroidRuntime(17135): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) 06-06 23:12:45.561: E/AndroidRuntime(17135): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646) </code></pre> <p>This is my ProductDetail.java</p> <pre><code>public class ProductDetail extends Activity { Button btnAddtoShoppingList; Button btnDeleteShoppingList; TextView detail_productType; TextView detail_wdh; TextView detail_volume; TextView detail_weight; TextView detail_cont20; TextView detail_cont40; TextView detail_pack; TextView detail_quantity; TextView detail_colour; TextView detail_cetegories; TextView detail_series; TextView detail_price; ImageView detail_imageView; String shown_id, shown_type, shown_wdh, shown_volume, shown_weight, shown_cont20, shown_cont40, shown_pack, shown_quantity, shown_colour, shown_categories, shown_series, shown_price; String customer_id, error_message ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_product_detail); btnAddtoShoppingList = (Button)findViewById(R.id.btnAddtoShoppingList); btnDeleteShoppingList = (Button)findViewById(R.id.btnDeleteShoppingList); SharedPreferences userInformation = getApplicationContext().getSharedPreferences(&quot;userinfo&quot;, 0); customer_id = userInformation.getString(&quot;customer_id&quot;, &quot;none&quot;); detail_productType = (TextView)findViewById(R.id.detail_productType); detail_wdh = (TextView)findViewById(R.id.detail_wdh); detail_volume = (TextView)findViewById(R.id.detail_volume); detail_weight = (TextView)findViewById(R.id.detail_weight); detail_cont20 = (TextView)findViewById(R.id.detail_cont20); detail_cont40 = (TextView)findViewById(R.id.detail_cont40); detail_pack = (TextView)findViewById(R.id.detail_pack); detail_quantity = (TextView)findViewById(R.id.detail_quantity); detail_colour = (TextView)findViewById(R.id.detail_colour); detail_cetegories = (TextView)findViewById(R.id.detail_categories); detail_series = (TextView)findViewById(R.id.detail_series); detail_price = (TextView)findViewById(R.id.detail_price); detail_imageView = (ImageView)findViewById(R.id.detail_imageView); // Get Value from previous activity Intent i = getIntent(); shown_id = i.getStringExtra(&quot;shown_id&quot;); shown_type = i.getStringExtra(&quot;shown_type&quot;); shown_wdh = i.getStringExtra(&quot;shown_wdh&quot;); shown_volume = i.getStringExtra(&quot;shown_volume&quot;); shown_weight = i.getStringExtra(&quot;shown_weight&quot;); shown_cont20 = i.getStringExtra(&quot;shown_cont20&quot;); shown_cont40 = i.getStringExtra(&quot;shown_cont40&quot;); shown_pack = i.getStringExtra(&quot;shown_pack&quot;); shown_quantity = i.getStringExtra(&quot;shown_quantity&quot;); shown_colour = i.getStringExtra(&quot;shown_colour&quot;); shown_categories = i.getStringExtra(&quot;shown_categories&quot;); shown_series = i.getStringExtra(&quot;shown_series&quot;); shown_price = i.getStringExtra(&quot;shown_price&quot;); String checkOrigin = i.getStringExtra(&quot;from_activity&quot;); if(checkOrigin.equals(&quot;shoppinglist&quot;)){ btnAddtoShoppingList.setVisibility(View.GONE); btnDeleteShoppingList.setVisibility(View.VISIBLE); } Bitmap bitmap = (Bitmap) i.getParcelableExtra(&quot;shown_bitmap&quot;); detail_productType.setText(&quot;PRODUCT TYPE: &quot;+shown_type); detail_wdh.setText(&quot;W x D x H: &quot;+shown_wdh); detail_volume.setText(&quot;VOLUME: &quot;+shown_volume); detail_weight.setText(&quot;WEIGHT: &quot;+shown_weight); detail_cont20.setText(&quot;CONT20: &quot;+shown_cont20); detail_cont40.setText(&quot;CONT40: &quot;+shown_cont40); detail_pack.setText(&quot;PACK: &quot;+shown_pack); detail_quantity.setText(&quot;QUANTITY:&quot;+shown_quantity); detail_colour.setText(&quot;COLOUR :&quot;+shown_colour); detail_cetegories.setText(&quot;CATEGORIES:&quot;+shown_categories); detail_series.setText(&quot;SERIES:&quot;+shown_series); detail_price.setText(&quot;PRICE Rp &quot;+shown_price); detail_imageView.setImageBitmap(bitmap); btnAddtoShoppingList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addtoShoppingListTask addtoShoppingList = new addtoShoppingListTask(); addtoShoppingList.execute((Void) null); } }); btnDeleteShoppingList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deleteShoppingListTask deletetoShoppingList = new deleteShoppingListTask(); deletetoShoppingList.execute((Void) null); } }); } </code></pre> <p>can anyone tell me where is the error and how to fix it please? if anyone can help i will be so thankful.</p>
30,684,669
3
2
null
2015-06-06 15:30:36.03 UTC
1
2022-02-24 09:12:20.433 UTC
2022-02-24 09:12:20.433 UTC
null
17,436,751
null
4,069,252
null
1
-1
java|android|nullpointerexception
59,155
<p>Your String <code>checkOrigin</code> is <code>null</code> thus giving you a <code>NullPointerException</code>. This is what is causing it:</p> <pre><code>String checkOrigin = i.getStringExtra("from_activity"); if(checkOrigin.equals("shoppinglist")){ btnAddtoShoppingList.setVisibility(View.GONE); btnDeleteShoppingList.setVisibility(View.VISIBLE); } </code></pre> <p>The String <code>checkOrigin</code> is <code>null</code> because you are not receiving any value from your <code>Intent</code>. This might be because you forgot to pass a value from your previous <code>Activity</code>.<br> However, you can check to see if your String is <code>null</code> and if it is, then those actions won't be performed. You would do this by the following:</p> <pre><code>String checkOrigin = i.getStringExtra("from_activity"); if(checkOrigin != null &amp;&amp; checkOrigin.equals("shoppinglist")){ btnAddtoShoppingList.setVisibility(View.GONE); btnDeleteShoppingList.setVisibility(View.VISIBLE); } </code></pre> <p>Therefore, if <code>checkOrigin</code> is null, then those actions won't be performed. </p> <p>But I would recommend checking the <code>Activity</code> that you are receiving the <code>Intent</code> from to make sure that you are sending and receiving the <code>Intent</code> correctly.</p> <p>If you want to read more about <code>NullPointerException</code>s, have a look at <a href="https://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it">this question and its answers for more detail</a>.</p>
29,619,376
How to exclude Log Tag in logcat Android Studio?
<p>I'm not sure if this kind of question been asked before (I did Google it but not found the proper way to solve my question).</p> <p><em>what I hope is I can disable (exclude) Log Tag from libraries used in my project.</em></p> <p>I tried to go in <strong>Logcat console > Edit Filter Configuration > Log Tag(regex)</strong> but here I have to add new Log Tag every time I create it. (and this way will not show any exception in my logcat)</p> <p>Same as this topic <a href="https://stackoverflow.com/questions/19931987/how-to-filter-logcat-in-android-studio">How to filter logcat in Android Studio?</a> I selected <strong>select the process running</strong> as @dmsherazi suggest but I still can see lots of log tag from libraries.</p> <p>So, is there a way to exclude specific log tag in android studio (I'm using v1.2 beta3)?</p>
29,619,554
1
1
null
2015-04-14 04:49:52.92 UTC
19
2021-09-09 19:57:50.2 UTC
2017-05-23 11:33:26.547 UTC
null
-1
null
4,019,662
null
1
63
android-studio|logcat|android-logcat
23,407
<p>I'm sorry for answering my own question after 20 minutes of asking. My friend just sent me a link that solves my question</p> <p>here it is: <a href="https://stackoverflow.com/questions/5511433/how-to-exclude-certain-messages-by-tag-name-using-android-adb-logcat">How to exclude certain messages by TAG name using Android adb logcat?</a></p> <p>for android studio users</p> <p>go to <strong>Logcat console &gt; Edit Filter Configuration &gt; Log Tag(regex)</strong> and put this instead</p> <pre><code>^(?!(EXCLUDE_TAG1|EXCLUDE_TAG2)) </code></pre> <p>note that EXCLUDE_TAG1 and EXCLUDE_TAG2 are Log Tag you exclude from logcat.</p> <hr /> <p>Another way to answer the question is to exclude all, except ... To block all tags from showing up, except INCLUDE_TAG</p> <pre><code>(?:INCLUDE_TAG) for one tag (?:(INCLUDE_TAG1|INCLUDE_TAGx)) for multiple tags </code></pre>
29,485,035
dyld: Library not loaded: @rpath/Alamofire.framework/Versions/A/Alamofire Reason: image not found
<p>I'm using <code>CocoaPods v0.36</code> with my <code>Swift</code> project and the following pods: <code>Alamofire</code>, <code>CocoaLumberjack</code>, <code>SwiftyJSON</code>.</p> <p>Everything was fine till I used my Developer ID. Compiler started to have problems to compile the project, after some fixes and updates for <code>CocoaPods</code> my project compiles but at runtime I get the following error:</p> <pre><code>dyld: Library not loaded: @rpath/Alamofire.framework/Versions/A/Alamofire Referenced from: /Users/Ivan/Library/Developer/Xcode/DerivedData/myApp-bsxfcnwqpaxnzbhencwzteasshzf/Build/Products/Debug/myApp.app/Contents/MacOS/myApp Reason: image not found </code></pre> <p>I read different posts related to this:</p> <ul> <li><a href="http://blog.cocoapods.org/CocoaPods-0.36/" rel="noreferrer">http://blog.cocoapods.org/CocoaPods-0.36/</a></li> <li><a href="http://samdmarshall.com/blog/swift_and_objc.html" rel="noreferrer">http://samdmarshall.com/blog/swift_and_objc.html</a></li> <li><a href="https://github.com/Alamofire/Alamofire/issues/101" rel="noreferrer">https://github.com/Alamofire/Alamofire/issues/101</a></li> </ul> <p>But none seems to solve the issue.</p> <p>The only clue that I have is that the 3 frameworks are in red, so it seems that are not generated/linked.</p> <p><img src="https://i.stack.imgur.com/xe2fR.png" alt="enter image description here"></p> <p>Now, I've removed my Developer ID, but the issue is still there. Does anybody have an idea?</p>
35,882,506
14
2
null
2015-04-07 06:19:43.097 UTC
9
2020-06-26 18:29:34.64 UTC
2018-10-26 08:15:11.707 UTC
null
3,950,397
null
1,734,106
null
1
33
ios|xcode|cocoa|cocoapods
37,121
<p>Solved Below the steps I did:</p> <ul> <li>pod deintegrate, pod update, pod install</li> <li>Reimported the three swift library files (generated by cocoapods)</li> <li>Imported the three frameworks only in the Linked Frameworks and Libraries</li> <li>Full clean and a build</li> </ul>
36,577,020
PHP - Failed to open stream : No such file or directory
<p>In PHP scripts, whether calling <code>include()</code>, <code>require()</code>, <code>fopen()</code>, or their derivatives such as <code>include_once</code>, <code>require_once</code>, or even, <code>move_uploaded_file()</code>, one often runs into an error or warning: </p> <blockquote> <p>Failed to open stream : No such file or directory.</p> </blockquote> <p>What is a good process to quickly find the root cause of the problem?</p>
36,577,021
10
3
null
2016-04-12 14:58:40.19 UTC
84
2022-06-01 20:54:02.817 UTC
2017-08-19 10:13:32.623 UTC
null
1,033,581
null
2,873,507
null
1
214
php|require|fopen|include-path
733,005
<p>There are many reasons why one might run into this error and thus a good checklist of what to check first helps considerably.</p> <p>Let's consider that we are troubleshooting the following line:</p> <pre><code>require "/path/to/file" </code></pre> <p><br></p> <h1>Checklist</h1> <p><br></p> <h2>1. Check the file path for typos</h2> <ul> <li>either check manually (by visually checking the path)</li> <li><p>or move whatever is called by <code>require*</code> or <code>include*</code> to its own variable, echo it, copy it, and try accessing it from a terminal:</p> <pre><code>$path = "/path/to/file"; echo "Path : $path"; require "$path"; </code></pre> <p>Then, in a terminal:</p> <pre><code>cat &lt;file path pasted&gt; </code></pre></li> </ul> <p><br></p> <h2>2. Check that the file path is correct regarding relative vs absolute path considerations</h2> <ul> <li>if it is starting by a forward slash "/" then it is not referring to the root of your website's folder (the document root), but to the root of your server. <ul> <li>for example, your website's directory might be <code>/users/tony/htdocs</code></li> </ul></li> <li>if it is not starting by a forward slash then it is either relying on the include path (see below) or the path is relative. If it is relative, then PHP will calculate relatively to the path of the <a href="https://secure.php.net/manual/en/function.getcwd.php" rel="noreferrer">current working directory</a>. <ul> <li>thus, not relative to the path of your web site's root, or to the file where you are typing</li> <li>for that reason, always use absolute file paths</li> </ul></li> </ul> <p>Best practices :</p> <p>In order to make your script robust in case you move things around, while still generating an absolute path at runtime, you have 2 options :</p> <ol> <li>use <code>require __DIR__ . "/relative/path/from/current/file"</code>. The <a href="https://secure.php.net/manual/en/language.constants.predefined.php" rel="noreferrer"><code>__DIR__</code> magic constant</a> returns the directory of the current file.</li> <li><p>define a <code>SITE_ROOT</code> constant yourself :</p> <ul> <li>at the root of your web site's directory, create a file, e.g. <code>config.php</code></li> <li><p>in <code>config.php</code>, write</p> <pre><code>define('SITE_ROOT', __DIR__); </code></pre></li> <li><p>in every file where you want to reference the site root folder, include <code>config.php</code>, and then use the <code>SITE_ROOT</code> constant wherever you like :</p> <pre><code>require_once __DIR__."/../config.php"; ... require_once SITE_ROOT."/other/file.php"; </code></pre></li> </ul></li> </ol> <p>These 2 practices also make your application more portable because it does not rely on ini settings like the include path.</p> <p><br></p> <h2>3. Check your include path</h2> <p>Another way to include files, neither relatively nor purely absolutely, is to rely on the <a href="https://secure.php.net/manual/en/ini.core.php#ini.include-path" rel="noreferrer">include path</a>. This is often the case for libraries or frameworks such as the Zend framework.</p> <p>Such an inclusion will look like this :</p> <pre><code>include "Zend/Mail/Protocol/Imap.php" </code></pre> <p>In that case, you will want to make sure that the folder where "Zend" is, is part of the include path.</p> <p>You can check the include path with :</p> <pre><code>echo get_include_path(); </code></pre> <p>You can add a folder to it with :</p> <pre><code>set_include_path(get_include_path().":"."/path/to/new/folder"); </code></pre> <p><br></p> <h2>4. Check that your server has access to that file</h2> <p>It might be that all together, the user running the server process (Apache or PHP) simply doesn't have permission to read from or write to that file.</p> <p>To check under what user the server is running you can use <a href="https://secure.php.net/manual/en/function.posix-getpwuid.php" rel="noreferrer">posix_getpwuid</a> :</p> <pre><code>$user = posix_getpwuid(posix_geteuid()); var_dump($user); </code></pre> <p>To find out the permissions on the file, type the following command in the terminal:</p> <pre><code>ls -l &lt;path/to/file&gt; </code></pre> <p>and look at <a href="https://en.wikipedia.org/wiki/File_system_permissions#Symbolic_notation" rel="noreferrer">permission symbolic notation</a></p> <p><br></p> <h2>5. Check PHP settings</h2> <p>If none of the above worked, then the issue is probably that some PHP settings forbid it to access that file.</p> <p>Three settings could be relevant :</p> <ol> <li><a href="https://secure.php.net/manual/en/ini.core.php#ini.open-basedir" rel="noreferrer">open_basedir</a> <ul> <li>If this is set PHP won't be able to access any file outside of the specified directory (not even through a symbolic link).</li> <li>However, the default behavior is for it not to be set in which case there is no restriction</li> <li>This can be checked by either calling <a href="https://secure.php.net/manual/en/function.phpinfo.php" rel="noreferrer"><code>phpinfo()</code></a> or by using <code>ini_get("open_basedir")</code></li> <li>You can change the setting either by editing your php.ini file or your httpd.conf file</li> </ul></li> <li><a href="https://secure.php.net/manual/en/features.safe-mode.php" rel="noreferrer">safe mode</a> <ul> <li>if this is turned on restrictions might apply. However, this has been removed in PHP 5.4. If you are still on a version that supports safe mode upgrade to a PHP version that is <a href="http://php.net/eol.php" rel="noreferrer">still being supported</a>.</li> </ul></li> <li><a href="https://secure.php.net/manual/en/filesystem.configuration.php" rel="noreferrer">allow_url_fopen and allow_url_include</a> <ul> <li>this applies only to including or opening files through a network process such as http:// not when trying to include files on the local file system</li> <li>this can be checked with <code>ini_get("allow_url_include")</code> and set with <code>ini_set("allow_url_include", "1")</code></li> </ul></li> </ol> <p><br></p> <h1>Corner cases</h1> <p>If none of the above enabled to diagnose the problem, here are some special situations that could happen :</p> <p><br></p> <h2>1. The inclusion of library relying on the include path</h2> <p>It can happen that you include a library, for example, the Zend framework, using a relative or absolute path. For example :</p> <pre><code>require "/usr/share/php/libzend-framework-php/Zend/Mail/Protocol/Imap.php" </code></pre> <p>But then you still get the same kind of error.</p> <p>This could happen because the file that you have (successfully) included, has itself an include statement for another file, and that second include statement assumes that you have added the path of that library to the include path.</p> <p>For example, the Zend framework file mentioned before could have the following include :</p> <pre><code>include "Zend/Mail/Protocol/Exception.php" </code></pre> <p>which is neither an inclusion by relative path, nor by absolute path. It is assuming that the Zend framework directory has been added to the include path.</p> <p>In such a case, the only practical solution is to add the directory to your include path.</p> <p><br></p> <h2>2. SELinux</h2> <p>If you are running Security-Enhanced Linux, then it might be the reason for the problem, by denying access to the file from the server.</p> <p><strong>To check whether SELinux is enabled</strong> on your system, run the <code>sestatus</code> command in a terminal. If the command does not exist, then SELinux is not on your system. If it does exist, then it should tell you whether it is enforced or not.</p> <p><strong>To check whether SELinux policies are the reason</strong> for the problem, you can try turning it off temporarily. However be CAREFUL, since this will disable protection entirely. Do not do this on your production server.</p> <pre><code>setenforce 0 </code></pre> <p>If you no longer have the problem with SELinux turned off, then this is the root cause.</p> <p><strong>To solve it</strong>, you will have to configure SELinux accordingly.</p> <p>The following context types will be necessary :</p> <ul> <li><code>httpd_sys_content_t</code> for files that you want your server to be able to read</li> <li><code>httpd_sys_rw_content_t</code> for files on which you want read and write access</li> <li><code>httpd_log_t</code> for log files</li> <li><code>httpd_cache_t</code> for the cache directory</li> </ul> <p>For example, to assign the <code>httpd_sys_content_t</code> context type to your website root directory, run :</p> <pre><code>semanage fcontext -a -t httpd_sys_content_t "/path/to/root(/.*)?" restorecon -Rv /path/to/root </code></pre> <p>If your file is in a home directory, you will also need to turn on the <code>httpd_enable_homedirs</code> boolean :</p> <pre><code>setsebool -P httpd_enable_homedirs 1 </code></pre> <p>In any case, there could be a variety of reasons why SELinux would deny access to a file, depending on your policies. So you will need to enquire into that. <a href="http://www.serverlab.ca/tutorials/linux/web-servers-linux/configuring-selinux-policies-for-apache-web-servers/" rel="noreferrer">Here</a> is a tutorial specifically on configuring SELinux for a web server.</p> <p><br></p> <h2>3. Symfony</h2> <p>If you are using Symfony, and experiencing this error when uploading to a server, then it can be that the app's cache hasn't been reset, either because <code>app/cache</code> has been uploaded, or that cache hasn't been cleared.</p> <p>You can test and fix this by running the following console command:</p> <pre><code>cache:clear </code></pre> <p><br></p> <h2>4. Non ACSII characters inside Zip file</h2> <p>Apparently, this error can happen also upon calling <code>zip-&gt;close()</code> when some files inside the zip have non-ASCII characters in their filename, such as "é".</p> <p>A potential solution is to wrap the file name in <code>utf8_decode()</code> before creating the target file.</p> <p><em>Credits to <a href="https://stackoverflow.com/users/4217158/fran-cano">Fran Cano</a> for identifying and suggesting a solution to this issue</em></p>
14,268,141
Services with missing/unavailable dependencies
<p>Any idea why I'm getting this error:</p> <pre><code>JBAS014775: New missing/unsatisfied dependencies: service jboss.jdbc-driver.mysql (missing) dependents: [service jboss.data-source.jboss/datasources/UserDS] </code></pre> <hr> <pre><code>ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) `{"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" =&gt; {"Operation step-2" =&gt; {"JBAS014771: Services with missing/unavailable dependencies" =&gt; ["jboss.data-source.jboss/datasources/UserDSjboss.jdbc-driver.com_mysql_jdbcMissing[jboss.data-source.jboss/datasources/UserDSjboss.jdbc-driver.com_mysql_jdbc]"]}}}` </code></pre> <p><strong>persistence.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"&gt; &lt;persistence-unit name="primary"&gt; &lt;jta-data-source&gt;java:jboss/datasources/UserDS&lt;/jta-data-source&gt; &lt;properties&gt; &lt;!-- Properties for Hibernate --&gt; &lt;property name="hibernate.hbm2ddl.auto" value="create-drop" /&gt; &lt;property name="hibernate.show_sql" value="true" /&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </code></pre> <hr> <p><strong>mydatasource-ds.xml</strong></p> <pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;datasources xmlns="http://www.jboss.org/ironjacamar/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.jboss.org/ironjacamar/schema http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd"&gt; &lt;datasource jndi-name="java:jboss/datasources/UserDS" pool-name="kitchensink-quickstart" enabled="true" use-java-context="true"&gt; &lt;!-- jdbc:h2:mem:kitchensink-quickstart;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1 --&gt; &lt;connection-url&gt; jdbc:mysql://localhost:3306/test &lt;/connection-url&gt; &lt;driver&gt;mysql&lt;/driver&gt; &lt;security&gt; &lt;user-name&gt;root&lt;/user-name&gt; &lt;password&gt;root&lt;/password&gt; &lt;/security&gt; &lt;/datasource&gt; &lt;/datasources&gt; </code></pre> <hr> <p>module.xml</p> <pre><code>&lt;module xmlns="urn:jboss:module:1.0" name="com.mysql"&gt; &lt;resources&gt; &lt;resource-root path="mysql-connector-java-5.1.22.jar"/&gt; &lt;/resources&gt; &lt;dependencies&gt; &lt;module name="javax.api"/&gt; &lt;/dependencies&gt; &lt;/module&gt; </code></pre>
19,552,619
3
0
null
2013-01-10 22:06:54.687 UTC
null
2019-11-14 09:17:48.817 UTC
2013-01-10 22:54:40.91 UTC
null
1,243,905
null
1,243,905
null
1
6
java|mysql|persistence|ejb-3.0
48,547
<p>the reason for the error is you are missing the dependence java:jboss/datasources/UserDS. With Jboss 7.x+ these datasource can be added directly to the app servers configuration as you discovered.</p> <p>the difference between Standalone and Domain configuration is the standalone configuration is designed for only one app server w/ said configuration. If you look closely at the domain.xml you will see several app server configurations (aka profiles). These will be much like standalone, standalone-full, standalone-ha, standalone-full-ha config files found under the standalone/conf* directory. Operating in domain mode allows you to control many different server instances running on that domain from a central location (ie the domain controller). ( this includes nodes of a cluster if you have ha configured)</p> <p>This is closely related to your original question in that the domain controller has the ability to gracefully share this datasource configuration to all of its nodes. </p>
31,553,560
Visual Studio 2015 is very slow
<p>I just finished the installation and the whole IDE is super slow. It seems like it's making some kind of heavy CPU calls in the background where the whole IDE literally freezes and becomes unresponsive for about 2-3 seconds.</p> <p>I was not having this issue with Visual Studio 2013 Ultimate. I am running Visual Studio 2015 Professional.</p> <p>Installed Add-Ons/Packages:</p> <ul> <li>Node.js Tools</li> <li>ReSharper</li> </ul> <p>Anyone have any ideas?</p>
31,655,079
19
14
null
2015-07-22 03:52:39.077 UTC
27
2019-07-17 21:46:09.69 UTC
2016-12-26 20:41:52.623 UTC
null
63,550
null
862,919
null
1
145
visual-studio-2015
139,466
<p>My Visual Studio 2015 RTM was also very slow using ReSharper 9.1.2, but it has worked fine since I upgraded to 9.1.3 (see <a href="http://blog.jetbrains.com/dotnet/2015/07/24/resharper-9-1-3-to-the-rescue/" rel="noreferrer" title="ReSharper 9.1.3 to the Rescue">ReSharper 9.1.3 to the Rescue</a>). Perhaps a cue.</p> <p>One more cue. A ReSharper 9.2 version was made available to:</p> <blockquote> <p>refines integration with Visual Studio 2015 RTM, addressing issues discovered in versions 9.1.2 and 9.1.3</p> </blockquote>
48,673,408
Should JavaScript npm packages be minified?
<p>I have created <a href="https://www.npmjs.com/~mrmartineau" rel="noreferrer">quite a few npm packages</a>, but I still don't know the right answer to this question: "Should JavaScript npm packages be minified?"</p> <p>I have always understood that minifying minified code is a bad idea so have not done that in my npm packages. However, I see that some npm packages <a href="https://github.com/axios/axios" rel="noreferrer">axios</a>, <a href="https://github.com/styled-components/styled-components" rel="noreferrer">styled-components</a> provide minified versions of their "dist" files alongside unminified versions, while <a href="https://lodash.com" rel="noreferrer">Lodash</a> does not. </p> <p>Which are right? Who would consume the minified versions?</p>
48,673,965
1
5
null
2018-02-07 21:18:23.917 UTC
9
2020-07-13 03:53:49.417 UTC
null
null
null
null
91,359
null
1
43
javascript|node.js|npm
9,709
<p><strong>It all depends on the environment of your package consumers</strong></p> <hr> <h2>NodeJS</h2> <p>For a NodeJS audience your package does not have to be minified, since node runtimes normally have <em>direct file access</em> to the <code>node_modules</code> folder. No network transfers are required, and no additional code transformations are performed prior to running the code.</p> <hr> <h2>Bundlers / build pipelines</h2> <p>For consumption through a dev environment that uses a bundler in its build pipeline your package <strong>is best not</strong> minified. In most cases package consumers do implement their own minification process as part of their builds. Moreover, when providing your package in a module format for example:</p> <ul> <li>the dependency tree of implementing codebases can be analyzed more accurately, which might lead to better tree-shaking performance. </li> <li>Common dependencies across packages are actually <strong>the same symbols</strong> for all such packages (modules are 'singletons'). This helps with code splitting as well as with keeping bundles small. </li> </ul> <p><em>The above statement relies on the assumption that, if multiple source files are included, minification is preceded by a bundling process. Minifying separate modules is uncommon. If you do provide separate modules, e.g. for a RequireJS runtime in the browser, minification is still relevant, since these files are mostly fetched over the network.</em></p> <hr> <p>If you decide not to supply minified code, it's still advisable to run your own tests to see if a standard minification process - e.g. with UglifyJS - does not break the software.</p> <p>Despite that it is for many consumers unnecessary to minify your code, it's still advisable to supply a minified bundle <em>in addition to</em> your regular distribution, just in case somebody could benefit from it.</p> <blockquote> <p>For plugins / extensions for frameworks like Angular, Vue, Ember etc. it's usually unnecessary to minify your code, since they all implement their own build pipeline, often through a <em>cli</em>.</p> </blockquote> <hr> <h2>Script tags / CDN</h2> <p>These are the cases towards which minification is primarily targeted. If you're hosting a file on a CDN, or otherwise provide it over the web for direct <code>&lt;script&gt;</code> tag usage, what you see is what you get. In both cases the file will have to go over the network. Minification saves bytes.</p> <hr> <h2>Minification v.s. transpilation</h2> <p>A very important distinction is to be made between these two. Although minification is not always necessary, it <strong>is</strong> usually your responsibility to transpile any code that is unlikely to be 100% compatible with the target environments of your package audience. This includes:</p> <ul> <li>Transpiling new <code>ES20XX</code> syntax to - probably - ES5</li> <li>Polyfilling any <code>ES20XX</code> API implementations</li> </ul> <hr> <h2>Minification and bundling</h2> <p>If your package consists of a <strong>single bundle</strong> instead of a bunch of separate modules, minification is always a safe bet. Since a bundler will never try anything funny with a single module/entity (like tree-shaking), it's likely your code will technically not change at all by any build process.</p> <hr> <h2>Debugging</h2> <p>If you're going to distribute a minified bundle of your software, it would be nice to also ship a non-minified version for debugging purposes.</p>
6,587,360
change to database to 'online' and set db to 'multi-user'
<p>I have a 2008 sql database that is offline that I would like to take online and set to multi-user. Using sql server management studio - new query window - when i execute the following:</p> <pre><code> ALTER DATABASE mydb SET ONLINE; ALTER DATABASE mydb SET MULTI_USER; </code></pre> <p>I receive this error message:</p> <blockquote> <p>Msg 5064, Level 16, State 1, Line 1 Changes to the state or options of database 'mydb' cannot be made at this time. The database is in single-user mode, and a user is currently connected to it.<br> Msg 5069, Level 16, State 1, Line 1 ALTER DATABASE statement failed. Msg 5064, Level 16, State 1, Line 3 Changes to the state or options of database 'mydb' cannot be made at this time. The database is in single-user mode, and a user is currently connected to it. Msg 5069, Level 16, State 1, Line 3 ALTER DATABASE statement failed.</p> </blockquote> <p>How would I get the database online and in multi-user mode?</p>
6,587,461
2
0
null
2011-07-05 18:44:47.113 UTC
2
2021-05-12 13:34:26.92 UTC
2011-07-05 18:48:13.203 UTC
null
527,185
null
185,961
null
1
9
sql|sql-server-2008
55,144
<blockquote> <p>a user is currently connected to it</p> </blockquote> <p>^ This is the problem you need to solve.</p> <p>Make sure you are not IN that database. Close any query windows that are connected to it, shut down Object Explorer Details, close SSMS and re-open it without Object Explorer connected to that server, etc. Run this:</p> <pre><code>USE [master]; GO ALTER DATABASE mydb SET SINGLE_USER WITH ROLLBACK IMMEDIATE; GO USE mydb; GO </code></pre> <p>That should allow you to bring it online, then you would run the commands you listed.</p> <p>However:</p> <ul> <li>This can take longer than you might, depending on what rollback activity has to happen to the sessions you're kicking out.</li> <li>It's always possible that when you set it to single user, another process can be faster than you and take that single connection. If you find that this happens, you can figure out who it is using <a href="http://whoisactive.com/" rel="nofollow noreferrer">sp_whoisactive</a> or DMVs like <a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-tran-locks-transact-sql" rel="nofollow noreferrer"><code>sys.dm_tran_locks</code></a> - it may be that you need to suspend connecting applications and/or shut down SQL Server Agent.</li> </ul>
7,406,946
Why is Apple Deprecating OpenSSL in MacOS 10.7 (Lion)?
<p>Apple has marked most (but not all) of the OpenSSL API as "deprecated" in MacOS 10.7. Has Apple made any statements explaining why they are moving from OpenSSL to Common Crypto?</p>
7,406,994
3
4
null
2011-09-13 18:52:20.157 UTC
8
2018-04-09 01:34:05.92 UTC
2018-04-09 01:34:05.92 UTC
null
51,167
null
51,167
null
1
30
openssl|osx-lion
17,708
<p>Apple is migrating from OpenSSL to Common Crypto (which Apple develops).</p> <p>Some docs: <a href="http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/CC_crypto.3cc.html" rel="noreferrer">http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/CC_crypto.3cc.html</a></p> <p>Info on WHY Apple is doing this: <a href="http://adcdownload.apple.com/wwdc_2011/adc_on_itunes__wwdc11_sessions__pdf/212_nextgeneration_cryptographic_services.pdf" rel="noreferrer">http://adcdownload.apple.com/wwdc_2011/adc_on_itunes__wwdc11_sessions__pdf/212_nextgeneration_cryptographic_services.pdf</a></p> <p>If the above link fails (it probably will), here are navigation instructions:</p> <ul> <li>Logon to <a href="http://developer.apple.com" rel="noreferrer">http://developer.apple.com</a></li> <li>Scroll to bottom, click on 'Development Videos'</li> <li>On the next page, click 'Learn more' under WWDC 2011</li> <li>Scroll down about half-way (or search) until you see 'Next Generation Cryptographic Services', and click it</li> <li>You have now reached the buried treasure, download the 'Presentation Slides'</li> </ul>
7,641,876
Java - The difference between class "ClassName" and public class "ClassName"
<p>What's the difference between</p> <pre><code>class x { //code here } </code></pre> <p>and</p> <pre><code>public class x { //code here } </code></pre> <p>Sometimes I see examples on the Internet and they'll have <code>public class</code> instead of <code>class</code> and they're all simple programs. I use <code>class</code> for my assignments and so does everybody else</p>
7,641,889
4
1
null
2011-10-03 23:40:17.31 UTC
12
2014-06-18 08:01:24.887 UTC
null
null
null
null
706,853
null
1
28
java|class
31,066
<p>The first one will result in your class being assigned the default visibility, that is <code>package-private</code> (ie: accessible within the same <code>package</code>).</p> <p>The second one makes it <code>public</code>, that is, visible to any other class.</p> <h3>Reference: <a href="http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html" rel="noreferrer">Controlling Access to Members of a Class</a></h3>
7,958,738
Example of implementation of Baum-Welch
<p>I'm trying to learn about Baum-Welch algorithm(to be used with a hidden markov model). I understand the basic theory of forward-backward models, but it would be nice for someone to help explain it with some code(I find it easier to read code because I can play around to understand it). I checked github and bitbucket and didn't find anything that was easily understandable.</p> <p>There are many HMM tutorials on the net but the probabilities are either already provided or, in the case of spell checkers, add occurrences of words to make the models. It would be cool if someone had examples of creating a Baum-Welch model with only the observations. For example, in <a href="http://en.wikipedia.org/wiki/Hidden_Markov_model#A_concrete_example">http://en.wikipedia.org/wiki/Hidden_Markov_model#A_concrete_example</a> if you only had:</p> <pre><code>states = ('Rainy', 'Sunny') observations = ('walk', 'shop', 'clean') </code></pre> <p>This is just an example, I think any example that explains it and we can play with the good to understand better is great. I have a specific problem I am trying to solve but I was thinking it would maybe more valuable to show code that people can learn from and apply to their own problems(if its not acceptable I can post my own problem). If possible though, It would be nice to have it in python(or java).</p> <p>Thanks in advance!</p>
7,962,692
1
0
null
2011-10-31 19:35:42.19 UTC
11
2014-07-15 16:55:11.757 UTC
2011-11-01 09:31:08.403 UTC
null
344,821
null
640,558
null
1
15
java|python|algorithm|statistics|machine-learning
14,544
<p>Here's some code that I wrote several years ago for a class, based on the presentation in Jurafsky/Martin (2nd edition, chapter 6, if you have access to the book). It's really not very good code, doesn't use numpy which it absolutely should, and it does some crap to have the arrays be 1-indexed instead of just tweaking the formulae to be 0-indexed, but, well, maybe it'll help. Baum-Welch is referred to as "forward-backward" in the code.</p> <p>The example/test data is based on <a href="http://www.cs.jhu.edu/~jason/papers/#tnlp02" rel="noreferrer">Jason Eisner's spreadsheet</a> that implements some HMM-related algorithms. Note that the implemented version of the model uses an absorbing END state which other states have transition probabilities to, rather than assuming a pre-existing fixed sequence length.</p> <p>(Also available <a href="https://gist.github.com/1329976" rel="noreferrer">as a gist</a> if you prefer.)</p> <p><code>hmm.py</code>, half of which is testing code based on the following files:</p> <pre><code>#!/usr/bin/env python """ CS 65 Lab #3 -- 5 Oct 2008 Dougal Sutherland Implements a hidden Markov model, based on Jurafsky + Martin's presentation, which is in turn based off work by Jason Eisner. We test our program with data from Eisner's spreadsheets. """ identity = lambda x: x class HiddenMarkovModel(object): """A hidden Markov model.""" def __init__(self, states, transitions, emissions, vocab): """ states - a list/tuple of states, e.g. ('start', 'hot', 'cold', 'end') start state needs to be first, end state last states are numbered by their order here transitions - the probabilities to go from one state to another transitions[from_state][to_state] = prob emissions - the probabilities of an observation for a given state emissions[state][observation] = prob vocab: a list/tuple of the names of observable values, in order """ self.states = states self.real_states = states[1:-1] self.start_state = 0 self.end_state = len(states) - 1 self.transitions = transitions self.emissions = emissions self.vocab = vocab # functions to get stuff one-indexed state_num = lambda self, n: self.states[n] state_nums = lambda self: xrange(1, len(self.real_states) + 1) vocab_num = lambda self, n: self.vocab[n - 1] vocab_nums = lambda self: xrange(1, len(self.vocab) + 1) num_for_vocab = lambda self, s: self.vocab.index(s) + 1 def transition(self, from_state, to_state): return self.transitions[from_state][to_state] def emission(self, state, observed): return self.emissions[state][observed - 1] # helper stuff def _normalize_observations(self, observations): return [None] + [self.num_for_vocab(o) if o.__class__ == str else o for o in observations] def _init_trellis(self, observed, forward=True, init_func=identity): trellis = [ [None for j in range(len(observed))] for i in range(len(self.real_states) + 1) ] if forward: v = lambda s: self.transition(0, s) * self.emission(s, observed[1]) else: v = lambda s: self.transition(s, self.end_state) init_pos = 1 if forward else -1 for state in self.state_nums(): trellis[state][init_pos] = init_func( v(state) ) return trellis def _follow_backpointers(self, trellis, start): # don't bother branching pointer = start[0] seq = [pointer, self.end_state] for t in reversed(xrange(1, len(trellis[1]))): val, backs = trellis[pointer][t] pointer = backs[0] seq.insert(0, pointer) return seq # actual algorithms def forward_prob(self, observations, return_trellis=False): """ Returns the probability of seeing the given `observations` sequence, using the Forward algorithm. """ observed = self._normalize_observations(observations) trellis = self._init_trellis(observed) for t in range(2, len(observed)): for state in self.state_nums(): trellis[state][t] = sum( self.transition(old_state, state) * self.emission(state, observed[t]) * trellis[old_state][t-1] for old_state in self.state_nums() ) final = sum(trellis[state][-1] * self.transition(state, -1) for state in self.state_nums()) return (final, trellis) if return_trellis else final def backward_prob(self, observations, return_trellis=False): """ Returns the probability of seeing the given `observations` sequence, using the Backward algorithm. """ observed = self._normalize_observations(observations) trellis = self._init_trellis(observed, forward=False) for t in reversed(range(1, len(observed) - 1)): for state in self.state_nums(): trellis[state][t] = sum( self.transition(state, next_state) * self.emission(next_state, observed[t+1]) * trellis[next_state][t+1] for next_state in self.state_nums() ) final = sum(self.transition(0, state) * self.emission(state, observed[1]) * trellis[state][1] for state in self.state_nums()) return (final, trellis) if return_trellis else final def viterbi_sequence(self, observations, return_trellis=False): """ Returns the most likely sequence of hidden states, for a given sequence of observations. Uses the Viterbi algorithm. """ observed = self._normalize_observations(observations) trellis = self._init_trellis(observed, init_func=lambda val: (val, [0])) for t in range(2, len(observed)): for state in self.state_nums(): emission_prob = self.emission(state, observed[t]) last = [(old_state, trellis[old_state][t-1][0] * \ self.transition(old_state, state) * \ emission_prob) for old_state in self.state_nums()] highest = max(last, key=lambda p: p[1])[1] backs = [s for s, val in last if val == highest] trellis[state][t] = (highest, backs) last = [(old_state, trellis[old_state][-1][0] * \ self.transition(old_state, self.end_state)) for old_state in self.state_nums()] highest = max(last, key = lambda p: p[1])[1] backs = [s for s, val in last if val == highest] seq = self._follow_backpointers(trellis, backs) return (seq, trellis) if return_trellis else seq def train_on_obs(self, observations, return_probs=False): """ Trains the model once, using the forward-backward algorithm. This function returns a new HMM instance rather than modifying this one. """ observed = self._normalize_observations(observations) forward_prob, forwards = self.forward_prob( observations, True) backward_prob, backwards = self.backward_prob(observations, True) # gamma values prob_of_state_at_time = posat = [None] + [ [0] + [forwards[state][t] * backwards[state][t] / forward_prob for t in range(1, len(observations)+1)] for state in self.state_nums()] # xi values prob_of_transition = pot = [None] + [ [None] + [ [0] + [forwards[state1][t] * self.transition(state1, state2) * self.emission(state2, observed[t+1]) * backwards[state2][t+1] / forward_prob for t in range(1, len(observations))] for state2 in self.state_nums()] for state1 in self.state_nums()] # new transition probabilities trans = [[0 for j in range(len(self.states))] for i in range(len(self.states))] trans[self.end_state][self.end_state] = 1 for state in self.state_nums(): state_prob = sum(posat[state]) trans[0][state] = posat[state][1] trans[state][-1] = posat[state][-1] / state_prob for oth in self.state_nums(): trans[state][oth] = sum(pot[state][oth]) / state_prob # new emission probabilities emit = [[0 for j in range(len(self.vocab))] for i in range(len(self.states))] for state in self.state_nums(): for output in range(1, len(self.vocab) + 1): n = sum(posat[state][t] for t in range(1, len(observations)+1) if observed[t] == output) emit[state][output-1] = n / sum(posat[state]) trained = HiddenMarkovModel(self.states, trans, emit, self.vocab) return (trained, posat, pot) if return_probs else trained # ====================== # = reading from files = # ====================== def normalize(string): if '#' in string: string = string[:string.index('#')] return string.strip() def make_hmm_from_file(f): def nextline(): line = f.readline() if line == '': # EOF return None else: return normalize(line) or nextline() n = int(nextline()) states = [nextline() for i in range(n)] # &lt;3 list comprehension abuse num_vocab = int(nextline()) vocab = [nextline() for i in range(num_vocab)] transitions = [[float(x) for x in nextline().split()] for i in range(n)] emissions = [[float(x) for x in nextline().split()] for i in range(n)] assert nextline() is None return HiddenMarkovModel(states, transitions, emissions, vocab) def read_observations_from_file(f): return filter(lambda x: x, [normalize(line) for line in f.readlines()]) # ========= # = tests = # ========= import unittest class TestHMM(unittest.TestCase): def setUp(self): # it's complicated to pass args to a testcase, so just use globals self.hmm = make_hmm_from_file(file(HMM_FILENAME)) self.obs = read_observations_from_file(file(OBS_FILENAME)) def test_forward(self): prob, trellis = self.hmm.forward_prob(self.obs, True) self.assertAlmostEqual(prob, 9.1276e-19, 21) self.assertAlmostEqual(trellis[1][1], 0.1, 4) self.assertAlmostEqual(trellis[1][3], 0.00135, 5) self.assertAlmostEqual(trellis[1][6], 8.71549e-5, 9) self.assertAlmostEqual(trellis[1][13], 5.70827e-9, 9) self.assertAlmostEqual(trellis[1][20], 1.3157e-10, 14) self.assertAlmostEqual(trellis[1][27], 3.1912e-14, 13) self.assertAlmostEqual(trellis[1][33], 2.0498e-18, 22) self.assertAlmostEqual(trellis[2][1], 0.1, 4) self.assertAlmostEqual(trellis[2][3], 0.03591, 5) self.assertAlmostEqual(trellis[2][6], 5.30337e-4, 8) self.assertAlmostEqual(trellis[2][13], 1.37864e-7, 11) self.assertAlmostEqual(trellis[2][20], 2.7819e-12, 15) self.assertAlmostEqual(trellis[2][27], 4.6599e-15, 18) self.assertAlmostEqual(trellis[2][33], 7.0777e-18, 22) def test_backward(self): prob, trellis = self.hmm.backward_prob(self.obs, True) self.assertAlmostEqual(prob, 9.1276e-19, 21) self.assertAlmostEqual(trellis[1][1], 1.1780e-18, 22) self.assertAlmostEqual(trellis[1][3], 7.2496e-18, 22) self.assertAlmostEqual(trellis[1][6], 3.3422e-16, 20) self.assertAlmostEqual(trellis[1][13], 3.5380e-11, 15) self.assertAlmostEqual(trellis[1][20], 6.77837e-9, 14) self.assertAlmostEqual(trellis[1][27], 1.44877e-5, 10) self.assertAlmostEqual(trellis[1][33], 0.1, 4) self.assertAlmostEqual(trellis[2][1], 7.9496e-18, 22) self.assertAlmostEqual(trellis[2][3], 2.5145e-17, 21) self.assertAlmostEqual(trellis[2][6], 1.6662e-15, 19) self.assertAlmostEqual(trellis[2][13], 5.1558e-12, 16) self.assertAlmostEqual(trellis[2][20], 7.52345e-9, 14) self.assertAlmostEqual(trellis[2][27], 9.66609e-5, 9) self.assertAlmostEqual(trellis[2][33], 0.1, 4) def test_viterbi(self): path, trellis = self.hmm.viterbi_sequence(self.obs, True) self.assertEqual(path, [0] + [2]*13 + [1]*14 + [2]*6 + [3]) self.assertAlmostEqual(trellis[1][1] [0], 0.1, 4) self.assertAlmostEqual(trellis[1][6] [0], 5.62e-05, 7) self.assertAlmostEqual(trellis[1][7] [0], 4.50e-06, 8) self.assertAlmostEqual(trellis[1][16][0], 1.99e-09, 11) self.assertAlmostEqual(trellis[1][17][0], 3.18e-10, 12) self.assertAlmostEqual(trellis[1][23][0], 4.00e-13, 15) self.assertAlmostEqual(trellis[1][25][0], 1.26e-13, 15) self.assertAlmostEqual(trellis[1][29][0], 7.20e-17, 19) self.assertAlmostEqual(trellis[1][30][0], 1.15e-17, 19) self.assertAlmostEqual(trellis[1][32][0], 7.90e-19, 21) self.assertAlmostEqual(trellis[1][33][0], 1.26e-19, 21) self.assertAlmostEqual(trellis[2][ 1][0], 0.1, 4) self.assertAlmostEqual(trellis[2][ 4][0], 0.00502, 5) self.assertAlmostEqual(trellis[2][ 6][0], 0.00045, 5) self.assertAlmostEqual(trellis[2][12][0], 1.62e-07, 9) self.assertAlmostEqual(trellis[2][18][0], 3.18e-12, 14) self.assertAlmostEqual(trellis[2][19][0], 1.78e-12, 14) self.assertAlmostEqual(trellis[2][23][0], 5.00e-14, 16) self.assertAlmostEqual(trellis[2][28][0], 7.87e-16, 18) self.assertAlmostEqual(trellis[2][29][0], 4.41e-16, 18) self.assertAlmostEqual(trellis[2][30][0], 7.06e-17, 19) self.assertAlmostEqual(trellis[2][33][0], 1.01e-18, 20) def test_learning_probs(self): trained, gamma, xi = self.hmm.train_on_obs(self.obs, True) self.assertAlmostEqual(gamma[1][1], 0.129, 3) self.assertAlmostEqual(gamma[1][3], 0.011, 3) self.assertAlmostEqual(gamma[1][7], 0.022, 3) self.assertAlmostEqual(gamma[1][14], 0.887, 3) self.assertAlmostEqual(gamma[1][18], 0.994, 3) self.assertAlmostEqual(gamma[1][23], 0.961, 3) self.assertAlmostEqual(gamma[1][27], 0.507, 3) self.assertAlmostEqual(gamma[1][33], 0.225, 3) self.assertAlmostEqual(gamma[2][1], 0.871, 3) self.assertAlmostEqual(gamma[2][3], 0.989, 3) self.assertAlmostEqual(gamma[2][7], 0.978, 3) self.assertAlmostEqual(gamma[2][14], 0.113, 3) self.assertAlmostEqual(gamma[2][18], 0.006, 3) self.assertAlmostEqual(gamma[2][23], 0.039, 3) self.assertAlmostEqual(gamma[2][27], 0.493, 3) self.assertAlmostEqual(gamma[2][33], 0.775, 3) self.assertAlmostEqual(xi[1][1][1], 0.021, 3) self.assertAlmostEqual(xi[1][1][12], 0.128, 3) self.assertAlmostEqual(xi[1][1][32], 0.13, 3) self.assertAlmostEqual(xi[2][1][1], 0.003, 3) self.assertAlmostEqual(xi[2][1][22], 0.017, 3) self.assertAlmostEqual(xi[2][1][32], 0.095, 3) self.assertAlmostEqual(xi[1][2][4], 0.02, 3) self.assertAlmostEqual(xi[1][2][16], 0.018, 3) self.assertAlmostEqual(xi[1][2][29], 0.010, 3) self.assertAlmostEqual(xi[2][2][2], 0.972, 3) self.assertAlmostEqual(xi[2][2][12], 0.762, 3) self.assertAlmostEqual(xi[2][2][28], 0.907, 3) def test_learning_results(self): trained = self.hmm.train_on_obs(self.obs) tr = trained.transition self.assertAlmostEqual(tr(0, 0), 0, 5) self.assertAlmostEqual(tr(0, 1), 0.1291, 4) self.assertAlmostEqual(tr(0, 2), 0.8709, 4) self.assertAlmostEqual(tr(0, 3), 0, 4) self.assertAlmostEqual(tr(1, 0), 0, 5) self.assertAlmostEqual(tr(1, 1), 0.8757, 4) self.assertAlmostEqual(tr(1, 2), 0.1090, 4) self.assertAlmostEqual(tr(1, 3), 0.0153, 4) self.assertAlmostEqual(tr(2, 0), 0, 5) self.assertAlmostEqual(tr(2, 1), 0.0925, 4) self.assertAlmostEqual(tr(2, 2), 0.8652, 4) self.assertAlmostEqual(tr(2, 3), 0.0423, 4) self.assertAlmostEqual(tr(3, 0), 0, 5) self.assertAlmostEqual(tr(3, 1), 0, 4) self.assertAlmostEqual(tr(3, 2), 0, 4) self.assertAlmostEqual(tr(3, 3), 1, 4) em = trained.emission self.assertAlmostEqual(em(0, 1), 0, 4) self.assertAlmostEqual(em(0, 2), 0, 4) self.assertAlmostEqual(em(0, 3), 0, 4) self.assertAlmostEqual(em(1, 1), 0.6765, 4) self.assertAlmostEqual(em(1, 2), 0.2188, 4) self.assertAlmostEqual(em(1, 3), 0.1047, 4) self.assertAlmostEqual(em(2, 1), 0.0584, 4) self.assertAlmostEqual(em(2, 2), 0.4251, 4) self.assertAlmostEqual(em(2, 3), 0.5165, 4) self.assertAlmostEqual(em(3, 1), 0, 4) self.assertAlmostEqual(em(3, 2), 0, 4) self.assertAlmostEqual(em(3, 3), 0, 4) # train 9 more times for i in range(9): trained = trained.train_on_obs(self.obs) tr = trained.transition self.assertAlmostEqual(tr(0, 0), 0, 4) self.assertAlmostEqual(tr(0, 1), 0, 4) self.assertAlmostEqual(tr(0, 2), 1, 4) self.assertAlmostEqual(tr(0, 3), 0, 4) self.assertAlmostEqual(tr(1, 0), 0, 4) self.assertAlmostEqual(tr(1, 1), 0.9337, 4) self.assertAlmostEqual(tr(1, 2), 0.0663, 4) self.assertAlmostEqual(tr(1, 3), 0, 4) self.assertAlmostEqual(tr(2, 0), 0, 4) self.assertAlmostEqual(tr(2, 1), 0.0718, 4) self.assertAlmostEqual(tr(2, 2), 0.8650, 4) self.assertAlmostEqual(tr(2, 3), 0.0632, 4) self.assertAlmostEqual(tr(3, 0), 0, 4) self.assertAlmostEqual(tr(3, 1), 0, 4) self.assertAlmostEqual(tr(3, 2), 0, 4) self.assertAlmostEqual(tr(3, 3), 1, 4) em = trained.emission self.assertAlmostEqual(em(0, 1), 0, 4) self.assertAlmostEqual(em(0, 2), 0, 4) self.assertAlmostEqual(em(0, 3), 0, 4) self.assertAlmostEqual(em(1, 1), 0.6407, 4) self.assertAlmostEqual(em(1, 2), 0.1481, 4) self.assertAlmostEqual(em(1, 3), 0.2112, 4) self.assertAlmostEqual(em(2, 1), 0.00016,5) self.assertAlmostEqual(em(2, 2), 0.5341, 4) self.assertAlmostEqual(em(2, 3), 0.4657, 4) self.assertAlmostEqual(em(3, 1), 0, 4) self.assertAlmostEqual(em(3, 2), 0, 4) self.assertAlmostEqual(em(3, 3), 0, 4) if __name__ == '__main__': import sys HMM_FILENAME = sys.argv[1] if len(sys.argv) &gt;= 2 else 'example.hmm' OBS_FILENAME = sys.argv[2] if len(sys.argv) &gt;= 3 else 'observations.txt' unittest.main() </code></pre> <p><code>observations.txt</code>, a sequence of observations for testing:</p> <pre><code>2 3 3 2 3 2 3 2 2 3 1 3 3 1 1 1 2 1 1 1 3 1 2 1 1 1 2 3 3 2 3 2 2 </code></pre> <p><code>example.hmm</code>, the model used to generate the data</p> <pre><code>4 # number of states START COLD HOT END 3 # size of vocab 1 2 3 # transition matrix 0.0 0.5 0.5 0.0 # from start 0.0 0.8 0.1 0.1 # from cold 0.0 0.1 0.8 0.1 # from hot 0.0 0.0 0.0 1.0 # from end # emission matrix 0.0 0.0 0.0 # from start 0.7 0.2 0.1 # from cold 0.1 0.2 0.7 # from hot 0.0 0.0 0.0 # from end </code></pre>
1,558,291
Push elements from one array into rows of another array (one element per row)
<p>I need to push elements from one array into respective rows of another array.</p> <p>The 2 arrays are created from <code>$_POST</code> and <code>$_FILES</code> and I need them to be associated with each other based on their indexes.</p> <pre><code>$array1 = [ [123, &quot;Title #1&quot;, &quot;Name #1&quot;], [124, &quot;Title #2&quot;, &quot;Name #2&quot;], ]; $array2 = [ 'name' =&gt; ['Image001.jpg', 'Image002.jpg'] ]; </code></pre> <p>New Array</p> <pre><code>array ( 0 =&gt; array ( 0 =&gt; 123, 1 =&gt; 'Title #1', 2 =&gt; 'Name #1', 3 =&gt; 'Image001.jpg', ), 1 =&gt; array ( 0 =&gt; 124, 1 =&gt; 'Title #2', 2 =&gt; 'Name #2', 3 =&gt; 'Image002.jpg', ), ) </code></pre> <p>The current code I'm using works, but only for the last item in the array.<br> I'm presuming by looping the <code>array_merge</code> function it wipes my new array every loop.</p> <pre><code>$i = 0; $NewArray = array(); foreach ($OriginalArray as $value) { $NewArray = array_merge($value, array($_FILES['Upload']['name'][$i])); $i++; } </code></pre> <p>How do I correct this?</p>
1,558,316
4
0
null
2009-10-13 05:10:21.58 UTC
3
2022-09-16 12:45:07.833 UTC
2022-09-16 12:45:07.833 UTC
null
2,943,403
null
99,106
null
1
19
php|multidimensional-array|merge|append|array-push
56,696
<pre><code>$i=0; $NewArray = array(); foreach($OriginalArray as $value) { $NewArray[] = array_merge($value,array($_FILES['Upload']['name'][$i])); $i++; } </code></pre> <p>the [] will append it to the array instead of overwriting.</p>
2,264,750
Poll Database Schema
<p>What is the best database schema for polls? Is one-to-many relationship good for this? I'm thinking about having two tables:</p> <pre><code>poll_questions int id varchar body datetime created_at datetime updated_at poll_answers int id varchar body int votes default 0 int question_id (foreign key to poll_questions.id) datetime created_at datetime updated_at </code></pre> <p>Then there would also be third table for tracking who voted for an answer so users are able to vote only once:</p> <pre><code>poll_voting_history int id int question_id (foreign key to poll_questions.id) int answer_id (foreign key to poll_answers.id) int user_id (foreign key to the id in the users table) datetime created_at datetime updated_at </code></pre> <p>What are your thoughts? Am I thinking about it right?</p>
2,264,761
4
2
null
2010-02-15 08:39:47.877 UTC
10
2019-08-08 04:17:12.71 UTC
2010-02-15 08:51:10.107 UTC
null
95,944
null
95,944
null
1
25
mysql|database-schema
9,890
<p>The schema looks good, and yes, you'd need to <a href="https://stackoverflow.com/questions/2260406/voting-stopping-abuse-from-client-side-asp-net-mvc/2263045#2263045">track the user votes as well</a>.</p>
1,814,169
Geographical boundaries of states/provinces -> Google Maps Polygon
<p>I'm building a web application that is going to dynamically highlight certain U.S. states and Canadian provinces on a Google Map, based on buttons and click events.</p> <p>Plan A) Polygons</p> <p>My primary idea for this was to draw Polygons. For this I need lists of coordinates (latitude + longitude) of all state and province outlines (clockwise or counter-clockwise). On government websites I found all sorts of different formats (i.e. E00), but I have trouble converting these formats into a simple list of coordinates, that I could use to create markers or a polygon on a map. Do you have any tips where to get these coordinates?</p> <p>Plan B) Overlays</p> <p>AFAIK, if you use overlays on Google Maps, they become pixelated as you zoom in further (or can you overlay SVGs?) In my case I would need 50 + 11 overlays in the worst-case (all states and all provinces). Is that still possible with Google Maps or will it get unsuably slow?</p> <p>I'm a bit startled that there isn't a straight-forward way to highlight a state or province, as I would think this is a very common tasks for people using an API for maps.</p> <p>Thanks in advance</p>
1,814,325
4
1
null
2009-11-28 23:49:09.097 UTC
34
2018-05-11 18:47:54.83 UTC
null
null
null
null
149,231
null
1
36
google-maps|coordinates|geography|gis
51,589
<p>I've got XML for US state polygons <a href="http://econym.org.uk/gmap/states.xml" rel="noreferrer">here</a>. I use them like <a href="http://econym.org.uk/gmap/example_states4.htm" rel="noreferrer">this</a>.</p> <p>I deliberately kept the detail fairly light to reduce the loading time and end up with a map that's reasonably responsive in slow browsers.</p> <p>I don't have anything for Canada.</p>
2,314,179
How to browse TFS changesets?
<p>I want to browse TFS changesets.</p> <p>I do NOT want to search changesets by specifying a file contained within the changeset. I do not want to specify which user I think created the changeset.</p> <p>I simply want to key in a changeset number and look at that changeset. Or maybe view a range, and then browse those.</p> <p>No specified file, no specified user. TFS 2008 seems to not want to allow me to do this.</p> <p>I must be missing something.</p> <p>How do you do this?</p>
2,316,695
4
4
null
2010-02-22 21:05:06.763 UTC
11
2017-11-30 22:27:31.51 UTC
null
null
null
null
630
null
1
66
tfs
50,537
<p>In Source Control Explorer, hit CTRL+G. This will bring up the Find Changesets dialog. Unfortunately it's kind of one-size-fits-all in VS 2008: you have to work inside a big bulky search dialog, even if you already know the number(s). In your case, flip the radio button to search by range and then key in the desired changeset number as both the start &amp; end of the range. </p> <p>The VS 2010 version of this dialog simplifies the "lookup single changeset by #" use case, FWIW.</p> <p>My personal preference: if you have a console window open, there's a quicker route. Simply type <strong>tf changeset 12345</strong>. If using the Power Tools, you can substitute "Get-TfsChangeset" or "tfchangeset" for improved performance and programmability.</p>
10,584,948
Doubles, commas and dots
<p>I'm making an Android Java program which is taking double values from the user. If I run the program on the computer, it works great because of the locale of my computer, EN_UK. But when I run it on my mobile phone with FI_FI locale, it won't work. I know the reason: In UK, people use dot as decimal separator but here in Finland, the decimal separator is comma. </p> <pre><code>DecimalFormat df = new DecimalFormat("#.#"); Double returnValue = Double.valueOf(df.format(doubleNumber)); </code></pre> <p>When I'm using comma, it says <code>java.lang.NumberFormatException: Invalid double: "1234,5"</code>.</p> <p>How can I make it work with them both, comma and dot?</p>
10,585,046
7
2
null
2012-05-14 14:06:54.867 UTC
7
2019-07-21 11:59:29.073 UTC
2019-07-21 11:59:29.073 UTC
null
7,983,864
null
1,279,334
null
1
18
java|android|decimal
41,512
<p>Use one of the other constructors of DecimalFormat:</p> <pre><code>new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.US)) </code></pre> <p>And then try and parse it using both separators.</p>
49,296,318
How to set different font sizes for different devices using Xcode Storyboard?
<p>I want to set different font sizes for iPhone 5, iPhone 6 Plus, iPhone 7 Plus and iPhone X using Xcode Storyboard.</p> <p>Can anyone offer any advice?</p> <p><a href="https://i.stack.imgur.com/rqADm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rqADm.png" alt="Example is shown in the image where i was stuck."></a></p>
49,296,508
3
4
null
2018-03-15 09:56:50.397 UTC
10
2019-06-13 07:40:59.77 UTC
2019-06-13 07:40:59.77 UTC
null
5,638,630
null
7,241,050
null
1
14
ios|fonts|font-size|xcode-storyboard
8,279
<p>Use <a href="https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/TheAdaptiveModel.html" rel="noreferrer">Size-Class</a> and add size variation for fonts from <code>Attribute Inspector</code> of Label property.</p> <p>Here are different possible variations, you can set with Size class:</p> <p><a href="https://i.stack.imgur.com/840pL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/840pL.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/uEHG9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uEHG9.png" alt="enter image description here" /></a></p> <p>Try this:</p> <p><a href="https://i.stack.imgur.com/rthJM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rthJM.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/HIi8O.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HIi8O.png" alt="enter image description here" /></a></p> <p>Here is (result) preview of font-size variation, in iPhone and iPad</p> <p><a href="https://i.stack.imgur.com/dYJYo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dYJYo.png" alt="enter image description here" /></a></p> <h1>Update</h1> <p>The result you are expecting, may not be possible using IB (Storyboard) but you can try it with following programmatic solution:</p> <pre><code>extension UIDevice { enum DeviceType: String { case iPhone4_4S = &quot;iPhone 4 or iPhone 4S&quot; case iPhones_5_5s_5c_SE = &quot;iPhone 5, iPhone 5s, iPhone 5c or iPhone SE&quot; case iPhones_6_6s_7_8 = &quot;iPhone 6, iPhone 6S, iPhone 7 or iPhone 8&quot; case iPhones_6Plus_6sPlus_7Plus_8Plus = &quot;iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus or iPhone 8 Plus&quot; case iPhoneX = &quot;iPhone X&quot; case unknown = &quot;iPadOrUnknown&quot; } var deviceType: DeviceType { switch UIScreen.main.nativeBounds.height { case 960: return .iPhone4_4S case 1136: return .iPhones_5_5s_5c_SE case 1334: return .iPhones_6_6s_7_8 case 1920, 2208: return .iPhones_6Plus_6sPlus_7Plus_8Plus case 2436: return .iPhoneX default: return .unknown } } } // Get device type (with help of above extension) and assign font size accordingly. let label = UILabel() let deviceType = UIDevice.current.deviceType switch deviceType { case .iPhone4_4S: label.font = UIFont.systemFont(ofSize: 10) case .iPhones_5_5s_5c_SE: label.font = UIFont.systemFont(ofSize: 12) case .iPhones_6_6s_7_8: label.font = UIFont.systemFont(ofSize: 14) case .iPhones_6Plus_6sPlus_7Plus_8Plus: label.font = UIFont.systemFont(ofSize: 16) case .iPhoneX: label.font = UIFont.systemFont(ofSize: 18) default: print(&quot;iPad or Unkown device&quot;) label.font = UIFont.systemFont(ofSize: 20) } </code></pre>
49,042,830
Why does the node inspector not start when I am using nodemon and ts-node?
<p>I have a simple node server written in typescript. My package.json is configured as:</p> <pre><code>"scripts": { "build": "tsc", "dev": "nodemon --watch src/**/* -e ts,json --exec ts-node ./src/server.ts", "debug": "nodemon --verbose --watch src/**/* -e ts,json --exec ts-node --inspect ./src/server.ts" }, </code></pre> <p>When I run <code>npm run dev</code> nodemon will launch the server and restart it when any changes are made. </p> <pre><code>[02/28/18 20:45:53] npm run dev &gt; [email protected] dev C:\Users\joe\pq\pq-api &gt; nodemon --watch src/**/* -e ts,json --exec ts-node ./src/server.ts [nodemon] 1.15.1 [nodemon] to restart at any time, enter `rs` [nodemon] watching: src/**/* [nodemon] starting `ts-node ./src/server.ts` initializing config to development info: PQ-API running on port 3000 </code></pre> <p>However, when I run <code>npm run debug</code> (so I can attach a debugger) It looks like it begins to start, but just hangs forever</p> <pre><code>[02/28/18 20:39:30] npm run debug &gt; [email protected] debug C:\Users\joe\pq\pq-api &gt; nodemon --verbose --watch src/**/* -e ts,json --exec ts-node --inspect ./src/server.ts [nodemon] 1.15.1 [nodemon] to restart at any time, enter `rs` [nodemon] or send SIGHUP to 10156 to restart [nodemon] watching: src/**/* [nodemon] watching extensions: ts,json [nodemon] starting `ts-node --inspect ./src/server.ts` [nodemon] spawning [nodemon] child pid: 13344 [nodemon] watching 12 files </code></pre> <p>That is all the output has. The script is never executed; the server never starts up, and the inspector is never available to connect to. </p> <p><strong>node 8.94</strong><br> <strong>nodemon 1.15.1</strong><br> <strong>ts-node 5.0.0</strong><br> <strong>typescript 2.7.2</strong></p>
49,122,820
6
4
null
2018-03-01 04:51:30.977 UTC
10
2022-05-05 10:30:51.033 UTC
null
null
null
user60456
null
null
1
33
node.js|typescript|debugging|nodemon|ts-node
22,406
<p>With ts-node 5.0.0 you no longer pass the <code>--inspect flag</code> the same way. The suggested way is <code>node --inspect -r ts-node/register path/to/ts</code>. For example:</p> <p><code>nodemon --watch src/**/* -e ts,json --exec node --inspect-brk -r ts-node/register src/app.ts</code></p> <p>see <a href="https://github.com/TypeStrong/ts-node/issues/537" rel="noreferrer">https://github.com/TypeStrong/ts-node/issues/537</a></p>
7,637,482
How do browsers resolve conflicting classes?
<p>I know it's possible to specify multiple classes on an element in HTML: </p> <pre><code>&lt;div class='one two'&gt;Text&lt;/div&gt; </code></pre> <p>It seems like classes are accessible from Javascript as a single string. </p> <p>What happens when the classes are specified with conflicting properties? For instance</p> <pre><code>div.one { background-color: red; color: blue; } div.two { background-color: green; } </code></pre> <p>Will the result depend on the order the classes are specified in? For instance could I reasonably expect the div above to appear with blue text and a green background, because the <code>two</code> class becomes evaluated second, overwriting the <code>background-color</code> property? </p>
7,637,536
6
6
null
2011-10-03 15:59:05.217 UTC
2
2011-10-03 21:27:40.35 UTC
2011-10-03 16:06:16.82 UTC
null
798,818
null
340,947
null
1
32
html|css|dom
11,831
<p>Read about specificity:</p> <ul> <li><a href="http://www.htmldog.com/guides/cssadvanced/specificity/" rel="noreferrer">Simple explanation</a></li> <li><a href="http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/" rel="noreferrer">More in depth explanation</a></li> </ul> <p>Short answer: if two selectors have the same specificity, the last one to be declared wins.</p>
7,420,937
run program in Python shell
<p>I have a demo file: <code>test.py</code>. In the Windows Console I can run the file with: <code>C:\&gt;test.py</code></p> <p>How can I execute the file in the Python Shell instead?</p>
7,420,972
6
2
null
2011-09-14 18:09:14.167 UTC
41
2021-02-07 22:00:14.207 UTC
2018-05-27 17:09:45.443 UTC
null
9,170,457
null
537,173
null
1
65
python|executable
246,292
<p>Use <a href="https://docs.python.org/2.7/library/functions.html#execfile" rel="noreferrer">execfile</a> for <strong>Python 2</strong>:</p> <pre><code>&gt;&gt;&gt; execfile('C:\\test.py') </code></pre> <p>Use <a href="https://docs.python.org/3/library/functions.html#exec" rel="noreferrer">exec</a> for <strong>Python 3</strong></p> <pre><code>&gt;&gt;&gt; exec(open("C:\\test.py").read()) </code></pre>
7,439,977
Changing date format in R
<p>I have some very simple data in R that needs to have its date format changed:</p> <pre><code> date midpoint 1 31/08/2011 0.8378 2 31/07/2011 0.8457 3 30/06/2011 0.8147 4 31/05/2011 0.7970 5 30/04/2011 0.7877 6 31/03/2011 0.7411 7 28/02/2011 0.7624 8 31/01/2011 0.7665 9 31/12/2010 0.7500 10 30/11/2010 0.7734 11 31/10/2010 0.7511 12 30/09/2010 0.7263 13 31/08/2010 0.7158 14 31/07/2010 0.7110 15 30/06/2010 0.6921 16 31/05/2010 0.7005 17 30/04/2010 0.7113 18 31/03/2010 0.7027 19 28/02/2010 0.6973 20 31/01/2010 0.7260 21 31/12/2009 0.7154 22 30/11/2009 0.7287 23 31/10/2009 0.7375 </code></pre> <p>Rather than <code>%d/%m/%Y</code>, I would like it in the standard R format of <code>%Y-%m-%d</code></p> <p>How can I make this change? I have tried:</p> <pre><code>nzd$date &lt;- format(as.Date(nzd$date), "%Y/%m/%d") </code></pre> <p>But that just cut off the year and added zeros to the day:</p> <pre><code> [1] "0031/08/20" "0031/07/20" "0030/06/20" "0031/05/20" "0030/04/20" [6] "0031/03/20" "0028/02/20" "0031/01/20" "0031/12/20" "0030/11/20" [11] "0031/10/20" "0030/09/20" "0031/08/20" "0031/07/20" "0030/06/20" [16] "0031/05/20" "0030/04/20" "0031/03/20" "0028/02/20" "0031/01/20" [21] "0031/12/20" "0030/11/20" "0031/10/20" "0030/09/20" "0031/08/20" [26] "0031/07/20" "0030/06/20" "0031/05/20" "0030/04/20" "0031/03/20" [31] "0028/02/20" "0031/01/20" "0031/12/20" "0030/11/20" "0031/10/20" [36] "0030/09/20" "0031/08/20" "0031/07/20" "0030/06/20" "0031/05/20" </code></pre> <p>Thanks!</p>
7,440,055
7
0
null
2011-09-16 03:56:48.34 UTC
20
2020-07-12 11:26:45.973 UTC
2020-07-12 11:26:45.973 UTC
null
1,851,712
null
855,046
null
1
36
r|date|format|strptime|r-faq
222,424
<p>There are two steps here:</p> <ul> <li>Parse the data. Your example is not fully reproducible, is the data in a file, or the variable in a text or factor variable? Let us assume the latter, then if you data.frame is called X, you can do</li> </ul> <blockquote> <pre><code> X$newdate &lt;- strptime(as.character(X$date), "%d/%m/%Y") </code></pre> </blockquote> <p>Now the <code>newdate</code> column should be of type <code>Date</code>.</p> <ul> <li>Format the data. That is a matter of calling <code>format()</code> or <code>strftime()</code>:</li> </ul> <blockquote> <pre><code> format(X$newdate, "%Y-%m-%d") </code></pre> </blockquote> <p>A more complete example:</p> <pre><code>R&gt; nzd &lt;- data.frame(date=c("31/08/2011", "31/07/2011", "30/06/2011"), + mid=c(0.8378,0.8457,0.8147)) R&gt; nzd date mid 1 31/08/2011 0.8378 2 31/07/2011 0.8457 3 30/06/2011 0.8147 R&gt; nzd$newdate &lt;- strptime(as.character(nzd$date), "%d/%m/%Y") R&gt; nzd$txtdate &lt;- format(nzd$newdate, "%Y-%m-%d") R&gt; nzd date mid newdate txtdate 1 31/08/2011 0.8378 2011-08-31 2011-08-31 2 31/07/2011 0.8457 2011-07-31 2011-07-31 3 30/06/2011 0.8147 2011-06-30 2011-06-30 R&gt; </code></pre> <p>The difference between columns three and four is the type: <code>newdate</code> is of class <code>Date</code> whereas <code>txtdate</code> is character.</p>
7,456,807
Python name mangling
<p>In other languages, a general guideline that helps produce better code is always make everything as hidden as possible. If in doubt about whether a variable should be private or protected, it's better to go with private.</p> <p>Does the same hold true for Python? Should I use two leading underscores on everything at first, and only make them less hidden (only one underscore) as I need them?</p> <p>If the convention is to use only one underscore, I'd also like to know the rationale.</p> <p>Here's a comment I left on <a href="https://stackoverflow.com/questions/7456807/python-name-mangling-when-in-doubt-do-what/7456958#7456958">JBernardo's answer</a>. It explains why I asked this question and also why I'd like to know why Python is different from the other languages:</p> <blockquote> <p>I come from languages that train you to think everything should be only as public as needed and no more. The reasoning is that this will reduce dependencies and make the code safer to alter. The Python way of doing things in reverse -- starting from public and going towards hidden -- is odd to me.</p> </blockquote>
7,456,865
11
0
null
2011-09-17 18:07:49.92 UTC
68
2021-08-06 17:38:39.44 UTC
2017-05-23 11:54:31.18 UTC
null
-1
null
627,005
null
1
141
python|naming-conventions
57,661
<p>When in doubt, leave it &quot;public&quot; - I mean, do not add anything to obscure the name of your attribute. If you have a class with some internal value, do not bother about it. Instead of writing:</p> <pre><code>class Stack(object): def __init__(self): self.__storage = [] # Too uptight def push(self, value): self.__storage.append(value) </code></pre> <p>write this by default:</p> <pre><code>class Stack(object): def __init__(self): self.storage = [] # No mangling def push(self, value): self.storage.append(value) </code></pre> <p>This is for sure a controversial way of doing things. Python newbies hate it, and even some old Python guys despise this default - but it is the default anyway, so I recommend you to follow it, even if you feel uncomfortable.</p> <p>If you <em>really</em> want to send the message &quot;Can't touch this!&quot; to your users, the usual way is to precede the variable with <em>one</em> underscore. This is just a convention, but people understand it and take double care when dealing with such stuff:</p> <pre><code>class Stack(object): def __init__(self): self._storage = [] # This is ok, but Pythonistas use it to be relaxed about it def push(self, value): self._storage.append(value) </code></pre> <p>This can be useful, too, for avoiding conflict between property names and attribute names:</p> <pre><code> class Person(object): def __init__(self, name, age): self.name = name self._age = age if age &gt;= 0 else 0 @property def age(self): return self._age @age.setter def age(self, age): if age &gt;= 0: self._age = age else: self._age = 0 </code></pre> <p>What about the double underscore? Well, we use the double underscore magic mainly <a href="https://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private/70900#70900">to avoid accidental overloading of methods and name conflicts with superclasses' attributes</a>. It can be pretty valuable if you write a class to be extended many times.</p> <p>If you want to use it for other purposes, you can, but it is neither usual nor recommended.</p> <p><strong>EDIT</strong>: Why is this so? Well, the usual Python style does not emphasize making things private - on the contrary! There are many reasons for that - most of them controversial... Let us see some of them.</p> <h1>Python has properties</h1> <p>Today, most OO languages use the opposite approach: what should not be used should not be visible, so attributes should be private. Theoretically, this would yield more manageable, less coupled classes because no one would change the objects' values recklessly.</p> <p>However, it is not so simple. For example, Java classes have many getters that only <em>get</em> the values <em>and</em> setters that only <em>set</em> the values. You need, let us say, seven lines of code to declare a single attribute - which a Python programmer would say is needlessly complex. Also, you write a lot of code to get one public field since you can change its value using the getters and setters in practice.</p> <p>So why follow this private-by-default policy? Just make your attributes public by default. Of course, this is problematic in Java because if you decide to add some validation to your attribute, it would require you to change all:</p> <pre><code>person.age = age; </code></pre> <p>in your code to, let us say,</p> <pre><code>person.setAge(age); </code></pre> <p><code>setAge()</code> being:</p> <pre><code>public void setAge(int age) { if (age &gt;= 0) { this.age = age; } else { this.age = 0; } } </code></pre> <p>So in Java (and other languages), the default is to use getters and setters anyway because they can be annoying to write but can spare you much time if you find yourself in the situation I've described.</p> <p>However, you do not need to do it in Python since Python has properties. If you have this class:</p> <pre><code> class Person(object): def __init__(self, name, age): self.name = name self.age = age </code></pre> <p>...and then you decide to validate ages, you do not need to change the <code>person.age = age</code> pieces of your code. Just add a property (as shown below)</p> <pre><code> class Person(object): def __init__(self, name, age): self.name = name self._age = age if age &gt;= 0 else 0 @property def age(self): return self._age @age.setter def age(self, age): if age &gt;= 0: self._age = age else: self._age = 0 </code></pre> <p>Suppose you can do it and still use <code>person.age = age</code>, why would you add private fields and getters and setters?</p> <p>(Also, see <a href="http://dirtsimple.org/2004/12/python-is-not-java.html" rel="noreferrer">Python is not Java</a> and <a href="http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html?page=1" rel="noreferrer">this article about the harms of using getters and setters</a>.).</p> <h1>Everything is visible anyway - and trying to hide complicates your work</h1> <p>Even in languages with private attributes, you can access them through some reflection/introspection library. And people do it a lot, in frameworks and for solving urgent needs. The problem is that introspection libraries are just a complicated way of doing what you could do with public attributes.</p> <p>Since Python is a very dynamic language, adding this burden to your classes is counterproductive.</p> <h1>The problem is not being possible to see - it is being <em>required</em> to see</h1> <p>For a Pythonista, encapsulation is not the inability to see the internals of classes but the possibility of avoiding looking at it. Encapsulation is the property of a component that the user can use without concerning about the internal details. If you can use a component without bothering yourself about its implementation, then it is encapsulated (in the opinion of a Python programmer).</p> <p>Now, if you wrote a class you can use it without thinking about implementation details, there is no problem if you <em>want</em> to look inside the class for some reason. The point is: your API should be good, and the rest is details.</p> <h1>Guido said so</h1> <p>Well, this is not controversial: <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=211430" rel="noreferrer">he said so, actually</a>. (Look for &quot;open kimono.&quot;)</p> <h1>This is culture</h1> <p>Yes, there are some reasons, but no critical reason. This is primarily a cultural aspect of programming in Python. Frankly, it could be the other way, too - but it is not. Also, you could just as easily ask the other way around: why do some languages use private attributes by default? For the same main reason as for the Python practice: because it is the culture of these languages, and each choice has advantages and disadvantages.</p> <p>Since there already is this culture, you are well-advised to follow it. Otherwise, you will get annoyed by Python programmers telling you to remove the <code>__</code> from your code when you ask a question in Stack Overflow :)</p>
7,402,801
"Cannot connect to iTunes Store" in-app purchases
<p>I am having problems testing my in-app purchases. I get back valid product identifiers, but upon purchase I receive the dreaded "Cannot connect to iTunes Store". Interesting thing is that restore purchases seems to work - iTunes login pops up.</p> <p>I have: - Checked that my in-app purchases are cleared for sale - Checked, rechecked my source code to be in sync with Apple's documentation - Added appropiate test users - app id does not contain wildcard - in-app purchases are linked to the app (app itself is in developer rejected state, purchases are in ready to submit) - waited - reinstalled app, cleaned solution, all the voodoo stuff</p>
13,666,186
17
2
null
2011-09-13 13:36:39.213 UTC
10
2020-08-24 10:03:28.31 UTC
2015-08-10 07:27:21.97 UTC
null
916,299
null
942,654
null
1
102
ios|cocoa-touch|in-app-purchase
64,038
<p>Make sure you have signed out of any production iTunes accounts on the device.</p> <p>I was getting this error on my test phone which was logged in with my actual iTunes account. You cannot test apps using your production iTunes account, hence the error. I just wish Apple provided a better error so as to avoid this guesswork...</p>
29,887,429
How can I programmatically force stop an Android app with Java?
<p>How can I force stop an app with Java? I'm trying to build a memory cleaner that can help clean out background processes.</p> <p>I know there is a way to kill the process of an app, but when you go to the running list, the app is still there even after you have killed it. And I have tried a lot of similar memory cleaning apps, only one of them can totally force stop apps but it has so many useless notifications - very annoying.</p> <p>P.S.: When you go to Settings -> Apps, you will see a list of apps. Click on one of these apps and you end up on the app's info. There is a button named <em>"force stop"</em>. By clicking on it, the app is killed. I want to perform that kind of action in my app. How can this be done?</p> <p><img src="https://i.stack.imgur.com/9MHDG.png" alt="force stop example"></p>
29,887,666
2
9
null
2015-04-27 04:51:03.83 UTC
10
2019-04-11 15:19:28.45 UTC
2019-04-11 15:16:56.66 UTC
null
6,782,707
null
4,817,254
null
1
11
java|android|process
28,726
<p>get the process ID of your application, and kill that process onDestroy() method</p> <pre><code>@Override public void onDestroy() { super.onDestroy(); int id= android.os.Process.myPid(); android.os.Process.killProcess(id); } </code></pre> <p>or </p> <pre><code>getActivity().finish(); System.exit(0); </code></pre> <p>and if you want to kill other apps from your activity, then this should work </p> <p>You can send the signal using:</p> <pre><code>Process.sendSignal(pid, Process.SIGNAL_KILL); </code></pre> <p>To completely kill the process, it's recommended to call:</p> <pre><code>ActivityManager.killBackgroundProcesses(packageNameToKill) </code></pre> <p>before sending the signal.</p> <p>Please, note that your app needs to own the KILL_BACKGROUND_PROCESSES permission. Thus, in the AndroidManifest.xml, you need to include:</p> <pre class="lang-xml prettyprint-override"><code>&lt;uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" /&gt; </code></pre>
43,329,654
Android Back Button on a Progressive Web Application closes de App
<p>Can a "pure" HTML5/Javascript (progressive) web application intercept the mobile device back button in order to avoid the App to exit?</p> <p>This question is similar to <a href="https://stackoverflow.com/questions/8602722/phonegap-android-back-button-close-app-with-back-button-on-homepage">this one</a> but I want to know if it is possible to achieve such behavior without depending on PhoneGap/Ionic or Cordova.</p>
49,719,812
5
1
null
2017-04-10 17:41:56.137 UTC
18
2021-03-18 19:48:29.747 UTC
2017-05-23 11:46:36.667 UTC
null
-1
null
1,260,910
null
1
30
android|html|service-worker|progressive-web-apps
21,465
<p>While the android back button cannot be directly hooked into from within a progressive web app context, there exists a history api which we can use to achieve your desired result.</p> <p>First up, when there's no browser history for the page that the user is on, pressing the back button immediately closes the app.<br> We can prevent this by adding a previous history state when the app is first opens:</p> <pre><code>window.addEventListener('load', function() { window.history.pushState({}, '') }) </code></pre> <p>The documentation for this function can be found on <a href="https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method" rel="noreferrer">mdn</a>:</p> <blockquote> <p>pushState() takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL[...] if it isn't specified, it's set to the document's current URL.</p> </blockquote> <p>So now the user has to press the back button twice. One press brings us back to the original history state, the next press closes the app.</p> <hr> <p>Part two is we hook into the window's <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate" rel="noreferrer">popstate</a> event which is fired whenever the browser navigates backwards or forwards in history via a user action (so not when we call history.pushState).</p> <blockquote> <p>A popstate event is dispatched to the window each time the active history entry changes between two history entries for the same document.</p> </blockquote> <p>So now we have:</p> <pre><code>window.addEventListener('load', function() { window.history.pushState({}, '') }) window.addEventListener('popstate', function() { window.history.pushState({}, '') }) </code></pre> <p>When the page is loaded, we immediately create a new history entry, and each time the user pressed 'back' to go to the first entry, we add the new entry back again!</p> <hr> <p>Of course this solution is only so simple for single-page apps with no routing. It will have to be adapted for applications that already use the history api to keep the current url in sync with where the user navigates.</p> <p>To do this, we will add an identifier to the history's state object. This will allow us to take advantage of the following aspect of the <code>popstate</code> event:</p> <blockquote> <p>If the activated history entry was created by a call to history.pushState(), [...] the popstate event's state property contains a copy of the history entry's state object.</p> </blockquote> <p>So now during our <code>popstate</code> handler we can distinguish between the history entry we are using to prevent the back-button-closes-app behaviour versus history entries used for routing within the app, and only re-push our preventative history entry when it specifically has been popped:</p> <pre><code>window.addEventListener('load', function() { window.history.pushState({ noBackExitsApp: true }, '') }) window.addEventListener('popstate', function(event) { if (event.state &amp;&amp; event.state.noBackExitsApp) { window.history.pushState({ noBackExitsApp: true }, '') } }) </code></pre> <hr> <p>The final observed behaviour is that when the back button is pressed, we either go back in the history of our progressive web app's router, or we remain on the first page seen when the app was opened.</p>
43,360,852
Cannot parse String in ISO 8601 format, lacking colon in offset, to Java 8 Date
<p>I'm a little bit frustrated of java 8 date format/parse functionality. I was trying to find Jackson configuration and <code>DateTimeFormatter</code> to parse <code>"2018-02-13T10:20:12.120+0000"</code> string to any Java 8 date, and didn't find it.<br> This is <code>java.util.Date</code> example which works fine:</p> <pre><code>Date date = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZZZ") .parse("2018-02-13T10:20:12.120+0000"); </code></pre> <p>The same format doesn't work with new date time api</p> <pre><code>ZonedDateTime dateTime = ZonedDateTime.parse("2018-02-13T10:20:12.120+0000", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm:ss.SSSZZZ")); </code></pre> <p>We should be able to format/parse date in any format suitable for FE UI application. Maybe I misunderstand or mistake something, but I think <code>java.util.Date</code> gives more format flexibility and easier to use.</p>
43,361,405
3
1
null
2017-04-12 05:18:41.533 UTC
9
2020-09-08 05:50:08.61 UTC
2018-02-03 04:59:43.48 UTC
null
642,706
null
7,854,401
null
1
25
java|parsing|datetime|java-8|iso8601
7,161
<h1>tl;dr</h1> <p>Until bug is fixed:</p> <pre><code>OffsetDateTime.parse( "2018-02-13T10:20:12.120+0000" , DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSX" ) ) </code></pre> <p>When bug is fixed:</p> <pre><code>OffsetDateTime.parse( "2018-02-13T10:20:12.120+0000" ) </code></pre> <h1>Details</h1> <p>You are using the wrong classes.</p> <p>Avoid the troublesome old legacy classes such as <code>Date</code>, <code>Calendar</code>, and <code>SimpleDateFormat</code>. Now supplanted by the <a href="http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="noreferrer">java.time</a> classes.</p> <p>The <a href="https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html" rel="noreferrer"><code>ZonedDateTime</code></a> class you used is good, it is part of java.time. But it is intended for a full time zone. Your input string has merely an <a href="https://en.wikipedia.org/wiki/UTC_offset" rel="noreferrer">offset-from-UTC</a>. A full time zone, in contrast, is a collection of offsets in effect for a region at different points in time, past, present, and future. For example, with Daylight Saving Time (DST) in most of North America, the offsets change twice a year growing smaller in the Spring as we shift clocks forward an hour, and restoring to a longer value in the Autumn when we shift clocks back an hour.</p> <h2><code>OffsetDateTime</code></h2> <p>For only an offset rather than a time zone, use the <a href="https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html" rel="noreferrer"><code>OffsetDateTime</code></a> class.</p> <p>Your input string complies with the <a href="https://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a> standard. The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.</p> <pre><code>OffsetDateTime odt = OffsetDateTime.parse( "2018-02-13T10:20:12.120+0000" ); </code></pre> <p>Well, that <em>should</em> have worked. Unfortunately, there is a <strong>bug in Java 8</strong> (at least up through Java 8 Update 121) where that class fails to parse an offset omitting the colon between hours and minutes. So the bug bites on <code>+0000</code> but not <code>+00:00</code>. So until a fix arrives, you have a choice of two workarounds: (a) a hack, manipulating the input string, or (b) define an explicit formatting pattern. </p> <p>The hack: Manipulate the input string to insert the colon. </p> <pre><code>String input = "2018-02-13T10:20:12.120+0000".replace( "+0000" , "+00:00" ); OffsetDateTime odt = OffsetDateTime.parse( input ); </code></pre> <h3><code>DateTimeFormatter</code></h3> <p>The more robust workaround is to define and pass a formatting pattern in a <code>DateTimeFormatter</code> object.</p> <pre><code>String input = "2018-02-13T10:20:12.120+0000" ; DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSX" ); OffsetDateTime odt = OffsetDateTime.parse( input , f ); </code></pre> <blockquote> <p>odt.toString(): 2018-02-13T10:20:12.120Z</p> </blockquote> <p>By the way, here is a tip: I have found that with many protocols and libraries, your life is easier if your offsets always have the colon, always have both hours and minutes (even if minutes are zero), and always use a padding zero (<code>-05:00</code> rather than <code>-5</code>).</p> <h3><code>DateTimeFormatterBuilder</code></h3> <p>For a more flexible formatter, created via <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatterBuilder.html" rel="noreferrer"><code>DateTimeFormatterBuilder</code></a>, see <a href="https://stackoverflow.com/a/46488425/642706">this excellent Answer</a> on a duplicate Question.</p> <h2><code>Instant</code></h2> <p>If you want to work with values that are always in UTC (and you should), extract an <code>Instant</code> object.</p> <pre><code>Instant instant = odt.toInstant(); </code></pre> <h2><code>ZonedDateTime</code></h2> <p>If you want to view that moment through the lens of some region’s <a href="https://en.wikipedia.org/wiki/Wall_clock_time" rel="noreferrer">wall-clock time</a>, apply a time zone.</p> <pre><code>ZoneId z = ZoneId.of( "America/Montreal" ); ZonedDateTime zdt = odt.atZoneSameInstant( z ); </code></pre> <p>See this <a href="http://ideone.com/CSYGHW" rel="noreferrer">code run live at IdeOne.com</a>.</p> <p>All of this has been covered many times in many Answers for many Questions. Please search Stack Overflow thoroughly before posting. You would have discovered many dozens, if not hundreds, of examples.</p> <hr> <h1>About <em>java.time</em></h1> <p>The <a href="http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html" rel="noreferrer"><em>java.time</em></a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href="https://en.wikipedia.org/wiki/Legacy_system" rel="noreferrer">legacy</a> date-time classes such as <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Date.html" rel="noreferrer"><code>java.util.Date</code></a>, <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html" rel="noreferrer"><code>Calendar</code></a>, &amp; <a href="http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer"><code>SimpleDateFormat</code></a>.</p> <p>The <a href="http://www.joda.org/joda-time/" rel="noreferrer"><em>Joda-Time</em></a> project, now in <a href="https://en.wikipedia.org/wiki/Maintenance_mode" rel="noreferrer">maintenance mode</a>, advises migration to the <a href="http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html" rel="noreferrer">java.time</a> classes.</p> <p>To learn more, see the <a href="http://docs.oracle.com/javase/tutorial/datetime/TOC.html" rel="noreferrer"><em>Oracle Tutorial</em></a>. And search Stack Overflow for many examples and explanations. Specification is <a href="https://jcp.org/en/jsr/detail?id=310" rel="noreferrer">JSR 310</a>.</p> <p>You may exchange <em>java.time</em> objects directly with your database. Use a <a href="https://en.wikipedia.org/wiki/JDBC_driver" rel="noreferrer">JDBC driver</a> compliant with <a href="http://openjdk.java.net/jeps/170" rel="noreferrer">JDBC 4.2</a> or later. No need for strings, no need for <code>java.sql.*</code> classes.</p> <p>Where to obtain the java.time classes? </p> <ul> <li><a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8" rel="noreferrer"><strong>Java SE 8</strong></a>, <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9" rel="noreferrer"><strong>Java SE 9</strong></a>, <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10" rel="noreferrer"><strong>Java SE 10</strong></a>, and later <ul> <li>Built-in. </li> <li>Part of the standard Java API with a bundled implementation.</li> <li>Java 9 adds some minor features and fixes.</li> </ul></li> <li><a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6" rel="noreferrer"><strong>Java SE 6</strong></a> and <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7" rel="noreferrer"><strong>Java SE 7</strong></a> <ul> <li>Much of the java.time functionality is back-ported to Java 6 &amp; 7 in <a href="http://www.threeten.org/threetenbp/" rel="noreferrer"><strong><em>ThreeTen-Backport</em></strong></a>.</li> </ul></li> <li><a href="https://en.wikipedia.org/wiki/Android_(operating_system)" rel="noreferrer"><strong>Android</strong></a> <ul> <li>Later versions of Android bundle implementations of the <em>java.time</em> classes.</li> <li>For earlier Android (&lt;26), the <a href="https://github.com/JakeWharton/ThreeTenABP" rel="noreferrer"><strong><em>ThreeTenABP</em></strong></a> project adapts <a href="http://www.threeten.org/threetenbp/" rel="noreferrer"><strong><em>ThreeTen-Backport</em></strong></a> (mentioned above). See <a href="http://stackoverflow.com/q/38922754/642706"><em>How to use ThreeTenABP…</em></a>.</li> </ul></li> </ul> <p>The <a href="http://www.threeten.org/threeten-extra/" rel="noreferrer"><strong>ThreeTen-Extra</strong></a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html" rel="noreferrer"><code>Interval</code></a>, <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html" rel="noreferrer"><code>YearWeek</code></a>, <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html" rel="noreferrer"><code>YearQuarter</code></a>, and <a href="http://www.threeten.org/threeten-extra/apidocs/index.html" rel="noreferrer">more</a>.</p>
43,122,113
Sizing elements to percentage of screen width/height
<p>Is there a simple (non-LayoutBuilder) way to size an element relative to screen size (width/height)? For example: how do I set the width of a CardView to be 65% of the screen width.</p> <p>It can't be done inside the <code>build</code> method (obviously) so it would have to be deferred until post build. Is there a preferred place to put logic like this?</p>
43,130,622
14
2
null
2017-03-30 15:26:13.63 UTC
79
2022-07-22 13:15:23.383 UTC
2021-12-26 09:41:49.583 UTC
user10563627
null
null
353,463
null
1
303
flutter|dart|flutter-layout|screen-size
296,567
<p><code>FractionallySizedBox</code> may also be useful. You can also read the screen width directly out of <code>MediaQuery.of(context).size</code> and create a sized box based on that</p> <pre><code>MediaQuery.of(context).size.width * 0.65 </code></pre> <p>if you really want to size as a fraction of the screen regardless of what the layout is.</p>
9,220,432
HTTP 401 Unauthorized or 403 Forbidden for a "disabled" user?
<p>An authentication service allows user accounts be disabled (a sort of soft-delete).</p> <p>If the server then receives an authentication request for a disabled user that would otherwise be valid, should the server return 401 or 403? With either status code, I would return a message indicating that the account had been disabled.</p> <p>For quick reference, relevant quotes from <a href="https://www.rfc-editor.org/rfc/rfc2616#page-66" rel="nofollow noreferrer">HTTP/1.1 spec</a> (emphasis mine):</p> <p><strong>401 Unauthorized</strong></p> <blockquote> <p>The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. <strong>The client MAY repeat the request</strong> with a suitable Authorization header field (section 14.8). <strong>If the request already included Authorization credentials</strong>, then the 401 response indicates that <strong>authorization has been refused for those credentials</strong>. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the <strong>user SHOULD be presented the entity that was given in the response</strong>, since that entity might include relevant diagnostic information. HTTP access authentication is explained in &quot;HTTP Authentication: Basic and Digest Access Authentication&quot; [43].</p> </blockquote> <p><strong>403 Forbidden</strong></p> <blockquote> <p>The server understood the request, but is refusing to fulfill it. <strong>Authorization will not help</strong> and the <strong>request SHOULD NOT be repeated</strong>. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it <strong>SHOULD describe the reason for the refusal in the entity</strong>. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.</p> </blockquote>
9,281,494
3
1
null
2012-02-09 23:14:38.73 UTC
10
2019-11-20 22:58:06.557 UTC
2021-10-07 05:46:31.917 UTC
null
-1
null
176,741
null
1
28
http|rest|restful-authentication
64,800
<p>Based on <a href="http://lists.w3.org/Archives/Public/ietf-http-wg/2010JulSep/0085.html" rel="noreferrer">an email</a> written by <a href="http://roy.gbiv.com/" rel="noreferrer">Roy T. Fielding</a>, there's apparently <a href="http://trac.tools.ietf.org/wg/httpbis/trac/ticket/294" rel="noreferrer">a bug</a> in the current HTTP spec.</p> <p>The way the spec is <em>intended</em> to be read is as follows (using quotes from above email):</p> <p><strong>401 "Unauthenticated"</strong>:</p> <blockquote> <p>you can't do this because you haven't authenticated</p> </blockquote> <p><strong>403 "Unauthorized"</strong>:</p> <blockquote> <p>user agent sent valid credentials but doesn't have access</p> </blockquote> <p>So, in the case of a disabled user, 403 is the correct response (and 404 is also an option).</p>
9,623,258
Passing an Array or List to @Pathvariable - Spring/Java
<p>I am doing a simple 'get' in JBoss/Spring. I want the client to pass me an array of integers in the url. How do I set that up on the server? And show should the client send the message? </p> <p>This is what I have right now. </p> <pre><code>@RequestMapping(value="/test/{firstNameIds}", method=RequestMethod.GET) @ResponseBody public String test(@PathVariable List&lt;Integer&gt; firstNameIds) { //What do I do?? return "Dummy"; } </code></pre> <p>On the client I would like to pass something like </p> <pre> http://localhost:8080/public/test/[1,3,4,50] </pre> <p>When I did that I get an error:</p> <blockquote> <p>java.lang.IllegalStateException: Could not find @PathVariable [firstNameIds] in @RequestMapping</p> </blockquote>
22,298,768
5
1
null
2012-03-08 18:58:16.813 UTC
19
2020-05-10 05:33:35.42 UTC
2012-03-08 21:47:52.36 UTC
null
21,234
null
805,082
null
1
71
java|spring-mvc|path-variables
105,564
<pre><code>GET http://localhost:8080/public/test/1,2,3,4 @RequestMapping(value="/test/{firstNameIds}", method=RequestMethod.GET) @ResponseBody public String test(@PathVariable String[] firstNameIds) { // firstNameIds: [1,2,3,4] return "Dummy"; } </code></pre> <p>(tested with Spring MVC 4.0.1)</p>
45,723,819
What is a "span" and when should I use one?
<p>Recently I've gotten suggestions to use <code>span&lt;T&gt;</code>'s in my code, or have seen some answers here on the site which use <code>span</code>'s - supposedly some kind of container. But - I can't find anything like that in the C++17 standard library. </p> <p>So what is this mysterious <code>span&lt;T&gt;</code>, and why (or when) is it a good idea to use it if it's non-standard?</p>
45,723,820
3
5
null
2017-08-16 22:15:05.487 UTC
102
2022-09-10 16:31:52.07 UTC
2020-04-09 12:19:48.257 UTC
null
1,593,077
null
1,593,077
null
1
367
c++|c++20|c++-faq|cpp-core-guidelines|std-span
120,516
<h2>What is it?</h2> <p>A <code>span&lt;T&gt;</code> is:</p> <ul> <li>A very lightweight abstraction of a contiguous sequence of values of type <code>T</code> somewhere in memory.</li> <li>Basically a <code>struct { T * ptr; std::size_t length; }</code> with a bunch of convenience methods.</li> <li>A non-owning type (i.e. a <a href="https://stackoverflow.com/questions/24827592/what-is-definition-of-reference-type">&quot;reference-type&quot;</a> rather than a &quot;value type&quot;): It never allocates nor deallocates anything and does not keep smart pointers alive.</li> </ul> <p>It was formerly known as an <a href="https://stackoverflow.com/q/34832090/1593077"><code>array_view</code></a> and even earlier as <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3334.html" rel="noreferrer"><code>array_ref</code></a>.</p> <h2>When should I use it?</h2> <p>First, when <em>not</em> to use spans:</p> <ul> <li>Don't use a span in code that could just take any pair of start &amp; end iterators (like <code>std::sort</code>, <code>std::find_if</code>, <code>std::copy</code> and other templated functions from <code>&lt;algorithm&gt;</code>), and also not in code that takes an arbitrary range (see <a href="https://en.cppreference.com/w/cpp/ranges" rel="noreferrer">The C++20 ranges library for information</a> about those). A span has stricter requirements than a pair of iterators or a range: element contiguity and presence of the elements in memory.</li> <li>Don't use a span if you have a standard library container (or a Boost container etc.) which you know is the right fit for your code. spans are not intended to supplant existing containers.</li> </ul> <p>Now for when to actually use a span:</p> <blockquote> <p>Use <code>span&lt;T&gt;</code> (respectively, <code>span&lt;const T&gt;</code>) instead of a free-standing <code>T*</code> (respectively <code>const T*</code>) when the allocated length or size also matter. So, replace functions like:</p> <pre><code>void read_into(int* buffer, size_t buffer_size); </code></pre> <p>with:</p> <pre><code>void read_into(span&lt;int&gt; buffer); </code></pre> </blockquote> <h2>Why should I use it? Why is it a good thing?</h2> <p>Oh, spans are awesome! Using a span...</p> <ul> <li><p>means that you can work with that pointer+length / start+end pointer combination like you would with a fancy, pimped-out standard library container, e.g.:</p> <ul> <li><code>for (auto&amp; x : my_span) { /* do stuff */ }</code></li> <li><code>std::find_if(my_span.cbegin(), my_span.cend(), some_predicate);</code></li> <li><code>std::ranges::find_if(my_span, some_predicate);</code> (in C++20) <br> <br></li> </ul> <p>... but with absolutely none of the overhead most container classes incur.</p> </li> <li><p>lets the compiler do more work for you sometimes. For example, this:</p> <pre><code>int buffer[BUFFER_SIZE]; read_into(buffer, BUFFER_SIZE); </code></pre> <p>becomes this:</p> <pre><code>int buffer[BUFFER_SIZE]; read_into(buffer); </code></pre> <p>... which will do what you would want it to do. See also <a href="https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#p5-prefer-compile-time-checking-to-run-time-checking" rel="noreferrer">Guideline P.5</a>.</p> </li> <li><p>is the reasonable alternative to passing <code>const vector&lt;T&gt;&amp;</code> to functions when you expect your data to be contiguous in memory. No more getting scolded by high-and-mighty C++ gurus!</p> </li> <li><p>facilitates static analysis, so the compiler might be able to help you catch silly bugs.</p> </li> <li><p>allows for debug-compilation instrumentation for runtime bounds-checking (i.e. <code>span</code>'s methods will have some bounds-checking code within <code>#ifndef NDEBUG</code> ... <code>#endif</code>)</p> </li> <li><p>indicates that your code (that's using the span) doesn't own the pointed-to memory.</p> </li> </ul> <p>There's even more motivation for using <code>span</code>s, which you could find in the <a href="https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md" rel="noreferrer">C++ core guidelines</a> - but you catch the drift.</p> <h2>But is it in the standard library?</h2> <p><strong>edit:</strong> Yes, <a href="https://en.cppreference.com/w/cpp/container/span" rel="noreferrer"><code>std::span</code></a> was added to C++ with the C++20 version of the language!</p> <p>Why only in C++20? Well, While the idea is not new - its current form was conceived in conjunction with the <a href="https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md" rel="noreferrer">C++ core guidelines</a> project, which only started taking shape in 2015. So it took a while.</p> <h2>So how do I use it if I'm writing C++17 or earlier?</h2> <p>It's part of the <a href="https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#p3-express-intent" rel="noreferrer">Core Guidelines</a>'s Support Library (GSL). Implementations:</p> <ul> <li>Microsoft / Neil Macintosh's <a href="https://github.com/Microsoft/GSL" rel="noreferrer">GSL</a> contains a standalone implementation: <a href="https://github.com/Microsoft/GSL/blob/master/include/gsl/span" rel="noreferrer"><code>gsl/span</code></a></li> <li><a href="https://github.com/martinmoene/gsl-lite" rel="noreferrer">GSL-Lite</a> is a single-header implementation of the whole GSL (it's not that big, don't worry), including <code>span&lt;T&gt;</code>.</li> </ul> <p>The GSL implementation does generally assume a platform that implements C++14 support [<a href="https://github.com/microsoft/GSL/blob/7d78b743e43ecba06ca47426d03d9d16076dec16/README.md#L9" rel="noreferrer">12</a>]. These alternative single-header implementations do not depend on GSL facilities:</p> <ul> <li><a href="https://github.com/martinmoene/span-lite" rel="noreferrer"><code>martinmoene/span-lite</code></a> requires C++98 or later</li> <li><a href="https://github.com/tcbrindle/span" rel="noreferrer"><code>tcbrindle/span</code></a> requires C++11 or later</li> </ul> <p>Note that these different span implementations have some differences in what methods/support functions they come with; and they may also differ somewhat from the version adopted into the standard library in C++20.</p> <hr /> <p><strong>Further reading:</strong> You can find all the details and design considerations in the final official proposal before C++17, P0122R7: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0122r7.pdf" rel="noreferrer">span: bounds-safe views for sequences of objects</a> by Neal Macintosh and Stephan J. Lavavej. It's a bit long though. Also, in C++20, the span comparison semantics changed (following <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1085r2.md" rel="noreferrer">this short paper</a> by Tony van Eerd).</p>
19,314,228
Find Positions of a Character in a String
<p>How can I find a character in a <code>String</code> and print the position of character all over the string? For example, I want to find positions of <code>'o'</code> in this string : <code>"you are awesome honey"</code> and get the answer = <code>1 12 17</code>.</p> <p>I wrote this, but it doesn't work : </p> <pre><code>public class Pos { public static void main(String args[]){ String string = ("You are awesome honey"); for (int i = 0 ; i&lt;string.length() ; i++) if (string.charAt(i) == 'o') System.out.println(string.indexOf(i)); } } </code></pre>
19,314,980
5
2
null
2013-10-11 09:02:46.1 UTC
0
2017-02-14 19:00:30.52 UTC
2016-11-06 11:47:47.847 UTC
null
3,885,376
null
2,870,273
null
1
8
java|string|character|indices
63,042
<p>You were almost right. The issue is your last line. You should print <code>i</code> instead of <code>string.indexOf(i)</code>:</p> <pre><code>public class Pos{ public static void main(String args[]){ String string = ("You are awesome honey"); for (int i = 0 ; i&lt;string.length() ; i++) if (string.charAt(i) == 'o') System.out.println(i); } } </code></pre>
19,719,767
override class variable in python?
<p>Below, <code>base_id</code> and <code>_id</code> is a class variable and shared among all child classes.<br> Is there a way to separate them into each class?</p> <pre><code>from itertools import count class Parent(object): base_id = 0 _id = count(0) def __init__(self): self.id = self.base_id + self._id.next() class Child1(Parent): base_id = 100 def __init__(self): Parent.__init__(self) print 'Child1:', self.id class Child2(Parent): base_id = 200 def __init__(self): Parent.__init__(self) print 'Child2:', self.id c1 = Child1() # 100 c2 = Child2() # 201 &lt;- want this to be 200 c1 = Child1() # 102 &lt;- want this to be 101 c2 = Child2() # 203 &lt;- want this to be 201 </code></pre>
19,719,831
3
2
null
2013-11-01 02:09:40.143 UTC
2
2013-11-01 03:37:22.903 UTC
2013-11-01 02:14:41.623 UTC
null
2,225,682
null
433,570
null
1
15
python|class
44,456
<p>If you don't want to violate the DRY principle like falsetru suggests, you'll need to use metaclasses. I was thinking of writing something up, but <a href="https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">there's already a good long description of metaclasses on SO</a>, so check it out.</p> <p>Metaclasses, in short, let you control subclass creation.</p> <p>Basically, what you need to do is, upon the creation of a subclass of <code>Parent</code>, add the <code>_id</code> member to the newly-created subclass.</p>
19,446,544
Post request to include 'Content-Type' and JSON
<p>I'm to work with goo.gl for URL shortening. I need to make the following request: </p> <pre><code>POST https://www.googleapis.com/urlshortener/v1/url Content-Type: application/json {"longUrl": "http://www.google.com/"} </code></pre> <p>my html:-</p> <pre><code>&lt;form method="post" action="https://www.googleapis.com/urlshortener/v1/"&gt; &lt;button type="submit"&gt; submit &lt;/button&gt; &lt;/form&gt; </code></pre> <p>how do i add the 'content-type' and json here? </p>
19,446,993
4
3
null
2013-10-18 09:46:45.52 UTC
8
2020-10-27 05:44:26.957 UTC
null
null
null
null
2,596,724
null
1
19
html|http|post
59,765
<p>Browsers do not support JSON as a media type for form submissions (the supported types are <a href="https://www.w3.org/TR/html5/sec-forms.html#element-attrdef-form-enctype" rel="noreferrer">listed in the spec</a>).</p> <p>The only way to make such a request from a web page is to use the XMLHttpRequest object.</p> <p>Google provide <a href="https://code.google.com/p/google-api-javascript-client/" rel="noreferrer">a JavaScript library</a> (which wraps XMLHttpRequest) that can interact with their <a href="https://developers.google.com/url-shortener/v1/getting_started?csw=1" rel="noreferrer">URL Shortener API</a>.</p>
432,637
Materials for SICP with python?
<p>I want to try out SICP with Python.</p> <p>Can any one point to materials (video.article...) that teaches Structure and Interpretation of Computer Programs in <strong>python</strong>.</p> <p>Currently learning from SICP videos of Abelson, Sussman, and Sussman.</p>
433,688
5
1
null
2009-01-11 09:13:48.41 UTC
11
2018-11-14 11:59:07.45 UTC
2011-12-09 15:20:13.9 UTC
null
3,043
rajKumar
22,076
null
1
6
python|sicp
12,062
<p>Don't think there is a complete set of materials, <a href="http://www.codepoetics.com/wiki/index.php?title=Topics:SICP_in_other_languages" rel="noreferrer">this</a> is the best I know.</p> <p>If you are up to generating the material yourself, a bunch of us plan to work through SICP collectively <a href="http://hn-sicp.pbwiki.com/" rel="noreferrer">at</a>. I know at least one guy will be using Haskell, so you will not be alone in pursuing an alternative route.</p>
233,411
How do I enable a second monitor in C#?
<p>Is it possible to enable a second monitor programatically and extend the Windows Desktop onto it in C#? It needs to do the equivalent of turning on the checkbox in the image below.</p> <p><img src="https://i.stack.imgur.com/ss2sE.png" alt="alt text"></p>
233,826
5
0
null
2008-10-24 12:55:47.603 UTC
16
2019-02-14 20:40:30.677 UTC
2019-02-14 20:40:30.677 UTC
whatknott
4,751,173
matt
4,500
null
1
21
c#|winforms|desktop|multiple-monitors
22,631
<p><a href="http://msdn.microsoft.com/en-us/library/ms533259.aspx" rel="noreferrer">MSDN Device Context Functions</a></p> <p>What you basically need to do:</p> <blockquote> <p>Use the EnumDisplayDevices() API call to enumerate the display devices on the system and look for those that don't have the <code>DISPLAY_DEVICE_ATTACHED_TO_DESKTOP</code> flag set (this will include any mirroring devices so not all will be physical displays.) Once you've found the display device you'll need to get a valid display mode to change it to, you can find this by calling the EnumDisplaySettingsEx() API call - Generally you'd display all the available modes and allow the user to choose however in your case it sounds like this may be possible to hard-code and save you an additional step. For the sake of future-proofing your application though I'd suggest having this easily changeable without having to dig through the source every time, a registry key would be the obvious choice. Once you've got that sorted out populate a DevMode display structure with the information about the display positioning (set the PelsWidth/Height, Position, DisplayFrequency and BitsPerPel properties) then set these flags in the fields member. Finally call ChangeDisplaySettingsEx() with this settings structure and be sure to send the reset and update registry flags. That should be all you need, hope this helps,</p> </blockquote> <p><a href="http://www.pinvoke.net/default.aspx/Structures/DISPLAY_DEVICE.html" rel="noreferrer">DISPLAY_DEVICE</a> structure import using PInvoke</p> <p><a href="http://www.pinvoke.net/default.aspx/user32/EnumDisplayDevices.html" rel="noreferrer">EnumDisplayDevices</a> function import</p> <p><a href="http://www.pinvoke.net/default.aspx/user32/EnumDisplaySettingsEx.html" rel="noreferrer">EnumDisplaySettingsEx</a> function import</p> <p>etc. the rest of them functions can be found with a simple search by name.</p>