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
20,398,799
Find K nearest Points to Point P in 2-dimensional plane
<p><em><strong>Source: AMAZON INTERVIEW QUESTION</em></strong></p> <p>Given a <strong>point P and other N points</strong> in two dimensional space, find <strong>K points</strong> out of the N points which are <strong>nearest</strong> to P.</p> <p>What is the most optimal way to do this ?</p> <p>This <a href="http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm">Wiki</a> page does not provide much of help in building a algorithm.Any ideas/approaches people.</p>
20,399,027
9
4
null
2013-12-05 11:28:25.327 UTC
13
2021-01-26 15:48:33.593 UTC
2013-12-05 11:34:03.46 UTC
null
2,426,101
null
2,426,101
null
1
26
performance|algorithm|math|language-agnostic
35,335
<p><strong>Solution 1</strong> make heap of size K and collect points by minimal distance <strong>O(NLogK)</strong> complexity.</p> <p><strong>Solution 2</strong>: Take and array of size N and Sort by distance. Should be used QuickSort (Hoare modification). As answer take first K points. This is too NlogN complexity but it is possible optimize to approximate O(N). If skip sorting of unnecessary sub arrays. When you split array by 2 sub arrays you should take only array where Kth index located. complexity will be : N +N/2 +N/4 + ... = <strong>O(N)</strong>.</p> <p><strong>Solution 3</strong>: search Kth element in result array and takes all point lesser then founded. Exists <strong>O(N)</strong> alghoritm, similar to search of median.</p> <p><strong>Notes</strong>: better use sqr of distance to avoid of sqrt operations, it will be greater faster if point has integer coordinates.</p> <p>As interview answer better use Solution 2 or 3.</p>
20,540,831
Java object analogue to R data.frame
<p>I really like data.frames in R because you can store different types of data in one data structure and you have a lot of different methods to modify the data (add column, combine data.frames,...), it is really easy to extract a <em>subset</em> from the data,...</p> <p>Is there any Java library available which have the same functionality? I'm mostly interested in storing different types of data in a matrix-like fashion and be able to extract a subset of the data. </p> <p>Using a two-dimensional array in Java can provide a similar structure, but it is much more difficult to add a column and afterwards extract the top k records.</p>
32,481,425
6
6
null
2013-12-12 10:24:08.303 UTC
11
2018-08-16 00:45:10.98 UTC
null
null
null
null
1,054,451
null
1
46
java|r|dataframe
26,456
<p>I have just open-sourced a first draft version of <a href="https://github.com/netzwerg/paleo" rel="noreferrer">Paleo</a>, a Java 8 library which offers data frames based on typed columns (including support for primitive values). Columns can be created programmatically (through a simple builder API), or imported from text file.</p> <p>Please refer to the <a href="https://github.com/netzwerg/paleo/blob/master/README.adoc" rel="noreferrer">README</a> for further details.</p> <p>The project is still wet from birth – I am very interested in feedback / PRs, tia!</p>
20,886,911
PHP: self:: vs parent:: with extends
<p>I'm wondering what is the difference between using self:: and parent:: when a static child class is extending static parent class e.g.</p> <pre><code>class Parent { public static function foo() { echo 'foo'; } } class Child extends Parent { public static function func() { self::foo(); } public static function func2() { parent::foo(); } } </code></pre> <p>Is there any difference between func() and func2() and if so then what is it ? </p> <p>Thank you</p> <p>Regards</p>
20,887,205
2
6
null
2014-01-02 16:11:42.023 UTC
13
2014-01-02 17:04:38.99 UTC
null
null
null
null
1,509,200
null
1
26
php|class|static|parent|self
25,990
<pre><code> Child has foo() Parent has foo() self::foo() YES YES Child foo() is executed parent::foo() YES YES Parent foo() is executed self::foo() YES NO Child foo() is executed parent::foo() YES NO ERROR self::foo() NO YES Parent foo() is executed parent::foo() NO YES Parent foo() is executed self::foo() NO NO ERROR parent::foo() NO NO ERROR </code></pre> <p>If you are looking for the correct cases for their use. <code>parent</code> allows access to the inherited class, whereas <code>self</code> is a reference to the class the method running (static or otherwise) belongs to.</p> <p>A popular use of the <code>self</code> keyword is when using the Singleton pattern in PHP, <code>self</code> doesn't honour child classes, whereas <code>static</code> does <a href="https://stackoverflow.com/questions/5197300/new-self-vs-new-static">New self vs. new static</a></p> <p><code>parent</code> provides the ability to access the inherited class methods, often useful if you need to retain some default functionality.</p>
10,995,972
Get validation error messages without saving
<pre><code>Post :belongs_to :user User :has_many :posts </code></pre> <p>In my signup workflow they draft a Post first, then on the next page enter their User information to signup.</p> <pre><code># intermediate step, validate that Post is valid before moving on to User creation # posts_controller: @post = Post.new(params[:post]) if @post.valid? # go on to create User else render 'new' end </code></pre> <p>BUT! @post error messages aren't created since I'm not saving the @post model I'm just checking for <code>.valid?</code>. How do I create the error messages without saving?</p>
10,996,090
2
0
null
2012-06-12 11:44:59.813 UTC
3
2012-06-12 11:51:46.613 UTC
null
null
null
null
811,111
null
1
32
ruby-on-rails|ruby-on-rails-3
24,283
<p>If I understand your question correctly you want to get the errors without saving the model?</p> <p>That is exactly what is happening. <code>@post.valid?</code></p> <p>will return true or false depending on whether there are any errors. If there are errors. they will be added to <code>@post.errors</code>hash. </p> <p>In the situation where you want to save just call <code>@post.save</code> It will return true if successfully saved or false if errors are present while populating <code>@post.errors</code> in the process</p>
10,987,444
How to use global variable in node.js?
<p>For example I want to use custom logger:</p> <pre><code>logger = require('basic-logger'), logger.setLevel('info') var customConfig = { showMillis: true, showTimestamp: true } var log = new logger(customConfig) </code></pre> <p>How to use this logger in other modules instead of console.log ?</p>
10,987,543
7
4
null
2012-06-11 20:59:17.603 UTC
18
2019-07-09 12:09:56.933 UTC
2012-06-11 21:16:06.427 UTC
null
1,407,156
null
418,507
null
1
101
node.js
264,890
<p>Most people advise against using global variables. If you want the same logger class in different modules you can do this</p> <p>logger.js</p> <pre><code> module.exports = new logger(customConfig); </code></pre> <p>foobar.js</p> <pre><code> var logger = require('./logger'); logger('barfoo'); </code></pre> <p>If you do want a global variable you can do:</p> <pre><code>global.logger = new logger(customConfig); </code></pre>
48,201,729
Difference between np.dot and np.multiply with np.sum in binary cross-entropy loss calculation
<p>I have tried the following code but didn't find the difference between <strong>np.dot</strong> and <strong>np.multiply with np.sum</strong> </p> <p>Here is <strong>np.dot</strong> code</p> <pre><code>logprobs = np.dot(Y, (np.log(A2)).T) + np.dot((1.0-Y),(np.log(1 - A2)).T) print(logprobs.shape) print(logprobs) cost = (-1/m) * logprobs print(cost.shape) print(type(cost)) print(cost) </code></pre> <p>Its output is </p> <pre><code>(1, 1) [[-2.07917628]] (1, 1) &lt;class 'numpy.ndarray'&gt; [[ 0.693058761039 ]] </code></pre> <p>Here is the code for <strong>np.multiply with np.sum</strong></p> <pre><code>logprobs = np.sum(np.multiply(np.log(A2), Y) + np.multiply((1 - Y), np.log(1 - A2))) print(logprobs.shape) print(logprobs) cost = - logprobs / m print(cost.shape) print(type(cost)) print(cost) </code></pre> <p>Its output is </p> <pre><code>() -2.07917628312 () &lt;class 'numpy.float64'&gt; 0.693058761039 </code></pre> <p>I'm unable to understand the type and shape difference whereas the result value is same in both cases </p> <p>Even in the case of squeezing former code <strong>cost value become same as later but type remains same</strong></p> <pre><code>cost = np.squeeze(cost) print(type(cost)) print(cost) </code></pre> <p>output is </p> <pre><code>&lt;class 'numpy.ndarray'&gt; 0.6930587610394646 </code></pre>
48,202,241
4
7
null
2018-01-11 07:21:47.19 UTC
19
2021-02-22 09:35:59.09 UTC
2019-05-08 18:41:35.553 UTC
null
2,956,066
null
4,539,906
null
1
34
python|numpy|neural-network|sum|difference
55,812
<p>What you're doing is calculating the <a href="https://en.wikipedia.org/wiki/Cross_entropy#Cross-entropy_loss_function_and_logistic_regression" rel="nofollow noreferrer"><strong>binary cross-entropy loss</strong></a> which measures how bad the predictions (here: <code>A2</code>) of the model are when compared to the true outputs (here: <code>Y</code>).</p> <p>Here is a reproducible example for your case, which should explain why you get a scalar in the second case using <code>np.sum</code></p> <pre><code>In [88]: Y = np.array([[1, 0, 1, 1, 0, 1, 0, 0]]) In [89]: A2 = np.array([[0.8, 0.2, 0.95, 0.92, 0.01, 0.93, 0.1, 0.02]]) In [90]: logprobs = np.dot(Y, (np.log(A2)).T) + np.dot((1.0-Y),(np.log(1 - A2)).T) # `np.dot` returns 2D array since its arguments are 2D arrays In [91]: logprobs Out[91]: array([[-0.78914626]]) In [92]: cost = (-1/m) * logprobs In [93]: cost Out[93]: array([[ 0.09864328]]) In [94]: logprobs = np.sum(np.multiply(np.log(A2), Y) + np.multiply((1 - Y), np.log(1 - A2))) # np.sum returns scalar since it sums everything in the 2D array In [95]: logprobs Out[95]: -0.78914625761870361 </code></pre> <p>Note that the <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.dot.html" rel="nofollow noreferrer"><code>np.dot</code></a> sums along <em>only the inner dimensions</em> which match here <code>(1x8) and (8x1)</code>. So, the <code>8</code>s will be gone during the dot product or matrix multiplication yielding the result as <code>(1x1)</code> which is just a <em>scalar</em> but returned as 2D array of shape <code>(1,1)</code>.</p> <hr /> <p>Also, most importantly note that here <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.dot.html" rel="nofollow noreferrer"><code>np.dot</code> is <strong>exactly same</strong> as doing <code>np.matmul</code></a> since the inputs are 2D arrays (i.e. matrices)</p> <pre><code>In [107]: logprobs = np.matmul(Y, (np.log(A2)).T) + np.matmul((1.0-Y),(np.log(1 - A2)).T) In [108]: logprobs Out[108]: array([[-0.78914626]]) In [109]: logprobs.shape Out[109]: (1, 1) </code></pre> <hr /> <h3>Return result as a <em>scalar</em> value</h3> <p><a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.dot.html" rel="nofollow noreferrer"><code>np.dot</code></a> or <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html#numpy.matmul" rel="nofollow noreferrer"><code>np.matmul</code></a> returns whatever the resulting array shape would be, based on input arrays. Even with <code>out=</code> argument it's not possible to return a <em>scalar</em>, if the inputs are 2D arrays. However, we can use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.asscalar.html" rel="nofollow noreferrer"><code>np.asscalar()</code></a> on the result to convert it to a scalar if the result array is of shape <code>(1,1)</code> (or more generally a <em>scalar</em> value wrapped in an nD array)</p> <pre><code>In [123]: np.asscalar(logprobs) Out[123]: -0.7891462576187036 In [124]: type(np.asscalar(logprobs)) Out[124]: float </code></pre> <hr /> <blockquote> <p><em>ndarray</em> of size 1 to <em>scalar</em> value</p> </blockquote> <pre><code>In [127]: np.asscalar(np.array([[[23.2]]])) Out[127]: 23.2 In [128]: np.asscalar(np.array([[[[23.2]]]])) Out[128]: 23.2 </code></pre>
12,965,296
How to get maximum document scrolltop value
<p>I am making some plugin and I need to get maximum <code>scrollTop</code> value of the document. Maximum <code>scrollTop</code> value is <code>2001</code> , but <code>$(document).height()</code> returns <code>2668</code> and <code>$('body')[0].scrollHeight</code> gives me <code>undefined</code>.</p> <p>How to get <code>2001</code> through javascript/jquery?!</p>
12,965,383
5
6
null
2012-10-18 23:30:43.08 UTC
4
2021-06-26 04:40:22.38 UTC
2012-10-18 23:44:48.617 UTC
null
498,031
null
855,705
null
1
21
javascript|jquery|scrolltop
45,883
<p>The code in your comments should work:</p> <pre><code>$(document).height() - $(window).height() </code></pre> <p>Here's an example that alerts when you scroll to the maximum scroll position: <a href="http://jsfiddle.net/DWn7Z/">http://jsfiddle.net/DWn7Z/</a></p>
12,750,864
Temporary e-mail accounts for integration tests
<p>I would like to write some integration tests which verify if user receive registration confirmation e-mails.</p> <p>Ideally, for this purpose I would like:</p> <ol> <li>Create temporary e-mail account.</li> <li>Pass it in registration form.</li> <li>Check if we receive e-mail.</li> <li>Delete e-mail account.</li> </ol> <p>Are there any disposable e-mail accounts which provides a simple API? I couldn't find any, but existing ones are fairly easy to parse/make requests (e.g. <a href="http://10minutemail.com/" rel="noreferrer">http://10minutemail.com/</a>).</p> <p>Is this sounds like a good idea? The alternative is use some gmail account and use tags for this purpose. However, dealing with msgs in spam folder, other folders, etc. sounds a bit more complicated.</p>
13,053,612
5
4
null
2012-10-05 17:03:24.763 UTC
10
2020-10-13 23:10:48.26 UTC
null
null
null
null
341,181
null
1
36
email|testing|integration-testing
56,625
<p><a href="http://mailinator.com">http://mailinator.com</a> supports POP3.</p> <p>Connect to the server via POP3 with any username and check e-mail.</p>
13,013,781
How to draw a rectangle over a specific region in a matplotlib graph
<p>I have a graph, computed from some data, drawn in matplotlib. I want to draw a rectangular region around the global maximum of this graph. I tried <code>plt.axhspan,</code> but the rectangle doesn't seem to appear when I call <code>plt.show()</code></p> <p>So, how can a rectangular region be drawn onto a matplotlib graph? Thanks!</p>
13,014,729
2
0
null
2012-10-22 14:39:00.767 UTC
6
2021-10-23 17:58:19.67 UTC
null
null
null
null
1,084,573
null
1
43
python|matplotlib
59,972
<p>The most likely reason is that you used data units for the x arguments when calling axhspan. From <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.axhspan.html" rel="nofollow noreferrer">the function's docs</a> (my emphasis):</p> <blockquote> <p>y coords are in data units and <em>x coords are in axes (relative 0-1) units</em>.</p> </blockquote> <p>So any rectangle stretching left of 0 or right of 1 is simply drawn off-plot.</p> <p>An easy alternative might be to add a <a href="http://matplotlib.org/api/artist_api.html#matplotlib.patches.Rectangle" rel="nofollow noreferrer"><code>Rectangle</code></a> to your axis (e.g., via <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.gca.html" rel="nofollow noreferrer"><code>plt.gca</code></a> and <a href="http://matplotlib.org/api/axes_api.html" rel="nofollow noreferrer"><code>add_patch</code></a>); <code>Rectangle</code> uses data units for both dimensions. The following would add a grey rectangle with width &amp; height of 1 centered on (2,3):</p> <pre class="lang-py prettyprint-override"><code>from matplotlib.patches import Rectangle import matplotlib.pyplot as plt fig = plt.figure() plt.xlim(0, 10) plt.ylim(0, 12) someX, someY = 2, 5 currentAxis = plt.gca() currentAxis.add_patch(Rectangle((someX - .5, someY - .5), 4, 6, facecolor=&quot;grey&quot;)) </code></pre> <p><a href="https://i.stack.imgur.com/TAf4C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TAf4C.png" alt="enter image description here" /></a></p> <ul> <li>Without <code>facecolor</code></li> </ul> <pre class="lang-py prettyprint-override"><code>currentAxis.add_patch(Rectangle((someX - .5, someY - .5), 4, 6, facecolor=&quot;none&quot;, ec='k', lw=2)) </code></pre> <p><a href="https://i.stack.imgur.com/vAOkh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vAOkh.png" alt="enter image description here" /></a></p>
12,709,074
How do you explicitly set a new property on `window` in TypeScript?
<p>I setup global namespaces for my objects by explicitly setting a property on <code>window</code>.</p> <pre><code>window.MyNamespace = window.MyNamespace || {}; </code></pre> <p>TypeScript underlines <code>MyNamespace</code> and complains that:</p> <blockquote> <p>The property 'MyNamespace' does not exist on value of type 'window' any"</p> </blockquote> <p>I can make the code work by declaring <code>MyNamespace</code> as an ambient variable and dropping the <code>window</code> explicitness but I don't want to do that.</p> <pre><code>declare var MyNamespace: any; MyNamespace = MyNamespace || {}; </code></pre> <p>How can I keep <code>window</code> in there and make TypeScript happy?</p> <p>As a side note I find it especially funny that TypeScript complains since it tells me that <code>window</code> is of type <code>any</code> which by definitely can contain anything.</p>
12,709,880
29
1
null
2012-10-03 13:01:15.793 UTC
178
2022-06-29 10:02:33.567 UTC
null
null
null
null
31,308
null
1
1,076
typescript
627,061
<p>I just found the answer to this in <a href="https://stackoverflow.com/a/12703866/31308">another Stack Overflow question's answer</a>.</p> <pre><code>declare global { interface Window { MyNamespace: any; } } window.MyNamespace = window.MyNamespace || {}; </code></pre> <p>Basically, you need to extend the existing <code>window</code> interface to tell it about your new property.</p>
12,731,428
jQuery "Does not have attribute" selector?
<p>I can find a div that has an attribute like so:</p> <pre><code>$('.funding-plan-container[data-timestamp]') </code></pre> <p>But if I try to find a div that does not have that attribute, I get an error - my code is:</p> <pre><code>$('.funding-plan-container[!data-timestamp]') </code></pre> <p>Is there a "does not have attribute" selector in jQuery?</p> <p>For reference, the use case here is that any div that does not have a timestamp attribute was not added dynamically, and hence is useful.</p> <p>Thanks!</p>
12,731,439
3
0
null
2012-10-04 16:13:47.49 UTC
10
2020-05-29 15:10:46.067 UTC
null
null
null
null
726,221
null
1
158
javascript|jquery
89,121
<p>Use the <a href="http://api.jquery.com/not-selector/" rel="noreferrer"><code>:not()</code></a> selector.</p> <pre><code>$('.funding-plan-container:not([data-timestamp])') </code></pre> <hr> <p>This, by the way, is a valid <a href="http://www.w3.org/TR/selectors-api/" rel="noreferrer"><em>Selectors API</em></a> selector, so it isn't specific to jQuery. It'll work with <code>querySelectorAll()</code> and in your CSS <em>(given <a href="https://caniuse.com/#feat=css-sel3" rel="noreferrer">browser support</a>)</em>.</p>
17,075,577
Database Design with Change History
<p>I am looking to design a database that keeps track of every set of changes so that I can refer back to them in the future. So for example:</p> <pre><code>Database A +==========+========+==========+ | ID | Name | Property | 1 Kyle 30 </code></pre> <p>If I change the row's 'property' field to 50, it should update the row to:</p> <pre><code>1 Kyle 50 </code></pre> <p>But should save the fact that the row's property was 30 at some point in time. Then if the row is again updated to be 70:</p> <pre><code>1 Kyle 70 </code></pre> <p>Both facts that the row's property was 50 and 70 should be preserved, such that with some query I could retrieve:</p> <pre><code>1 Kyle 30 1 Kyle 50 </code></pre> <p>It should recognize that these were the "same entries" just at different points in time. </p> <p>Edit: This history will need to be presented to the user at some point in time so ideally, there should be an understanding of which rows belong to the same "revision cluster"</p> <p>What is the best way to approach the design of this database?</p>
17,075,789
4
4
null
2013-06-12 21:21:05.773 UTC
22
2020-03-17 23:20:29.517 UTC
2019-08-02 14:30:51.543 UTC
null
1,828,296
null
1,109,360
null
1
39
sql|postgresql|change-tracking
28,497
<p>One way is to have a <code>MyTableNameHistory</code> for every table in your database, and make its schema identical to the schema of table <code>MyTableName</code>, except that the Primary Key of the History table has one additional column named <code>effectiveUtc</code> as a DateTime. For example, if you have a table named <code>Employee</code>,</p> <pre><code>Create Table Employee { employeeId integer Primary Key Not Null, firstName varChar(20) null, lastName varChar(30) Not null, HireDate smallDateTime null, DepartmentId integer null } </code></pre> <p>Then the History table would be</p> <pre><code>Create Table EmployeeHistory { employeeId integer Not Null, effectiveUtc DateTime Not Null, firstName varChar(20) null, lastName varChar(30) Not null, HireDate smallDateTime null, DepartmentId integer null, Primary Key (employeeId , effectiveUtc) } </code></pre> <p>Then, you can put a trigger on Employee table, so that every time you insert, update, or delete anything in the Employee table, a new record is inserted into the EmployeeHistory table with the exact same values for all the regular fields, and current UTC datetime in the effectiveUtc column.</p> <p>Then to find the values at any point in the past, you just select the record from the history table whose effectiveUtc value is the highest value prior to the asOf datetime you want the value as of.</p> <pre><code> Select * from EmployeeHistory h Where EmployeeId = @EmployeeId And effectiveUtc = (Select Max(effectiveUtc) From EmployeeHistory Where EmployeeId = h.EmployeeId And effcetiveUtc &lt; @AsOfUtcDate) </code></pre>
16,824,355
Logging in Ruby on Rails in Production Mode
<p>I would like to view some variables in controller, it tried the following:</p> <p><code>Rails.logger.debug "Year: #{Time.now.year}"</code></p> <p><code>puts "Year: #{Time.now.year}, Month: #{@month}"</code></p> <p>where can I see the output for Logger or Puts in production mode? Do I need so set something up to view these somewhere?</p>
16,832,519
3
0
null
2013-05-29 21:41:24.237 UTC
8
2021-10-12 14:54:41.417 UTC
2014-04-14 19:29:40.58 UTC
null
2,800,417
null
1,135,541
null
1
51
ruby-on-rails|logging|production
66,893
<p>The normal log level in production is <code>info</code>, so <code>debug</code> logs are not shown.<br> Change your logging to</p> <pre><code>Rails.logger.info "Year: #{Time.now.year}" </code></pre> <p>to show it in <code>production.log</code>.</p> <p>Alternatively (but not a good idea) you can raise the logging level in <code>/config/environments/production.rb</code>:</p> <pre><code>config.log_level = :debug </code></pre> <p><strong>Update</strong> Rails 4.2:</p> <p>Now the default debug level in all environments is <code>:debug</code> (as @nabilh mentioned).<br> If you want you production environment less chattery, you can reset your log level in <code>/config/environments/production.rb</code> to the former <code>:info</code>:</p> <pre><code>config.log_level = :info </code></pre>
17,095,324
Fastest way to determine if an integer is between two integers (inclusive) with known sets of values
<p>Is there a faster way than <code>x &gt;= start &amp;&amp; x &lt;= end</code> in C or C++ to test if an integer is between two integers?</p> <p><em>UPDATE</em>: My specific platform is iOS. This is part of a box blur function that restricts pixels to a circle in a given square.</p> <p><em>UPDATE</em>: After trying the <a href="https://stackoverflow.com/a/17095534/1165522">accepted answer</a>, I got an order of magnitude speedup on the one line of code over doing it the normal <code>x &gt;= start &amp;&amp; x &lt;= end</code> way.</p> <p><em>UPDATE</em>: Here is the after and before code with assembler from XCode:</p> <p><strong>NEW WAY</strong></p> <pre><code>// diff = (end - start) + 1 #define POINT_IN_RANGE_AND_INCREMENT(p, range) ((p++ - range.start) &lt; range.diff) Ltmp1313: ldr r0, [sp, #176] @ 4-byte Reload ldr r1, [sp, #164] @ 4-byte Reload ldr r0, [r0] ldr r1, [r1] sub.w r0, r9, r0 cmp r0, r1 blo LBB44_30 </code></pre> <p><strong>OLD WAY</strong></p> <pre><code>#define POINT_IN_RANGE_AND_INCREMENT(p, range) (p &lt;= range.end &amp;&amp; p++ &gt;= range.start) Ltmp1301: ldr r1, [sp, #172] @ 4-byte Reload ldr r1, [r1] cmp r0, r1 bls LBB44_32 mov r6, r0 b LBB44_33 LBB44_32: ldr r1, [sp, #188] @ 4-byte Reload adds r6, r0, #1 Ltmp1302: ldr r1, [r1] cmp r0, r1 bhs LBB44_36 </code></pre> <p>Pretty amazing how reducing or eliminating branching can provide such a dramatic speed up.</p>
17,095,534
7
31
2013-08-19 15:24:53.37 UTC
2013-06-13 19:21:42.93 UTC
199
2021-02-16 02:47:53.837 UTC
2017-05-23 12:09:54.79 UTC
null
-1
null
56,079
null
1
409
c++|c|performance|math
82,296
<p>There's an old trick to do this with only one comparison/branch. Whether it'll really improve speed may be open to question, and even if it does, it's probably too little to notice or care about, but when you're only starting with two comparisons, the chances of a huge improvement are pretty remote. The code looks like:</p> <pre><code>// use a &lt; for an inclusive lower bound and exclusive upper bound // use &lt;= for an inclusive lower bound and inclusive upper bound // alternatively, if the upper bound is inclusive and you can pre-calculate // upper-lower, simply add + 1 to upper-lower and use the &lt; operator. if ((unsigned)(number-lower) &lt;= (upper-lower)) in_range(number); </code></pre> <p>With a typical, modern computer (i.e., anything using twos complement), the conversion to unsigned is really a nop -- just a change in how the same bits are viewed.</p> <p>Note that in a typical case, you can pre-compute <code>upper-lower</code> outside a (presumed) loop, so that doesn't normally contribute any significant time. Along with reducing the number of branch instructions, this also (generally) improves branch prediction. In this case, the same branch is taken whether the number is below the bottom end or above the top end of the range.</p> <p>As to how this works, the basic idea is pretty simple: a negative number, when viewed as an unsigned number, will be larger than anything that started out as a positive number. </p> <p>In practice this method translates <code>number</code> and the interval to the point of origin and checks if <code>number</code> is in the interval <code>[0, D]</code>, where <code>D = upper - lower</code>. If <code>number</code> below lower bound: <em>negative</em>, and if above upper bound: <em>larger than <code>D</code></em>. </p>
4,380,054
Calling Clojure from .NET
<p>I have been spending some time playing with Clojure-CLR. My REPL is working, I can call .NET classes from Clojure, but I have not been able to figure out calling compiled Clojure dlls from C# classes. </p> <p>I have been trying to adapt the java example found <a href="https://stackoverflow.com/questions/2181774/calling-clojure-from-java">here:</a></p> <p>I removed the :name line from the top of the example because it causes a "Duplicate key: :name" error. Without the ":name" line, the code compiles fine and I can add the reference in Visual Studio, but I can't seem to figure out how to use the code. I've tried a variety of 'using' statements, but so far nothing has worked. Can anyone provide a little insight on this? Here is the Clojure code I am attempting to use.</p> <pre><code>(ns code.clojure.example.hello (:gen-class :methods [#^{:static true} [output [int int] int]])) (defn output [a b] (+ a b)) (defn -output [a b] (output a b)) </code></pre>
4,394,405
2
0
null
2010-12-07 18:11:36.07 UTC
12
2013-07-26 19:00:50.397 UTC
2017-05-23 12:17:00.903 UTC
null
-1
null
388,187
null
1
21
.net|clojure|clojureclr
3,742
<p>I was able to get it to work doing the following:</p> <p>First I changed your code a bit, I was having trouble with the namespace and the compiler thinking the dots were directories. So I ended up with this.</p> <pre><code>(ns hello (:require [clojure.core]) (:gen-class :methods [#^{:static true} [output [int int] int]])) (defn output [a b] (+ a b)) (defn -output [a b] (output a b)) (defn -main [] (println (str "(+ 5 10): " (output 5 10)))) </code></pre> <p>Next I compiled it by calling:</p> <p><code>Clojure.Compile.exe hello</code></p> <p>This creates several files: hello.clj.dll, hello.clj.pdb, hello.exe, and hello.pdb You can execute hello.exe and it should run the -main function.</p> <p>Next I created a simple C# console application. I then added the following references: Clojure.dll, hello.clj.dll, and hello.exe</p> <p>Here is the code of the console app:</p> <pre><code>using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { hello h = new hello(); System.Console.WriteLine(h.output(5, 9)); System.Console.ReadLine(); } } } </code></pre> <p>As you can see, you should be able to create and use the hello class, it resides in the hello.exe assembly. I am not why the function "output" is not static, I assume it's a bug in the CLR compiler. I also had to use the 1.2.0 version of ClojureCLR as the latest was throwing assembly not found exceptions.</p> <p>In order to execute the application, make sure to set the clojure.load.path environment variable to where your Clojure binaries reside.</p> <p>Hope this helps.</p>
10,037,887
How can I put titles in ViewPager using fragments?
<p>I am using ViewPager to allow user to swipe between fragments.</p> <p>How can I add a the title of each fragment to the screen?</p> <pre><code>package com.multi.andres; import java.util.List; import java.util.Vector; import com.viewpagerindicator.TitlePageIndicator; import com.viewpagerindicator.TitleProvider; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; public class ViewPagerFragment extends FragmentActivity{ private PagerAdapter mPagerAdapter; //contiene el pager adapter private static String[] titulosPaginas = { "APP 1", "APP 2" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.lcmeter); //layout que contiene el ViewPager initialisePaging(); //inicializo las paginas } private void initialisePaging() { List&lt;Fragment&gt; fragments = new Vector&lt;Fragment&gt;(); fragments.add(Fragment.instantiate(this, FragmentPrueba1.class.getName())); fragments.add(Fragment.instantiate(this, FragmentPrueba2.class.getName())); this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments); ViewPager pager = (ViewPager)super.findViewById(R.id.pager); pager.setAdapter(this.mPagerAdapter); //Agrega los titulos TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.titulos); //layout XML titleIndicator.setViewPager(pager); } /** ************************************************************************************************* /** Clase: public class PagerAdapter extends FragmentPagerAdapter implements TitleProvider /** Notas: extends FragmentPagerAdapter permite el uso de las paginas de ViewPager pero con Fragments /** implements TitleProvider permite el uso de los titulos en las paginas /** Funcion: crea paginas por las cuales deslizarse horizontalmente las cuales son usadas ****************************************************************************************************/ public class PagerAdapter extends FragmentPagerAdapter implements TitleProvider { private List&lt;Fragment&gt; fragments; public String getTitle(int position) { // TODO Auto-generated method stub return titulosPaginas[position]; // titulo de la pagina } public PagerAdapter(FragmentManager fm, List&lt;Fragment&gt; fragments) { super(fm); this.fragments = fragments; } @Override public int getCount() { return this.fragments.size(); } @Override public Fragment getItem(int position) { return this.fragments.get(position); } } } </code></pre> <p>But it doesn't show the titles of ViewPager and I don't know why. I used ViewPager with titles before but not with fragments and I cannot get titles working now.</p>
10,039,279
4
1
null
2012-04-06 00:39:14.157 UTC
11
2016-02-15 08:26:36.16 UTC
2014-12-13 15:21:09.27 UTC
null
844,882
null
1,314,019
null
1
7
java|android|android-fragments|android-viewpager|android-fragmentactivity
25,790
<p>You can also use Jake Wharton's <a href="http://viewpagerindicator.com/" rel="noreferrer">ViewPagerIndicator</a> library to get the desired effect. Davek804's answer works too, but it requires you to reference the entire ActionBarSherlock library, which isn't as preferable if you only need a <code>ViewPager</code> that supports custom/styled titles.</p> <p>Setting it up to work correctly is simply a matter of writing a tiny bit of XML, initializing your <code>ViewPager</code> in your <code>Activity</code>, and implementing a <code>FragmentAdapter</code> (which <code>extends FragmentPagerAdapter implements TitleProvider</code>) to specify which pages hold which <code>Fragment</code>s.</p> <ol> <li><p>XML layout</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;com.viewpagerindicator.TabPageIndicator android:id="@+id/titles" android:layout_height="wrap_content" android:layout_width="match_parent"/&gt; &lt;android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/&gt; &lt;/LinearLayout&gt; </code></pre></li> <li><p>Initialize in your <code>Activity</code></p> <pre><code>//Set the pager with an adapter ViewPager pager = (ViewPager)findViewById(R.id.pager); pager.setAdapter(new CustomAdapter(getSupportFragmentManager())); //Bind the title indicator to the adapter TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.titles); titleIndicator.setViewPager(pager); </code></pre></li> <li><p>Implement a <code>CustomFragmentAdapter</code></p> <pre><code>public static class CustomFragmentAdapter extends FragmentPagerAdapter implements TitleProvider { public static final int POSITION_PAGE_1 = 0; public static final int POSITION_PAGE_2 = 1; public static final int POSITION_PAGE_3 = 2; private static final String[] TITLES = new String[] { "Title 1", "Title 2", "Title 3" }; public static final int NUM_TITLES = TITLES.length; public CustomFragmentAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case POSITION_TITLE_1: return PageOneFragment.newInstance(); case POSITION_TITLE_2: return PageTwoFragment.newInstance(); case POSITION_TITLE_3: return PageThreeFragment.newInstance(); } return null; } @Override public int getCount() { return NUM_TITLES; } @Override public String getTitle(int position) { return TITLES[position % NUM_TITLES].toUpperCase(); } } </code></pre></li> </ol> <hr> <h2>Edit:</h2> <p>The <a href="http://viewpagerindicator.com/" rel="noreferrer"><code>ViewPagerIndicator</code></a> library supports the titling features:</p> <ol> <li><p><code>TitlePageIndicator</code></p> <p><img src="https://i.stack.imgur.com/ZC7o2.png" alt="TitlePageIndicator"></p></li> <li><p><code>TabPageIndicator</code></p> <p><img src="https://i.stack.imgur.com/r10yp.png" alt="TabPageIndicator"></p></li> <li><p><code>CirclePageIndicator</code></p> <p><img src="https://i.stack.imgur.com/jUEcN.png" alt="CirclePageIndicator"></p></li> </ol>
9,906,571
Semantic Grid with Bootstrap + LESS Mixins ¿ HOW?
<p>Twitter bootstrap documentation talks about three mixins to generate grid systems:</p> <pre><code>.container-fixed(); #grid &gt; .core(); #grid &gt; .fluid(); </code></pre> <p>I know how to setup the page to use bootstrap and less... But I don't know how to use the grid system semantically. The documentation says what mixins to use but not how... ¿ Could anyone ilustrate how to use them in order to create semantic grids ? Just to figure out or to see how it works :S</p> <p>Thank you !!</p>
11,569,397
1
1
null
2012-03-28 11:30:05.127 UTC
9
2012-08-25 04:04:47.64 UTC
2012-03-28 15:55:45.11 UTC
null
1,267,307
null
1,092,437
null
1
9
css|twitter|twitter-bootstrap|less|mixins
5,207
<p>In navbar.less of bootstrap you will find the following.</p> <h1>grid and .core are used to namespace the .span()</h1> <pre><code>.navbar-fixed-top .container, .navbar-fixed-bottom .container { #grid &gt; .core &gt; .span(@gridColumns); } </code></pre> <p>In cases where you want to keep &quot;span3&quot; etc out of your html you could very well do something similar to:</p> <pre><code>header { #grid &gt; .core .span(12) } article.right { #grid &gt; .core .span(6) } aside.right { #grid &gt; .core .span(6) } footer { #grid &gt; .core .span(12) } </code></pre> <p>(12) and (6) are the number of columns you'd like your header element to span. This is of course replacing</p> <pre><code>&lt;header class=&quot;span12&quot;&gt;&lt;/header&gt; &lt;article class=&quot;span6&quot;&gt;&lt;/article&gt; &lt;aside class=&quot;span6&quot;&gt;&lt;/aside&gt; &lt;footer class=&quot;span12&quot;&gt;&lt;/footer&gt; </code></pre>
10,061,597
Creating materialized view that refreshes every 5 min
<p>I created a materialized view that refreshed every 5 min but when I do insert and perform select on materialized view I get same old data? Do I need to refresh manually?</p> <pre><code>CREATE MATERIALIZED VIEW MVW_TEST REFRESH FORCE ON DEMAND START WITH TO_DATE('01-01-2009 00:01:00', 'DD-MM-YYYY HH24:MI:SS') NEXT SYSDATE + 1/1152 As select * from TEST12 </code></pre>
10,062,283
2
3
null
2012-04-08 08:51:24.957 UTC
9
2017-04-20 12:30:22.543 UTC
2012-04-08 09:15:01.7 UTC
null
2,214,674
null
2,214,674
null
1
12
oracle|oracle11g
89,373
<p>I have demonstrated in steps where a materialized view refresh after every <code>one minute</code> ,for having a mv which refresh after 5 minute use <code>next(sysdate+5/1440)</code></p> <p>Step1: </p> <pre><code>Create table temp (A int); </code></pre> <p>Step2:</p> <pre><code>Create Materialized view temp_mv refresh complete start with (sysdate) next (sysdate+1/1440) with rowid as select * from temp; </code></pre> <p>Step3: </p> <pre><code>select count(*) from temp; COUNT(*) ---------- 0 </code></pre> <p>Step4:</p> <pre><code>select count(*) from temp_mv; COUNT(*) ---------- 0 </code></pre> <p>Step5:</p> <pre><code>begin for i in 1..10 loop insert into temp values (i+1); end loop; end; / </code></pre> <p>Step6: </p> <pre><code>commit; </code></pre> <p>Step7: </p> <pre><code>select count(*) from temp; COUNT(*) ---------- 10 </code></pre> <p>Step8:</p> <pre><code>select count(*) from temp_mv; COUNT(*) ---------- 0 </code></pre> <p>Step9: </p> <pre><code>select to_char(sysdate,'hh:mi') from dual; TO_CH ----- 04:28 </code></pre> <p>Step10:</p> <pre><code>select to_char(sysdate,'hh:mi') from dual; TO_CH ----- 04:29 </code></pre> <p>Step11:</p> <pre><code>select count(*) from temp; COUNT(*) ---------- 10 </code></pre> <p>Step12:</p> <pre><code>select count(*) from temp_mv; COUNT(*) ---------- 10 </code></pre>
10,087,782
Error: Specified cast is not valid. (SqlManagerUI)
<p>I have a backup from database in SQL Server 2008 R2. When I want to restore this backup to SQL Server, I get this error: "Error: Specified cast is not valid. (SqlManagerUI)" How to I resolve this error? Thanks.</p>
10,125,525
4
1
null
2012-04-10 11:22:05.733 UTC
2
2017-08-17 20:05:08.91 UTC
null
null
null
null
492,361
null
1
16
sql-server-2008-r2|database-restore
121,954
<p>There are some <a href="http://social.msdn.microsoft.com/forums/en-us/sqlsetupandupgrade/thread/071DA5BB-32C5-4C3F-9378-7E67C5DF2D44" rel="noreferrer">funnies</a> restoring old databases into SQL 2008 via the guy; have you tried doing it via TSQL ?</p> <pre><code>Use Master Go RESTORE DATABASE YourDB FROM DISK = 'C:\YourBackUpFile.bak' WITH MOVE 'YourMDFLogicalName' TO 'D:\Data\YourMDFFile.mdf',--check and adjust path MOVE 'YourLDFLogicalName' TO 'D:\Data\YourLDFFile.ldf' </code></pre>
10,217,489
methods in foreach and for loops in java
<p>My question is regarding optimization in java using the Android compiler. Will map.values() in the following be called every iteration, or will the Android compiler optimize it out.</p> <pre><code>LinkedHashMap&lt;String, Object&gt; map; for (Object object : map.values()) { //do something with object } </code></pre> <p>Likewise here is another example. will aList.size() be called every iteration?</p> <pre><code>List&lt;Object&gt; aList; for (int i = 0; i &lt; aList.size(); i++) { object = aList.get(i); //do something with i } </code></pre> <p>And after all this, does it really matter if it calls the methods every iteration? Does Map.values(), and List.size() do much of anything?</p>
10,217,534
1
4
null
2012-04-18 20:32:27.563 UTC
4
2016-07-17 22:19:32 UTC
2012-04-18 21:02:54.937 UTC
null
758,074
null
758,074
null
1
28
java|android
87,566
<p>In the first example, <code>map.values()</code> will be evaluated once. According to the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2" rel="noreferrer">Section 14.4.2 of the Java Language Specification</a>, it is equivalent to:</p> <pre><code>for (Iterator&lt;Object&gt; i = map.values().iterator(); i.hasNext(); ) { Object object = i.next(); // do something with object } </code></pre> <p>In the second, <code>aList.size()</code> will be called every time the test is evaluated. For readability, it would be better to code it as:</p> <pre><code>for (Object object : aList) { // do something with object } </code></pre> <p>However, per the <a href="https://developer.android.com/training/articles/perf-tips.html#Loops" rel="noreferrer">Android docs</a>, this will be slower. Assuming that you aren't changing the list size inside the loop, <strike>the fastest</strike> another way would be to pull out the list size ahead of the loop:</p> <pre><code>final int size = aList.size(); for (int i = 0; i &lt; size; i++) { object = aList.get(i); //do something with i } </code></pre> <p>This will be substantially faster (the Android docs linked to above say by a factor of 3) if <code>aList</code> happens to be an <code>ArrayList</code>, but is likely to be slower (possibly by a lot) for a <code>LinkedList</code>. It all depends on exactly what kind of <code>List</code> implementation class <code>aList</code> is.</p>
10,225,727
Should ConditionalWeakTable<TKey, TValue> be used for non-compiler purposes?
<p>I've recently come across the <a href="http://msdn.microsoft.com/en-us/library/dd287757.aspx" rel="noreferrer"><code>ConditionalWeakTable&lt;TKey,TValue&gt;</code></a> class in my search for an <code>IDictionary</code> which uses weak references, as suggested in answers <a href="https://stackoverflow.com/questions/2784291/good-implementation-of-weak-dictionary-in-net">here</a> and <a href="https://stackoverflow.com/questions/5764556/best-time-to-cull-weakreferences-in-a-collection-in-net/5764855#5764855">here</a>.</p> <p>There is <a href="http://blogs.msdn.com/b/dotnet/archive/2009/05/18/the-conditional-weak-table-enabling-dynamic-object-properties.aspx" rel="noreferrer">a definitive MSDN article</a> which introduced the class and which states:</p> <blockquote> <p>You can find the class ... in the System.Runtime.CompilerServices namespace. It’s in CompilerServices because it’s not a general-purpose dictionary type: we intend for it to only be used by compiler writers.</p> </blockquote> <p>and later again:</p> <blockquote> <p>...the conditional weak table is not intended to be a general purpose collection... But if you’re writing a .NET language of your own and need to expose the ability to attach properties to objects you should definitely look into the Conditional Weak Table.</p> </blockquote> <p>In line with this, the MSDN entry description of the class reads:</p> <blockquote> <p>Enables compilers to dynamically attach object fields to managed objects.</p> </blockquote> <p>So obviously it was originally created for a very specific purpose - to help the DLR, and the <code>System.Runtime.CompilerServices</code> namespace embodies this. But it seems to have found a much wider use than that - even within the CLR. If I search for references of <a href="http://msdn.microsoft.com/en-us/library/dd287757.aspx" rel="noreferrer">ConditionalWeakTable</a> in <a href="http://wiki.sharpdevelop.net/ILSpy.ashx" rel="noreferrer">ILSpy</a>, for example, I can see that is used in the MEF class <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.catalogexportprovider.aspx" rel="noreferrer"><code>CatalogExportProvider</code></a> and in the internal WPF <code>DataGridHelper</code> class, amongst others.</p> <p>My question is whether it is okay to use <a href="http://msdn.microsoft.com/en-us/library/dd287757.aspx" rel="noreferrer">ConditionalWeakTable</a> outside of compiler writing and language tools, and whether there is any risk in doing so in terms of incurring additional overhead or of the implementation changing significantly in future .NET versions. (Or should it be avoided and a custom implementation like <a href="http://blogs.msdn.com/b/nicholg/archive/2006/06/04/617466.aspx" rel="noreferrer">this one</a> be used instead).</p> <p>There is also further reading <a href="http://weblog.ikvm.net/PermaLink.aspx?guid=7f47ad08-cdef-4dc2-b2fd-5dfdc1baf11d" rel="noreferrer">here</a>, <a href="http://blog.gx.weltkante.de/2011/06/true-weak-keyed-dictionary.html" rel="noreferrer">here</a> and <a href="https://stackoverflow.com/questions/8441055/is-it-possible-to-create-a-truely-weak-keyed-dictionary-in-c">here</a> about how the <a href="http://msdn.microsoft.com/en-us/library/dd287757.aspx" rel="noreferrer">ConditionalWeakTable</a> makes use of a hidden CLR implementation of <a href="http://en.wikipedia.org/wiki/Ephemeron" rel="noreferrer">ephemerons</a> (via <code>System.Runtime.Compiler.Services. DependentHandle</code>) to deal with the problem of cycles between keys and values, and how this cannot easily be accomplished in a custom manner.</p>
10,267,942
1
0
null
2012-04-19 10:00:25.85 UTC
8
2016-06-09 13:40:43.29 UTC
2017-05-23 10:34:12.23 UTC
null
-1
null
177,117
null
1
33
c#|garbage-collection|clr|weak-references|ephemeron
5,206
<p>I don't see anything wrong with using <code>ConditionalWeakTable</code>. If you need ephemerons, you pretty much have no other choice.</p> <p>I don't think future .NET versions will be a problem - even if only compilers would use this class, Microsoft still couldn't change it without breaking compatibility with existing binaries.</p> <p>As for overhead - there certainly will be overhead compared to a normal Dictionary. Having many <code>DependentHandle</code>s probably will be expensive similarly to how many <code>WeakReference</code>s are more expensive than normal references (the GC has to do additional work to scan them to see if they need to be nulled out). But that's not a problem unless you have lots (several million) of entries.</p>
10,021,847
For loop in multidimensional javascript array
<p>Since now, I'm using this loop to iterate over the elements of an array, which works fine even if I put objects with various properties inside of it.</p> <pre><code>var cubes[]; for (i in cubes){ cubes[i].dimension cubes[i].position_x ecc.. } </code></pre> <p>Now, let's suppose cubes[] is declared this way</p> <pre><code>var cubes[][]; </code></pre> <p>Can I do this in JavaScript? How can I then automatically iterate in</p> <pre><code>cubes[0][0] cubes[0][1] cubes[0][2] cubes[1][0] cubes[1][1] cubes[1][2] cubes[2][0] ecc... </code></pre> <p>As a workaround, I can just declare:</p> <pre><code>var cubes[]; var cubes1[]; </code></pre> <p>and work separately with the two arrays. Is this a better solution?</p>
10,021,901
8
0
null
2012-04-05 02:22:11.003 UTC
30
2022-01-18 20:33:45 UTC
2022-01-18 20:33:45 UTC
null
215,552
null
1,307,020
null
1
49
javascript|loops|multidimensional-array
210,183
<p>You can do something like this:</p> <pre><code>var cubes = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; for(var i = 0; i &lt; cubes.length; i++) { var cube = cubes[i]; for(var j = 0; j &lt; cube.length; j++) { display("cube[" + i + "][" + j + "] = " + cube[j]); } } </code></pre> <p>Working jsFiddle:</p> <ul> <li><a href="http://jsfiddle.net/TRR4n/" rel="noreferrer">http://jsfiddle.net/TRR4n/</a></li> </ul> <p>The output of the above:</p> <pre><code>cube[0][0] = 1 cube[0][1] = 2 cube[0][2] = 3 cube[1][0] = 4 cube[1][1] = 5 cube[1][2] = 6 cube[2][0] = 7 cube[2][1] = 8 cube[2][2] = 9 </code></pre>
9,666,471
jQuery advantages/differences in .trigger() vs .click()
<p>In terms of performance, what are the gains (or just differences) between:</p> <pre><code>$('.myEl').click(); </code></pre> <p>and </p> <pre><code>$('.myEl').trigger('click'); </code></pre> <p>Are there any at all?</p>
9,666,577
4
0
null
2012-03-12 11:49:47.777 UTC
11
2015-06-16 19:52:41.81 UTC
null
null
null
null
478,144
null
1
78
jquery
26,877
<p><a href="http://james.padolsey.com/jquery/#v=1.7.2&amp;fn=$.fn.click" rel="noreferrer">This is the code for the <code>click</code> method</a>: </p> <pre><code>jQuery.fn.click = function (data, fn) { if (fn == null) { fn = data; data = null; } return arguments.length &gt; 0 ? this.on("click", null, data, fn) : this.trigger("click"); } </code></pre> <p>as you can see; if no arguments are passed to the function it will trigger the click event.</p> <hr> <p>Using <code>.trigger("click")</code> will call one less function.</p> <p>And as @Sandeep pointed out in his <a href="https://stackoverflow.com/a/9666547/887539">answer</a> <code>.trigger("click")</code> is faster: </p> <hr> <p><a href="http://james.padolsey.com/jquery/#v=1.9.0&amp;fn=$.fn.click" rel="noreferrer">As of 1.9.0 the check for <code>data</code> and <code>fn</code> has been moved to the <code>.on</code> function</a>:</p> <pre><code>$.fn.click = function (data, fn) { return arguments.length &gt; 0 ? this.on("click", null, data, fn) : this.trigger("click"); } </code></pre>
9,679,375
How can I run an EXE file from my C# code?
<p>I have an EXE file reference in my C# project. How do I invoke that EXE file from my code?</p>
9,679,614
4
0
null
2012-03-13 06:35:57.36 UTC
47
2021-08-31 13:21:47.817 UTC
2021-08-31 13:21:47.817 UTC
null
63,550
null
969,188
null
1
210
c#|.net
410,409
<pre><code>using System.Diagnostics; class Program { static void Main() { Process.Start("C:\\"); } } </code></pre> <p>If your application needs cmd arguments, use something like this:</p> <pre><code>using System.Diagnostics; class Program { static void Main() { LaunchCommandLineApp(); } /// &lt;summary&gt; /// Launch the application with some options set. /// &lt;/summary&gt; static void LaunchCommandLineApp() { // For the example const string ex1 = "C:\\"; const string ex2 = "C:\\Dir"; // Use ProcessStartInfo class ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; startInfo.FileName = "dcm2jpg.exe"; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2; try { // Start the process with the info we specified. // Call WaitForExit and then the using statement will close. using (Process exeProcess = Process.Start(startInfo)) { exeProcess.WaitForExit(); } } catch { // Log error. } } } </code></pre>
8,246,520
Does Python's os.system() wait for an end of the process?
<p>The <a href="http://docs.python.org/library/os.html#os.system">Python manual</a> says nothing about whether <code>os.system("cmd")</code> waits or not for a process to end:</p> <p>To quote the manual:</p> <blockquote> <p>Execute the command (a string) in a subshell.</p> </blockquote> <p>It looks like it does wait (same behaviour as Perl's <code>system</code>). Is this correct?</p>
8,246,562
3
1
null
2011-11-23 17:24:09.103 UTC
1
2021-02-12 11:21:57.783 UTC
2011-11-23 20:03:28.72 UTC
null
102,441
Adobe
788,700
null
1
30
python
38,197
<p>Yes it does. The return value of the call is the exit code of the subprocess.</p>
7,891,697
Numpy Adding two vectors with different sizes
<p>If I have two numpy arrays of different sizes, how can I superimpose them.</p> <pre><code>a = numpy([0, 10, 20, 30]) b = numpy([20, 30, 40, 50, 60, 70]) </code></pre> <p>What is the cleanest way to add these two vectors to produce a new vector (20, 40, 60, 80, 60, 70)?</p> <p>This is my generic question. For background, I am specifically applying a Green's transform function and need to superimpose the results for each time step in the evaulation unto the responses previously accumulated.</p>
7,891,889
3
1
null
2011-10-25 15:28:03.683 UTC
6
2020-07-02 00:55:57.343 UTC
2011-10-25 15:41:44.07 UTC
null
53,850
null
454,217
null
1
36
python|numpy|linear-algebra
35,629
<p>This could be what you are looking for</p> <pre><code>if len(a) &lt; len(b): c = b.copy() c[:len(a)] += a else: c = a.copy() c[:len(b)] += b </code></pre> <p>basically you copy the longer one and then add in-place the shorter one</p>
11,698,935
Jquery element+class selector performance
<p>I was hoping <code>$('#childDiv2 .txtClass')</code> or <code>$('#childDiv2 input.txtClass')</code> perform better when selecting <code>&lt;input type="text" id="txtID" class="txtClass"/&gt;</code> element. But according to this <a href="http://jsperf.com/selectors-perf/3" rel="noreferrer">performance analysis</a> <code>$('.txtClass');</code> is the best selector among this. I'm using JQuery 1.7.2 Does anybody have explanation for this?</p> <p><img src="https://i.stack.imgur.com/ctiCn.png" alt="Performance analysis for class selectors"></p> <p><em>HTML</em></p> <pre><code>&lt;div class="childDiv2"&gt; &lt;input type="text" id="txtID" class="txtClass"/&gt; &lt;p class="child"&gt;Blah Blah Blah&lt;/p&gt; &lt;/div&gt;​ </code></pre> <p><em>JS</em></p> <pre><code>$('.txtClass'); $('#childDiv2 .txtClass') $('#childDiv2 &gt; .txtClass') $('input.txtClass') $('#childDiv2 input.txtClass') </code></pre>
11,699,147
4
3
null
2012-07-28 06:45:04.73 UTC
21
2013-10-16 13:56:40.737 UTC
2012-07-28 07:37:48.447 UTC
null
106,224
null
857,956
null
1
30
jquery|jquery-selectors|performance
61,762
<p>Modern browsers expose a very efficient <a href="https://developer.mozilla.org/en/DOM/document.getElementsByClassName" rel="noreferrer">getElementsByClassName()</a> method that returns the elements having a given class. That's why a single class selector is faster in your case.</p> <p>To elaborate on your examples:</p> <pre><code>$(".txtClass") =&gt; getElementsByClassName() $("#childDiv2 .txtClass") =&gt; getElementById(), then getElementsByClassName() $("#childDiv2 &gt; .txtClass") =&gt; getElementById(), then iterate over children and check class $("input.txtClass") =&gt; getElementsByTagName(), then iterate over results and check class $("#childDiv2 input.txtClass") =&gt; getElementById(), then getElementsByTagName(), then iterate over results and check class </code></pre> <p>As you can see, it's quite logical for the first form to be the fastest on modern browsers.</p>
11,989,746
Escape special chars in RegEx?
<p>I have a form, that sends the contents of a text field to my Rails application and I have to generate a regular expression of this string. </p> <p>I tried it like this:</p> <pre><code>regex = /#{params[:text]}/ </code></pre> <p>In general this is working, but if brackets or special characters are contained in the string, this method will not work.</p> <p>I don't want Rails to take care of the chars. They should be escaped automatically.</p> <p>I tried it like this:</p> <pre><code>/\Q#{params[:text]}\E/ </code></pre> <p>but this isn't working either.</p>
11,989,938
2
0
null
2012-08-16 14:44:49.327 UTC
4
2018-01-03 08:59:33.957 UTC
2012-08-16 14:59:04.597 UTC
null
128,421
null
1,414,540
null
1
32
ruby-on-rails|ruby|regex
13,935
<p>You should use <a href="http://www.ruby-doc.org/core-1.9.3/Regexp.html#method-c-escape" rel="noreferrer"><code>Regexp.escape</code></a></p> <pre><code>regex = /#{Regexp.escape(params[:text])}/ # in rails models/controllers with mongoid use: # ::Regexp.escape(params[:text]) instead. ([more info][2]) </code></pre>
11,587,119
Is this a web page or an image?
<p><a href="http://lcamtuf.coredump.cx/squirrel/" rel="noreferrer">http://lcamtuf.coredump.cx/squirrel/</a></p> <p>According to the author, </p> <blockquote> <p>This is an embedded landing page for an image. You can link to this URL and get the HTML document you are viewing right now (soon to include essential squirrel facts); or embed the exact same URL as an image on your own squirrel-themed page: <code>&lt;a href="http://lcamtuf.coredump.cx/squirrel/"&gt;Click here!&lt;/a&gt; &lt;img src="http://lcamtuf.coredump.cx/squirrel/"&gt;</code> No server-side hacks involved - the magic happens in your browser. </p> </blockquote> <p>In other words, if you pop that URL into your browser it renders as a web page, but you can also use the same URL as an image source. </p> <p>What kind of witchcraft is at work here?</p> <p><sub>(Edit: <a href="http://pastebin.com/jMqbie7C" rel="noreferrer">source code</a> from the above link if that site ever goes offline.)</sub></p>
11,587,183
2
4
null
2012-07-20 21:23:50.353 UTC
25
2015-03-06 16:52:40.03 UTC
2015-03-06 16:52:40.03 UTC
null
616,443
null
616,443
null
1
46
html|image|encoding
4,604
<p>The file you linked is a polyglot - a combination of languages. It can be read and understood as <strong>both</strong> an image and an HTML file. It's a simple trick. If you look at the HTML source you can see this at the top:</p> <pre><code>ÿØÿà </code></pre> <p>A quick Google shows this looks like a JPEG header. What the creator does is store the HTML in JPEG metadata, and the JPEG image data in a html comment. Pretty nifty but not magic.</p> <p>To hide the JPEG header he uses CSS rules to hide the body and show only some elements:</p> <pre><code>body { visibility: hidden; } .n { visibility: visible; position: absolute; ...... } </code></pre> <p>Also note that it isn't valid HTML, for example because the comment to hide the image data is not closed, but that browsers still happily accept and render it.</p>
11,976,223
How to deal with missing src/test/java source folder in Android/Maven project?
<p>I'm not very experienced with Maven in combination with Android yet, so I followed <a href="http://rgladwell.github.com/m2e-android/" rel="noreferrer">these</a> instructions to make a new Android project. When the project has been created, I get the following error message: </p> <blockquote> <p>Project 'xxx-1.0-SNAPSHOT' is missing required source folder: 'src/test/java'</p> </blockquote> <p>When I try to add a new source folder with New->Other->Java-Source Folder with src/test/java, I get another error message:</p> <blockquote> <p>The folder is already a source folder.</p> </blockquote> <p>But I don't have any src/test/java folder in my project. How should I deal with that? What's the clean way to setup the project, because I assume that there is something missing in this instruction. So what is the Maven way to let src/test/java appear?</p> <p>I'm using Eclipse Juno, m2e 1.1.0, Android Configuration for m2e 0.4.2.</p>
11,978,134
10
4
null
2012-08-15 19:51:58.51 UTC
12
2021-12-18 20:46:16.333 UTC
2021-12-18 20:46:16.333 UTC
null
1,824,361
null
319,773
null
1
49
java|android|eclipse|maven|m2eclipse
136,733
<p>I realise this annoying thing too since latest m2e-android plugin upgrade (version 0.4.2), it happens in both new project creation and existing project import (if you don't use src/test/java).</p> <p>It looks like m2e-android (or perhaps m2e) now always trying to add <code>src/test/java</code> as a source folder, regardless of whether it is actually existed in your project directory, in the .classpath file:</p> <pre><code>&lt;classpathentry kind="src" output="bin/classes" path="src/test/java"&gt; &lt;attributes&gt; &lt;attribute name="maven.pomderived" value="true"/&gt; &lt;/attributes&gt; &lt;/classpathentry&gt; </code></pre> <p>As it is already added in the project metadata file, so if you trying to add the source folder via Eclipse, Eclipse will complain that the classpathentry is already exist:</p> <p><img src="https://i.stack.imgur.com/zkRtb.png" alt="enter image description here"></p> <p>There are several ways to fix it, the easiest is manually create src/test/java directory in the file system, then refresh your project by press <kbd>F5</kbd> and run Maven -> Update Project (Right click project, choose Maven -> Update Project...), this should fix the missing required source folder: 'src/test/java' error.</p>
11,525,717
When does the App Engine scheduler use a new thread vs. a new instance?
<p>If I set <code>threadsafe: true</code> in my <code>app.yaml</code> file, what are the rules that govern when a new instance will be created to serve a request, versus when a new thread will be created on an existing instance?</p> <p>If I have an app which performs something computationally intensive on each request, does multi-threading buy me anything? In other words, is an instance a multi-core instance or a single core?</p> <p>Or, are new threads only spun up when existing threads are waiting on IO?</p>
11,882,719
3
2
null
2012-07-17 15:23:33.387 UTC
12
2012-08-09 16:45:00.83 UTC
null
null
null
null
23,786
null
1
60
python|google-app-engine
2,840
<p>The following set of rules are currently used to determine if a given instance can accept a new request:</p> <pre><code>if processing more than N concurrent requests (today N=10): false elif exceeding the soft memory limit: false elif exceeding the instance class CPU limit: false elif warming up: false else true </code></pre> <p>The following of total CPU/core limits currently apply to each instance classes:</p> <pre><code>CLASS 1: 600MHz 1 core CLASS 2: 1.2GHz 1 core CLASS 4: 2.4GHz 1 core CLASS 8: 4.8GHz 2 core </code></pre> <p>So only a <code>B8</code> instance can process up to 2 fully CPU bound requests in parallel.</p> <p>Setting <code>threadsafe: true</code> (Python) or <code>&lt;threadsafe&gt;true&lt;/threadsafe&gt;</code> (Java) for instances classes &lt; 8 would not allow more than one CPU bound requests to be processed in parallel on a single instance.</p> <p>If you are not fully CPU bound or doing I/O, the Python and Java runtime will spawn new threads for handling new request up to 10 concurrent requests with <code>threadsafe: true</code></p> <p>Also note that even though the Go runtime is single threaded, it does support concurrent requests: It will spawn 1 goroutine per requests and yield control between goroutines while they are performing I/O.</p>
11,930,996
PGError: ERROR: permission denied for relation (when using Heroku)
<p>I've recently gone through the database migration process as outlined here:</p> <p><a href="https://devcenter.heroku.com/articles/migrating-from-shared-database-to-heroku-postgres" rel="noreferrer">https://devcenter.heroku.com/articles/migrating-from-shared-database-to-heroku-postgres</a></p> <p>Now I'm seeing a number of errors in the logs like this:</p> <p>PGError: ERROR: permission denied for relation </p> <p>Any ideas on what I should do to fix it?</p>
11,935,926
6
1
null
2012-08-13 08:56:45.63 UTC
13
2019-02-28 01:54:23.193 UTC
2014-02-05 19:47:46.707 UTC
null
2,229,277
null
492,242
null
1
78
database|postgresql|heroku|permissions
37,880
<p>I had a similar problem but the root cause was that my app was pointing to the old dev database which had exceeded it's limit of 10,000 rows.</p> <p>Although I created a new Basic db and backed everything up, the app was still pointing the old dev DB.</p> <pre><code>heroku pg:info </code></pre> <p>Check to see the rows: 10300/10000 (then you have a problem)</p> <p>You will need to <br/><br/> 1) Create new DB with more rows (Basic or the "Production" ones -> Heroku seems to be forcing an upgrade to make more money errrrrr)<br/><br/> 2) backup the old DB using pgbackups: <code>heroku pg:backups:capture SMALL_DB_NAME</code><br/><br/> 3) restore the backup to the new DB: <code>heroku pg:backups:restore BACKUP_ID BIG_DB_NAME</code> (see links below for more details)<br/><br/> 4) PROMOTE the new DB to the primary for the app: <code>heroku pg:promote BIG_DB_NAME</code><br/><br/></p> <p>can always utilize:<br/></p> <blockquote> <blockquote> <p><code>heroku maintenance:on</code> (to disable the app while updating)</p> </blockquote> </blockquote> <p><br/></p> <blockquote> <blockquote> <p><code>heroku maintenance:off</code> </p> </blockquote> </blockquote> <p><br/></p> <blockquote> <blockquote> <p><code>heroku pg:info</code> (to check the status)</p> </blockquote> </blockquote> <p>If this is the problem you may want to check out: <a href="https://devcenter.heroku.com/articles/heroku-postgres-starter-tier" rel="noreferrer">https://devcenter.heroku.com/articles/heroku-postgres-starter-tier</a> <a href="https://devcenter.heroku.com/articles/migrating-from-shared-database-to-heroku-postgres" rel="noreferrer">https://devcenter.heroku.com/articles/migrating-from-shared-database-to-heroku-postgres</a></p>
3,984,019
MySQL user-defined variable in WHERE clause
<p>I want to know if there is a way to use a user-defined variable in <code>WHERE</code> clause, as in this example:</p> <pre><code>SELECT id, location, @id := 10 FROM songs WHERE id = @id </code></pre> <p>This query runs with no errors but doesn't work as expected.</p>
6,021,738
4
2
null
2010-10-21 03:14:45.467 UTC
1
2016-12-01 11:32:13.697 UTC
2012-04-16 12:16:26.513 UTC
null
225,037
null
222,758
null
1
25
mysql|where-clause
42,876
<p>Not far from what Mike E. proposed, but one statement:</p> <pre><code>SELECT id, location FROM songs, ( SELECT @id := 10 ) AS var WHERE id = @id; </code></pre> <p>I used similar queries to emulate window functions in MySQL. E.g. <a href="http://explainextended.com/2009/03/05/row-sampling/" rel="noreferrer">Row sampling</a> - just an example of using variables in the same statement</p>
3,289,198
Custom attribute on property - Getting type and value of attributed property
<p>I have the following custom attribute, which can be applied on properties:</p> <pre><code>[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class IdentifierAttribute : Attribute { } </code></pre> <p>For example:</p> <pre><code>public class MyClass { [Identifier()] public string Name { get; set; } public int SomeNumber { get; set; } public string SomeOtherProperty { get; set; } } </code></pre> <p>There will also be other classes, to which the Identifier attribute could be added to properties of different type:</p> <pre><code>public class MyOtherClass { public string Name { get; set; } [Identifier()] public int SomeNumber { get; set; } public string SomeOtherProperty { get; set; } } </code></pre> <p>I then need to be able to get this information in my consuming class. For example:</p> <pre><code>public class TestClass&lt;T&gt; { public void GetIDForPassedInObject(T obj) { var type = obj.GetType(); //type.GetCustomAttributes(true)??? } } </code></pre> <p>What's the best way of going about this? I need to get the type of the [Identifier()] field (int, string, etc...) and the actual value, obviously based on the type.</p>
3,289,235
4
0
null
2010-07-20 10:51:49.987 UTC
11
2019-11-27 10:55:33.057 UTC
2014-06-12 17:45:42.543 UTC
null
1,804,678
null
131,809
null
1
37
c#|.net|custom-attributes
77,932
<p>Something like the following,, this will use only the first property it comes accross that has the attribute, of course you could place it on more than one..</p> <pre><code> public object GetIDForPassedInObject(T obj) { var prop = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance) .FirstOrDefault(p =&gt; p.GetCustomAttributes(typeof(IdentifierAttribute), false).Count() ==1); object ret = prop !=null ? prop.GetValue(obj, null) : null; return ret; } </code></pre>
3,840,784
Appending turns my list to NoneType
<p>In Python Shell, I entered: </p> <pre><code>aList = ['a', 'b', 'c', 'd'] for i in aList: print(i) </code></pre> <p>and got </p> <pre><code>a b c d </code></pre> <p>but when I tried: </p> <pre><code>aList = ['a', 'b', 'c', 'd'] aList = aList.append('e') for i in aList: print(i) </code></pre> <p>and got </p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#22&gt;", line 1, in &lt;module&gt; for i in aList: TypeError: 'NoneType' object is not iterable </code></pre> <p>Does anyone know what's going on? How can I fix/get around it?</p>
3,840,802
4
0
null
2010-10-01 15:45:13 UTC
7
2021-07-14 10:57:25.683 UTC
2010-10-01 15:52:33.863 UTC
null
12,855
null
460,847
null
1
37
python|mutators
72,068
<p><code>list.append</code> is a method that modifies the existing list. It doesn't return a new list -- it returns <code>None</code>, like most methods that modify the list. Simply do <code>aList.append('e')</code> and your list will get the element appended.</p>
3,580,802
How to use git (git config --global)?
<p>The <a href="http://www.pragprog.com/titles/pg_git/pragmatic-guide-to-git" rel="noreferrer">Pragmatic Guide to GIT</a> has the following "Git uses both to calculate the commit ID—a SHA-111 hash—that identifies each commit." in page 21.</p> <p>And in page 22, I can use the following command to 'Configure Git to know who you are'.</p> <pre> git config --global smcho "Your Name" </pre> <p>When I ran it, I got the following error message. </p> <pre> error: key does not contain a section: smcho </pre> <p>What's wrong with this? I guess it has something to do with SHA-111 hash, but I don't know how to get it to be used with git. </p> <h2>ADDED</h2> <p>I thought user.name is to be replaced my name, not a section/parameter structured name. After changing that it works OK. </p> <pre> git config --global user.name "Your Name" </pre>
3,580,841
4
1
null
2010-08-27 01:53:08.877 UTC
5
2018-09-13 11:43:11.09 UTC
2010-08-27 02:20:25.653 UTC
null
260,127
null
260,127
null
1
43
git|configuration
68,764
<p>Not sure where "smcho" comes from, but the setting to set your name is <code>user.name</code>:</p> <pre><code>git config --global user.name "Your Name" </code></pre> <p>You can set your e-mail address too:</p> <pre><code>git config --global user.email "name@domain.example" </code></pre> <p>I guess the reason it complains about the lack of a section is that the name of the parameter to set probably needs to be in two parts: <code>section.parameter_name</code> (You can see the sections names within <code>[]</code> if you look in the configuration file, for example in <code>.git/config</code>).</p> <p>(None of this is specific to OSX as far as I'm aware.)</p>
3,643,580
Is there a portable C compiler for windows?
<p>I want to carry one in my flash drive and run it. </p> <p>Thanks</p>
3,643,595
6
0
null
2010-09-04 18:59:37.287 UTC
6
2017-08-01 13:36:25.607 UTC
null
null
null
null
88,447
null
1
16
c|windows|compiler-construction|portability
48,211
<p><a href="http://www.mingw.org/" rel="noreferrer">MinGW</a> is a pretty good one and can be easily copied to a flash drive. Admittedly this is a port of GCC, but it works well in Windows. A drawback of this compiler is that it does not understand some of the specific Microsoft <a href="http://msdn.microsoft.com/en-us/library/6bh0054z.aspx" rel="noreferrer">keywords</a> that can be used when compiling with <code>cl.exe</code>.</p>
3,494,115
What does $_ mean in PowerShell?
<p>I've seen the following a lot in PowerShell, but what does it do exactly?</p> <pre><code>$_ </code></pre>
3,494,138
7
1
null
2010-08-16 14:33:33.923 UTC
58
2022-02-22 14:00:19.43 UTC
2016-02-01 19:54:15.27 UTC
null
63,550
null
17,744
null
1
280
powershell
301,349
<p>This is the variable for the current value in the pipe line, which is called <code>$PSItem</code> in Powershell 3 and newer. </p> <pre><code>1,2,3 | %{ write-host $_ } </code></pre> <p>or</p> <pre><code>1,2,3 | %{ write-host $PSItem } </code></pre> <p>For example in the above code the <code>%{}</code> block is called for every value in the array. The <code>$_</code> or <code>$PSItem</code> variable will contain the current value. </p>
3,515,264
Can I change the Android startActivity() transition animation?
<p>I am starting an activity and would rather have a alpha fade-in for <code>startActivity()</code>, and a fade-out for the <code>finish()</code>. How can I go about this in the Android SDK?</p>
3,515,625
10
2
null
2010-08-18 18:16:33.777 UTC
37
2021-12-03 12:46:29.81 UTC
null
null
null
null
69,634
null
1
120
android|animation|fade|transition
154,739
<p>In the same statement in which you execute finish(), execute your animation there too. Then, in the new activity, run another animation. See this code:</p> <p>fadein.xml</p> <pre><code>&lt;set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true"&gt; &lt;alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500"/&gt; //Time in milliseconds &lt;/set&gt; </code></pre> <p>In your finish-class</p> <pre><code>private void finishTask() { if("blabbla".equals("blablabla"){ finish(); runFadeInAnimation(); } } private void runFadeInAnimation() { Animation a = AnimationUtils.loadAnimation(this, R.anim.fadein); a.reset(); LinearLayout ll = (LinearLayout) findViewById(R.id.yourviewhere); ll.clearAnimation(); ll.startAnimation(a); } </code></pre> <p>fadeout.xml</p> <pre><code>&lt;set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true"&gt; &lt;alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500"/&gt; &lt;/set&gt; </code></pre> <p>In your new Activity-class you create a similiar method like the runFadeAnimation I wrote and then you run it in onCreate and don't forget to change the resources id to fadeout.</p>
3,453,085
What is :: (double colon) in Python when subscripting sequences?
<p>I know that I can use something like <code>string[3:4]</code> to get a substring in Python, but what does the 3 mean in <code>somesequence[::3]</code>?</p>
3,453,103
11
3
null
2010-08-10 20:21:53.817 UTC
105
2021-07-22 21:39:48.077 UTC
2017-02-03 23:08:27.097 UTC
null
15,168
null
414,064
null
1
370
python|syntax|slice
310,879
<p>it means 'nothing for the first argument, nothing for the second, and jump by three'. It gets every third item of the sequence sliced. <a href="http://docs.python.org/release/2.3.5/whatsnew/section-slices.html">Extended slices</a> is what you want. New in Python 2.3</p>
8,330,838
VBA Date as integer
<p>is there a way to get the underlying integer for <code>Date</code> function in VBA ? I'm referring to the integer stored by Excel to describe dates in memory in terms of number of days (when time is included it can be a float then I guess). I'm only interest in the integer part though. Is there just another function for that ?</p> <p>For example, for today() I'd like to be able to get back 40877..</p>
8,330,916
4
0
null
2011-11-30 18:16:43.997 UTC
2
2020-07-06 10:15:41.483 UTC
2020-07-06 10:15:41.483 UTC
null
6,296,561
null
1,029,944
null
1
24
excel|vba|date|datetime
180,879
<p>Date is not an Integer in VB(A), it is a Double.</p> <p>You can get a Date's value by passing it to <code>CDbl()</code>.</p> <pre class="lang-vb prettyprint-override"><code>CDbl(Now()) ' 40877.8052662037 </code></pre> <p>From the <a href="https://docs.microsoft.com/en-us/office/troubleshoot/excel/1900-and-1904-date-system" rel="noreferrer">documentation</a>:</p> <blockquote> <h3>The 1900 Date System</h3> <p>In the 1900 date system, the first day that is supported is January 1, 1900. When you enter a date, the date is converted into a serial number that represents the number of elapsed days starting with 1 for January 1, 1900. For example, if you enter July 5, 1998, Excel converts the date to the serial number 35981.</p> </blockquote> <p>So in the 1900 system, <code>40877.805...</code> represents 40,876 days after January 1, 1900 (29 November 2011), and ~80.5% of one day (~19:19h). There is a setting for 1904-based system in Excel, numbers will be off when this is in use (that's a per-workbook setting).</p> <p>To get the integer part, use</p> <pre class="lang-vb prettyprint-override"><code>Int(CDbl(Now())) ' 40877 </code></pre> <p>which would return a <strike>Long</strike>Double with no decimal places (i.e. what <code>Floor()</code> would do in other languages). </p> <p>Using <code>CLng()</code> or <code>Round()</code> would result in rounding, which will return a "day in the future" when called after 12:00 noon, so don't do that.</p>
8,118,741
CSS Font "Helvetica Neue"
<p>I often see the websites using font "Helvetica Neue". Is this font safe to use, like eg. Arial? Or do the browsers have trouble rendering it or not many machines have this font? Thanks.</p>
8,118,772
5
2
null
2011-11-14 07:57:33.903 UTC
18
2020-07-12 16:15:08.657 UTC
null
null
null
null
523,364
null
1
45
css|fonts
176,639
<p>This font is not standard on all devices. It is installed by default on some Macs, but rarely on PCs and mobile devices.</p> <p>To use this font on all devices, use a <a href="http://www.css3.info/preview/web-fonts-with-font-face/" rel="noreferrer">@font-face declaration</a> in your CSS to link to it on your domain if you wish to use it.</p> <pre><code>@font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); } @font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf'); } </code></pre> <p>Taken from <a href="http://www.css3.info" rel="noreferrer">css3.info</a></p>
8,158,987
rails 3.1 asset pipeline css caching in development
<p>I'm a bit confused as it seems like the application.css is including itself twice, once when it lists the resources from the manifest and then a cache of that. So when I delete an individual file it still seems to stay alive inside the application.css file.</p> <h1>application.css (source)</h1> <pre><code>/* *= require twitter/bootstrap *= require_self *= require_tree ./common *= require_tree ./helpers */ </code></pre> <p>Which works as expected and outputs in dev mode all the relevant individual files</p> <h1>development.rb</h1> <pre><code> # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true </code></pre> <h1>output</h1> <pre><code>&lt;link href="/assets/twitter/bootstrap.css?body=1" media="screen" rel="stylesheet" type="text/css" /&gt; &lt;link href="/assets/application.css?body=1" media="screen" rel="stylesheet" type="text/css" /&gt; &lt;link href="/assets/common/announcement.css?body=1" media="screen" rel="stylesheet" type="text/css" /&gt; &lt;link href="/assets/common/button.css?body=1" media="screen" rel="stylesheet" type="text/css" /&gt; &lt;Blah blah&gt; </code></pre> <h1>application.css (output)</h1> <p>This should be blank? Since all I have in my application.css file is the manifest and no actual css but instead i get all my concatenated code 106kb long.</p> <p>IE if I remove a file in the common directory, it doesn't go away. It is no longer listed in the output but the css still appears from the application.css</p>
8,164,860
10
3
null
2011-11-16 21:28:56.18 UTC
13
2013-09-27 01:38:28.02 UTC
2011-11-16 21:35:24.587 UTC
null
116,522
null
116,522
null
1
36
ruby-on-rails-3|ruby-on-rails-3.1|asset-pipeline|sass
20,552
<p>I had a problem like this before. It was caused after I had precompiled the assets it was going after the applcation.css inside the public folder as well as in the apps directory. I'm not sure how to fix it so that it doesn't keep happening while in dev mode but if you delete your <code>/public/assets</code> directory it should fix it.</p> <p>Check and see if you have a public/assets folder, if you do and it's full, it's probably why you're seeing double.</p>
4,091,441
How do I index and search text files in Lucene 3.0.2?
<p>I am newbie in Lucene, and I'm having some problems creating simple code <strong>to query a text file collection</strong>.</p> <p>I tried <a href="http://www.avajava.com/tutorials/lessons/how-do-i-use-lucene-to-index-and-search-text-files.html" rel="noreferrer">this example</a>, but is incompatible with the new version of Lucene.</p> <p><strong>UDPATE:</strong> <a href="http://pastebin.com/HqrbBPtp" rel="noreferrer">This is my new code</a>, but it still doesn't work yet.</p>
4,092,172
3
0
null
2010-11-03 20:36:41.607 UTC
9
2015-11-27 09:47:58.927 UTC
2011-08-08 22:11:04.413 UTC
null
709,202
null
284,932
null
1
11
java|indexing|lucene|text-files
17,546
<p>Lucene is a quite big topic with a lot of classes and methods to cover, and you normally cannot use it without understanding at least some basic concepts. If you need a quickly available service, use <a href="http://lucene.apache.org/solr/" rel="noreferrer">Solr</a> instead. If you need full control of Lucene, go on reading. I will cover some core Lucene concepts and classes, that represent them. (For information on how to read text files in memory read, for example, <a href="http://www.javapractices.com/topic/TopicAction.do?Id=42" rel="noreferrer">this</a> article).</p> <p>Whatever you are going to do in Lucene - indexing or searching - you need an analyzer. The goal of analyzer is to tokenize (break into words) and stem (get base of a word) your input text. It also throws out the most frequent words like "a", "the", etc. You can find analyzers for more then 20 languages, or you can use <a href="http://lucene.apache.org/java/3_0_1/api/contrib-snowball/org/apache/lucene/analysis/snowball/SnowballAnalyzer.html" rel="noreferrer">SnowballAnalyzer</a> and pass language as a parameter.<br> To create instance of SnowballAnalyzer for English you this:</p> <pre><code>Analyzer analyzer = new SnowballAnalyzer(Version.LUCENE_30, "English"); </code></pre> <p>If you are going to index texts in different languages, and want to select analyzer automatically, you can use <a href="http://tika.apache.org/0.7/api/org/apache/tika/language/LanguageIdentifier.html" rel="noreferrer">tika's LanguageIdentifier</a>.</p> <p>You need to store your index somewhere. There's 2 major possibilities for this: in-memory index, which is easy-to-try, and disk index, which is the most widespread one.<br> Use any of the next 2 lines:</p> <pre><code>Directory directory = new RAMDirectory(); // RAM index storage Directory directory = FSDirectory.open(new File("/path/to/index")); // disk index storage </code></pre> <p>When you want to add, update or delete document, you need IndexWriter:</p> <pre><code>IndexWriter writer = new IndexWriter(directory, analyzer, true, new IndexWriter.MaxFieldLength(25000)); </code></pre> <p>Any document (text file in your case) is a set of fields. To create document, which will hold information about your file, use this:</p> <pre><code>Document doc = new Document(); String title = nameOfYourFile; doc.add(new Field("title", title, Field.Store.YES, Field.Index.ANALYZED)); // adding title field String content = contentsOfYourFile; doc.add(new Field("content", content, Field.Store.YES, Field.Index.ANALYZED)); // adding content field writer.addDocument(doc); // writing new document to the index </code></pre> <p><code>Field</code> constructor takes field's name, it's text and <em>at least</em> 2 more parameters. First is a flag, that show whether Lucene must store this field. If it equals <code>Field.Store.YES</code> you will have possibility to get all your text back from the index, otherwise only index information about it will be stored.<br> Second parameter shows whether Lucene must index this field or not. Use <code>Field.Index.ANALYZED</code> for any field you are going to search on.<br> Normally, you use both parameters as shown above. </p> <p>Don't forget to close your <code>IndexWriter</code> after the job is done:</p> <pre><code>writer.close(); </code></pre> <p>Searching is a bit tricky. You will need several classes: <code>Query</code> and <code>QueryParser</code> to make Lucene query from the string, <code>IndexSearcher</code> for actual searching, <code>TopScoreDocCollector</code> to store results (it is passed to <code>IndexSearcher</code> as a parameter) and <code>ScoreDoc</code> to iterate through results. Next snippet shows how this all is composed: </p> <pre><code>IndexSearcher searcher = new IndexSearcher(directory); QueryParser parser = new QueryParser(Version.LUCENE_30, "content", analyzer); Query query = parser.parse("terms to search"); TopScoreDocCollector collector = TopScoreDocCollector.create(HOW_MANY_RESULTS_TO_COLLECT, true); searcher.search(query, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; // `i` is just a number of document in Lucene. Note, that this number may change after document deletion for (int i = 0; i &lt; hits.length; i++) { Document hitDoc = searcher.doc(hits[i].doc); // getting actual document System.out.println("Title: " + hitDoc.get("title")); System.out.println("Content: " + hitDoc.get("content")); System.out.println(); } </code></pre> <p>Note second argument to the <code>QueryParser</code> constructor - it is default field, i.e. field that will be searched if no qualifier was given. For example, if your query is "title:term", Lucene will search for a word "term" in field "title" of all docs, but if your query is just "term" if will search in default field, in this case - "contents". For more info see <a href="http://lucene.apache.org/java/2_4_0/queryparsersyntax.html" rel="noreferrer">Lucene Query Syntax</a>.<br> <code>QueryParser</code> also takes analyzer as a last argument. This must be same analyzer as you used to index your text. </p> <p>The last thing you must know is a <code>TopScoreDocCollector.create</code> first parameter. It is just a number that represents how many results you want to collect. For example, if it is equal 100, Lucene will collect only first (by score) 100 results and drop the rest. This is just an act of optimization - you collect best results, and if you're not satisfied with it, you repeat search with a larger number. </p> <p>Finally, don't forget to close searcher and directory to not loose system resources:</p> <pre><code>searcher.close(); directory.close(); </code></pre> <p><strong>EDIT:</strong> Also see <a href="http://lucene.apache.org/java/3_0_1/api/demo/org/apache/lucene/demo/IndexFiles.html" rel="noreferrer">IndexFiles demo class</a> from <a href="http://www.apache.org/dyn/closer.cgi/lucene/java/" rel="noreferrer">Lucene 3.0 sources</a>.</p>
4,264,540
Grand Central Dispatch (GCD) with CoreData
<p>I'm using Grand Central Dispatch (GCD) in my application to do some heavy lifting. The application is using Core-Data for data storage purposes. Here's my scenario (along with relevant question):</p> <pre><code>dispatch_queue_t main_queue = dispatch_get_main_queue(); dispatch_queue_t request_queue = dispatch_queue_create("com.app.request", NULL); dispatch_async(request_queue, ^{ MyNSManagedObject *mObject = [self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; // … // &lt;heavy lifting&gt; // … // … // &lt;update mObject&gt; // … [self saveManagedObjectContext]; }); </code></pre> <p>As a result of <code>[self saveManagedObjectContext]</code>, <code>fetchResultsController</code> delegate methods are called automatically. Consequently, the UI updation logic kicks.</p> <p>Now my question is, do I need to use <code>main_queue</code> for <code>-saveManagedObjectContext</code>? Should I perform all operations on my <code>NSManagedObject</code> in <code>main_queue</code>? Some of the operations that update the <code>NSManagedObject</code> might take 2-3 seconds. Please advise.</p>
4,264,911
3
0
null
2010-11-24 07:55:02.77 UTC
44
2012-08-20 14:13:23.603 UTC
2011-09-16 00:06:02.79 UTC
user557219
null
null
49,739
null
1
22
iphone|core-data|objective-c-blocks|grand-central-dispatch
15,170
<p>As you probably know or have noticed you must perform UI operations on the main thread. As you mention it is when you save the UI update takes place. You can solve this by nesting a call to <code>dispatch_sync</code> on the main thread.</p> <pre><code>dispatch_queue_t main_queue = dispatch_get_main_queue(); dispatch_queue_t request_queue = dispatch_queue_create("com.app.request", NULL); __block __typeof__(self) blockSelf = self; dispatch_async(request_queue, ^{ MyNSManagedObject *mObject = [blockSelf.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; // update and heavy lifting... dispatch_sync(main_queue, ^{ [blockSelf saveManagedObjectContext]; }); }); </code></pre> <p><em>The use of</em> <code>blockSelf</code> <em>is to avoid creating accidentally reference cycles.</em> (<a href="http://www.mikeash.com/pyblog/friday-qa-2009-08-14-practical-blocks.html" rel="noreferrer">Practical blocks</a>)</p>
4,454,861
How do I edit a table in order to enable CASCADE DELETE?
<p>I have a table representing users. When a user is deleted I get: </p> <blockquote> <p>DELETE statement conflicted with the REFERENCE constraint</p> </blockquote> <p>Apparently, <code>CASCADE DELETE</code> is not as easy as I imagined in SQL Server, and the option needs to be added to the table.</p> <p>The problem is: I cannot figure out how to add the <code>CASCADE DELETE</code> option.</p> <p>I'm using: <strong>SQL Server 2008</strong>. Any ideas how to do this?</p>
4,454,994
3
0
null
2010-12-15 21:03:45.227 UTC
5
2016-03-09 08:46:09.177 UTC
2015-10-20 10:18:05.677 UTC
null
2,771,704
null
208,827
null
1
26
sql|sql-server|sql-server-2008|cascading-deletes
46,946
<p>Read this Microsoft article first. <a href="http://msdn.microsoft.com/en-us/library/ms186973.aspx" rel="noreferrer">Read Me</a>. I use the GUI during design so here is a picture of how it is selected in SSMS. <img src="https://i.stack.imgur.com/Y3cVQ.jpg" alt="alt text"> The syntax added to the foreign key is " ON DELETE CASCADE "</p>
4,483,972
Only select text directly in node, not in child nodes
<p>How does one retrieve the text in a node without selecting the text in the children?</p> <pre><code>&lt;div id="comment"&gt; &lt;div class="title"&gt;Editor's Description&lt;/div&gt; &lt;div class="changed"&gt;Last updated: &lt;/div&gt; &lt;br class="clear"&gt; Lorem ipsum dolor sit amet. &lt;/div&gt; </code></pre> <p>In other words, I want <code>Lorem ipsum dolor sit amet.</code> rather than <code>Editor's DescriptionLast updated: Lorem ipsum dolor sit amet.</code></p>
4,484,036
3
0
null
2010-12-19 16:50:23.633 UTC
15
2019-04-15 17:14:46.967 UTC
2019-04-15 17:14:46.967 UTC
user357812
81,785
null
81,785
null
1
47
xpath|xquery
27,412
<p>In the provided XML document:</p> <pre><code>&lt;div id="comment"&gt; &lt;div class="title"&gt;Editor's Description&lt;/div&gt; &lt;div class="changed"&gt;Last updated: &lt;/div&gt; &lt;br class="clear"&gt; Lorem ipsum dolor sit amet. &lt;/div&gt; </code></pre> <p>the top element <code>/div</code> has 4 children nodes that are text nodes. The first three of these four <code>text-node</code> children are <code>whitespace-only</code>. The last of these 4 <code>text-node</code> children is the one that is wanted.</p> <p><strong>Use</strong>:</p> <pre><code>/div/text()[last()] </code></pre> <p><strong>This is different from</strong>:</p> <pre><code>/div/text() </code></pre> <p>The latter may (depending on whether <code>whitespace-only</code> nodes are preserved by the XML parser) select all 4 text nodes, but you only want the last of them.</p> <p><strong>An alternative is</strong> (when you don't know exactly which <code>text-node</code> you want):</p> <pre><code>/div/text()[normalize-space()] </code></pre> <p>This selects all <code>text-node-children</code> of <code>/div</code> that are not <code>whitespace-only</code> text nodes.</p>
4,394,273
What's the difference between update and pull?
<p>Can someone clarify what's the exact difference between <em>update</em> and <em>pull</em> commands?</p> <p>Thanks.</p>
4,394,287
4
2
null
2010-12-09 02:17:47.417 UTC
10
2020-03-17 16:46:48.89 UTC
null
null
null
null
504,715
null
1
37
version-control|mercurial
29,932
<p>hg update : <a href="http://www.selenic.com/mercurial/hg.1.html#update" rel="noreferrer">http://www.selenic.com/mercurial/hg.1.html#update</a></p> <ul> <li>Update the repository's working directory (the "working copy") to the specified revision of the repository</li> </ul> <p>hg pull : <a href="http://www.selenic.com/mercurial/hg.1.html#pull" rel="noreferrer">http://www.selenic.com/mercurial/hg.1.html#pull</a></p> <ul> <li>Allows you to bring changes from a remote repository </li> </ul> <p>So when you do an hg pull, you bring changes to your repository which is under <code>.hg</code>. It will not reflect in your working directory.</p> <p>After that, when you do a <code>hg update</code>, the changes are brought to your working copy.</p> <pre><code>Your repo Remote Repo \ \ | hg pull | |-.hg &lt;-------------------------------- |-.hg | | --------------------------------&gt; | | hg update hg push | | | | |- working folder |- working folder </code></pre> <p>This is very usual confusion when coming from subversion like version control systems.</p> <p>In subversion : svn update bring the changes from central repo server to your working copy</p> <p>But in DVCSs , you have both a local repository and working copy. So update does exactly the same but pulls the changes from your local repo to local working copy.</p>
4,494,708
Using CSS selectors to access specific table rows with selenium
<p>If I have the following HTML:</p> <pre><code>&lt;tbody id="items"&gt; &lt;tr&gt;&lt;td&gt;Item 1&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Item 2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Item 3&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Item 4&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Item 5&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Item 6&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; </code></pre> <p>How would I use CSS selectors with Selenium to access Item 4(or really any item I wanted)?</p>
4,494,743
5
0
null
2010-12-20 22:42:04.713 UTC
4
2018-11-01 15:18:11.67 UTC
null
null
null
null
462,112
null
1
12
css|selenium|css-selectors
51,372
<p>You can use nth-child selector:</p> <pre><code>#items tr:nth-child(4) {color:#F00;} </code></pre> <p>Live example: <a href="https://jsfiddle.net/7ow15mv2/1/" rel="noreferrer">https://jsfiddle.net/7ow15mv2/1/</a></p> <p>But no idea if it works with Selenium.</p> <p>But according to docs it should.</p> <blockquote> <p>Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after). </p> </blockquote>
4,147,707
Python - mysqlDB, sqlite result as dictionary
<p>When I do someting like</p> <pre><code>sqlite.cursor.execute("SELECT * FROM foo") result = sqlite.cursor.fetchone() </code></pre> <p>I think have to remember the order the columns appear to be able to fetch them out, eg</p> <pre><code>result[0] is id result[1] is first_name </code></pre> <p>is there a way to return a dictionary? so I can instead just use result['id'] or similar?</p> <p>The problem with the numbered columns is, if you write your code then insert a column you might have to change the code eg result[1] for first_name might now be a date_joined so would have to update all the code...</p>
4,147,752
5
1
null
2010-11-10 18:23:21.84 UTC
13
2019-10-02 18:22:43.93 UTC
2017-12-13 21:18:12.71 UTC
null
42,223
null
133,498
null
1
22
python|mysql|sqlite|dictionary|dataformat
16,784
<p>David Beazley has a nice example of this in his <a href="https://rads.stackoverflow.com/amzn/click/com/0672329786" rel="nofollow noreferrer" rel="nofollow noreferrer">Python Essential Reference</a>.<br> I don't have the book at hand, but I think his example is something like this:</p> <pre><code>def dict_gen(curs): ''' From Python Essential Reference by David Beazley ''' import itertools field_names = [d[0].lower() for d in curs.description] while True: rows = curs.fetchmany() if not rows: return for row in rows: yield dict(itertools.izip(field_names, row)) </code></pre> <p>Sample usage:</p> <pre><code>&gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; conn = sqlite3.connect(':memory:') &gt;&gt;&gt; c = conn.cursor() &gt;&gt;&gt; c.execute('create table test (col1,col2)') &lt;sqlite3.Cursor object at 0x011A96A0&gt; &gt;&gt;&gt; c.execute("insert into test values (1,'foo')") &lt;sqlite3.Cursor object at 0x011A96A0&gt; &gt;&gt;&gt; c.execute("insert into test values (2,'bar')") &lt;sqlite3.Cursor object at 0x011A96A0&gt; # `dict_gen` function code here &gt;&gt;&gt; [r for r in dict_gen(c.execute('select * from test'))] [{'col2': u'foo', 'col1': 1}, {'col2': u'bar', 'col1': 2}] </code></pre>
4,584,089
What is the function of the push / pop instructions used on registers in x86 assembly?
<p>When reading about assembler I often come across people writing that they <em>push</em> a certain register of the processor and <em>pop</em> it again later to restore it's previous state.</p> <ul> <li>How can you push a register? Where is it pushed on? Why is this needed?</li> <li>Does this boil down to a single processor instruction or is it more complex? </li> </ul>
4,584,131
5
2
null
2011-01-03 11:36:03.06 UTC
57
2022-02-06 12:35:51.933 UTC
2021-12-12 06:31:06.167 UTC
null
224,132
null
561,174
null
1
131
assembly|x86|terminology|stack-memory|stack-pointer
389,601
<p><em>pushing</em> a value (not necessarily stored in a register) means writing it to the stack.</p> <p><em>popping</em> means restoring whatever is on top of the stack <em>into</em> a register. Those are basic instructions:</p> <pre><code>push 0xdeadbeef ; push a value to the stack pop eax ; eax is now 0xdeadbeef ; swap contents of registers push eax mov eax, ebx pop ebx </code></pre>
4,591,889
Get default value of an input using jQuery
<pre><code>$(".box_yazi2").each(function () { var default_value = this.value; $(this).css('color', '#555'); // this could be in the style sheet instead $(this).focus(function () { if (this.value == default_value) { this.value = ''; $(this).css('color', '#000'); } }); $(this).blur(function () { if (this.value == '') { $(this).css('color', '#555'); this.value = default_value; } }); }); </code></pre> <p>This function of default value of input doesnt work in FF, but perfectly works in IE and ofcourse the input itself looks like this:</p> <pre><code>&lt;input type="text" class="box_yazi2" id="konu" name="konu" value="Boş" /&gt; </code></pre>
4,591,938
6
5
null
2011-01-04 08:50:34.367 UTC
2
2016-03-18 15:27:00.623 UTC
2015-01-23 14:08:42.943 UTC
null
87,015
null
532,309
null
1
19
javascript|jquery|html|input|default-value
81,522
<p>The solution is quite easy; you have an extra <code>});</code> in your code (thanks @ Box9).</p> <p>I would encourage you to reuse the variable and not create dozens of jQuery objects.</p> <p>I've changed your example to <code>background-color</code> but it will work.</p> <pre><code>$('.box_yazi2').each(function(index, element) { var $element = $(element); var defaultValue = $element.val(); $element.css('background-color', '#555555'); $element.focus(function() { var actualValue = $element.val(); if (actualValue == defaultValue) { $element.val(''); $element.css('background-color', '#3399FF'); } }); $element.blur(function() { var actualValue = $element.val(); if (!actualValue) { $element.val(defaultValue); $element.css('background-color', '#555555'); } }); }); </code></pre> <p><a href="http://jsfiddle.net/nBYLP/" rel="nofollow noreferrer">demo</a></p>
4,726,768
Function returning a lambda expression
<p>I wonder if it's possible to write a function that returns a lambda function in C++11. Of course one problem is how to declare such function. Each lambda has a type, but that type is not expressible in C++. I don't think this would work:</p> <pre><code>auto retFun() -&gt; decltype ([](int x) -&gt; int) { return [](int x) { return x; } } </code></pre> <p>Nor this:</p> <pre><code>int(int) retFun(); </code></pre> <p>I'm not aware of any automatic conversions from lambdas to, say, pointers to functions, or some such. Is the only solution handcrafting a function object and returning it? </p>
4,727,021
6
6
null
2011-01-18 17:01:00.303 UTC
27
2020-07-27 17:33:55.007 UTC
2016-06-29 10:15:06.957 UTC
null
3,919,155
null
90,088
null
1
101
c++|function|c++11|lambda
42,676
<p>You don't need a handcrafted function object, just use <code>std::function</code>, to which lambda functions are convertible:</p> <p>This example returns the integer identity function:</p> <pre><code>std::function&lt;int (int)&gt; retFun() { return [](int x) { return x; }; } </code></pre>
4,205,317
Capture keyboardinterrupt in Python without try-except
<p>Is there some way in Python to capture <code>KeyboardInterrupt</code> event without putting all the code inside a <code>try</code>-<code>except</code> statement?</p> <p>I want to cleanly exit without trace if user presses <kbd><strong>Ctrl</strong></kbd>+<kbd><strong>C</strong></kbd>.</p>
4,205,386
6
0
null
2010-11-17 14:24:51.997 UTC
40
2020-07-09 14:34:16.213 UTC
2018-09-16 12:19:23.643 UTC
null
3,702,377
null
483,265
null
1
115
python|try-catch|keyboardinterrupt
134,951
<p>Yes, you can install an interrupt handler using the module <a href="https://docs.python.org/3/library/signal.html" rel="noreferrer">signal</a>, and wait forever using a <a href="https://docs.python.org/3/library/threading.html#threading.Event" rel="noreferrer">threading.Event</a>:</p> <pre><code>import signal import sys import time import threading def signal_handler(signal, frame): print('You pressed Ctrl+C!') sys.exit(0) signal.signal(signal.SIGINT, signal_handler) print('Press Ctrl+C') forever = threading.Event() forever.wait() </code></pre>
4,830,900
How do I find the index of an item in a vector?
<p>Any ideas what <code>????</code> should be? Is there a built in? What would be the best way to accomplish this task?</p> <pre><code>(def v ["one" "two" "three" "two"]) (defn find-thing [ thing vectr ] (????)) (find-thing "two" v) ; ? maybe 1, maybe '(1,3), actually probably a lazy-seq </code></pre>
4,831,043
9
2
null
2011-01-28 16:56:57.723 UTC
17
2021-04-14 22:18:50.453 UTC
2017-06-30 16:09:23.643 UTC
null
254,837
null
254,837
null
1
90
clojure
63,679
<p>Built-in:</p> <pre><code>user&gt; (def v ["one" "two" "three" "two"]) #'user/v user&gt; (.indexOf v "two") 1 user&gt; (.indexOf v "foo") -1 </code></pre> <p>If you want a lazy seq of the indices for all matches:</p> <pre><code>user&gt; (map-indexed vector v) ([0 "one"] [1 "two"] [2 "three"] [3 "two"]) user&gt; (filter #(= "two" (second %)) *1) ([1 "two"] [3 "two"]) user&gt; (map first *1) (1 3) user&gt; (map first (filter #(= (second %) "two") (map-indexed vector v))) (1 3) </code></pre>
4,674,623
Why do we have to normalize the input for an artificial neural network?
<p>Why do we have to normalize the input for a neural network?</p> <p>I understand that sometimes, when for example the input values are non-numerical a certain transformation must be performed, but when we have a numerical input? Why the numbers must be in a certain interval?</p> <p>What will happen if the data is not normalized?</p>
4,674,770
10
1
null
2011-01-12 22:16:11.363 UTC
58
2021-02-20 00:04:37.75 UTC
2021-02-20 00:04:37.75 UTC
null
4,685,471
null
481,828
null
1
180
machine-learning|neural-network|normalization
129,801
<p>It's explained well <a href="http://www.faqs.org/faqs/ai-faq/neural-nets/part2/" rel="noreferrer">here</a>.</p> <blockquote> <p>If the input variables are combined linearly, as in an MLP [multilayer perceptron], then it is rarely strictly necessary to standardize the inputs, at least in theory. The reason is that any rescaling of an input vector can be effectively undone by changing the corresponding weights and biases, leaving you with the exact same outputs as you had before. However, there are a variety of practical reasons why standardizing the inputs can make training faster and reduce the chances of getting stuck in local optima. Also, weight decay and Bayesian estimation can be done more conveniently with standardized inputs. </p> </blockquote>
14,729,475
Can I make a Java HttpServer threaded/process requests in parallel?
<p>I have built a simple HttpServer following tutorials i have found online, using Sun's lightweight HttpServer.</p> <p>Basically the main function looks like this:</p> <pre><code>public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0); //Create the context for the server. server.createContext("/", new BaseHandler()); server.setExecutor(null); // creates a default executor server.start(); } </code></pre> <p>And I have implemented the BaseHandler Interface's method to process the Http request and return a response.</p> <pre><code>static class BaseHandler implements HttpHandler { //Handler method public void handle(HttpExchange t) throws IOException { //Implementation of http request processing //Read the request, get the parameters and print them //in the console, then build a response and send it back. } } </code></pre> <p>I have also created a Client that sends multiple requests via threads. Each thread sends the following request to the server:</p> <blockquote> <p>http://localhost:8000/[context]?int="+threadID</p> </blockquote> <p>On Each client run, The requests seem to arrive in different order to the server, but they are served in a serial manner. </p> <p>What i wish to acomplish is for the requests to be processed in a parallel manner if that is possible.</p> <p>Is it possible, for example, to run each handler in a seperate thread, and if so, is it a good thing to do.</p> <p>Or should i just drop using Sun's lightweight server altogether and focus an building something from scratch?</p> <p>Thanks for any help.</p>
14,729,886
2
4
null
2013-02-06 12:47:35.233 UTC
8
2019-02-25 13:55:37.787 UTC
null
null
null
null
1,985,558
null
1
11
java|httpserver
18,754
<p>As you can see in <a href="http://www.docjar.com/html/api/sun/net/httpserver/ServerImpl.java.html" rel="noreferrer">ServerImpl</a>, the default executor just "run" the task :</p> <pre><code> 157 private static class DefaultExecutor implements Executor { 158 public void execute (Runnable task) { 159 task.run(); 160 } 161 } </code></pre> <p>you must provide a real executor for your httpServer, like that :</p> <pre><code>server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool()); </code></pre> <p>and your server will run in parallel. Carefull, this is a non-limited Executor, see <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)" rel="noreferrer">Executors.newFixedThreadPool</a> to limit the number of Thread.</p>
2,928,325
What is the definition of a Service object?
<p>I've been working a lot with PHP.</p> <p>But recently I was assigned some work which uses Java. In PHP I used to do a lot of Singleton object but this pattern has not the same signification in Java that it has in PHP.</p> <p>So I wanted to go for an utility class (a class with static method) but my chief doesn't like this kind of classes and ask me to go for services object. So my guess was that a service object is just a class with a constructor that implement some public methods...</p> <p>Am I right?</p>
2,928,521
2
0
null
2010-05-28 10:50:05.363 UTC
10
2020-07-31 04:33:26.18 UTC
2020-07-31 04:33:26.18 UTC
null
214,143
null
352,808
null
1
31
java|design-patterns|terminology
16,473
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0321125215" rel="noreferrer" rel="nofollow noreferrer">Domain-Driven Design</a> defines a Service as:</p> <blockquote> <p>A SERVICE is an operation offered as an interface that stands alone in the model, without encapsulating state... [p. 105]</p> </blockquote> <p>Yes, it's a class with public methods, but in addition to that, it implements an interface that exposes those methods. At its core, <strong>the Service is the interface</strong> - the class that implements it is just an implementation detail.</p>
3,156,778
No matching function for call to operator new
<p>I'm trying to wrap a class from a library I'm using in Lua. Specifially, I'm trying to wrap the color class from SFML. The full source for the color class can be seen <a href="http://www.sfml-dev.org/documentation/1.6/Color_8cpp-source.htm" rel="noreferrer">here</a> and <a href="http://www.sfml-dev.org/documentation/1.6/Color_8hpp-source.htm" rel="noreferrer">here</a>. </p> <p>This is the function that's that I'm failing in. </p> <pre><code>int SFColor_new(lua_State* L) { // omitting part where I set r, g, b, and a new (lua_newuserdata(L, sizeof(Color))) Color(r, g, b, a); // Line 47 luaL_getmetatable(L, LuaInfo&lt;Color&gt;::myMetaTableName); lua_setmetatable(L, -2); return 1; } </code></pre> <p>And this is the error</p> <pre><code>LuaSFMLColor.cpp: In function ‘int ag::SFColor_new(lua_State*)’: LuaSFMLColor.cpp:47: error: no matching function for call to ‘operator new(unsigned int, void*)’ &lt;built-in&gt;:0: note: candidates are: void* operator new(unsigned int) make: *** [game] Error 1 </code></pre> <p>I do similar things in a few other places without running into this error, so I'm not sure what would be causing it. Looking at the Color's source code I don't see anything weird or out of the ordinary, and I've run out of ideas. I've also tried using the default constructor (i.e. no arguments) and then just setting the value afterward, but that didn't do any good either. </p>
3,156,822
2
1
null
2010-07-01 10:05:17.03 UTC
5
2022-09-11 12:36:45.22 UTC
2010-07-02 00:40:10.27 UTC
null
63,791
null
63,791
null
1
43
c++|new-operator
17,998
<p>To use the standard placement form of <code>new</code> you have to <code>#include &lt;new&gt;</code>.</p> <p>The form of <code>new</code> that you are using requires a declaration of <code>void* operator new(std::size_t, void*) throw();</code>.</p> <p>You don't have to <code>#include &lt;new&gt;</code> to use non-placement <code>new</code>.</p>
1,504,261
java override during object creation
<p>in the following java code a JButton is created but at the same time one of its methods gets overridden. Qestion: is there a name for overriding in this way while creating the object?</p> <p>the code:</p> <pre><code> JButton myButton; myButton = new JButton ("ok"){ @Override public void setText(String text) { super.setText(text +", delete"); } </code></pre> <p>the jbutton's label is now "ok, delete"</p>
1,504,271
1
0
null
2009-10-01 14:21:59.637 UTC
9
2013-01-20 18:12:29.81 UTC
2013-01-20 18:12:29.81 UTC
karl
1,592,796
karl
null
null
1
20
java|overriding|instantiation
10,419
<p>That's an anonymous class. From <a href="http://hell.org.ua/Docs/oreilly/javaenterprise/jnut/ch03_12.htm" rel="noreferrer">Java in a Nutshell</a></p> <blockquote> <p>An anonymous class is a local class without a name. An anonymous class is defined and instantiated in a single succinct expression using the new operator. While a local class definition is a statement in a block of Java code, an anonymous class definition is an expression, which means that it can be included as part of a larger expression, such as a method call. When a local class is used only once, consider using anonymous class syntax, which places the definition and use of the class in exactly the same place.</p> </blockquote> <p>It's a common means of providing a specialisation of a base class without explicitly defining a new class via the <code>class</code> expression.</p>
27,070,269
Ripple effect for lollipop views
<p>I have been developing an app for Lollipop (API 21). </p> <p>When I change the <code>Button</code> color to something, the ripple effect doesn't works. </p> <p>I found some third party libraries for the ripple effect, but I want to do this with standard API. </p> <p>This <a href="https://stackoverflow.com/questions/24607339/lollipop-rippledrawable-vs-selector-for-pre-lollipop">answer</a> didn't help either.</p> <p>XML:</p> <pre><code>&lt;Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Button" android:id="@+id/button" android:layout_below="@+id/textView" android:background="@android:color/holo_blue_bright" android:layout_alignParentStart="true" android:layout_marginTop="76dp" /&gt; </code></pre>
27,071,381
4
0
null
2014-11-21 21:00:51.427 UTC
8
2016-10-04 16:01:35.2 UTC
2017-05-23 11:53:49.037 UTC
null
-1
null
2,203,061
null
1
20
android|material-design
21,211
<p>You have to set your button's background to a RippleDrawable which you can define in XML. (I'll name it <code>holo_blue_ripple.xml</code>)</p> <pre><code>&lt;ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@android:color/white"&gt; &lt;!-- ripple color --&gt; &lt;item android:drawable="@android:color/holo_blue_bright"/&gt; &lt;!-- normal color --&gt; &lt;/ripple&gt; </code></pre> <p>Then reference it with <code>android:background="@drawable/holo_blue_ripple"</code>.</p>
55,897,065
Terraform: Validation error ... Member must satisfy regular expression pattern: arn:aws:iam::
<p>I'm trying to stream rds through kinesis data stream but it is giving me this error:</p> <blockquote> <p>botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the PutRecord operation: 1 validation error detected: Value 'arn:aws:kinesis:us-west-2:xxxxxxxxxx:stream/rds-temp-leads-stream' at 'streamName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+</p> </blockquote> <p>What can I do to fix this?</p> <pre><code> import json import boto3 from datetime import datetime from pymysqlreplication import BinLogStreamReader from pymysqlreplication.row_event import ( DeleteRowsEvent, UpdateRowsEvent, WriteRowsEvent, ) class DateTimeEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, datetime): return o.isoformat() return json.JSONEncoder.default(self, o) def main(): mysql = { "host": "", "port":, "user": "", "passwd": "", "db": ""} kinesis = boto3.client("kinesis", region_name = 'us-west-2') stream = BinLogStreamReader( connection_settings = mysql, server_id=100, blocking = True, log_file='mysql-bin.000003', resume_stream=True, only_events=[DeleteRowsEvent, WriteRowsEvent, UpdateRowsEvent]) for binlogevent in stream: for row in binlogevent.rows: print row event = {"schema": binlogevent.schema, "table": binlogevent.table, "type": type(binlogevent).__name__, "row": row } kinesis.put_record(StreamName="jhgjh", Data=json.dumps(event, cls=DateTimeEncoder), PartitionKey="default") #print json.dumps(event) if __name__ == "__main__": main() </code></pre>
55,897,749
3
0
null
2019-04-29 04:41:59.203 UTC
4
2021-10-04 02:04:11.137 UTC
2021-10-04 02:04:11.137 UTC
null
10,907,864
null
7,806,643
null
1
17
python|amazon-rds|amazon-kinesis
45,880
<p>remove 'arn:aws:kinesis:us-west-2:xxxxxxxxxx:stream/rds-temp-leads-stream' this from stream name. Just put the name of stream there like "rds-temp-leads-stream"</p>
38,717,543
How do I filter date range in DataTables?
<p>I have a large dataTable which contains ride information. Every row has a start datetime and an end datetime of the following format(yyyy-mm-dd HH:mm:ss). How can I use a datepicker for setting a filter range in dataTables? I want to have a datepicker which only selects a day and not the time. I've searched everywhere for the proper answer but I couldn't find it. Thanks in advance for helping.</p> <p>For example I want to see all rows of July by selecting (01-07-2016 - 31-07-2016).</p>
38,718,922
7
1
null
2016-08-02 10:09:34.07 UTC
18
2021-02-16 22:17:12.76 UTC
2016-08-02 11:15:03.953 UTC
null
6,666,514
null
3,397,167
null
1
25
javascript|datetime|filter|datatables
145,973
<p>Here is <code>DataTable</code> with Single <code>DatePicker</code> as "from" Date Filter</p> <p><kbd><a href="http://plnkr.co/edit/8z7cojpJoCSJXRn9prNj?p=preview" rel="noreferrer">LiveDemo</a></kbd></p> <p>Here is <code>DataTable</code> with Two <code>DatePickers</code> for DateRange (To and From) Filter</p> <p><kbd><a href="http://plnkr.co/edit/mdeEYoZtnvpfHCdtSxDP?p=preview" rel="noreferrer">LiveDemo</a></kbd></p>
27,768,033
ui router - nested views with shared controller
<p>I have an abstract parent view that is meant to share a controller with its nested views.</p> <pre><code>.state('edit', { abstract: true, url: '/home/edit/:id', templateUrl: 'app/templates/editView.html', controller: 'editController' }) .state('edit.details', { url: '/details', templateUrl: 'app/templates/editDetailsView.html' }) .state('edit.info', { url: '/info', templateUrl: 'app/templates/editInfoView.html' }) </code></pre> <p>The routing works as expected.</p> <p>The problem is that when I update a <code>$scope</code> variable from one of the nested views, the change is not reflected in the view. When I do the same from the parent view, it works fine. This is not situation that requires an <code>$apply</code>.</p> <p>My guess is that a new instance of <code>editController</code> is being created for each view, but I'm not sure why or how to fix it.</p>
27,768,108
4
0
null
2015-01-04 17:04:08.63 UTC
13
2018-04-04 19:57:51.493 UTC
null
null
null
null
2,124,351
null
1
32
angularjs|angular-ui-router
40,563
<p>The issue here would be related to this Q &amp; A: <a href="https://stackoverflow.com/q/27696612/1679310">How do I share $scope data between states in angularjs ui-router?</a>.</p> <p>The way how to solve it is hidden in the:</p> <h3><a href="https://github.com/angular/angular.js/wiki/Understanding-Scopes" rel="nofollow noreferrer">Understanding Scopes</a></h3> <blockquote> <p>In AngularJS, a child scope normally prototypically inherits from its parent scope.<br> ...</p> <p>Having a '.' in your models will ensure that prototypal inheritance is in play. </p> </blockquote> <pre><code>// So, use &lt;input type="text" ng-model="someObj.prop1"&gt; // rather than &lt;input type="text" ng-model="prop1"&gt;. </code></pre> <p>And also this</p> <h3><a href="https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#scope-inheritance-by-view-hierarchy-only" rel="nofollow noreferrer">Scope Inheritance by View Hierarchy Only</a></h3> <blockquote> <p>Keep in mind that scope properties only inherit down the state chain if the views of your states are nested. Inheritance of scope properties has nothing to do with the nesting of your states and everything to do with the nesting of your views (templates).</p> <p>It is entirely possible that you have nested states whose templates populate ui-views at various non-nested locations within your site. In this scenario you cannot expect to access the scope variables of parent state views within the views of children states.</p> </blockquote> <p>Having that we should do this in edit Controller</p> <pre><code>controller('editController', function ($scope) { $scope.Model = $scope.Model || {SomeProperty : "xxx"}; }) </code></pre> <p>And we can even reuse that <code>controller: 'editController'</code> <em>(we can do not have to, because the $scope.Model will be there - thanks to inheritance)</em></p> <pre><code>.state('edit', { abstract: true, url: '/home/edit/:id', templateUrl: 'app/templates/editView.html', controller: 'editController' }) .state('edit.details', { url: '/details', templateUrl: 'app/templates/editDetailsView.html', controller: 'editController' }) .state('edit.info', { url: '/info', templateUrl: 'app/templates/editInfoView.html', controller: 'editController' }) </code></pre> <p>Now, the same controller will be instantiated many times (parent all the children) but the <code>$scope.Model</code> will be initiated only once (inside of parent) and available everywhere</p> <p>Check this <a href="http://plnkr.co/edit/cqx77pb4CDI2TXyESYGN?p=preview" rel="nofollow noreferrer">similar working example here</a></p>
35,326,115
Laravel5 how to pass array to view
<p>I am confuse as how to pass variable from controller to view. I know there is a lot about this already on stockoverflow but unable to find one that works, please point me in the right direction. Thank you. </p> <p>CONTROLLER</p> <pre><code> class StoreController extends Controller { public function index() { $store = Store::all(); // got this from database model return view('store', $store); } { </code></pre> <p>VIEW</p> <pre><code>// try a couple of differnt things nothing works print_r($store); print_r($store[0]-&gt;id); print_r($id); </code></pre>
35,326,267
9
0
null
2016-02-10 21:19:09.167 UTC
4
2021-01-05 18:10:21.23 UTC
null
null
null
null
1,975,187
null
1
19
laravel
75,008
<pre><code>public function index() { $store = Store::all(); // got this from database model return view('store')-&gt;with('store', $store); } </code></pre> <p>You've three options in general. </p> <ol> <li><p><code>return view('store')-&gt;with('store', $store);</code> </p></li> <li><p><code>return view('store')-&gt;withStore($store);</code> </p></li> <li><p><code>return view('store')-&gt;with(compact('store'));</code> </p></li> </ol> <p>1.Creates a variable named <code>store</code> which will be available in your <code>view</code> and stores the value in the variable <code>$store</code> in it. </p> <p>2.Shorthand for the above one. </p> <p>3.Also a short hand and it creates the same variable name as of the value passing one. </p> <p>Now in your <code>view</code> you can access this variable using</p> <p><code>{{ $store-&gt;name }}</code></p> <p>it will be same for all 3 methods. </p>
29,401,626
How do I return a reference to something inside a RefCell without breaking encapsulation?
<p>I have a struct that has inner mutability.</p> <pre><code>use std::cell::RefCell; struct MutableInterior { hide_me: i32, vec: Vec&lt;i32&gt;, } struct Foo { //although not used in this particular snippet, //the motivating problem uses interior mutability //via RefCell. interior: RefCell&lt;MutableInterior&gt;, } impl Foo { pub fn get_items(&amp;self) -&gt; &amp;Vec&lt;i32&gt; { &amp;self.interior.borrow().vec } } fn main() { let f = Foo { interior: RefCell::new(MutableInterior { vec: Vec::new(), hide_me: 2, }), }; let borrowed_f = &amp;f; let items = borrowed_f.get_items(); } </code></pre> <p>Produces the error:</p> <pre class="lang-none prettyprint-override"><code>error[E0597]: borrowed value does not live long enough --&gt; src/main.rs:16:10 | 16 | &amp;self.interior.borrow().vec | ^^^^^^^^^^^^^^^^^^^^^^ temporary value does not live long enough 17 | } | - temporary value only lives until here | note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 15:5... --&gt; src/main.rs:15:5 | 15 | / pub fn get_items(&amp;self) -&gt; &amp;Vec&lt;i32&gt; { 16 | | &amp;self.interior.borrow().vec 17 | | } | |_____^ </code></pre> <p>The problem is that I can't have a function on <code>Foo</code> that returns a borrowed <code>vec</code>, because the borrowed <code>vec</code> is only valid for the lifetime of the <code>Ref</code>, but the <code>Ref</code> goes out of scope immediately.</p> <p>I think the <code>Ref</code> must stick around <a href="http://doc.rust-lang.org/std/cell/struct.RefCell.html" rel="noreferrer">because</a>:</p> <blockquote> <p><code>RefCell&lt;T&gt;</code> uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can claim temporary, exclusive, mutable access to the inner value. Borrows for <code>RefCell&lt;T&gt;</code>s are tracked 'at runtime', unlike Rust's native reference types which are entirely tracked statically, at compile time. Because <code>RefCell&lt;T&gt;</code> borrows are dynamic it is possible to attempt to borrow a value that is already mutably borrowed; when this happens it results in task panic.</p> </blockquote> <p>Now I could instead write a function like this that returns the entire interior:</p> <pre><code>pub fn get_mutable_interior(&amp;self) -&gt; std::cell::Ref&lt;MutableInterior&gt;; </code></pre> <p>However this potentially exposes fields (<code>MutableInterior.hide_me</code> in this example) that are really private implementation details to <code>Foo</code>.</p> <p>Ideally I just want to expose the <code>vec</code> itself, potentially with a guard to implement the dynamic borrowing behavior. Then callers do not have to find out about <code>hide_me</code>.</p>
29,401,865
3
0
null
2015-04-01 22:02:00.03 UTC
14
2018-12-18 17:54:46.987 UTC
2018-12-18 17:54:46.987 UTC
null
493,729
null
116,834
null
1
48
rust|encapsulation|contravariance|mutability|interior-mutability
9,555
<p>You can create a new struct similar to the <code>Ref&lt;'a,T&gt;</code> guard returned by <code>RefCell::borrow()</code>, in order to wrap this <code>Ref</code> and avoid having it going out of scope, like this:</p> <pre><code>use std::cell::Ref; struct FooGuard&lt;'a&gt; { guard: Ref&lt;'a, MutableInterior&gt;, } </code></pre> <p>then, you can implement the <code>Deref</code> trait for it, so that it can be used as if it was a <code>&amp;Vec&lt;i32&gt;</code>:</p> <pre><code>use std::ops::Deref; impl&lt;'b&gt; Deref for FooGuard&lt;'b&gt; { type Target = Vec&lt;i32&gt;; fn deref(&amp;self) -&gt; &amp;Vec&lt;i32&gt; { &amp;self.guard.vec } } </code></pre> <p>after that, update your <code>get_items()</code> method to return a <code>FooGuard</code> instance:</p> <pre><code>impl Foo { pub fn get_items(&amp;self) -&gt; FooGuard { FooGuard { guard: self.interior.borrow(), } } } </code></pre> <p>and <code>Deref</code> does the magic:</p> <pre><code>fn main() { let f = Foo { interior: RefCell::new(MutableInterior { vec: Vec::new(), hide_me: 2, }), }; let borrowed_f = &amp;f; let items = borrowed_f.get_items(); let v: &amp;Vec&lt;i32&gt; = &amp;items; } </code></pre>
45,163,256
How to format numbers as percentage values in JavaScript?
<p>Was using ExtJS for formatting numbers to percentage earlier. Now as we are not using ExtJS anymore same has to be accomplished using normal JavaScript.</p> <p>Need a method that will take number and format (usually in %) and convert that number to that format. </p> <pre><code>0 -&gt; 0.00% = 0.00% 25 -&gt; 0.00% = 25.00% 50 -&gt; 0.00% = 50.00% 150 -&gt; 0.00% = 150.00% </code></pre>
45,163,358
6
0
null
2017-07-18 09:52:22.36 UTC
4
2022-01-05 20:50:40.113 UTC
null
null
null
null
2,160,616
null
1
37
javascript
71,708
<p>Here is what you need.</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-js lang-js prettyprint-override"><code>var x=150; console.log(parseFloat(x).toFixed(2)+"%"); x=0; console.log(parseFloat(x).toFixed(2)+"%"); x=10 console.log(parseFloat(x).toFixed(2)+"%");</code></pre> </div> </div> </p>
64,500,342
Creating requirements.txt in pip compatible format in a conda virtual environment
<p>I have created a conda virtual environment on a Windows 10 PC to work on a project. To install the required packages and dependencies, I am using <code>conda install &lt;package&gt;</code> instead of <code>pip install &lt;package&gt;</code> as per the best practices mentioned in <a href="https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#using-pip-in-an-environment" rel="noreferrer">https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#using-pip-in-an-environment</a></p> <p>In order to distribute my software, I choose to create an environment.yml and a requirements.txt file targeting the conda and non-conda users respectively. I am able to export the current virtual environment into a yml file, so the conda users are taken care of. But, for the non-conda users to be able to replicate the same environment, I need to create and share the requirements.txt file. This file can be created using <code>conda list --export &gt; requirements.txt</code> but this format is not compatible with pip and other users can't use <code>pip install -r requirements.txt</code> on their systems.</p> <p>Using <code>pip freeze &gt; requiremens.txt</code> is a solution that is mentioned <a href="https://stackoverflow.com/questions/48787250/set-up-virtualenv-using-a-requirements-txt-generated-by-conda">here</a> and <a href="https://stackoverflow.com/questions/50777849/from-conda-create-requirements-txt-for-pip3">here</a>. This means that non-conda users can simply execute <code>pip install -r requirements.txt</code> inside a virtual environment which they may create using virtualenv in the absence of conda.</p> <p>However, if you generate a requiremets.txt file in the above style, you will end up with a requirements.txt file that has symbolic links. This is because we tried to create a requirements.txt file for packages that are installed using <code>conda install</code> and not <code>pip install</code>. For example, the requirements.txt file that I generated in a similar fashion looks like this.</p> <pre><code>certifi==2020.6.20 cycler==0.10.0 kiwisolver==1.2.0 matplotlib @ file:///C:/ci/matplotlib-base_1603355780617/work mkl-fft==1.2.0 mkl-random==1.1.1 mkl-service==2.3.0 numpy @ file:///C:/ci/numpy_and_numpy_base_1596215850360/work olefile==0.46 pandas @ file:///C:/ci/pandas_1602083338010/work Pillow @ file:///C:/ci/pillow_1602770972588/work pyparsing==2.4.7 python-dateutil==2.8.1 pytz==2020.1 sip==4.19.13 six==1.15.0 tornado==6.0.4 wincertstore==0.2 </code></pre> <p>These symbolic links will lead to errors when this file is used to install the dependencies.</p> <p>Steps I took that landed me to the above requirements.txt file:</p> <ol> <li>Created a new conda virtual environment using <code>conda create -n myenv python=3.8</code></li> <li>Activated the newly created conda virtual environment using <code>conda activate myenv</code></li> <li>Installed pip using <code>conda install pip</code></li> <li>Installed pandas using <code>conda intall pandas</code></li> <li>Installed matplotlib using <code>conda install matplotlib</code></li> <li>generated a pip compatible requrements.txt file using <code>pip freeze &gt; requirements.txt</code></li> </ol> <p>So, my question is how do you stick to the best practice of using <code>conda install</code> instead of <code>pip install</code> while still being able to distribute your software package to both conda and non-conda users?</p>
64,501,566
2
0
null
2020-10-23 12:48:45.99 UTC
8
2022-08-05 15:22:49.747 UTC
2020-10-23 13:14:08.167 UTC
null
14,477,880
null
14,477,880
null
1
9
python|pip|conda|requirements.txt
18,217
<p>The best solution I've found for the above is the combination I will describe below. For <code>conda</code>, I would first export the environment list as <code>environment.yml</code> and omit the package build numbers, which is often what makes it hard to reproduce the environment on another OS:</p> <pre><code>conda env export &gt; environment.yml --no-builds </code></pre> <p>Output:</p> <pre class="lang-sh prettyprint-override"><code>name: myenv channels: - defaults - conda-forge dependencies: - blas=1.0 - ca-certificates=2020.10.14 - certifi=2020.6.20 ... </code></pre> <p>For <code>pip</code>, what you describe above is apparently a <a href="https://github.com/pypa/pip/issues/8176" rel="noreferrer">well-known issue</a> in more recent versions of pip. The workaround to get a &quot;clean&quot; <code>requirements.txt</code> file, is to export as such:</p> <pre><code>pip list --format=freeze &gt; requirements.txt </code></pre> <p>Output:</p> <pre class="lang-sh prettyprint-override"><code>certifi==2020.6.20 cycler==0.10.0 kiwisolver==1.2.0 matplotlib==3.3.2 mkl-fft==1.2.0 ... </code></pre> <p>Notice that the above are different between <code>pip</code> and <code>conda</code> and that is most likely because <code>conda</code> is more generic than <code>pip</code> and includes not only Python packages.</p> <p>Personally, I have found that for distributing a package, it is perhaps more concise to determine the minimum set of packages required and their versions by inspecting your code (what imports do you make?), instead of blindly exporting the full <code>pip</code> or <code>conda</code> lists, which might end up (accidentally or not) including packages that are not really necessary to use the package.</p>
32,087,809
How to change bottom layout constraint in iOS, Swift
<p>I have scroll view as @IBOutlet</p> <pre><code>@IBOutlet weak var mainScrollView: UIScrollView! </code></pre> <p>I want to change the </p> <pre><code>"Bottom space to: Bottom Layout Guide" </code></pre> <p>constraint programmatically.</p> <pre><code>First Item : Bottom Layout Guide.Top Relation : Equal Second Item: Scroll View.Bottom Constant: 0 -&gt; 50 // (I want to change this programmatically) Priority: 1000 Multiplier: 1 </code></pre> <p>How can I do this?</p>
32,087,869
3
0
null
2015-08-19 06:17:08.007 UTC
8
2015-08-19 06:30:10.117 UTC
null
null
null
null
4,582,207
null
1
18
ios|xcode|swift|storyboard|nslayoutconstraint
38,768
<p>Take the constraint as <code>IBOutlet</code> of <code>NSLayoutConstraint</code>.</p> <p><img src="https://i.stack.imgur.com/gtitj.png" alt="enter image description here"></p> <p>Set the constraint outlets and change <code>constant</code> value by :</p> <pre><code>self.sampleConstraint.constant = 20 self.view.layoutIfNeeded() </code></pre>
27,945,031
OpenID Connect delegation with Google now that they are deprecating their OpenID2 provider?
<p>For years I have used OpenID delegation to log in to Stack Overflow (among other sites) using my own URI as OpenID but having Google handle the authentication. I use the technique described in <a href="https://stackoverflow.com/questions/2541526/delegate-openid-to-google-not-google-apps">this Stack Overflow question</a>; so, my custom OpenID <a href="http://tupelo-schneck.org/robert" rel="nofollow noreferrer">http://tupelo-schneck.org/robert</a> resolves to an HTML page containing this:</p> <pre><code>&lt;link href="https://www.google.com/accounts/o8/ud" rel="openid2.provider" /&gt; &lt;link href="https://www.google.com/profiles/schneck" rel="openid2.local_id" /&gt; </code></pre> <p>Now, however, I have logged into Stack Overflow and had Google tell me "<strong>Important notice:</strong> OpenID2 for Google accounts is going away on April 20, 2015. <a href="https://support.google.com/accounts/answer/6135882" rel="nofollow noreferrer">Learn more</a>." <a href="https://developers.google.com/accounts/docs/OpenID" rel="nofollow noreferrer">This page</a> explains that Google has deprecated OpenID 2.0 and developers should migrate their apps to OpenID Connect.</p> <p>Can I continue to use a custom URI for OpenID login, but delegate to Google's OpenID Connect provider for authentication? How?</p>
28,054,173
3
0
null
2015-01-14 14:15:53.307 UTC
6
2015-01-21 04:01:03.407 UTC
2017-05-23 12:06:46.683 UTC
null
-1
null
394,431
null
1
32
openid|google-openid|openid-connect|stackexchange
2,072
<p>OpenID Connect <em>only</em> supports Discovery that is meant to <strong>find</strong> your Provider based on some hint you give it (e-mail, account, URL, domain etc.); it won't give you a persistent identifier for which you can <strong>delegate</strong> authentication to a configurable Provider of your choice.</p> <p>So if you only want to use a custom URI to find your provider, you can use the approach that Nat gave (except for the last bit that Google does not and can not do and assuming that SO supports Discovery).</p> <p>But if you want true delegation, so that RPs can use an identifier returned by the OP that is persistent over different OPs that you delegate to, then you can't.</p> <p>For StackOverflow you probably don't need either one of those: SO uses its own primary identifier/account and you can link several accounts to that, including Google's. Only if SO would have used your custom URI as its primary identifier you would have had a problem. In this case there's no problem and you can:</p> <ol> <li>use the Google login button, or</li> <li>type your custom URI in the OpenID URL entry box, assuming both you and have implemented Discovery</li> </ol> <p>But both 1. and 2. really yield the same result: they <em>find</em> out that Google is where you want to authenticate.</p>
40,358,434
TypeScript TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'
<p>Im getting this compilation error in my Angular 2 app:</p> <blockquote> <p>TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.</p> </blockquote> <p>The piece of code causing it is:</p> <pre><code>getApplicationCount(state:string) { return this.applicationsByState[state] ? this.applicationsByState[state].length : 0; } </code></pre> <p>This however doesn't cause this error:</p> <pre><code>getApplicationCount(state:string) { return this.applicationsByState[&lt;any&gt;state] ? this.applicationsByState[&lt;any&gt;state].length : 0; } </code></pre> <p>This doesn't make any sense to me. I would like to solve it when defining the attributes the first time. At the moment I'm writing:</p> <pre><code>private applicationsByState: Array&lt;any&gt; = []; </code></pre> <p>But someone mentioned that the problem is trying to use a string type as index in an array and that I should use a map. But I'm not sure how to do that.</p> <p>Thans for your help!</p>
40,358,512
5
2
null
2016-11-01 10:40:55.9 UTC
16
2022-05-05 07:29:14.697 UTC
2021-10-14 09:31:57.67 UTC
null
209,259
null
69,349
null
1
135
javascript|angular|typescript
210,492
<p>If you want a key/value data structure then don't use an array.</p> <p>You can use a regular object:</p> <pre><code>private applicationsByState: { [key: string]: any[] } = {}; getApplicationCount(state: string) { return this.applicationsByState[state] ? this.applicationsByState[state].length : 0; } </code></pre> <p>Or you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" rel="noreferrer">a Map</a>:</p> <pre><code>private applicationsByState: Map&lt;string, any[]&gt; = new Map&lt;string, any[]&gt;(); getApplicationCount(state: string) { return this.applicationsByState.has(state) ? this.applicationsByState.get(state).length : 0; } </code></pre>
40,484,717
PrimeNG dropdown hidden by dialog
<p>I have an Angular2 app using PrimeNG components.</p> <p>I want a dropdown inside a dialog box. However, when i have implemented this, the dropdown is cut off by the limit of the dialog box as shown in the screenshot below. What i want is for it to display above the dialog and have all the options visible. </p> <p><a href="https://i.stack.imgur.com/niMee.png" rel="noreferrer"><img src="https://i.stack.imgur.com/niMee.png" alt="enter image description here"></a></p> <p>It is only a small dialog and i do not want to create a large one for this as there will be lots of empty unused space. </p> <p>My html code for this is as below:</p> <pre><code>&lt;p-dialog header="Repack" [(visible)]="display" showEffect="fade" minHeight="200"&gt; &lt;div class="row col-md-12" align="center"&gt; &lt;button pButton (click)="viewRepack()" label="View Repack"&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class="row col-md-12"&gt;&lt;strong&gt;Edit Table Assignment: &lt;/strong&gt;&lt;/div&gt; &lt;p-dropdown [options]="tables" [(ngModel)]="selectedTable" [style]="{width: '100%'}"&gt;&lt;/p-dropdown&gt; &lt;button pButton label="Save" (click)="save()" style="float:right;margin-right:3px;margin-top:5px;"&gt;&lt;/button&gt; &lt;/p-dialog&gt; </code></pre> <p>If anyone can offer any advice on this it would be greatly appreciated.</p>
42,930,704
6
3
null
2016-11-08 10:36:20.66 UTC
7
2021-07-05 20:20:31.833 UTC
2021-07-05 20:20:31.833 UTC
null
1,077,309
null
2,858,948
null
1
31
angular|typescript|primeng|primeng-dropdowns|primeng-dialog
38,547
<p>It is necessary to add an attribute <code>appendTo</code>.</p> <p>e.g.</p> <pre><code>&lt;p-dropdown appendTo="body" [options]="tables" [(ngModel)]="selectedTable" [style]="{width: '100%'}"&gt;&lt;/p-dropdown&gt; </code></pre>
39,194,917
How to use Laravel Passport with a custom username column
<p>Now I'm using something like that for authenticating the user on my base site:</p> <pre><code>if (Auth::attempt($request-&gt;only(['id', 'password']))) { // } </code></pre> <p>How can I modify this code for using custom column as username? <a href="https://laravel.com/docs/5.3/passport#password-grant-tokens" rel="noreferrer">https://laravel.com/docs/5.3/passport#password-grant-tokens</a></p>
39,194,932
2
0
null
2016-08-28 19:18:05.89 UTC
9
2021-02-24 05:20:53.383 UTC
2018-02-19 17:24:29.467 UTC
null
100,297
null
4,417,142
null
1
45
php|laravel|oauth-2.0|laravel-passport
23,296
<p>You can use findForPassport method in your user model.</p> <p>This method take username as argument, and return user model</p> <p>For example:</p> <pre><code>class User extends Authenticatable { use HasApiTokens, Notifiable; // ... some code public function findForPassport($username) { return $this-&gt;where('id', $username)-&gt;first(); } } </code></pre>
6,255,796
What does the 'N' command do in sed?
<p>It looks like the 'N' command works on every other line:</p> <pre class="lang-sh prettyprint-override"><code>$ cat in.txt a b c d $ sed '=;N' in.txt 1 a b 3 c d </code></pre> <p>Maybe that would be natural because command 'N' joins the next line and changes the current line number. But (I saw this <a href="http://www.thegeekstuff.com/2009/11/unix-sed-tutorial-multi-line-file-operation-with-6-practical-examples/" rel="nofollow noreferrer">here</a>):</p> <pre class="lang-sh prettyprint-override"><code>$ sed 'N;$!P;$!D;$d' thegeekstuff.txt </code></pre> <p>The above example deletes the last two lines of a file. This works not only for even-line-numbered files but also for odd-line-numbered files. In this example 'N' command runs on every line. What's the difference?</p> <p>And could you tell me why I cannot see the last line when I run sed like this:</p> <pre class="lang-sh prettyprint-override"><code># sed N odd-lined-file.txt </code></pre>
6,257,542
1
0
null
2011-06-06 17:33:17.13 UTC
7
2021-07-10 10:53:39.303 UTC
2021-07-10 10:53:39.303 UTC
null
11,407,695
null
766,330
null
1
18
sed
43,120
<p>Excerpt from <code>info sed</code>: </p> <pre><code>`sed' operates by performing the following cycle on each lines of input: first, `sed' reads one line from the input stream, removes any trailing newline, and places it in the pattern space. Then commands are executed; each command can have an address associated to it: addresses are a kind of condition code, and a command is only executed if the condition is verified before the command is to be executed. ... When the end of the script is reached, unless the `-n' option is in use, the contents of pattern space are printed out to the output stream, ... Unless special commands (like 'D') are used, the pattern space is deleted between two cycles ... `N' Add a newline to the pattern space, then append the next line of input to the pattern space. If there is no more input then `sed' exits without processing any more commands. ... `D' Delete text in the pattern space up to the first newline. If any text is left, restart cycle with the resultant pattern space (without reading a new line of input), otherwise start a normal new cycle. </code></pre> <p>This should pretty much resolve your query. But still I will try to explain your three different cases:</p> <p><strong>CASE 1:</strong> </p> <ol> <li><code>sed</code> reads a line from input. [<strong>Now there is 1 line in pattern space.</strong>]</li> <li><code>=</code> Prints the current line no.</li> <li><code>N</code> reads the next line into pattern space.[<strong>Now there are 2 lines in pattern space.</strong>] <ul> <li>If there is no next line to read then sed exits here. [<strong>ie: In case of odd lines, sed exits here - and hence the last line is swallowed without printing.</strong>]</li> </ul></li> <li><code>sed</code> prints the pattern space and cleans it. [<strong>Pattern space is empty.</strong>]</li> <li>If <code>EOF</code> reached <code>sed</code> exits here. <strong>Else Restart the complete cycle from step 1.</strong> [<strong>ie: In case of even lines, sed exits here.</strong>]</li> </ol> <p>Summary: In this case sed reads 2 lines and prints 2 lines at a time. Last line is swallowed it there are odd lines (see step 3).</p> <p><strong>CASE 2:</strong> </p> <ol> <li><code>sed</code> reads a line from input. [<strong>Now there is 1 line in pattern space.</strong>]</li> <li><code>N</code> reads the next line into pattern space. [<strong>Now there are 2 lines in pattern space.</strong>] <ul> <li><em>If it fails exit here. This occurs only if there is 1 line.</em></li> </ul></li> <li>If its not last line(<code>$!</code>) print the first line(<code>P</code>) from pattern space. [<strong>The first line from pattern space is printed. But still there are 2 lines in pattern space.</strong>]</li> <li>If its not last line(<code>$!</code>) delete the first line(<code>D</code>) from pattern space [<strong>Now there is only 1 line (the second one) in the pattern space.</strong>] and <strong>restart the command cycle from step 2.</strong> And its because of the command <code>D</code> <em>(see the excerpt above)</em>.</li> <li>If its last line(<code>$</code>) then delete(<code>d</code>) the complete pattern space. [ie. reached EOF ] [<strong>Before beginning this step there were 2 lines in the pattern space which are now cleaned up by <code>d</code> - at the end of this step, the pattern space is empty.</strong>]</li> <li><code>sed</code> automatically stops at EOF.</li> </ol> <p>Summary: In this case :</p> <ul> <li><code>sed</code> reads 2 lines first.</li> <li>if there is next line available to read, print the first line and read the next line.</li> <li>else delete both lines from cache. <em>This way it always deletes the last 2 line.</em></li> </ul> <p><strong>CASE 3:</strong><br> Its the same case as CASE:1, just remove the Step 2 from it.</p>
38,034,049
is optionality (mandatory, optional) and participation (total, partial) are same?
<p>As i know optionality means the minimum cardinality of a relationship which is denoted as optional to optional, mandatory to optional, mandatory to mandatory.. </p> <p>And Participation denoted as bold line and a normal line. </p> <p>In the Internet some refer participation as the dependency of the entity to the relationship which is also looks like identifying and non identifying relationship.</p> <p>and some refer it as the minimum cardinality</p> <p>What is the correct definitions of those relationships and what is the difference..</p>
38,035,173
1
0
null
2016-06-26 00:07:17.293 UTC
12
2021-01-27 10:46:41.073 UTC
null
null
null
null
5,719,870
null
1
13
entity-relationship
31,315
<p>Let's start with definitions and examples of each of the concepts:</p> <p><strong>Total and partial participation:</strong></p> <p>Total participation (indicated by a double or thick association line) means that all the entities in an entity set must participate in the relationship. Partial participation (indicated by a single thin line) means that there can be entities in the entity set that don't participate in the relationship.</p> <p><a href="https://i.stack.imgur.com/5f7yC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5f7yC.png" alt="Total and partial relationship"></a></p> <p><code>Medicine</code> participates totally in the <code>Produce</code> relationship, meaning that <code>Medicine</code> can't exist unless <code>Produced</code> by a <code>Laboratory</code>. In contrast, a <code>Laboratory</code> can exist without <code>Producing</code> <code>Medicine</code> - <code>Laboratory</code> participates partially in the <code>Produce</code> relationsip.</p> <p><strong>Mandatory and optional roles:</strong></p> <p>In a relationship, roles can be optional or mandatory. This affects whether a relationship instance can exist without an entity in a given role. Mandatory roles are indicated with a solid association line, optional roles are indicated with a dotted line.</p> <p><a href="https://i.stack.imgur.com/fGsof.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fGsof.png" alt="Mandatory and optional entities"></a></p> <p>Roles aren't often talked about in database tutorials, but they're an important concept. Consider a marriage - a relationship with two mandatory roles filled by the same entity set. In most relationships, the entity sets also define the roles, but when an entity set appears multiple times in a single relationship, we distinguish them in different roles.</p> <p>In the example above, a <code>Patient</code> can <code>Purchase</code> <code>Medicine</code> with or without a <code>Prescription</code>. A <code>Purchase</code> can't exist without a <code>Patient</code> and <code>Medicine</code>, but a <code>Prescription</code> is optional (overall, though it may be required in specific cases).</p> <p><strong>Identifying relationship / weak entity:</strong></p> <p>A weak entity is an entity that can't be identified by its own attributes and therefore has another entity's key as part of its own. An identifying relationship is the relationship between a weak entity and its parent entity. Both the identifying relationship and the weak entity are indicated with double borders. Weak entity sets must necessarily participate totally in their identifying relationship.</p> <p><a href="https://i.stack.imgur.com/uJBJJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uJBJJ.png" alt="Identifying relationship / weak entities"></a></p> <p>In this example, a <code>Prescription</code> contains <code>LineItems</code> which are identified by the <code>Prescription</code>'s key and a line number. In other words, the <code>LineItems</code> table will have a composite key <code>(Prescription_ID, Line_Number)</code>.</p> <p>For examples of non-identifying relationships, see the previous examples. While <code>Medicine</code> participates totally in the <code>Produce</code> relationship, it has its own identity (e.g. a surrogate key, though I didn't indicate it). Note that surrogate keys always imply regular entities.</p> <p><strong>Mandatory/optional vs total/partial participation</strong></p> <p>Mandatory or optional roles indicate whether a certain role (with its associated entity set) is required for the relationship to exist. Total or partial participation indicate whether a certain relationship is required for an entity to exist.</p> <p>Mandatory partial participation: See above: A <code>Laboratory</code> can exist without producing any medicine, but <code>Medicine</code> can't be <code>Produced</code> without a <code>Laboratory</code>.</p> <p>Mandatory total participation: See above: <code>Medicine</code> can't exist without being <code>Produced</code>, and a <code>Laboratory</code> can't <code>Produce</code> something unspecified.</p> <p>Optional partial participation: See above: A <code>Prescription</code> can exist without being <code>Purchased</code>, and a <code>Purchase</code> can exist without a <code>Prescription</code>.</p> <p>That leaves optional total participation, which I had to think about a bit to find an example:</p> <p><a href="https://i.stack.imgur.com/0Ofu9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0Ofu9.png" alt="Optional total participation"></a></p> <p>Some <code>Patients</code> <code>Die</code> of an unknown <code>Cause</code>, but a <code>Cause</code> of death can't exist without a <code>Patient</code> <code>Dying</code> of it.</p> <p><strong>Total/partial participation vs identifying/non-identifying relationships</strong></p> <p>As I said before, weak entity sets always participate totally in their identifying relationship. See above: a <code>LineItem</code> must be <code>Contained</code> in a <code>Prescription</code>, it's identity and existence depends on that. Partial participation in an identifying relationship isn't possible.</p> <p>Total participation doesn't imply an identifying relationship - <code>Medicine</code> can't exist without being <code>Produced</code> by a <code>Laboratory</code> but <code>Medicine</code> is identified by its own attributes.</p> <p>Partial participation in a non-identifying relationship is very common. For example, <code>Medicine</code> can exist without being <code>Purchased</code>, and <code>Medicine</code> is identified by its own attributes.</p> <p><strong>Mandatory/optional vs identifying/non-identifying relationships</strong></p> <p>It's unusual for a relationship to have less than two mandatory roles. Identifying relationships are binary relationships, so the parent and child roles will be mandatory - the <code>Contain</code> relationship between <code>Prescription</code> and <code>LineItem</code> can't exist without both entities.</p> <p>Optional roles are usually only found on ternary and higher relationships (though see the example of patients dying of causes), and aren't involved in identification. An alternative to an optional role is a relationship on a relationship:</p> <p><a href="https://i.stack.imgur.com/VZBTa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VZBTa.png" alt="Associative entity"></a></p> <p>By turning <code>Purchase</code> into an associative entity, we can have it participate in a <code>Fill</code> relationship with <code>Prescription</code>. To maintain the same semantics as above I specified that a <code>Purchase</code> can only <code>Fill</code> one <code>Prescription</code>.</p> <p><strong>Physical modeling</strong></p> <p>If we translate from conceptual to physical model (skipping logical modeling / further normalization), making separate tables for each entity and relationship, things look pretty similar, though you have to know how to read the cardinality indicators on the foreign key lines to recover the ER semantics.</p> <p><a href="https://i.stack.imgur.com/w6nOQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/w6nOQ.png" alt="Physical model examples"></a></p> <p>However, it's common to denormalize tables with the same primary keys, meaning one-to-many relationships are combined with the entity table on the many side:</p> <p><a href="https://i.stack.imgur.com/Pva5X.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Pva5X.png" alt="Denormalized died relationship"></a></p> <p>A relationship is physically represented as two or more entity keys in a table. In this case, the entity keys - <code>patient_id</code> and <code>cause_of_death_id</code> are both found in the <code>Patient</code> table. Many people think the foreign key line represents the relationship, but this comes from confusing the entity-relationship model with the old network data model.</p> <p>This is a crucial point - in order to understand different kinds of relationships and constraints on relationships, it's essential to understand what relationships are first. Relationships in ER are associations between keys, not between tables. A relationship can have any number of roles of different entity sets, while foreign key constraints enforce a subset constraint between two columns of one entity set. Now, armed with this knowledge, read my whole answer again. ;)</p> <p>I hope this helps. Feel free to ask questions.</p>
28,794,089
Calling a Swift class factory method with leading dot notation?
<p>In a recent question, the poster had this interesting line of code:</p> <pre><code>self.view.backgroundColor = .whiteColor() </code></pre> <p>I was surprised to see this. I've only ever seen the <em>leading dot</em> notation used for enum values. In this case, <code>backgroundColor</code> is of type <code>UIColor?</code> and <code>whiteColor</code> is a class method on <code>UIColor</code> that returns a <code>UIColor</code>.</p> <p>Why does this work? It this a legitimate way to call a factory method?</p>
28,808,977
3
0
null
2015-03-01 13:31:00.407 UTC
9
2020-07-14 10:53:14.557 UTC
null
null
null
null
1,630,618
null
1
41
swift
12,355
<p>This <strong>feature</strong> is called &quot;<a href="https://docs.swift.org/swift-book/ReferenceManual/Expressions.html#ID394" rel="noreferrer">Implicit Member Expression</a>&quot;</p> <blockquote> <p>An implicit member expression is an abbreviated way to access a member of a type, such as an enumeration case <strong>or a class method</strong>, in a context where type inference can determine the implied type. It has the following form:</p> <blockquote> <p><code>.</code><kbd>member name</kbd></p> </blockquote> </blockquote> <hr /> <p>But, as of right now, I advise you <em>should not</em> use this feature in <code>Optional</code> or <code>ImplicitlyUnwrappedOptional</code> context.</p> <p>Although this works:</p> <pre><code>// store in Optional variable let col: UIColor? col = .redColor() // pass to function func f(arg:UIColor?) { println(arg) } f(.redColor()) </code></pre> <p>This crashes the compiler :(</p> <pre><code>func f(arg:UIColor?, arg2:Int) { println(arg) } // ^^^^^^^^^^ just added this. f(.redColor(), 1) </code></pre> <p>The compiler has some bugs. see: <a href="https://stackoverflow.com/q/26921177/3804019">does swift not allow initialization in function parameters?</a></p>
23,874,281
Scala - How to compile code from an external file at runtime?
<p>I want to design a Scala program that accepts Scala files as parameters which can customize the execution of the program. In particular, I want to supply at runtime files that contain implementations of methods that will be invoked by the program. How can I properly depend on external files and invoke their methods dynamically at runtime? Ideally, I would also like those files to be able to depend on methods and classes in my program.</p> <p>Example Scenario: I have a function that contains the line <code>val p: Plant = Greenhouse.getPlant()</code>, and the <code>Greenhouse</code> class with the <code>getPlant</code> method is defined in one of the files that will be supplied at runtime. In that file, the method <code>getPlant</code> returns a <code>Rose</code>, where <code>Rose &lt;: Plant</code> and <code>Plant</code> is defined in the original program. How do I achieve (or approximate) this interdependency, assuming the files are only joined at runtime and not at compile-time?</p>
23,879,115
2
0
null
2014-05-26 16:24:52.813 UTC
12
2014-05-27 16:24:53.05 UTC
2014-05-27 00:11:59.583 UTC
null
1,763,356
null
506,971
null
1
14
scala|scala-compiler|external-dependencies
4,912
<p>Here's how to do it using only standard Scala. The non-obvious stuff is all in <code>GreenhouseFactory</code>:</p> <pre><code>package customizable abstract class Plant case class Rose() extends Plant abstract class Greenhouse { def getPlant(): Plant } case class GreenhouseFactory(implFilename: String) { import reflect.runtime.currentMirror import tools.reflect.ToolBox val toolbox = currentMirror.mkToolBox() import toolbox.u._ import io.Source val fileContents = Source.fromFile(implFilename).getLines.mkString("\n") val tree = toolbox.parse("import customizable._; " + fileContents) val compiledCode = toolbox.compile(tree) def make(): Greenhouse = compiledCode().asInstanceOf[Greenhouse] } object Main { def main(args: Array[String]) { val greenhouseFactory = GreenhouseFactory("external.scala") val greenhouse = greenhouseFactory.make() val p = greenhouse.getPlant() println(p) } } </code></pre> <p>Put your override expression in <code>external.scala</code>:</p> <pre><code>new Greenhouse { override def getPlant() = new Rose() } </code></pre> <p>The output is:</p> <pre><code>Rose() </code></pre> <p>The only tricky thing is that <code>GreenhouseFactory</code> needs to prepend that <code>import</code> statement to provide access to all the types and symbols needed by the external files. To make that easy, make a single package with all those things.</p> <p>The compiler <code>ToolBox</code> is sort of documented <a href="http://www.scala-lang.org/api/2.11.1/scala-compiler/#scala.tools.reflect.ToolBox" rel="noreferrer">here</a>. The only thing you really need to know, other than the <a href="https://stackoverflow.com/questions/11283204/strange-behavior-with-reflection-in-scala">weird imports</a>, is that <code>toolbox.parse</code> converts a string (Scala source code) into an abstract syntax tree, and <code>toolbox.compile</code> converts the abstract syntax tree into a function with signature <code>() =&gt; Any</code>. Since this is dynamically compiled code, you have to live with casting the <code>Any</code> to the type that you expect.</p>
43,166,214
Merging http observables using forkjoin
<p>I'm trying to avoid nested observables by using <code>forkjoin</code>. The current (nested) version looks like this:</p> <pre><code> this.http.get('https://testdb1.firebaseio.com/.json').map(res =&gt; res.json()).subscribe(data_changes =&gt; { this.http.get('https://testdb2.firebaseio.com/.json').map(res =&gt; res.json()).subscribe(data_all =&gt; { /* Do this once resolved */ this.platform.ready().then(() =&gt; { this.storage.set('data_changes', data_changes); this.storage.set('data_all', data_all); document.getElementById("chart").innerHTML = ""; this.createChart(); }); }); }, err =&gt; { this.platform.ready().then(() =&gt; { console.log("server error 2"); document.getElementById("chart").innerHTML = ""; this.createChart(); }); }); } </code></pre> <p>I can rewrite the first part as:</p> <pre><code>Observable.forkJoin( this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) =&gt; res.json()), this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) =&gt; res.json()) ) </code></pre> <p>But i'm not sure how I would then add the <code>.subscribe</code> method to access both <code>data_changes</code> and <code>data_all</code>.</p> <p>Looking at another example, I know it should look something like <code>.subscribe(res =&gt; this.combined = {friends:res[0].friends, customer:res[1]});</code>, but i'm not sure how to adapt this to my example. </p>
43,166,302
1
0
null
2017-04-02 08:24:45.97 UTC
15
2017-10-24 10:08:33.14 UTC
null
null
null
null
2,278,894
null
1
29
angular|typescript|ionic2|observable
30,028
<p>Try to use <code>combineLatest</code> instead of <code>forkJoin</code> :</p> <p><strong>With <code>combineLatest</code> :</strong></p> <pre><code>const combined = Observable.combineLatest( this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) =&gt; res.json()), this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) =&gt; res.json()) ) combined.subscribe(latestValues =&gt; { const [ data_changes , data_all ] = latestValues; console.log( "data_changes" , data_changes); console.log( "data_all" , data_all); }); </code></pre> <p>You can also handle it by forkJoin , but forkJoin will return data when all calls are finished and return result , but in combineLatest When any observable emits a value, emit the latest value from each.</p> <p><strong>With <code>forkJoin</code> :</strong></p> <pre><code>const combined = Observable.forkJoin( this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) =&gt; res.json()), this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) =&gt; res.json()) ) combined.subscribe(latestValues =&gt; { const [ data_changes , data_all ] = latestValues; console.log( "data_changes" , data_changes); console.log( "data_all" , data_all); }); </code></pre> <p>Call both and check the console log , you will get idea.</p>
35,969,728
How to change TODO highlight in atom editor
<p>In my opinion the higlighting of a TODO "flag" in the atom editor is too weak/unobtrusively.</p> <p>How can I change this? I DON'T wanna list the todos in a sidebar (<a href="https://atom.io/packages/todo-show" rel="noreferrer">https://atom.io/packages/todo-show</a>).</p> <p>Here to compare:</p> <p>In Vim editor there is very strong highlighting (desired): <a href="https://i.stack.imgur.com/qXsfn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qXsfn.png" alt="enter image description here"></a></p> <p>In Atom editor: <a href="https://i.stack.imgur.com/Hj1fu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Hj1fu.png" alt="enter image description here"></a></p> <p>The main problem is, that atom highlights many other code words in this color...</p>
36,200,468
1
0
null
2016-03-13 11:35:32.547 UTC
8
2019-08-06 06:50:21.973 UTC
2016-03-17 19:34:40.287 UTC
null
2,518,200
null
3,567,888
null
1
13
editor|highlight|atom-editor|todo
5,360
<p>As GitHub's Atom Editor is built around HTML5 and CSS3 you can very easily change your style sheet, I've done a little recording on how to make this specific change below although you can apply the same principals to any styled element within the editor:</p> <p><a href="https://i.stack.imgur.com/QJcdp.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/QJcdp.gif" alt="Screen Capture of Style Configuration taking the Shadow DOM into account"></a></p> <h2>Step by Step</h2> <p>The first thing you will need to do is find an instance of the element you want to style, in this case I created a new, empty, file with the text <code>//TODO: is too subtle</code>.</p> <ol> <li>You now need to find the appropriate selector for the word <code>TODO</code>, simply place your cursor in between the letters of the word TODO and press <kbd>Ctrl</kbd><kbd>Alt</kbd><kbd>Shift</kbd><kbd>P</kbd> or select <code>Editor: Log Cursor Scope</code> from the <a href="https://atom.io/packages/command-palette" rel="noreferrer">command palette</a>.</li> <li>The selectors that apply to that location are listed from the least specific at the top to the most specific at the bottom, in this case you want the most specific selector at the bottom, go ahead and copy that into your clipboard.</li> <li>Next you need to open your personal stylesheet, you can do this by selecting "Edit" and then "Stylesheet...", you can also choose <code>Application: Open Your Stylesheet</code> from the command palette.</li> <li>Scroll to the bottom of the Stylesheet and paste in your selector from Step 2, you will need to add a period (full-stop) at the beginning to make this a valid selector.</li> <li>Go ahead and add your preferred styling such your VIM style preference:</li> </ol> <pre class="lang-css prettyprint-override"><code> atom-text-editor::shadow .type.class.todo { background-color: yellow; color: black; font-style: normal; } </code></pre> <ol start="6"> <li>Finally save your stylesheet and switch back to your test document to see the resulting changes.</li> </ol> <p>Thanks to zypro for pointing out that my original answer didn't account for the use of the <a href="http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/" rel="noreferrer">Shadow DOM</a> in <a href="http://blog.atom.io/2014/11/18/avoiding-style-pollution-with-the-shadow-dom.html" rel="noreferrer">recent versions of Atom</a>.</p> <p>Update: At some point, Atom got rid of the Shadow DOM. I'm using version 1.34.0 which takes the following entry in the above-mentioned stylesheet:</p> <pre><code>atom-text-editor.editor .syntax--type.syntax--class.syntax--todo { background-color: yellow; color: black; font-style: normal; } </code></pre> <p>Also, for Python (and some other languages) you will need to uncheck "Use Tree Sitter Parsers" in the Core settings.</p>
36,188,429
Retrieve length of slice from slice object in Python
<p>The title explains itself, how to get 2 out of the object</p> <pre><code>slice(0,2) </code></pre> <p>The documentation is somewhat confusing, or it is the wrong one</p> <p><a href="https://docs.python.org/2/c-api/slice.html" rel="noreferrer">https://docs.python.org/2/c-api/slice.html</a></p> <p>In particular I don't understand what is the meaning of the output of</p> <pre><code>slice(0,2).indices(0) # (0, 0, 1) slice(0,2).indices(10 ** 10) # (0, 2, 1) </code></pre> <p>One possible workaround is to slice a list with the slice object</p> <pre><code>a = [1,2,3,4,5] len(a[slice(0,2)]) # 2 </code></pre> <p>But this will fail for an arbitrary large slice.</p> <p>Thanks, I couldn't find an answer In other posts. </p>
36,188,683
7
0
null
2016-03-23 20:50:01.863 UTC
3
2022-04-03 15:38:24.017 UTC
null
null
null
null
5,748,462
null
1
30
python|list|slice
14,073
<p>There is no complete answer for this. <code>slice</code> doesn't give you a length because the length of the result is always dependent on the size of the sequence being sliced, a short sequence (including an empty sequence) will produce fewer items, and if the <code>slice</code> is unbounded, then the length will grow in tandem with the length of the sequence; a <code>slice</code> might just go "to end of sequence" by having a <code>start</code> or <code>stop</code> of <code>None</code>.</p> <p>For a quick and easy way to compute the length for a sequence of a known length, you just combine <code>.indices</code> with Py3's <code>range</code> (or <code>xrange</code> in Py2, though <code>xrange</code> has limitations on values that Py3 <code>range</code> does not). <a href="https://docs.python.org/3/reference/datamodel.html#slice.indices" rel="noreferrer"><code>slice.indices</code> gives you the concrete <code>start</code>, <code>stop</code> and <code>stride</code> values derived when a <code>slice</code> applies to a sequence of a given length</a>, it's basically the values you'd fill in in a C-style <code>for</code> loop that traverses the same indices as the <code>slice</code>:</p> <pre><code> for (ssize_t i = start; i &lt; stop; i += stride) </code></pre> <p>So to calculate the length of a <code>slice</code> when applied to a sequence with 1000 elements, you'd do:</p> <pre><code>&gt;&gt;&gt; len(range(*slice(0, 2).indices(1000))) 2 &gt;&gt;&gt; len(range(*slice(10, None, 3).indices(1000))) 330 </code></pre> <p>If you're on Python 2, and your values might exceed what <code>xrange</code> can handle (it's limited to bounds and total length equal to what a <code>ssize_t</code> can hold), you can just do the calculation by hand:</p> <pre><code>def slice_len_for(slc, seqlen): start, stop, step = slc.indices(seqlen) return max(0, (stop - start + (step - (1 if step &gt; 0 else -1))) // step) &gt;&gt;&gt; slice_len_for(slice(10, None, 3), 1000) 330 </code></pre> <p><strong>Update:</strong> Unfortunately, <code>slice.indices</code> itself won't accept a <code>len</code> for the sequence beyond what a <code>long</code> can hold, so this doesn't gain you anything over using <code>xrange</code> in Py2. Left in place for those interested, but the workaround doesn't workaround anything unless you also <a href="https://github.com/python/cpython/blob/2.7/Objects/sliceobject.c#L102" rel="noreferrer">perform the work <code>slice</code> does to convert negative values and <code>None</code> to concrete values based on the sequence length.</a> Sigh.</p>
56,895,273
How to use `GlobalKey` to maintain widgets' states when changing parents?
<p>In Emily Fortuna's article (and video) she mentions:</p> <blockquote> <p>GlobalKeys have two uses: they allow widgets to change parents anywhere in your app without losing state, or they can be used to access information about another widget in a completely different part of the widget tree. An example of the first scenario might if you wanted to show the same widget on two different screens, but holding all the same state, you’d want to use a GlobalKey.</p> </blockquote> <p>Her article includes a gif demo of an app called "Using GlobalKey to ReuseWidget" but does not provide source code (probably because it's too trivial). You can also see a quick video demo here, starting at 8:30 mark: <a href="https://youtu.be/kn0EOS-ZiIc?t=510" rel="noreferrer">https://youtu.be/kn0EOS-ZiIc?t=510</a></p> <p>How do I implement her demo? Where do I define the GlobalKey variable and how/where do I use it? Basically for example, I want to display a counter that counts up every second, and have it on many different screens. Is that something GlobalKey can help me with?</p>
62,226,807
3
0
null
2019-07-05 00:23:32.757 UTC
16
2021-05-26 15:00:05.797 UTC
2019-07-05 00:30:58.163 UTC
null
1,032,613
null
1,032,613
null
1
39
flutter
71,375
<p><strong>I would not recommend using GlobalKey for this task.</strong></p> <p>You should pass the data around, not the widget, not the widget state. For example, if you want a <code>Switch</code> and a <code>Slider</code> like in the demo, you are better off just pass the actual <code>boolean</code> and <code>double</code> behind those two widgets. For more complex data, you should look into <code>Provider</code>, <code>InheritedWidget</code> or alike.</p> <p>Things have changed since that video was released. Saed's answer (which I rewarded 50 bounty points) might be how it was done in the video, but it no longer works in recent Flutter versions. Basically <strong>right now there is no good way to easily implement the demo using GlobalKey</strong>.</p> <p><strong>But...</strong></p> <p>If you can guarantee that, the two widgets will <strong>never</strong> be on the screen at the same time, or more precisely, they will never be simultaneously inserted into the widget tree on the same frame, then you could try to use <code>GlobalKey</code> to have the same widget on different parts of the layout.</p> <p>Note this is a very strict limitation. For example, when swiping to another screen, there is usually a transition animation where both screens are rendered at the same time. That is not okay. So for this demo, I inserted a "blank page" to prevent that when swiping.</p> <p><a href="https://i.stack.imgur.com/L4gTz.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/L4gTz.gif" alt="Global key demo"></a></p> <p><strong>How to:</strong></p> <p>So, if you want the same widget, appearing on very different screens (that hopefully are far from each other), you can use a <code>GlobalKey</code> to do that, with basically 3 lines of code.</p> <p>First, declare a variable that you can access from both screens:</p> <pre><code>final _key = GlobalKey(); </code></pre> <p>Then, in your widget, have a constructor that takes in a key and pass it to the parent class:</p> <pre><code>Foo(key) : super(key: key); </code></pre> <p>Lastly, whenever you use the widget, pass the same key variable to it:</p> <pre><code>return Container( color: Colors.green[100], child: Foo(_key), ); </code></pre> <p><strong>Full Source:</strong></p> <pre><code>import 'package:flutter/material.dart'; void main() { runApp(MaterialApp(home: MyApp())); } class MyApp extends StatelessWidget { final _key = GlobalKey(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Global Key Demo")), body: PageView.builder( itemCount: 3, itemBuilder: (context, index) { switch (index) { case 0: return Container( color: Colors.green[100], child: Foo(_key), ); break; case 1: return Container( color: Colors.blue[100], child: Text("Blank Page"), ); break; case 2: return Container( color: Colors.red[100], child: Foo(_key), ); break; default: throw "404"; } }, ), ); } } class Foo extends StatefulWidget { @override _FooState createState() =&gt; _FooState(); Foo(key) : super(key: key); } class _FooState extends State&lt;Foo&gt; { bool _switchValue = false; double _sliderValue = 0.5; @override Widget build(BuildContext context) { return Column( children: [ Switch( value: _switchValue, onChanged: (v) { setState(() =&gt; _switchValue = v); }, ), Slider( value: _sliderValue, onChanged: (v) { setState(() =&gt; _sliderValue = v); }, ) ], ); } } </code></pre>
21,129,699
How does Symfony2 session fixation work?
<p>According to the standard 2.4 documentation, the security.yml config file allows for the following configuration option:</p> <pre><code>session_fixation_strategy: none | migrate | invalidate </code></pre> <p>source: <a href="http://symfony.com/doc/current/reference/configuration/security.html">http://symfony.com/doc/current/reference/configuration/security.html</a></p> <p>However, I fail to find any details in the official documentation (or elsewhere) on what this option actually does, or how it works in practice. </p> <p>So, if I set this option to either "migrate" or "invalidate", how will this affect session handling in my system? For example, if I set it to "invalidate", would this mean that a context-local session is invalidated when the user navigates to a different security context?</p>
23,952,177
1
0
null
2014-01-15 05:24:30.403 UTC
8
2014-05-30 10:15:28.473 UTC
null
null
null
null
1,155,721
null
1
20
security|symfony
4,845
<p>In short:</p> <ul> <li>NONE: the session is not changed </li> <li>MIGRATE: the session id is updated, attributes are kept </li> <li>INVALIDATE: the session id is updated, attributes are lost</li> </ul> <p>In detail: </p> <ol> <li><p>None strategy: Nothing is (supposed to be) done in the default session implementation, thus the session is maintained from one context to the other. </p></li> <li><p>Migrate strategy: "Migrates the current session to a new session id while maintaining all session attributes." (The session storage should regenerate the current session.) "Regenerates id that represents this storage. This method must invoke session_regenerate_id($destroy) unless this interface is used for a storage object designed for unit or functional testing where a real PHP session would interfere with testing. Note regenerate+destroy should not clear the session data in memory only delete the session data from persistent storage." Thus the session is retained from one context to the other. </p></li> <li><p>Invalidate strategy: "Clears all session attributes and flashes and regenerates the session and deletes the old session from persistence." Thus the session is regenerated from one context to the other. </p></li> </ol> <p>It was not revealed by your question what kind of session data you are trying to fetch.<br> But in any case, no separate session is generated for different security contexts: <a href="http://symfony.com/doc/current/reference/configuration/security.html#firewall-context" rel="noreferrer">http://symfony.com/doc/current/reference/configuration/security.html#firewall-context</a></p> <p>Security (authentication) related data is stored under a separate key (based on the firewall name). So for example if you have a firewall with a name 'main', the authentication token will be stored under '_security_main', if you have a firewall (a separate context) with a name 'foo', the user and related token data will be stored under '_security_foo', etc.</p> <p>So besides ->getToken ->getUser (etc.) the rest of the session variables will be available in different contexts provided you use the 'none' or the 'migrate' session strategies. </p> <p>Take a look at the session interface for details (quotes are from these files) vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/SessionInterface.php</p> <p>And the default implementation: vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/Session.php</p>
43,567,577
What is the different between force push and normal push in git
<p>I want to know what is the different between force push and normal push and at what kind of situations i should do force push in git?Is it a good practice to do force push into master branch?</p>
43,567,591
2
0
null
2017-04-23 05:02:58.17 UTC
9
2017-04-23 05:17:17.47 UTC
null
null
null
null
7,764,309
null
1
33
git|push
28,252
<p>You only force a push when you need to replace the remote history by your local history.</p> <p>This happens when you rewrite the local history, typically <a href="https://git-scm.com/book/es-ni/v1/Git-Branching-Rebasing" rel="noreferrer">through a <code>git rebase</code></a>.<br> For instance, if you just pushed an incorrect commit, and amend it locally, using a <code>push --force</code> can help correct a <em>recent</em> push</p> <p>If you are the only one working on the branch you are force pushing, this is not a big deal.<br> If you are <em>not</em> the only one, then you need to communicate clearly in order for other users to reset their own local branch to the new remote. Or you need to avoid force pushing in the first place.</p> <blockquote> <p>Is it a good practice to do force push into master branch?</p> </blockquote> <p>Generally, it is not a good practice (again unless you are the only one using the remote repo).<br> And don't forget that once a branch has been force pushed... <a href="https://stackoverflow.com/a/15030429/6309">you cannot know <em>who</em> did the <code>push --force</code></a>.</p>
49,572,786
Bootstrap 4 datepicker
<p>I want to use datepicker <a href="https://bootstrap-datepicker.readthedocs.io/en/latest/index.html" rel="noreferrer">https://bootstrap-datepicker.readthedocs.io/en/latest/index.html</a> with Bootstrap 4.</p> <p>Following the examples on above page, I can make it work with Bootstrap 3.</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;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; &lt;link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" rel="stylesheet"/&gt; &lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"&gt; &lt;/head&gt; &lt;body&gt; &lt;main class="container"&gt; &lt;div class="row" style="padding-top: 100px"&gt; &lt;div class="col"&gt; &lt;input data-date-format="dd/mm/yyyy" id="datepicker"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/main&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $('#datepicker').datepicker({ weekStart: 1, daysOfWeekHighlighted: "6,0", autoclose: true, todayHighlight: true, }); $('#datepicker').datepicker("setDate", new Date()); &lt;/script&gt; &lt;/body&gt;</code></pre> </div> </div> </p> <p>Using this code datepicker appears correctly.</p> <p>But doing the same with Bootstrap 4:</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;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; &lt;link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" rel="stylesheet"/&gt; &lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"&gt;&lt;/head&gt; &lt;body&gt; &lt;main class="container"&gt; &lt;div class="row" style="padding-top: 100px"&gt; &lt;div class="col"&gt; &lt;input data-date-format="dd/mm/yyyy" id="datepicker"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/main&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"&gt;&lt;/script&gt;&lt;script type="text/javascript"&gt; $('#datepicker').datepicker({ weekStart: 1, daysOfWeekHighlighted: "6,0", autoclose: true, todayHighlight: true, }); $('#datepicker').datepicker("setDate", new Date()); &lt;/script&gt; &lt;/body&gt;</code></pre> </div> </div> </p> <p>Makes it look less professional:</p> <p><a href="https://i.stack.imgur.com/mbVFO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mbVFO.png" alt="enter image description here"></a></p> <p>Looks like font and spacing are messed up in Bootstrap 4 version.</p> <p>How can I get same look and feel of datepicker in Bootstrap 4?</p> <p>Thanks</p>
49,586,564
3
1
null
2018-03-30 10:31:00.94 UTC
4
2020-06-11 05:51:29.953 UTC
null
null
null
null
184,041
null
1
14
datepicker|bootstrap-4|bootstrap-datepicker
109,113
<p>You can too override default datepicker classes like the following:</p> <p>the default bootstrap font size is 1rem or 16px so update .datepicker class <code>font-size: 0.875em;</code> or/and update the cell width and height:</p> <pre><code>.datepicker td, .datepicker th { width: 1.5em; height: 1.5em; } </code></pre> <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;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; &lt;link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" rel="stylesheet"/&gt; &lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"&gt;&lt;/head&gt; &lt;body&gt; &lt;main class="container"&gt; &lt;div class="row" style="padding-top: 100px"&gt; &lt;div class="col"&gt; &lt;input data-date-format="dd/mm/yyyy" id="datepicker"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/main&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;style type="text/css"&gt; // solution 1: .datepicker { font-size: 0.875em; } /* solution 2: the original datepicker use 20px so replace with the following:*/ .datepicker td, .datepicker th { width: 1.5em; height: 1.5em; } &lt;/style&gt; &lt;script type="text/javascript"&gt; $('#datepicker').datepicker({ weekStart: 1, daysOfWeekHighlighted: "6,0", autoclose: true, todayHighlight: true, }); $('#datepicker').datepicker("setDate", new Date()); &lt;/script&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
26,132,451
How to add bash command completion for Docker on Mac OS X?
<p>I am running docker and I want <code>bash</code> command completion for <code>docker</code> commands and parameters.</p>
26,132,452
8
0
null
2014-10-01 00:46:02.59 UTC
10
2020-07-27 01:02:40.093 UTC
2014-10-01 00:53:03.643 UTC
null
2,297,345
null
2,297,345
null
1
54
macos|docker
21,920
<p>If you have already <a href="http://brew.sh" rel="noreferrer">homebrew</a> <code>bash-completion</code> <a href="https://superuser.com/a/288491/231893">installed</a> just install the docker completion script into the <code>bash_completion.d</code> </p> <pre><code>curl -XGET https://raw.githubusercontent.com/docker/cli/master/contrib/completion/bash/docker &gt; $(brew --prefix)/etc/bash_completion.d/docker </code></pre> <p><strong>Note:</strong> If you do not have homebrew <code>bash-completion</code> installed, <a href="https://superuser.com/questions/819221/how-to-install-the-debian-bash-completion-using-homebrew">follow these instructions</a> to install it before you execute the line above.</p> <p><strong>Note:</strong> the completion depends on some functions defined in <a href="http://bash-completion.alioth.debian.org/" rel="noreferrer">debian bash-completion</a>. Therefore, just sourcing the docker completion script as described in <a href="https://github.com/docker/docker/blob/master/contrib/completion/bash/docker" rel="noreferrer">completion/bash/docker</a> may not work. If you try to complete <code>docker run</code> (by hitting TAB) you may get an error like <code>__ltrim_colon_completions: command not found</code>. This could mean that you have not installed the bash-completion scripts. </p>
26,005,641
Are cookies in UIWebView accepted?
<p>I have to question for you.</p> <p>1 : I'm using <code>UIWebView</code>s in my iPhone App. I wan't the users be able to add comments in the news. But, to comment they have to log-in. </p> <p>If not, how can I accept cookies in <code>UIWebView</code>s ?</p> <p>2 : Are the cookies created in on <code>UIWebView</code> available in others <code>UIWebView</code> in an other View ?</p> <p>Ex : I have my <code>LoginViewController</code>, with an embedded <code>UIWebView</code>, where my user can login/logout. If they log-in in this view, the cookie will be still available in the <code>CommentViewController</code> ?</p> <p>If not, how can I make this possible ?</p> <p>Thanks in advance !</p>
26,006,163
8
0
null
2014-09-23 22:23:03.543 UTC
10
2019-01-20 11:58:11.467 UTC
2017-07-17 08:14:15.563 UTC
null
7,456,236
null
4,059,455
null
1
17
ios|objective-c|iphone|cookies|uiwebview
32,161
<p>The <code>UIWebView</code> will automatically store the cookies in the <code>[NSHTTPCookieStorage sharedHTTPCookieStorage]</code> collection, and should be available in all other <code>UIWebView</code>s within your app, during the same app launch. However the <code>UIWebView</code> class does not automatically store cookies for the pages that are loaded between app launches. You need to manually store cookies when the app is moved into the background and reload the values when the app is brought back into the foreground.</p> <p>Place the following code in your AppDelegate class:</p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //Other existing code [self loadHTTPCookies]; return YES; } - (void)applicationDidEnterBackground:(UIApplication *)application { //Other existing code [self saveHTTPCookies]; } - (void)applicationWillEnterForeground:(UIApplication *)application { [self loadHTTPCookies]; } - (void)applicationWillTerminate:(UIApplication *)application { //Other existing code [self saveHTTPCookies]; } -(void)loadHTTPCookies { NSMutableArray* cookieDictionary = [[NSUserDefaults standardUserDefaults] valueForKey:@"cookieArray"]; for (int i=0; i &lt; cookieDictionary.count; i++) { NSMutableDictionary* cookieDictionary1 = [[NSUserDefaults standardUserDefaults] valueForKey:[cookieDictionary objectAtIndex:i]]; NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieDictionary1]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie]; } } -(void)saveHTTPCookies { NSMutableArray *cookieArray = [[NSMutableArray alloc] init]; for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) { [cookieArray addObject:cookie.name]; NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary]; [cookieProperties setObject:cookie.name forKey:NSHTTPCookieName]; [cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue]; [cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain]; [cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath]; [cookieProperties setObject:[NSNumber numberWithUnsignedInteger:cookie.version] forKey:NSHTTPCookieVersion]; [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires]; [[NSUserDefaults standardUserDefaults] setValue:cookieProperties forKey:cookie.name]; [[NSUserDefaults standardUserDefaults] synchronize]; } [[NSUserDefaults standardUserDefaults] setValue:cookieArray forKey:@"cookieArray"]; [[NSUserDefaults standardUserDefaults] synchronize]; } </code></pre>
26,275,736
How to pass a Map<String, String> with application.properties
<p>I have implemented some authorization in a webservice that needs be configured.</p> <p>Currently the user/password combo is hardcoded into the bean configuration. I would like to configure the map with users and passwords into the application.properties so the configuration can be external.</p> <p>Any clue on how this can be done?</p> <pre><code>&lt;bean id="BasicAuthorizationInterceptor" class="com.test.BasicAuthAuthorizationInterceptor"&gt; &lt;property name="users"&gt; &lt;map&gt; &lt;entry key="test1" value="test1"/&gt; &lt;entry key="test2" value="test2"/&gt; &lt;/map&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre>
26,276,729
4
0
null
2014-10-09 10:10:04.447 UTC
10
2019-11-21 16:51:07.297 UTC
2019-11-21 16:51:07.297 UTC
null
117,347
null
185,432
null
1
26
spring|spring-boot
93,871
<p>A <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html" rel="noreferrer"><code>java.util.Properties</code></a> object is already a <code>Map</code>, actually a <code>HashTable</code> which in turn implements <code>Map</code>.</p> <p>So when you create a properties file (lets name it <code>users.properties</code>) you should be able to load it using a <code>PropertiesFactoryBean</code> or <code>&lt;util:properties /&gt;</code> and inject it into your class. </p> <pre><code>test1=test1 test2=test2 </code></pre> <p>Then do something like </p> <pre><code>&lt;util:properties location="classpath:users.properties" id="users" /&gt; &lt;bean id="BasicAuthorizationInterceptor" class="com.test.BasicAuthAuthorizationInterceptor"&gt; &lt;property name="users" ref="users" /&gt; &lt;/bean&gt; </code></pre> <p>Although if you have a <code>Map&lt;String, String&gt;</code> as a type of the users property it might fail... I wouldn't put them in the <code>application.properties</code> file. But that might just be me..</p>
41,998,222
Best practice for handling error in Angular2
<p>Hi i am trying to receive error sent from catch block (service). in multiple components i need to show a popup with the error message displayed. please let me know how to create a generic method and call it inside service block. Like what i am doing now with "showErrorPage()".</p> <pre><code>import { Injectable } from '@angular/core'; import { Http, Headers, Response, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/map' @Injectable() export class DataService { private reqData = {}; private url: string; constructor(private http: Http) { } getResult(searchObject: {}): Observable&lt;Response&gt; { // some logic return this.http.post(&lt;my url&gt;, &lt;data to be sent&gt;) .map((response: Response) =&gt; { return response; }) .catch((error: any) =&gt; { if (error.status === 302 || error.status === "302" ) { // do some thing } else { return Observable.throw(new Error(error.status)); } }); } } </code></pre> <p>And in my component i am calling it like</p> <pre><code>import { Component,EventEmitter, Output, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; // importing DataService '; @Component({ selector: 'o-result', templateUrl: './o-result.component.html', }) export class AComp implements OnInit { constructor( private dataService: DataService ){ } ngOnInit() { this.dataService.getResult(&lt;url&gt;, &lt;params&gt;) .subscribe( response =&gt; { // doing logic with responce } , error =&gt; { this.showErrorPage(); } ) } showErrorPage(): void { // displaying error in popup } } </code></pre>
41,999,180
1
0
null
2017-02-02 09:14:24.853 UTC
12
2017-10-10 11:58:59.857 UTC
null
null
null
null
1,867,584
null
1
27
angular|angular2-services
28,887
<p>According to the <a href="https://angular.io/guide/styleguide#style-08-01" rel="noreferrer">angular style guide</a></p> <blockquote> <p>The details of data management, such as headers, HTTP methods, caching, error handling, and retry logic, are irrelevant to components and other data consumers.</p> </blockquote> <p>Your implementation seems to be the correct one.</p> <p>Furthermore the <a href="https://angular.io/docs/ts/latest/guide/server-communication.html#!#always-handle-errors" rel="noreferrer">http client</a> documentation provides the same implementation.</p>
21,979,782
How to push values to property array in Cypher?
<p>I have two nodes <code>user</code> and <code>files</code> with a relationship <code>:contains</code>, the relationship has a property <code>id</code>which is an array, represented as</p> <pre><code>(:user)-[:contains{id:[12345]}]-&gt;(:files) </code></pre> <p>However I want to populate the property array <code>id</code> with values <code>1111</code> and <code>14567</code> <strong>sequentially</strong> using <code>Cypher</code> queries, I dont find any method to push values into the array.</p> <p>After inserting 1111 to property <code>id</code> it will be:</p> <pre><code>(:user)-[:contains{id:[12345,1111]}]-&gt;(:files) </code></pre> <p>After inserting 14567 to property <code>id</code> it will be:</p> <pre><code>(:user)-[:contains{id:[12345,1111,14567]}]-&gt;(:files) </code></pre> <p>I don't know how to populate values to an property array sequentially.</p>
21,980,719
3
0
null
2014-02-24 05:45:07.333 UTC
9
2021-12-10 03:45:48.82 UTC
2021-12-10 03:45:48.82 UTC
null
3,416,774
null
2,472,111
null
1
30
arrays|neo4j|cypher
17,436
<p>Adding values to an array is analogous to incrementing an integer or concatenating a string and is signified the same way, in your case (let <code>c</code> be your <code>[c:contains {id:[12345]}]</code>)</p> <pre><code>c.id = c.id + 1111 // [12345,1111] c.id = c.id + 14567 // [12345,1111,14567] </code></pre> <p>or</p> <pre><code>c.id = c.id + [1111,14567] // [12345,1111,14567] </code></pre>
3,089,475
How Can I create A 5 second Countdown timer with jquery that ends with a login popup?
<p>How would i create a jquery timer that starts when a link is 'mouse-overed', Displays a 1,2,3, 4 and 5, one after the other. Then on 5 pops up a login box?</p> <p>Cheers.</p>
3,089,490
3
0
null
2010-06-22 00:48:29.21 UTC
16
2017-09-26 19:48:54.503 UTC
null
null
null
null
276,809
null
1
34
jquery
82,744
<p>How about:</p> <pre><code>var counter = 0; var interval = setInterval(function() { counter++; // Display 'counter' wherever you want to display it. if (counter == 5) { // Display a login box clearInterval(interval); } }, 1000); </code></pre>
2,413,427
How to use SQL Order By statement to sort results case insensitive?
<p>I have a SQLite database that I am trying to sort by Alphabetical order. The problem is, SQLite doesn't seem to consider A=a during sorting, thus I get results like this:</p> <p>A B C T a b c g</p> <p>I want to get:</p> <p>A a b B C c g T</p> <p>What special SQL thing needs to be done that I don't know about?</p> <pre><code>SELECT * FROM NOTES ORDER BY title </code></pre>
2,413,833
3
1
null
2010-03-09 23:30:55.843 UTC
26
2020-04-26 23:13:23.79 UTC
null
null
null
null
131,871
null
1
157
sql|sqlite|sorting|sql-order-by
118,583
<p>You can also do <code>ORDER BY TITLE COLLATE NOCASE</code>.</p> <p>Edit: If you need to specify <code>ASC</code> or <code>DESC</code>, add this after <code>NOCASE</code> like</p> <pre><code>ORDER BY TITLE COLLATE NOCASE ASC </code></pre> <p>or</p> <pre><code>ORDER BY TITLE COLLATE NOCASE DESC </code></pre>
13,129,805
MatLab algorithm for composite Simpson's rule
<p>I have tried, just for the fun of it, to write a MatLab-code for the composite Simpson's rule. As far as I can see, the code is correct, but my answers are not as accurate as I would like. If I try my code on the function f = cos(x) + e^(x^2), with a = 0, b = 1 and n = 7, my answer is roughly 1,9, when it should be 2,3. If I use the algorithm available at Wikipedia, I get a very close approximation with n = 7, so my code is obviously not good enough. If someone can see any mistakes in my code, I would really appreciate it!</p> <pre><code>function x = compsimp(a,b,n,f) % The function implements the composite Simpson's rule h = (b-a)/n; x = zeros(1,n+1); x(1) = a; x(n+1) = b; p = 0; q = 0; % Define the x-vector for i = 2:n x(i) = a + (i-1)*h; end % Define the terms to be multiplied by 4 for i = 2:((n+1)/2) p = p + (f(x(2*i -2))); end % Define the terms to be multiplied by 2 for i = 2:((n-1)/2) q = q + (f(x(2*i -1))); end % Calculate final output x = (h/3)*(f(a) + 2*q + 4*p + f(b)); </code></pre>
13,129,903
4
0
null
2012-10-29 21:15:24.643 UTC
2
2017-05-02 13:14:24.133 UTC
2012-10-29 21:41:12.13 UTC
null
933,410
null
933,410
null
1
0
matlab|numerical-integration
52,714
<p>Your interval <code>[a,b]</code> should be split into <code>n</code> intervals. This results in <code>n+1</code> values for <code>x</code> that form the boundary of each partition. Your vector <code>x</code> contains only <code>n</code> elements. It appears that your code is only dealing with <code>n</code> terms instead of <code>n+1</code> as required.</p> <p>EDIT:: Now you have modified the question based on the above, try this</p> <pre><code>% The 2 factor terms for i = 2:(((n+1)/2) - 1 ) q = q + (f(x(2*i))); end % The 4 factor terms for i = 2:((n+1)/2) p = p + (f(x(2*i -1))); end </code></pre>
40,635,107
Why does unique_ptr instantiation compile to larger binary than raw pointer?
<p>I was always under the impression that a <code>std::unique_ptr</code> had no overhead compared to using a raw pointer. However, compiling the following code</p> <pre><code>#include &lt;memory&gt; void raw_pointer() { int* p = new int[100]; delete[] p; } void smart_pointer() { auto p = std::make_unique&lt;int[]&gt;(100); } </code></pre> <p>with <code>g++ -std=c++14 -O3</code> produces the following assembly:</p> <pre><code>raw_pointer(): sub rsp, 8 mov edi, 400 call operator new[](unsigned long) add rsp, 8 mov rdi, rax jmp operator delete[](void*) smart_pointer(): sub rsp, 8 mov edi, 400 call operator new[](unsigned long) lea rdi, [rax+8] mov rcx, rax mov QWORD PTR [rax], 0 mov QWORD PTR [rax+392], 0 mov rdx, rax xor eax, eax and rdi, -8 sub rcx, rdi add ecx, 400 shr ecx, 3 rep stosq mov rdi, rdx add rsp, 8 jmp operator delete[](void*) </code></pre> <p>Why is the output for <code>smart_pointer()</code> almost three times as large as <code>raw_pointer()</code>?</p>
40,635,268
1
7
null
2016-11-16 14:49:01.423 UTC
3
2016-11-17 13:11:07.22 UTC
null
null
null
null
4,089,452
null
1
39
c++|assembly|smart-pointers
1,424
<p>Because <code>std::make_unique&lt;int[]&gt;(100)</code> performs <a href="http://en.cppreference.com/w/cpp/language/value_initialization" rel="nofollow noreferrer">value initialization</a> while <code>new int[100]</code> performs <a href="http://en.cppreference.com/w/cpp/language/default_initialization" rel="nofollow noreferrer">default initialization</a> - In the first case, elements are 0-initialized (for <code>int</code>), while in the second case elements are left uninitialized. Try:</p> <pre><code>int *p = new int[100](); </code></pre> <p>And you'll get the same output as with the <code>std::unique_ptr</code>.</p> <p>See <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique" rel="nofollow noreferrer">this</a> for instance, which states that <code>std::make_unique&lt;int[]&gt;(100)</code> is equivalent to:</p> <pre><code>std::unique_ptr&lt;T&gt;(new int[100]()) </code></pre> <p>If you want a non-initialized array with <code>std::unique_ptr</code>, you could use<sup>1</sup>:</p> <pre><code>std::unique_ptr&lt;int[]&gt;(new int[100]); </code></pre> <p><sub><sup>1</sup> As mentioned by <a href="https://stackoverflow.com/questions/22571202/differences-between-stdmake-unique-and-stdunique-ptr">@Ruslan</a> in the comments, be aware of the difference between <code>std::make_unique()</code> and <code>std::unique_ptr()</code> - See <a href="https://stackoverflow.com/questions/22571202/differences-between-stdmake-unique-and-stdunique-ptr">Differences between std::make_unique and std::unique_ptr</a>.</sub></p>
37,149,466
Axios spread() with unknown number of callback parameters
<p>I need to process an unknown number of AJAX requests (1 or more) with axios, and I am not sure how to handle the response. I want something along the lines of:</p> <pre><code>let urlArray = [] // unknown # of urls (1 or more) axios.all(urlArray) .then(axios.spread(function () { let temp = []; for (let i = 0; i &lt; arguments[i].length; i++) temp.push(arguments[i].data); })); </code></pre> <p>where arguments will contain the callback responses sent by axios. The problem is that <code>arguments</code> contains the given string urls instead of the actual responses. How can I resolve this problem?</p>
37,149,547
1
0
null
2016-05-10 21:42:32.257 UTC
10
2016-05-10 22:22:19.353 UTC
2016-05-10 22:22:19.353 UTC
user6246005
null
null
3,606,440
null
1
22
javascript|ajax|axios
19,930
<p>You somewhere will need to make the actual requests. And then don't use <code>spread</code> but only <code>then</code> to receive the array of results:</p> <pre><code>let urlArray = [] // unknown # of urls (1 or more) let promiseArray = urlArray.map(url =&gt; axios.get(url)); // or whatever axios.all(promiseArray) .then(function(results) { let temp = results.map(r =&gt; r.data); … }); </code></pre>
52,785,125
MySQL Workbench: Error in query (1064): Syntax error near 'VISIBLE' at line 1
<p>Any ideas why <code>VISIBLE</code> below is causing an issue?</p> <pre><code>CREATE TABLE IF NOT EXISTS `setting` ( `uuid` INT(10) NOT NULL, `type` VARCHAR(255) NOT NULL, `code` VARCHAR(255) NOT NULL COMMENT 'An unique name.', `value` MEDIUMTEXT NULL DEFAULT NULL, `comment` LONGTEXT NULL DEFAULT NULL, `created_on` INT UNSIGNED NOT NULL, `updated_on` INT UNSIGNED NOT NULL, PRIMARY KEY (`uuid`)) ENGINE = MyISAM DEFAULT CHARACTER SET = utf8; CREATE UNIQUE INDEX `name_UNIQUE` ON `setting` (`code` ASC) VISIBLE; CREATE UNIQUE INDEX `uuid_UNIQUE` ON `setting` (`uuid` ASC) VISIBLE; </code></pre> <p>Errors:</p> <blockquote> <p>CREATE UNIQUE INDEX <code>name_UNIQUE</code> ON <code>setting</code> (<code>code</code> ASC) VISIBLE Error in query (1064): Syntax error near 'VISIBLE' at line 1</p> <p>CREATE UNIQUE INDEX <code>uuid_UNIQUE</code> ON <code>setting</code> (<code>uuid</code> ASC) VISIBLE Error in query (1064): Syntax error near 'VISIBLE' at line 1</p> </blockquote> <p>No error if I remove <code>VISIBLE</code> but <strong>MySQL Workbench 8.0.12</strong> auto generates that. How can I stop MySQL Workbench from doing that?</p> <p>My MySQL info in my Ubuntu 18.04:</p> <blockquote> <p>MySQL version: 5.7.23-0ubuntu0.18.04.1 through PHP extension MySQLi</p> </blockquote>
52,785,302
3
0
null
2018-10-12 18:22:48.95 UTC
4
2019-04-28 06:16:05.397 UTC
null
null
null
null
413,225
null
1
34
mysql|mysql-workbench
20,358
<p>The problem here is the difference in syntax across different MySQL server versions. It seems that <strong>MySQL Workbench 8.0.12</strong> is auto-generating <code>CREATE UNIQUE INDEX</code> statement for the MySQL server <strong>version 8.0</strong>.</p> <p>From the <a href="https://dev.mysql.com/doc/refman/8.0/en/create-index.html" rel="noreferrer">MySQL Server 8.0 Docs</a>, the syntax for <code>CREATE INDEX</code> is:</p> <pre><code>CREATE [UNIQUE | FULLTEXT | SPATIAL] INDEX index_name [index_type] ON tbl_name (key_part,...) [index_option] [algorithm_option | lock_option] ... key_part: {col_name [(length)] | (expr)} [ASC | DESC] index_option: KEY_BLOCK_SIZE [=] value | index_type | WITH PARSER parser_name | COMMENT 'string' | {VISIBLE | INVISIBLE} /* Notice the option of VISIBLE / INVISIBLE */ index_type: USING {BTREE | HASH} </code></pre> <p>However, this option of <code>{VISIBLE | INVISIBLE}</code> is not available in the <strong>MySQL Server 5.7</strong>. From <a href="https://dev.mysql.com/doc/refman/5.7/en/create-index.html" rel="noreferrer">Docs</a>:</p> <pre><code>CREATE [UNIQUE | FULLTEXT | SPATIAL] INDEX index_name [index_type] ON tbl_name (key_part,...) [index_option] [algorithm_option | lock_option] ... key_part: col_name [(length)] [ASC | DESC] index_option: KEY_BLOCK_SIZE [=] value | index_type | WITH PARSER parser_name | COMMENT 'string' /* No option of VISIBLE / INVISIBLE */ index_type: USING {BTREE | HASH} </code></pre> <hr> <p>If you are not looking to upgrade to latest version of MySQL; you can disable this feature of auto-generating with <code>VISIBLE / INVISIBLE</code> index:</p> <p>In MySQL Workbench:</p> <p>Go to: </p> <blockquote> <p>Edit > Preferences > Modeling > MySQL.</p> </blockquote> <p>Then, set the "Default Target MySQL Version" to <strong>5.7</strong></p> <p>Check the screenshot below:</p> <p><img src="https://i.stack.imgur.com/raIxn.png" alt="MySQL WorkBench Modeling"></p>
3,072,205
How to use Maven in my Java Project and Why?
<p>I am trying to figure out the use of <a href="http://maven.apache.org/" rel="noreferrer">Maven</a> and I got many articles describing its features and uses. But I am just not able to understand the actual use of Maven from productivity standpoint. </p> <p>From what I am used to in our school projects was just create a new Java project in Eclipse, write your Code, create a .war (if web-based) and paste the code to the webapps folder of Tomcat and start the server!</p> <p>So, </p> <ol> <li><p>Where does Maven come into picture? I have used Ant and I understand Ants benefit of a standardized build process. But why do we need an advanced Ant in form of Maven?</p></li> <li><p>In any case, I need to use it, so where do I get started - basic flow, some good tutorials?</p></li> </ol> <p>Thanks</p>
3,072,246
7
1
null
2010-06-18 18:30:42.253 UTC
13
2020-12-31 18:14:14.473 UTC
2012-11-11 22:07:42.507 UTC
null
231,917
null
231,917
null
1
20
java|maven-2
14,857
<p>Maven is used to manage the build, testing, and deployment processes. It can separate the unit tests and integration tests so you only run them when necessary and cut down on build time. </p> <p>It is also a <em>dependency manager</em>, which means when you realize the server piece of your project needs <code>apache commons-logging 1.0.4</code> but the client conflicts with anything past <code>0.7.9</code>, you can just add a couple lines to the respective <code>pom.xml</code> files, and Maven handles all of that (downloading, installing, and keeping track of the different versions of those dependencies). </p> <p>I was not a believer before my current task, but after 2 years using it for large enterprise applications, I definitely respect what Maven brings to the table. There are a lot of online resources but if you are going to be the lead on this and really feel uncomfortable, I recommend getting a book -- <a href="http://oreilly.com/catalog/9780596517335" rel="noreferrer">the O'Reilly one</a> is helpful. </p> <hr> <p>Forgot to mention that there is an Eclipse plugin which makes it almost painless to use with Eclipse: <a href="http://m2eclipse.sonatype.org/" rel="noreferrer">m2Eclipse</a>. </p> <hr> <p>Second update for example <code>pom.xml</code> segment to answer OP question:</p> <p>Your <code>pom.xml</code> will contain XML code such as:</p> <pre><code>&lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;commons-logging&lt;/groupId&gt; &lt;artifactId&gt;commons-logging&lt;/artifactId&gt; &lt;version&gt;1.0.4&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>These are downloaded from the central Maven repository (google "maven nexus") or you can configure your own additional repositories (like for your own projects, or if you are not Internet-connected). </p>
3,058,164
Android: Scrolling an Imageview
<p>I have an ImageView that is twice the height of a normale screen ( 960 dip). I would like to scroll it nicely up and down on the screen. The bottom of the screen should contain a button. I have tried various combinations of ScrollView and Imageviews without any success. I have also thinkered with the :isScrollContainer attribute without results. Anyone knows how to do this? Cheers, Luca</p>
3,732,377
8
1
null
2010-06-17 00:36:39.923 UTC
41
2019-11-04 12:45:17.183 UTC
2011-08-15 21:01:55.883 UTC
null
156,771
null
368,819
null
1
26
android|scroll|imageview
97,959
<p>@cV2 Thank you so much for that code. It got me going in the direction I needed. Here's my modified version which stops scrolling at the edges of the image...</p> <pre><code> // set maximum scroll amount (based on center of image) int maxX = (int)((bitmapWidth / 2) - (screenWidth / 2)); int maxY = (int)((bitmapHeight / 2) - (screenHeight / 2)); // set scroll limits final int maxLeft = (maxX * -1); final int maxRight = maxX; final int maxTop = (maxY * -1); final int maxBottom = maxY; // set touchlistener ImageView_BitmapView.setOnTouchListener(new View.OnTouchListener() { float downX, downY; int totalX, totalY; int scrollByX, scrollByY; public boolean onTouch(View view, MotionEvent event) { float currentX, currentY; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: downX = event.getX(); downY = event.getY(); break; case MotionEvent.ACTION_MOVE: currentX = event.getX(); currentY = event.getY(); scrollByX = (int)(downX - currentX); scrollByY = (int)(downY - currentY); // scrolling to left side of image (pic moving to the right) if (currentX &gt; downX) { if (totalX == maxLeft) { scrollByX = 0; } if (totalX &gt; maxLeft) { totalX = totalX + scrollByX; } if (totalX &lt; maxLeft) { scrollByX = maxLeft - (totalX - scrollByX); totalX = maxLeft; } } // scrolling to right side of image (pic moving to the left) if (currentX &lt; downX) { if (totalX == maxRight) { scrollByX = 0; } if (totalX &lt; maxRight) { totalX = totalX + scrollByX; } if (totalX &gt; maxRight) { scrollByX = maxRight - (totalX - scrollByX); totalX = maxRight; } } // scrolling to top of image (pic moving to the bottom) if (currentY &gt; downY) { if (totalY == maxTop) { scrollByY = 0; } if (totalY &gt; maxTop) { totalY = totalY + scrollByY; } if (totalY &lt; maxTop) { scrollByY = maxTop - (totalY - scrollByY); totalY = maxTop; } } // scrolling to bottom of image (pic moving to the top) if (currentY &lt; downY) { if (totalY == maxBottom) { scrollByY = 0; } if (totalY &lt; maxBottom) { totalY = totalY + scrollByY; } if (totalY &gt; maxBottom) { scrollByY = maxBottom - (totalY - scrollByY); totalY = maxBottom; } } ImageView_BitmapView.scrollBy(scrollByX, scrollByY); downX = currentX; downY = currentY; break; } return true; } }); </code></pre> <p>I'm sure it could be refined a bit, but it works pretty well. :)</p>
2,929,175
What is the difference between a static class and a normal class?
<p>When should I prefer either a static or a normal class? Or: what is the difference between them?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace staticmethodlar { class Program { static void Main(string[] args) { SinifA.method1(); } } static class SinifA { public static void method1() { Console.WriteLine("Deneme1"); } } public static class SinifB { public static void method2() { Console.WriteLine("Deneme2"); } } public class sinifC { public void method3() { Console.WriteLine("Deneme3"); } } public class sinifD : sinifC { void method4() { Console.WriteLine("Deneme4"); } sinifC sinifc = new sinifC(); // I need to use it :) } } </code></pre>
2,929,251
9
2
null
2010-05-28 13:06:57.447 UTC
12
2020-12-14 16:35:21.007 UTC
2015-06-04 06:21:54.18 UTC
null
419,956
null
52,420
null
1
21
c#|.net|oop
40,538
<p>Static classes contain static objects that can't be instantiated multiple times. Usually what I use static classes for are to house static methods that provide calculations, general processing patterns, string output formats, etc. Static classes are light weight and don't need instantiation.</p> <p>For instance <code>System.IO.File</code> is a static class with static a method <code>Exists()</code>. You don't create a File object to call it. You invoke it like this</p> <p><code>System.IO.File.Exists(filePath)</code></p> <p>Rather than doing this</p> <p><code>System.IO.File myFile = new System.IO.File(filePath);</code></p> <p><code>if(myFile.Exists())</code> <code>{ /* do work */ }</code></p> <p>If you require several objects in software, then you use dynamic classes. For instance if you have an inventory system you may have several <code>Product</code> objects and in that case you would use a dynamic class such as this</p> <pre><code>public class Product { public int ProductID { get; private set; } public string ProductName { get; private set; } public int Qty { get; set; } public Product( int productID, string productName, int total ) { this.ProductID = productID; this.ProductName = productName; this.Qty = total; } } </code></pre>
2,603,363
Good Form Security - no CAPTCHA
<p>Is there a good method of form security that does <code>not</code> involve CAPTCHA? CAPTCHA is so annoying, but I need security because I am getting form spam. My form is PHP.</p>
2,603,377
9
0
null
2010-04-08 20:49:32.667 UTC
10
2019-07-22 07:10:33.037 UTC
null
null
null
null
290,051
null
1
35
php|security|forms
10,206
<p>Try <a href="http://akismet.com/" rel="nofollow noreferrer">akismet</a>. It's great at flagging spam. The API is easy to use and completely transparent to your users.</p>
3,200,329
View AJAX response content in Chrome developer tools?
<p>Traditionally I use FireBug to debug my AJAX requests. It lets you examine both the contents of your request as well as the response that was sent back from the server. (it also notifies you in the console when these occur, which is a useful feature that Chrome seems to lack).</p> <p>In Chrome, I only seem to be able to view the requests, not the responses. When I try to examine the response the UI just displays "No Content Available" (Developer Tools > Resources > myRequest.php > Content). Do I have to turn something on to make the Chrome developer tools remember these requests?</p> <p>EDIT: In case it matters, these requests are being made inside a Flash object.</p>
3,205,078
9
3
null
2010-07-08 02:33:09.927 UTC
13
2022-01-31 07:53:13.473 UTC
2010-07-08 02:40:52.453 UTC
null
134,658
null
134,658
null
1
55
ajax|google-chrome|webkit|developer-tools|web-developer-toolbar
80,045
<p>The content of ajax responses is not visible yet if the request is generated by a plugin. There is some chance that this problem will be fixed soon.</p>