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
25,701,356
Developing game app using Phaser.js and Ionic (slow/shaky rendering)
<h2>Just to let you know (in case someone wants to develop).</h2> <p>I developed a game app using Phaser.js. I sort of put the code into Ionic blank starter app. So basically the view is rendered using Ionic app and then Phaser picks up the div by the id and displays the game. </p> <h2>Problem:</h2> <p>Its a simple flappy bird clone. Its working fine but the blocks movement is a bit shaky (as though they were shivering). Since Phaser uses WebGL, could it be the reason for slow rendering or is it due to the ionic framework (/angularjs) ?</p> <p>Should I have used some other tools to build the game app?</p> <p>Thanks in advance.</p> <h2>Edit:</h2> <p>You can checkout the code here: <a href="https://github.com/vamshisuram/ionic-flappybird-clone.git">https://github.com/vamshisuram/ionic-flappybird-clone.git</a> I uploaded all code into Git. So, I guess you can directly install <strong>platforms/ant-build/Hello-Cordova-debug.apk</strong> into your mobile and test it. Or try build again and install.</p>
25,702,229
1
4
null
2014-09-06 14:41:04.49 UTC
8
2016-01-23 12:36:01.49 UTC
2014-09-06 17:55:32.747 UTC
null
2,767,573
null
2,767,573
null
1
11
javascript|html|angularjs|ionic-framework|phaser-framework
15,004
<p>You can make it work. BUT ... there is no support for WebGL on any Android device using the stock webview (Ionic uses Cordova to package the app which is then being run inside a webview on the device): <a href="http://caniuse.com/#feat=webgl">http://caniuse.com/#feat=webgl</a></p> <p>Phaser.js is built on top of Pixie.js which will fall back to 2D canvas rendering. That's why your game is running slow. </p> <p>If you want to use Ionic and WebGL you should <a href="https://github.com/crosswalk-project/cordova-plugin-crosswalk-webview">build your app using CrossWalk</a>. I have done that and it is awesome: <a href="https://crosswalk-project.org/">https://crosswalk-project.org/</a></p> <p>There's other options such as CocoonJS to get WebGL going, but I haven't used those myself. </p>
4,697,515
How to store row/column of mysql data in array
<p>I want to be able to store (not echo) some data that has been selected from a mysql database in a php array. So far, I have only been able to echo the information, I just want to be able to store it in an array for later use. Here is my code:</p> <pre><code>$query = "SELECT interests FROM signup WHERE username = '$username'"; $result = mysql_query($query) or die ("no query"); while($row = mysql_fetch_array($result)) { echo $row['interests']; echo "&lt;br /&gt;"; } </code></pre>
4,697,525
2
0
null
2011-01-15 01:24:44.877 UTC
2
2017-05-16 22:48:23.277 UTC
null
null
null
Austin908
null
null
1
7
php|mysql|arrays|select
62,478
<p>You could use</p> <pre><code>$query = "SELECT interests FROM signup WHERE username = '".mysql_real_escape_string($username)."'"; $result = mysql_query($query) or die ("no query"); $result_array = array(); while($row = mysql_fetch_assoc($result)) { $result_array[] = $row; } </code></pre> <p>This will basically store all of the data to the <code>$result_array</code> array.</p> <p>I've used <code>mysql_fetch_assoc</code> rather than <code>mysql_fetch_array</code> so that the values are mapped to their keys.</p> <p>I've also included <code>mysql_real_escape_string</code> for protection.</p>
4,145,602
How to implement a view holder?
<p>i am using a viewholder to display from a dynamic arrayadapter.it works but the data displayed changes irregularly when i scroll the List.<strong><em>i want my List View to be populated only once ,Not all the time when i scroll my list.</em></strong> Any suggestion? Here is my Code</p> <pre><code>public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unneccessary calls // to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no need // to reinflate it. We only inflate a new View when the convertView supplied // by ListView is null. if (convertView == null) { convertView = mInflater.inflate(R.layout.sample, null); // Creates a ViewHolder and store references to the two children views // we want to bind data to. holder = new ViewHolder(); holder.name = (TextView) convertView.findViewById(R.id.text); holder.icon = (ImageView) convertView.findViewById(R.id.icon); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } // Bind the data efficiently with the holder. if(_first==true) { if(id&lt;myElements.size()) { holder.name.setText(myElements.get(id)); holder.icon.setImageBitmap( mIcon1 ); id++; } else { _first=false; } } //holder.icon.setImageBitmap(mIcon2); /*try{ if(id&lt;myElements.size()) id++; else { id--; } } catch(Exception e) { android.util.Log.i("callRestService",e.getMessage()); }*/ return convertView; } static class ViewHolder { TextView name; ImageView icon; } </code></pre> <p>when the list is loaded it looks like this : <a href="https://i.stack.imgur.com/NrGhR.png" rel="noreferrer">http://i.stack.imgur.com/NrGhR.png</a> <img src="https://i.stack.imgur.com/sMbAD.png" alt="alt text"> after scrolling some data <a href="https://i.stack.imgur.com/sMbAD.png" rel="noreferrer">http://i.stack.imgur.com/sMbAD.png</a> <img src="https://i.stack.imgur.com/sMbAD.png" alt="alt text"> it looks like this, and again if i scroll to the beginning it looks <a href="https://i.stack.imgur.com/0KjMa.png" rel="noreferrer">http://i.stack.imgur.com/0KjMa.png</a><img src="https://i.stack.imgur.com/0KjMa.png" alt="alt text"></p> <p>P.S : my list have to be in alphabetic order</p>
4,146,070
2
2
null
2010-11-10 14:41:36.667 UTC
7
2012-08-01 17:37:12.583 UTC
2010-11-11 05:43:18.6 UTC
null
430,652
null
430,652
null
1
11
android|listview|view
39,794
<p>You would need to write you own version of <code>ListView</code> to do that (which is bad). If the <code>ListView</code> doesn't work properly, it probably means that you are doing something wrong. </p> <p>Where does the <code>id</code> element come from? You are getting the position in your <code>getView()</code> method, so you don't need to worry about exceeding list bounds. The position is linked to the element position in your list, so you can get the correct element like this: </p> <pre><code>myElements.get(position); </code></pre> <p>When the data in your list changes, you can call this:</p> <pre><code>yourAdapter.notifyDataSetChanged() </code></pre> <p>That will rebuild your list with new data (while keeping your scrolling and stuff).</p>
4,307,318
Best Practices for Integrating AutoMapper with WCF Data Services and EF4
<p>We are exposing a domain model via WCF Data Services. The model originates from EF4, and requires some additional work to get it into the required form for being published via the web-service.</p> <p>I'd like to handle this outside of EF4, to keep our EDMX focused on the model rather than it's usage. My idea is to create a customized "ServiceModel" which is specifically for the web-service and contains the service-specific concerns.</p> <p>My question is in how to best wire-up automapper in the middle of WCF Data Services. I'm using WCF Data Services with a custom (reflection-based) provider for the ServiceModels. Where can I convert the OData query (for ServiceModels) into an EF4 query (for DomainModels), and map the results back to ServiceModels?</p>
4,357,522
2
0
null
2010-11-29 19:34:24.337 UTC
10
2010-12-17 05:01:50.323 UTC
null
null
null
null
60,724
null
1
14
c#|.net|entity-framework-4|automapper|wcf-data-services
11,033
<p>I use Automapper in my WCF Services to map from database entities to data contracts. For each service I create a static AutomapBootstrap class with a method to InitializeMap. Then for each service, I decorate the service with an AutomapServiceBehavior attribute.</p> <p>I do not know if this will work for your scenario because WCF Data Services is a little different from vanilla WCF SOAP services and services using WCF WebBindings.</p> <p>However, its worth a look.</p> <p><strong>This is the Service Behavior</strong></p> <pre><code>[CoverageExclude(Reason.Framework)] public sealed class AutomapServiceBehavior : Attribute, IServiceBehavior { public AutomapServiceBehavior() { } #region IServiceBehavior Members public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection&lt;ServiceEndpoint&gt; endpoints, BindingParameterCollection bindingParameters) { AutomapBootstrap.InitializeMap(); } public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) { } public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) { } #endregion } </code></pre> <p><strong>This is my mapper</strong></p> <pre><code>public class AutomapBootstrap { public static void InitializeMap() { Mapper.CreateMap&lt;CreateBookmarkRequest, TagsToSaveRequest&gt;() .ForMember(dest =&gt; dest.TagsToSave, opt =&gt; opt.MapFrom(src =&gt; src.BookmarkTags)) .ForMember(dest =&gt; dest.SystemObjectId, opt =&gt; opt.UseValue((int)SystemObjectType.Bookmark)) .ForMember(dest =&gt; dest.SystemObjectRecordId, opt =&gt; opt.Ignore()); } } </code></pre> <p><strong>this is how I wire up my service to automap</strong></p> <pre><code>[AutomapServiceBehavior] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Clouds : ICloudService { // service operation implementation details elided } </code></pre> <p>Final note, my service is a vanilla WCF Service using the WebBinding and serving up data in a REST style fashion.</p>
4,728,644
How can the Ctrl+0 through Ctrl+9 key bindings be mapped in Vim?
<p>Why can’t I map—using any of the <code>*map</code> commands (<code>nmap</code>, <code>imap</code>, etc.)—the <kbd>Ctrl</kbd>+<kbd>0</kbd> through <kbd>Ctrl</kbd>+<kbd>9</kbd> key strokes? In fact, it appears that some of them, like <kbd>Ctrl</kbd>+<kbd>3</kbd>, are bound to <code>^[</code> at the X Window level. How can I make Vim override those default bindings?</p> <p>That is, if I do <code>imap &lt;C-3&gt; fancystuffhere</code>, typing <kbd>Ctrl</kbd>+<kbd>3</kbd> in Insert mode puts me into Normal mode, instead of inserting 'fancystuffhere'.</p> <p>I’m using X11 on Linux.</p>
4,728,904
2
1
null
2011-01-18 20:24:40.733 UTC
10
2020-09-26 06:52:49.233 UTC
2020-09-26 06:48:20.84 UTC
null
254,635
null
496,933
null
1
20
vim
5,965
<p>Both Vim and gVim use byte queue instead of keypress event queue, so that values from 0x40 (<code>@</code>) to 0x5F (<code>_</code>), including the 0x41–0x5A (<code>A</code>–<code>Z</code>) range) have corresponding control characters (you can get their codes by subtracting 0x40 from their value). Because of this, no characters above and beyond this range can be used together with <code>C-</code> (<kbd>Ctrl</kbd>).</p> <p>It is also the reason why <code>C-S-</code> (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>) for alphanumeric keys does not work even in gVim—functional keys generate more then one byte, so <code>&lt;C-S-F1&gt;</code> may work. Replacing <code>&lt;C-3&gt;</code> with <code>&lt;Esc&gt;</code> is done by terminal; you can try mapping it in almost any GUI application and see that <code>&lt;Esc&gt;</code> does not get mapped.</p>
10,034,470
Conditional Statement using Bitwise operators
<p>So I see that this question has already been asked, however the answers were a little vague and unhelpful. Okay, I need to implement a c expression using only "&amp; ^ ~ ! + | >> &lt;&lt;"</p> <p>The expression needs to resemble: a ? b : c</p> <p>So, from what I've been able to tell, the expression needs to look something like:</p> <p><code>return (a &amp; b) | (~a &amp; c)</code></p> <p>This works when a = 0, because anding it with b will give zero, and then the or expression will return the right side, <code>(~a &amp; c)</code> which works because ~0 gives all ones, and anding c with all ones returns c.</p> <p>However, this doesn't work when a > 0. Can someone try to explain why this is, or how to fix it?</p>
10,034,623
2
0
null
2012-04-05 19:03:43.6 UTC
8
2012-04-05 19:15:24.197 UTC
2012-04-05 19:05:19.28 UTC
null
505,088
null
1,224,798
null
1
12
c|conditional|bit-manipulation|bitwise-operators
22,434
<p>I would convert <code>a</code> to a boolean using <code>!!a</code>, to get 0 or 1. <code>x = !!a</code>. </p> <p>Then I'd negate that in two's complement. Since you don't have unary minus available, you use the definition of 2's complement negation: invert the bits, then add one: <code>y = ~x + 1</code>. That will give either all bits clear, or all bits set.</p> <p>Then I'd <code>and</code> that directly with one variable <code>y &amp; b</code>, its inverse with the other: <code>~y &amp; c</code>. That will give a 0 for one of the expressions, and the original variable for the other. When we <code>or</code> those together, the zero will have no effect, so we'll get the original variable, unchanged.</p>
10,123,633
How to run meteor server on a different ip address?
<p>How can i start meteor server on a different IP address? Currently in the examples am only able to run on a localhost:3000 address.</p>
10,128,489
9
1
null
2012-04-12 12:31:56.7 UTC
9
2018-11-30 18:42:00.09 UTC
null
null
null
null
26,143
null
1
19
meteor
22,671
<p>According to <code>netstat -tapn</code> Meteor/Node.js listens on all available IP addresses on the machine:</p> <pre><code>tcp 0 0 0.0.0.0:3000 0.0.0.0:* LISTEN 9098/node </code></pre> <p>Do you have something like iptables running?</p>
10,077,441
Deadlock detected in PL/pgSQL function
<p>I am facing a deadlock problem from a PL/pgSQL function in my PostgreSQL database. Please find the SQL statement in the code block (just example):</p> <pre><code>BEGIN UPDATE accounts SET balance = 0 WHERE acct_name like 'A%'; UPDATE accounts SET balance = balance + 100 WHERE acct_name like '%A'; EXCEPTION WHEN OTHERS THEN RAISE NOTICE SQLERRM; END; </code></pre> <p>I've found that the deadlock occurred during this statement was running. But I'm not sure that there were other statements trying to update this table in the same time (because I didn't find any in my logging system).</p> <p>So, is it possible that the deadlock occurred within this statement? As far as I know, if we blocked whole statement with <code>BEGIN</code>/<code>END</code>. There will be the same transaction and should not be locked by itself.</p>
10,077,634
3
3
null
2012-04-09 17:55:11.537 UTC
3
2017-05-26 14:50:49.883 UTC
2017-05-26 14:50:24.497 UTC
null
939,860
null
877,807
null
1
20
postgresql|concurrency|deadlock|plpgsql
65,209
<p>There is definitely <strong>some other process</strong> competing for the same resource. That is the nature of a deadlock. A function like you display can never deadlock itself. See <a href="https://stackoverflow.com/questions/10077441/postgresql-deadlock-detected/10077634#comment12902733_10077634">comment by @kgrittn below</a>, who is an expert on concurrency in PostgreSQL.</p> <p>Your version of PostgreSQL is missing. Modern versions raise a <strong>detailed error message</strong>. Both processes that compete for resources are listed in detail with standard logging settings. Check your db logs.</p> <p>The fact that you catch the error may prevent Postgres from giving you the full details. Remove the <strong>EXCEPTION</strong> block from your plpgsql function, if you don't get the information in the db log and try again.</p> <p>To alleviate deadlocks, you can do a number of things. If all your clients access resources in a synchronized order, deadlocks cannot occur. The manual provides the basic strategy to solve most cases in the chapter about <a href="http://www.postgresql.org/docs/current/interactive/explicit-locking.html#LOCKING-DEADLOCKS" rel="noreferrer">deadlocks</a>.</p> <hr> <p>As for <strong>version 8.3</strong>: consider upgrading to a more recent version. In particular this improvement in version 8.4 should be interesting for you (<a href="http://www.postgresql.org/docs/current/interactive/release-8-4.html" rel="noreferrer">quoting the release notes</a>):</p> <blockquote> <p>When reporting a deadlock, report the text of all queries involved in the deadlock to the server log (Itagaki Takahiro)</p> </blockquote> <p>Also, version 8.3 will meet its <a href="http://www.postgresql.org/support/versioning/" rel="noreferrer">end of life in February 2013</a>. You should start to consider upgrading.</p> <p>A deadlock situation involving <code>VACUUM</code> should have been <a href="http://www.postgresql.org/docs/current/interactive/release-8-3-1.html" rel="noreferrer">fixed in 8.3.1</a>.</p>
9,917,049
Inserting an image to ggplot2
<p>Is it possible to insert a raster image or a pdf image underneath a <code>geom_line()</code> on a <code>ggplot2</code> plot?</p> <p>I wanted to be quickly able to plot data over a previously calculated plot that takes a long time to generate as it uses a large amount of data.</p> <p>I read through this <a href="https://kohske.wordpress.com/2010/12/26/use-image-for-background-in-ggplot2/" rel="noreferrer">example</a>. However, as it is over one year old I thought there might be a different way of doing this now.</p>
9,917,684
4
0
null
2012-03-28 23:18:25.593 UTC
25
2021-02-16 12:23:04.12 UTC
2012-03-29 00:57:18.647 UTC
null
258,755
null
258,755
null
1
65
r|ggplot2
67,955
<p>try <code>?annotation_custom</code> in <code>ggplot2</code></p> <p>example,</p> <pre><code>library(png) library(grid) img &lt;- readPNG(system.file("img", "Rlogo.png", package="png")) g &lt;- rasterGrob(img, interpolate=TRUE) qplot(1:10, 1:10, geom="blank") + annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) + geom_point() </code></pre>
10,179,223
Find a row in dataGridView based on column and value
<p>I have a dataGridView that has 3 columns: SystemId, FirstName, LastName that is bound using database information. I would like to highlight a certain row, which I would do using:</p> <pre><code>dataGridView1.Rows[????].Selected = true; </code></pre> <p>The row ID I however do not know and the bindingsource keeps changing, thus row 10 could be "John Smith" in one instance but not even exist in another (I have a filter that filters out the source based on what user enters, so typing in "joh" would yield all rows where first / last name have "joh" in them, thus my list can go from 50 names to 3 in a click). </p> <p>I want to find a way how I can select a row based on SystemId and a corresponding number. I can get the system ID using the following method:</p> <pre><code>systemId = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["SystemId"].Value.ToString(); </code></pre> <p>Now I just need to apply it to the row selector. Something like dataGridView1.Columns["SystemId"].IndexOf(systemId} but that does not work (nor does such method exist). Any help is greatly appreciated.</p>
10,179,299
8
1
null
2012-04-16 18:02:02.927 UTC
21
2022-07-25 19:43:15.033 UTC
2014-07-29 12:37:52.103 UTC
null
451,518
null
593,388
null
1
66
c#|winforms|datagridview
247,187
<p>This will give you the gridview row index for the value:</p> <pre><code>String searchValue = &quot;somestring&quot;; int rowIndex = -1; foreach(DataGridViewRow row in DataGridView1.Rows) { if(row.Cells[1].Value.ToString().Equals(searchValue)) { rowIndex = row.Index; break; } } </code></pre> <p>Or a LINQ query</p> <pre><code>int rowIndex = -1; DataGridViewRow row = dgv.Rows .Cast&lt;DataGridViewRow&gt;() .Where(r =&gt; r.Cells[&quot;SystemId&quot;].Value.ToString().Equals(searchValue)) .First(); rowIndex = row.Index; </code></pre> <p>then you can do:</p> <pre><code>dataGridView1.Rows[rowIndex].Selected = true; </code></pre>
7,917,831
jQuery - Change color on click
<p>I'm looking at some jQuery because I want to create a div that changes color when you click it. </p> <p>And I've done that with: </p> <pre><code>$(function() { $('.star').click(function(){ $(this).css('background', 'yellow'); }); }); </code></pre> <p>And it works perfectly! But I want it to remove the background color, when you click it one more time. Is that possible, and how would you do something like that? </p>
7,917,877
3
1
null
2011-10-27 14:55:01.863 UTC
6
2021-02-19 11:05:40.783 UTC
null
null
null
null
804,506
null
1
14
jquery
68,951
<p>Create a CSS class:</p> <pre><code>.clicked { background-color: yellow; } </code></pre> <p>and then simply <a href="http://api.jquery.com/toggleClass/" rel="noreferrer">toggle that class</a> it via jQuery:</p> <pre><code>$('.star').click(function(){ $(this).toggleClass('clicked'); }); </code></pre>
7,907,410
std::atomic<int> decrement and comparison
<p>On the following code:</p> <pre class="lang-cpp prettyprint-override"><code>std::atomic&lt;int&gt; myint; //Shared variable //(...) if( --myint == 0) { //Code block B } </code></pre> <p>Is it possible that more than one thread access the block I named "Code Block B"?</p> <p>Please consider that overflow will not happen, that the 'if' is being executed concurrently by more than one thread, that the only modification to <em>myint</em> in the whole program is the <em>--myint</em> inside the if and that <em>myint</em> is initialized with a positive value.</p>
7,910,083
3
7
null
2011-10-26 18:47:27.627 UTC
8
2011-10-27 05:14:57.023 UTC
2011-10-27 05:14:57.023 UTC
null
46,642
null
809,384
null
1
24
c++|multithreading|concurrency|c++11|atomic
14,573
<p>C++0x paper <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2427.html#atomics.operations">N2427</a> (atomics) states roughly the following. I've changed the wording slightly so its easier to read for the specific decrement situation, the parts I changed are in <strong>bold</strong>:</p> <blockquote> <p>Effects: Atomically replace the <em>value</em> in <em>object</em> with result of the <strong>decrement</strong> applied to the <em>value</em> in <em>object</em> and the given operand. Memory is affected as per order. These operations are read-modify-write operations in the sense of the "synchronizes with" definition in [the new section added by N2334 or successor], and hence both such an operation and the evaluation that produced the input value synchronize with any evaluation that reads the updated value. </p> <p>Returns: Atomically, the value of <em>object</em> immediately before the <strong>decrement</strong>. </p> </blockquote> <p>The atomic operation guarantees that the decrement operator will return the value that the variable held immediately before the operation, this is atomic so there can be no intermediate value from updates by another thread.</p> <p>This means the following are <em>the only</em> possible executions of this code with 2 threads:</p> <pre><code>(Initial Value: 1) Thread 1: Decrement Thread 1: Compare, value is 0, enter region of interest Thread 2: Decrement Thread 2: Compare, value is -1, don't enter region </code></pre> <p>or </p> <pre><code>(Initial Value: 1) Thread 1: Decrement Thread 2: Decrement Thread 1: Compare, value is 0, enter region of interest Thread 2: Compare, value is -1, don't enter region </code></pre> <p>Case 1 is the uninteresting expected case.</p> <p>Case 2 interleaves the decrement operations and executes the comparison operations later. Because the decrement-and-fetch operation is <em>atomic</em>, it is impossible for thread 1 to receive a value other than 0 for comparison. It <em>cannot</em> receive a -1 because the operation was atomic... the read takes place at the time of the decrement and <em>not</em> at the time of the comparison. More threads will not change this behavior.</p>
11,852,515
Chrome Extension - edit a text field
<p>I'm trying to write my first Chrome extension. It would, when clicked, automatically fill the fields of an ID and password for my University's login page (which has its form's auto-fill disabled). It's a very specific page.</p> <p>I have a few problem. I've searched Google and SO but couldn't find an explanation on how to change the value of a text field through Chrome. I know how to do this in HTML and JavaScript, however I couldn't get the proper input to modify its text.</p> <p>I've also tried using jQuery using a few examples I've found, but no luck. I have an HTML page (popup.html) which calls a JavaScript file. I've also tried placing the JS in a content script</p> <p>Here's the manifest.json:</p> <pre><code>{ "name": "My First Extension", "version": "1.0", "manifest_version": 2, "description": "The first extension that I made.", "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "permissions": [ "tabs", "http://*/*" ], "content_scripts": [ { "matches": ["http://*/*"], "js": ["jquery-1.7.2.min.js","content.js"] } ] } </code></pre> <p>One of my attempt of popup.js (which gets called from popup.html) is:</p> <pre><code>chrome.tabs.getSelected(null, function(tab) { console.log(document) }); </code></pre> <p>I've also tried placing this code inside the content.js. same result, It prints to console, however it prints the popup.html content..</p> <p>I've also tried directly (and from the above method) to access an element directly by <code>document.getElementById()</code> but still no luck..</p> <p>So, Can anyone tell me what I'm doing wrong?</p>
11,852,610
3
3
null
2012-08-07 19:11:16.733 UTC
9
2012-08-08 04:34:32.443 UTC
null
null
null
null
975,959
null
1
5
javascript|google-chrome-extension
18,065
<p>You need to inject a JavaScript file to the page using the "web_accessible_resources" attribute. See here:</p> <p><strong>manifest.json</strong></p> <pre><code>{ "name": "My First Extension", "version": "1.0", "manifest_version": 2, "description": "The first extension that I made.", "browser_action": { "default_icon": "icon.png" }, "permissions": [ "tabs", "http://*/*" ], "content_scripts": [ { "matches": ["http://*/*"], "js": ["jquery-1.7.2.min.js","content.js"], "run_at": "document_start" } ], "web_accessible_resources": ["inject.js"] } </code></pre> <p><strong>inject.js</strong></p> <pre><code>(function () { console.log('test'); }()); </code></pre> <p><strong>content.js</strong></p> <pre><code>(function (chrome) { var js = document.createElement('script'); js.type = 'text/javascript'; js.src = chrome.extension.getURL('inject.js'); document.getElementsByTagName('head')[0].appendChild(js); }(chrome)); </code></pre> <p>Then just put the JavaScript code you want to use in inject.js to manipulate the page. Be sure to change matches to only match your University's login page.</p> <p>The reason this is the case is because Chrome extensions can run and operate on their own regardless of which website you're on. And they can continue to process as you switch pages. They're in their own sandboxed environment.</p>
11,837,078
Initialize a constant sized array in an initializer list
<p>I've got a situation which can be summarized in the following:</p> <pre><code>class Test { Test(); int MySet[10]; }; </code></pre> <p>is it possible to initialize <code>MySet</code> in an initializer list?</p> <p>Like this kind of initializer list:</p> <pre><code>Test::Test() : MySet({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) {} </code></pre> <p>Is there any way to initialize a constant-sized member array in a class's initalizer list?</p>
11,837,144
3
3
null
2012-08-06 22:52:58.78 UTC
6
2014-11-17 20:23:46.61 UTC
2014-11-17 20:23:46.61 UTC
null
1,079,635
null
1,079,635
null
1
27
c++|arrays|class|constants|initializer-list
76,770
<p>While not available in C++03, C++11 introduces <em>extended initializer lists</em>. You can indeed do it if using a compiler compliant with the C++11 standard.</p> <pre><code>struct Test { Test() : set { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } { }; int set[10]; }; </code></pre> <p>The above code compiles fine using <code>g++ -std=c++0x -c test.cc</code>.</p> <hr> <p>As pointed out below me by a helpful user in the comments, this code <strong>does not compile</strong> using Microsoft's VC++ compiler, cl. Perhaps someone can tell me if the equivalent using <code>std::array</code> will?</p> <pre><code>#include &lt;array&gt; struct Test { Test() : set { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } } { }; std::array&lt;int, 10&gt; set; }; </code></pre> <p>This also compiles fine using <code>g++ -std=c++0x -c test.cc</code>.</p>
11,793,067
How does ConcurrentHashMap work internally?
<p>I was reading the official Oracle documentation about Concurrency in Java and I was wondering what could be the difference between a <code>Collection</code> returned by</p> <pre><code>public static &lt;T&gt; Collection&lt;T&gt; synchronizedCollection(Collection&lt;T&gt; c); </code></pre> <p>and using for example a </p> <p><code>ConcurrentHashMap</code>. I'm assuming that I use <code>synchronizedCollection(Collection&lt;T&gt; c)</code> on a <code>HashMap</code>. I know that in general a synchronized collection is essentially just a decorator for my <code>HashMap</code> so it is obvious that a <code>ConcurrentHashMap</code> has something different in its internals. Do you have some information about those implementation details?</p> <p><strong>Edit: I realized that the source code is publicly available:</strong> <a href="http://www.docjar.com/html/api/java/util/concurrent/ConcurrentHashMap.java.html">ConcurrentHashMap.java</a></p>
11,793,153
6
2
null
2012-08-03 09:33:58.67 UTC
30
2022-09-17 06:30:30.697 UTC
2013-08-06 12:38:36.653 UTC
null
485,337
null
485,337
null
1
54
java|collections|concurrency|hashmap
49,427
<p>I would read the <a href="http://www.docjar.com/html/api/java/util/concurrent/ConcurrentHashMap.java.html" rel="noreferrer">source of ConcurrentHashMap</a> as it is rather complicated in the detail. In short it has</p> <ul> <li>Multiple partitions which can be locked independently. (16 by default)</li> <li>Using concurrent Locks operations for thread safety instead of synchronized.</li> <li>Has thread safe Iterators. synchronizedCollection's iterators are not thread safe.</li> <li>Does not expose the internal locks. synchronizedCollection does.</li> </ul>
11,662,028
WebAPI to Return XML
<p>I'm wanting my WEB API method to return an XML object back to the calling application. Currently it's just returning the XML as a string object. Is this a no no? If so how do you tell the webapi get method that it's returning an object of type XML?</p> <p>Thanks</p> <p>Edit: An example of the Get method:</p> <pre><code>[AcceptVerbs("GET")] public HttpResponseMessage Get(int tenantID, string dataType, string ActionName) { List&lt;string&gt; SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData ("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList(); string AllResults = ""; for (int i = 0; i &lt; SQLResult.Count - 1; i++) { AllResults += SQLResult[i]; } string sSyncData = "&lt;?xml version=\"1.0\"?&gt; " + AllResults; HttpResponseMessage response = new HttpResponseMessage(); response.Content = new StringContent(sSyncData); return response; } </code></pre> <p>Its a bit hacky because im still at the prototyping stage. Will refactor when i can prove its doable.</p>
11,662,185
5
0
null
2012-07-26 03:41:56.067 UTC
14
2019-11-22 09:20:14.127 UTC
2015-06-05 15:09:00.563 UTC
null
27,756
null
408,137
null
1
57
asp.net|asp.net-mvc|asp.net-web-api
151,868
<p>If you return a serializable object, WebAPI will automatically send JSON or XML based on the Accept header that your client sends.</p> <p>If you return a string, you'll get a string.</p>
3,653,788
How can I connect to Oracle Database 11g server through ssh tunnel chain (double tunnel, server in company network)?
<p>I have SSH access to 'public' server, which is also the gateway to company network. There is another server in the network, where <strong>local</strong> Oracle Database server is running (There is no access from outside of this server, only localhost DB connections are accepted). And of course, I have another SSH access to this server.</p> <p>Is there any way to join to this Oracle Database 11g Server from outside of the network ? I am asking if there is something like ssh tunnel chain, and how i configure it. This can be usefull, for example, for TOAD for Oracle (ORACLE client).</p> <p><strong>EDIT:</strong> Here is image</p> <p><img src="https://i.stack.imgur.com/vrfxt.png" alt="alt text"> Thanks</p>
3,653,850
4
0
null
2010-09-06 19:10:01.867 UTC
17
2020-08-13 17:48:56.227 UTC
2014-01-19 18:04:25.64 UTC
null
400,571
null
400,571
null
1
29
oracle|ssh|database-connection|ssh-tunnel
79,828
<p>Yes, it's possible. E.g. on Linux, run</p> <pre><code>ssh -N -Llocalport:dbserver:dbport yourname@connectionserver </code></pre> <p>where</p> <ul> <li>localport is the port on your machine which will be forwarded (can be 1521 if there is no local instance of oracle running)</li> <li>dbserver is the name or IP of the database server</li> <li>dbport is the port of the database (usually 1521)</li> <li>yourname is the login on the connectionserver</li> <li>connectionserver is the machine where you have ssh access</li> </ul> <p>The same can be done on Windows using Plink (which comes with Putty):</p> <pre><code>plink -N -L localport:dbserver:dbport yourname@connectionserver </code></pre> <p>Do this on both machines (your local machine and the server you have access to) to chain the ssh tunnels. Example:</p> <p>Connection server (assuming Linux):</p> <pre><code>ssh -N -L1521:dbserver:1521 dblogin@dbserver </code></pre> <p>Your PC:</p> <pre><code>plink -N -L 1521:connectionserver:1521 connlogin@connectionserver </code></pre> <p>The tnsnames.ora entry must look like you are running a local database, e.g.</p> <pre><code>prodoverssh = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)) ) (CONNECT_DATA = (SERVICE_NAME = prod) ) ) </code></pre>
3,945,361
SET versus SELECT when assigning variables?
<p>What are the differences between the <code>SET</code> and <code>SELECT</code> statements when assigning variables in T-SQL?</p>
3,945,396
4
0
null
2010-10-15 19:17:01.447 UTC
83
2019-04-04 15:33:11.51 UTC
2015-06-15 09:23:08.937 UTC
null
2,693,611
null
368,537
null
1
317
sql|sql-server|sql-server-2005|tsql|sql-server-2008
421,097
<p><a href="http://ryanfarley.com/blog/archive/2004/03/01/390.aspx" rel="noreferrer">Quote</a>, which summarizes from <a href="http://vyaskn.tripod.com/differences_between_set_and_select.htm" rel="noreferrer">this article</a>:</p> <blockquote> <ol> <li>SET is the ANSI standard for variable assignment, SELECT is not.</li> <li>SET can only assign one variable at a time, SELECT can make multiple assignments at once.</li> <li>If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)</li> <li>When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value)</li> <li>As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.</li> </ol> </blockquote>
3,886,617
getItemAtPosition() How to get readable data from the selected item in a ListView
<p>I have a listView of contacts that I got from the Android ContactManager sample. This list is showing up fine, but I can't figure out how to get info from the selected item, like "name" and "phone number".</p> <p>I can get the selected position, but the result of the mContactList.getItemAtPosition(position) is a ContentResolver$CursorWrapperInner and that doesn't really make any sense to me. I can't get heads or tails from that.</p> <p>Anyone know how I can get the name/id/phone number from the selected item in the listView? </p> <p>Here is my code. </p> <pre><code>@Override public void onCreate(Bundle savedInstanceState) { Log.v(TAG, "Activity State: onCreate()"); super.onCreate(savedInstanceState); setContentView(R.layout.choose_contact); // Obtain handles to UI objects mAddAccountButton = (Button) findViewById(R.id.addContactButton); mContactList = (ListView) findViewById(R.id.contactList); mShowInvisibleControl = (CheckBox) findViewById(R.id.showInvisible); // Initialize class properties mShowInvisible = false; mShowInvisibleControl.setChecked(mShowInvisible); mContactList.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { addContactAt(position); } }); mShowInvisibleControl.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Log.d(TAG, "mShowInvisibleControl changed: " + isChecked); mShowInvisible = isChecked; populateContactList(); } }); // Populate the contact list populateContactList(); } /** * Populate the contact list based on account currently selected in the account spinner. */ private SimpleCursorAdapter adapter; private void populateContactList() { // Build adapter with contact entries Cursor cursor = getContacts(); String[] fields = new String[] { ContactsContract.Data.DISPLAY_NAME }; adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor, fields, new int[] {R.id.contactEntryText}); mContactList.setAdapter(adapter); } /** * Obtains the contact list for the currently selected account. * * @return A cursor for for accessing the contact list. */ private Cursor getContacts() { // Run query Uri uri = ContactsContract.Contacts.CONTENT_URI; String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }; String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + (mShowInvisible ? "0" : "1") + "'"; String[] selectionArgs = null; String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"; return managedQuery(uri, projection, selection, selectionArgs, sortOrder); } private void addContactAt(int position) { Object o = mContactList.getItemAtPosition(position); } </code></pre> <p>}`</p>
3,886,863
5
0
null
2010-10-07 23:18:24.403 UTC
4
2017-10-25 07:17:56.96 UTC
null
null
null
null
469,682
null
1
6
android|listview|selecteditem
47,879
<p>BOOM!I figured it out. Basically you get the position number from the click event, then in my addContatAt() you use that position to search within the cursor for the field you want. In my case I wanted the display name.</p> <p>I'm used to doing things in Flex, so this Cursor business is different for me :)</p> <p>Anyways, for others here is my code:</p> <pre><code>@Override public void onCreate(Bundle savedInstanceState) { Log.v(TAG, "Activity State: onCreate()"); super.onCreate(savedInstanceState); setContentView(R.layout.choose_contact); // Obtain handles to UI objects mAddAccountButton = (Button) findViewById(R.id.addContactButton); mContactList = (ListView) findViewById(R.id.contactList); mShowInvisibleControl = (CheckBox) findViewById(R.id.showInvisible); // Initialize class properties mShowInvisible = false; mShowInvisibleControl.setChecked(mShowInvisible); mContactList.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { addContactAt(position); } }); mShowInvisibleControl.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Log.d(TAG, "mShowInvisibleControl changed: " + isChecked); mShowInvisible = isChecked; populateContactList(); } }); // Populate the contact list populateContactList(); } /** * Populate the contact list based on account currently selected in the account spinner. */ private SimpleCursorAdapter adapter; private void populateContactList() { // Build adapter with contact entries contactsCursor = getContacts(); String[] fields = new String[] { ContactsContract.Data.DISPLAY_NAME }; adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, contactsCursor, fields, new int[] {R.id.contactEntryText}); mContactList.setAdapter(adapter); } /** * Obtains the contact list for the currently selected account. * * @return A cursor for for accessing the contact list. */ private Cursor getContacts() { // Run query Uri uri = ContactsContract.Contacts.CONTENT_URI; String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }; String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + (mShowInvisible ? "0" : "1") + "'"; String[] selectionArgs = null; String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"; return managedQuery(uri, projection, selection, selectionArgs, sortOrder); } private void addContactAt(int position) { contactsCursor.moveToPosition(position); String name = contactsCursor.getString( contactsCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); } } </code></pre>
3,228,694
PHP database connection class
<p>I am trying to get a users ID from a database within a class, but I have very little to no experience with classes, how could I go about getting the uid from the DB and then return the uid?</p> <p>so basically something like this,</p> <pre><code>class hello { public function getUid(){ //connect to the db //get all of the users info $array = mysql_fetch_array($result); $uid = $array['uid']; return $uid; } } </code></pre> <p>Like I said, I am still new to classes, so any advice or help would be greatly appreciated!</p> <p>Thanx in advance!</p>
3,228,918
6
0
null
2010-07-12 12:57:07.23 UTC
11
2021-01-30 01:34:00.24 UTC
null
null
null
null
270,311
null
1
11
php|mysql|class
65,935
<p>First build a MySQL class library... suiting the requirements like in this sample piece:</p> <pre><code>&lt;?php include '../config/Dbconfig.php'; class Mysql extends Dbconfig { public $connectionString; public $dataSet; private $sqlQuery; protected $databaseName; protected $hostName; protected $userName; protected $passCode; function Mysql() { $this -&gt; connectionString = NULL; $this -&gt; sqlQuery = NULL; $this -&gt; dataSet = NULL; $dbPara = new Dbconfig(); $this -&gt; databaseName = $dbPara -&gt; dbName; $this -&gt; hostName = $dbPara -&gt; serverName; $this -&gt; userName = $dbPara -&gt; userName; $this -&gt; passCode = $dbPara -&gt;passCode; $dbPara = NULL; } function dbConnect() { $this -&gt; connectionString = mysql_connect($this -&gt; serverName,$this -&gt; userName,$this -&gt; passCode); mysql_select_db($this -&gt; databaseName,$this -&gt; connectionString); return $this -&gt; connectionString; } function dbDisconnect() { $this -&gt; connectionString = NULL; $this -&gt; sqlQuery = NULL; $this -&gt; dataSet = NULL; $this -&gt; databaseName = NULL; $this -&gt; hostName = NULL; $this -&gt; userName = NULL; $this -&gt; passCode = NULL; } function selectAll($tableName) { $this -&gt; sqlQuery = 'SELECT * FROM '.$this -&gt; databaseName.'.'.$tableName; $this -&gt; dataSet = mysql_query($this -&gt; sqlQuery,$this -&gt; connectionString); return $this -&gt; dataSet; } function selectWhere($tableName,$rowName,$operator,$value,$valueType) { $this -&gt; sqlQuery = 'SELECT * FROM '.$tableName.' WHERE '.$rowName.' '.$operator.' '; if($valueType == 'int') { $this -&gt; sqlQuery .= $value; } else if($valueType == 'char') { $this -&gt; sqlQuery .= &quot;'&quot;.$value.&quot;'&quot;; } $this -&gt; dataSet = mysql_query($this -&gt; sqlQuery,$this -&gt; connectionString); $this -&gt; sqlQuery = NULL; return $this -&gt; dataSet; #return $this -&gt; sqlQuery; } function insertInto($tableName,$values) { $i = NULL; $this -&gt; sqlQuery = 'INSERT INTO '.$tableName.' VALUES ('; $i = 0; while($values[$i][&quot;val&quot;] != NULL &amp;&amp; $values[$i][&quot;type&quot;] != NULL) { if($values[$i][&quot;type&quot;] == &quot;char&quot;) { $this -&gt; sqlQuery .= &quot;'&quot;; $this -&gt; sqlQuery .= $values[$i][&quot;val&quot;]; $this -&gt; sqlQuery .= &quot;'&quot;; } else if($values[$i][&quot;type&quot;] == 'int') { $this -&gt; sqlQuery .= $values[$i][&quot;val&quot;]; } $i++; if($values[$i][&quot;val&quot;] != NULL) { $this -&gt; sqlQuery .= ','; } } $this -&gt; sqlQuery .= ')'; #echo $this -&gt; sqlQuery; mysql_query($this -&gt; sqlQuery,$this -&gt;connectionString); return $this -&gt; sqlQuery; #$this -&gt; sqlQuery = NULL; } function selectFreeRun($query) { $this -&gt; dataSet = mysql_query($query,$this -&gt; connectionString); return $this -&gt; dataSet; } function freeRun($query) { return mysql_query($query,$this -&gt; connectionString); } } ?&gt; </code></pre> <p>and the configuration file...</p> <pre><code>&lt;?php class Dbconfig { protected $serverName; protected $userName; protected $passCode; protected $dbName; function Dbconfig() { $this -&gt; serverName = 'localhost'; $this -&gt; userName = 'root'; $this -&gt; passCode = 'pass'; $this -&gt; dbName = 'dbase'; } } ?&gt; </code></pre>
3,241,136
How to repeat some action certain times on Vim?
<p>In Vim, I usually want to repeat some series of commands some times. Say, I want to comment 5 lines, I would use</p> <pre><code>I//&lt;Esc&gt;j .j.j.j.j </code></pre> <p>Is there any way to repeat the last ".j" part several times?</p>
3,241,198
6
2
null
2010-07-13 20:17:24.07 UTC
8
2020-05-31 00:57:51.98 UTC
null
null
null
null
305,597
null
1
28
macros|vim|repeat
18,528
<p>One way to do this is to assign your key sequence to a macro, then run the macro once followed by the <code>@@</code> run-last-macro command. For example:</p> <pre><code>qa.jq@a@@ </code></pre> <p>If you know how many times you want to repeat the macro, you can use <code>4@@</code> or whatever.</p>
3,770,019
UISwitch in a UITableView cell
<p>How can I embed a <code>UISwitch</code> on a <code>UITableView</code> cell? Examples can be seen in the settings menu.</p> <p><strong>My current solution:</strong></p> <pre><code>UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease]; cell.accessoryView = mySwitch; </code></pre>
3,773,570
6
1
null
2010-09-22 14:03:09.06 UTC
21
2021-06-27 01:17:17.82 UTC
2010-09-22 17:12:41.177 UTC
null
426,227
null
426,227
null
1
82
iphone|objective-c|cocoa-touch|uitableview|uiswitch
62,492
<p>Setting it as the accessoryView is usually the way to go. You can set it up in <code>tableView:cellForRowAtIndexPath:</code> You may want to use target/action to do something when the switch is flipped. Like so:</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { switch( [indexPath row] ) { case MY_SWITCH_CELL: { UITableViewCell *aCell = [tableView dequeueReusableCellWithIdentifier:@"SwitchCell"]; if( aCell == nil ) { aCell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"SwitchCell"] autorelease]; aCell.textLabel.text = @"I Have A Switch"; aCell.selectionStyle = UITableViewCellSelectionStyleNone; UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero]; aCell.accessoryView = switchView; [switchView setOn:NO animated:NO]; [switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged]; [switchView release]; } return aCell; } break; } return nil; } - (void)switchChanged:(id)sender { UISwitch *switchControl = sender; NSLog( @"The switch is %@", switchControl.on ? @"ON" : @"OFF" ); } </code></pre>
3,914,445
How to write contents of one file to another file?
<p>I need to write contents of a file to another file using File.OpenRead and File.OpenWrite methods. I am unable to figure out how to do it.</p> <p>How can i modify the following code to work for me.</p> <pre><code>using (FileStream stream = File.OpenRead("C:\\file1.txt")) using (FileStream writeStream = File.OpenWrite("D:\\file2.txt")) { BinaryReader reader = new BinaryReader(stream); BinaryWriter writer = new BinaryWriter(writeStream); writer.Write(reader.ReadBytes(stream.Length)); } </code></pre>
3,914,744
8
3
null
2010-10-12 12:05:20.127 UTC
5
2020-12-09 14:31:28.437 UTC
2010-10-13 05:09:25.917 UTC
null
473,303
null
473,303
null
1
16
c#|.net
51,831
<pre><code> using (FileStream stream = File.OpenRead("C:\\file1.txt")) using (FileStream writeStream = File.OpenWrite("D:\\file2.txt")) { BinaryReader reader = new BinaryReader(stream); BinaryWriter writer = new BinaryWriter(writeStream); // create a buffer to hold the bytes byte[] buffer = new Byte[1024]; int bytesRead; // while the read method returns bytes // keep writing them to the output stream while ((bytesRead = stream.Read(buffer, 0, 1024)) &gt; 0) { writeStream.Write(buffer, 0, bytesRead); } } </code></pre> <p>Just wonder why not to use this:</p> <pre><code>File.Copy("C:\\file1.txt", "D:\\file2.txt"); </code></pre>
3,890,621
how does multiplication differ for NumPy Matrix vs Array classes?
<p>The numpy docs recommend using array instead of matrix for working with matrices. However, unlike octave (which I was using till recently), * doesn't perform matrix multiplication, you need to use the function matrixmultipy(). I feel this makes the code very unreadable.</p> <p>Does anybody share my views, and has found a solution?</p>
25,476,540
8
4
null
2010-10-08 12:50:47.82 UTC
58
2019-04-11 03:55:25.423 UTC
2014-12-13 07:24:22.65 UTC
null
66,549
null
470,229
null
1
143
python|arrays|numpy|matrix|matrix-multiplication
246,559
<p>In 3.5, Python finally <a href="http://legacy.python.org/dev/peps/pep-0465/" rel="noreferrer">got a matrix multiplication operator</a>. The syntax is <code>a @ b</code>.</p>
3,348,460
CSV file written with Python has blank lines between each row
<pre><code>import csv with open('thefile.csv', 'rb') as f: data = list(csv.reader(f)) import collections counter = collections.defaultdict(int) for row in data: counter[row[10]] += 1 with open('/pythonwork/thefile_subset11.csv', 'w') as outfile: writer = csv.writer(outfile) for row in data: if counter[row[10]] &gt;= 504: writer.writerow(row) </code></pre> <p>This code reads <code>thefile.csv</code>, makes changes, and writes results to <code>thefile_subset1</code>.</p> <p>However, when I open the resulting csv in Microsoft Excel, there is an extra blank line after each record!</p> <p>Is there a way to make it not put an extra blank line?</p>
3,348,664
11
5
null
2010-07-27 22:14:42.98 UTC
142
2022-05-19 18:46:51.527 UTC
2018-12-06 22:59:34.153 UTC
null
355,230
null
117,700
null
1
645
python|windows|csv
461,413
<p>The <code>csv.writer</code> module directly controls line endings and writes <code>\r\n</code> into the file directly. In <strong>Python 3</strong> the file must be opened in untranslated text mode with the parameters <code>'w', newline=''</code> (empty string) or it will write <code>\r\r\n</code> on Windows, where the default text mode will translate each <code>\n</code> into <code>\r\n</code>.</p> <pre><code>#!python3 with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile: writer = csv.writer(outfile) </code></pre> <p>In <strong>Python 2</strong>, use binary mode to open <code>outfile</code> with mode <code>'wb'</code> instead of <code>'w'</code> to prevent Windows newline translation. Python 2 also has problems with Unicode and requires other workarounds to write non-ASCII text. See the Python 2 link below and the <code>UnicodeReader</code> and <code>UnicodeWriter</code> examples at the end of the page if you have to deal with writing Unicode strings to CSVs on Python 2, or look into the 3rd party <a href="https://pypi.org/project/unicodecsv/" rel="noreferrer">unicodecsv</a> module:</p> <pre><code>#!python2 with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile: writer = csv.writer(outfile) </code></pre> <h3>Documentation Links</h3> <ul> <li><a href="https://docs.python.org/3/library/csv.html#csv.writer" rel="noreferrer">https://docs.python.org/3/library/csv.html#csv.writer</a></li> <li><a href="https://docs.python.org/2/library/csv.html#csv.writer" rel="noreferrer">https://docs.python.org/2/library/csv.html#csv.writer</a></li> </ul>
7,937,963
Batch file to upload .txt to FTP
<p>I have setup a separate FTP account for this. </p> <p>Here is the info:</p> <pre><code>FTP Username: [email protected] FTP Server: ftp.proflightsimulatoreview.com FTP Server Port: 21 FTP Password: ahktest </code></pre> <p>Text file I want to upload: <code>C:\Users\Kyle\Desktop\ftptest\thetest.txt</code></p> <p>Please show me how to do this with batch. My understanding is that you make a separate txt file with the FTP commands and then you use a batch file to run it. Well I must have not plugged in the info right because it didn't work.</p> <p>So here I am giving you the information. Please show me how to upload a text file.</p>
7,938,073
4
5
null
2011-10-29 09:13:50.923 UTC
6
2020-05-14 17:48:20.567 UTC
2020-05-14 17:48:20.567 UTC
null
850,848
null
1,019,588
null
1
13
windows|batch-file|cmd|ftp
86,847
<p>I just put HELLO.TXT in your ftp root by;</p> <p><strong>1</strong>. Saving this as <code>MYFTP.bat</code>:</p> <pre><code>@echo off echo user [email protected]&gt; ftpcmd.dat echo ahktest&gt;&gt; ftpcmd.dat echo put %1&gt;&gt; ftpcmd.dat echo quit&gt;&gt; ftpcmd.dat ftp -n -s:ftpcmd.dat ftp.proflightsimulatoreview.com del ftpcmd.dat </code></pre> <p><strong>2</strong>. From the command line, in the same directory as <code>MYFTP.BAT</code>, running;</p> <pre><code>MYFTP.BAT c:\temp\hello.txt </code></pre> <p>result</p> <pre><code>220---------- Welcome to Pure-FTPd [privsep] [TLS] ---------- 220-You are user number 2 of 50 allowed. 220-Local time is now 05:17. Server port: 21. 220 You will be disconnected after 15 minutes of inactivity. ftp&gt; user [email protected] 331 User [email protected] OK. Password required 230-OK. Current restricted directory is / 230 0 Kbytes used (0%) - authorized: 51200 Kb ftp&gt; put hello.txt 200 PORT command successful 150 Connecting to port 59363 226-0 Kbytes used (0%) - authorized: 51200 Kb 226-File successfully transferred 226 0.563 seconds (measured here), 14.20 bytes per second ftp: 8 bytes sent in 0.34Seconds 0.02Kbytes/sec. ftp&gt; quit 221-Goodbye. You uploaded 1 and downloaded 0 kbytes. 221 Logout. </code></pre>
8,297,860
where can I get FIX DATA (FIX as in FIX PROTOCOL)
<p>Can somebody suggest a place (websites) where to find 'real' FIX messages. By real I mean not examples but 'real' so that if I put them into an engine it won't complain that tag 10 is incorrect or that I am missing some mandatory tags. </p> <p>I am specifically after execution reports.</p> <p>Ideally I'd love to find a large sequence of fix messages representing few days of activities. I appreciate this can be sensitive data but surely tag 1,tag 207,tag 55 can all be obfuscated.</p> <p>Many Thanks</p>
8,605,102
7
1
null
2011-11-28 15:08:15.327 UTC
8
2015-09-29 22:27:02.067 UTC
null
null
null
null
246,394
null
1
8
fix-protocol
11,711
<p>You can get some sample data from validfix.</p> <p><a href="http://www.validfix.com/fix-analyzer.html" rel="nofollow">fix-analyzer.html</a> has many examples of different fix messages</p> <p><a href="http://www.validfix.com/fix-log-analyzer.html" rel="nofollow">fix-log-analyzer.html</a> has just one big example of a real log from some sort of fix engine.</p> <p>(fixed broken link)</p>
8,060,904
Add / Delete pages to ViewPager dynamically
<p>I would like to add or delete pages from my view pager dynamically. Is that possible?</p>
8,060,968
9
2
null
2011-11-09 05:50:55.567 UTC
26
2020-01-29 14:57:15.977 UTC
null
null
null
null
802,799
null
1
59
android|android-viewpager
74,388
<p>Yes, since ViewPager gets the child Views from a PagerAdapter, you can add new pages / delete pages on that, and call .notifyDataSetChanged() to reload it.</p>
8,356,358
jQuery Date Picker - disable past dates
<p>I am trying to have a date Range select using the UI date picker.</p> <p>in the from/to field people should not be able to view or select dates previous to the present day.</p> <p>This is my code:</p> <pre><code>$(function() { var dates = $( "#from, #to" ).datepicker({ defaultDate: "+1w", changeMonth: true, numberOfMonths: 1, onSelect: function( selectedDate ) { var option = this.id == "from" ? "minDate" : "maxDate", instance = $( this ).data( "datepicker" ), date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings ); dates.not( this ).datepicker( "option", option, date ); } }); }); </code></pre> <p>Can some one tell me how to disable dates previous the to the present date.</p>
8,356,601
16
0
null
2011-12-02 12:31:15.65 UTC
31
2020-09-03 09:04:55.553 UTC
null
null
null
null
155,196
null
1
94
jquery|jquery-ui|datepicker|uidatepicker|jquery-ui-datepicker
358,008
<p>You must create a new date object and set it as <code>minDate</code> when you initialize the datepickers</p> <pre><code>&lt;label for="from"&gt;From&lt;/label&gt; &lt;input type="text" id="from" name="from"/&gt; &lt;label for="to"&gt;to&lt;/label&gt; &lt;input type="text" id="to" name="to"/&gt; var dateToday = new Date(); var dates = $("#from, #to").datepicker({ defaultDate: "+1w", changeMonth: true, numberOfMonths: 3, minDate: dateToday, onSelect: function(selectedDate) { var option = this.id == "from" ? "minDate" : "maxDate", instance = $(this).data("datepicker"), date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings); dates.not(this).datepicker("option", option, date); } }); </code></pre> <p>Edit - from your comment now it works as expected <a href="http://jsfiddle.net/nicolapeluchetti/dAyzq/1/" rel="noreferrer">http://jsfiddle.net/nicolapeluchetti/dAyzq/1/</a></p>
4,708,613
Graphing the pitch (frequency) of a sound
<p>I want to plot the pitch of a sound into a graph.</p> <p>Currently I can plot the amplitude. The graph below is created by the data returned by <code>getUnscaledAmplitude()</code>:</p> <p><img src="https://i.stack.imgur.com/a2pVM.jpg" alt="alt text"></p> <pre><code>AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(file))); byte[] bytes = new byte[(int) (audioInputStream.getFrameLength()) * (audioInputStream.getFormat().getFrameSize())]; audioInputStream.read(bytes); // Get amplitude values for each audio channel in an array. graphData = type.getUnscaledAmplitude(bytes, 1); public int[][] getUnscaledAmplitude(byte[] eightBitByteArray, int nbChannels) { int[][] toReturn = new int[nbChannels][eightBitByteArray.length / (2 * nbChannels)]; int index = 0; for (int audioByte = 0; audioByte &lt; eightBitByteArray.length;) { for (int channel = 0; channel &lt; nbChannels; channel++) { // Do the byte to sample conversion. int low = (int) eightBitByteArray[audioByte]; audioByte++; int high = (int) eightBitByteArray[audioByte]; audioByte++; int sample = (high &lt;&lt; 8) + (low &amp; 0x00ff); toReturn[channel][index] = sample; } index++; } return toReturn; } </code></pre> <p>But I need to show the audio's pitch, not amplitude. <a href="http://en.wikipedia.org/wiki/Fast_Fourier_transform">Fast Fourier transform</a> appears to get the pitch, but it needs to know more variables than the raw bytes I have, and is very complex and mathematical.</p> <p>Is there a way I can do this?</p>
4,708,735
3
11
null
2011-01-16 22:46:09.413 UTC
30
2016-01-18 18:52:48.483 UTC
2011-01-16 22:52:52.78 UTC
null
224,004
null
224,004
null
1
35
java|audio|fft|frequency|pitch
35,256
<p><em>Frequency</em> (an objective metric) is not the same as <em>pitch</em> (a subjective quantity). In general, pitch detection is a very tricky problem.</p> <p>Assuming you just want to graph the frequency response for now, you have little choice but to use the FFT, as it is <em>THE</em> method to obtain the frequency response of time-domain data. (Well, there are other methods, such as the discrete cosine transform, but they're just as tricky to implement, and more tricky to interpret).</p> <p>If you're struggling with the implementation of the FFT, note that it's really just an efficient algorithm for calculating the discrete Fourier transform (DFT); see <a href="http://en.wikipedia.org/wiki/Discrete_Fourier_transform">http://en.wikipedia.org/wiki/Discrete_Fourier_transform</a>. The basic DFT algorithm is much easier (just two nested loops), but runs a <em>lot</em> slower (O(N^2) rather than O(N log N)).</p> <p>If you wish to do anything more complex than simply plotting frequency content (like pitch detection, or windowing (as others have suggested)), I'm afraid you are going to have learn what the maths means.</p>
4,349,900
How to Calculate the Square Root of a Float in C#
<p>How can I calculate the square root of a <code>Float</code> in <code>C#</code>, similar to <code>Core.Sqrt</code> in XNA?</p>
4,349,906
4
7
null
2010-12-03 21:09:42.693 UTC
null
2022-04-14 12:30:18.427 UTC
2015-01-05 21:48:20.577 UTC
null
758,458
null
449,534
null
1
9
c#|math|square-root
50,791
<p>Since .net core 2.0 you can use <a href="https://docs.microsoft.com/en-us/dotnet/api/system.mathf.sqrt" rel="nofollow noreferrer"><code>MathF.Sqrt</code></a>.</p> <p>In older versions, you can calculate it for <code>double</code> and then cast back to float. May be a bit slow, but should work.</p> <pre><code>(float)Math.Sqrt(inputFloat) </code></pre>
4,254,615
How to cast vector<unsigned char> to char*
<p>I have a buffer like this:</p> <pre><code>vector&lt;unsigned char&gt; buf </code></pre> <p>How can I cast it to char*?</p> <p>If I do:</p> <pre><code>(char *)buf </code></pre> <p>I get this error:</p> <pre><code>/home/richard/Desktop/richard/client/src/main.cc:102: error: invalid cast from type ‘std::vector&lt;unsigned char, std::allocator&lt;unsigned char&gt; &gt;’ to type ‘char*’ </code></pre> <p>For those wondering why I am trying to do this. I need to pass the buffer to this function:</p> <pre><code>n_sent = sendto(sk,(char *)buf,(int)size,0,(struct sockaddr*) &amp;server,sizeof(server)); </code></pre> <p>And it only accepts char*.</p>
4,254,644
4
0
null
2010-11-23 09:41:28.683 UTC
10
2015-03-11 19:23:24.893 UTC
2010-11-23 09:50:34.673 UTC
null
95,944
null
95,944
null
1
33
c++
54,244
<pre><code>reinterpret_cast&lt;char*&gt; (&amp;buf[0]); </code></pre> <p>The vector guarantees that its elements occupy contiguous memory. So the "data" you seek is actually the address of the first element (beware of <code>vector &lt;bool&gt;</code>, this trick will fail with it). Also, why isn't your buffer <code>vector&lt;char&gt;</code> so that you don't need to reinterpret_cast?</p> <h2>Update for C++11</h2> <pre><code>reinterpret_cast&lt;char*&gt;(buf.data()); </code></pre>
4,098,800
Oracle sql return true if exists question
<p>How do I check if a particular element exists in a table - how can I return true or false?</p> <p>I have a table that has </p> <ul> <li>user_id</li> <li>user_password</li> <li>user_secretQ</li> </ul> <p>Verbally, I want to do this: If a particular <code>user_id</code> exists in the <code>user_id</code> column, then return true -- otherwise return false.</p>
4,098,880
5
2
null
2010-11-04 16:22:21.333 UTC
2
2014-11-25 12:42:45.793 UTC
2010-11-04 16:26:13.147 UTC
null
135,152
null
368,651
null
1
22
sql|oracle|if-statement|exists
107,454
<p>There is no Boolean type in Oracle SQL. You will need to return a 1 or 0, or some such and act accordingly:</p> <pre><code>SELECT CASE WHEN MAX(user_id) IS NULL THEN 'NO' ELSE 'YES' END User_exists FROM user_id_table WHERE user_id = 'some_user'; </code></pre>
4,224,600
Can you do greater than comparison on a date in a Rails 3 search?
<p>I have this search in Rails 3:</p> <pre><code>Note.where(:user_id =&gt; current_user.id, :notetype =&gt; p[:note_type], :date =&gt; p[:date]).order('date ASC, created_at ASC') </code></pre> <p>But I need the <code>:date =&gt; p[:date]</code> condition to be equivilent to <code>:date &gt; p[:date]</code>. How can I do this? Thanks for reading.</p>
4,224,627
5
0
null
2010-11-19 11:40:21.19 UTC
25
2021-06-02 09:20:55.97 UTC
null
null
null
null
173,634
null
1
127
ruby-on-rails|activerecord|ruby-on-rails-3
123,039
<pre><code>Note. where(:user_id =&gt; current_user.id, :notetype =&gt; p[:note_type]). where("date &gt; ?", p[:date]). order('date ASC, created_at ASC') </code></pre> <p>or you can also convert everything into the SQL notation</p> <pre><code>Note. where("user_id = ? AND notetype = ? AND date &gt; ?", current_user.id, p[:note_type], p[:date]). order('date ASC, created_at ASC') </code></pre>
4,367,297
How to substitute variable contents in a Windows batch file
<p>I'm writing a simple script to substitute text in an environment variable with other text. The trouble I get is with the substituted or substituted text being pulled from other variables</p> <pre><code>SET a=The fat cat ECHO %a% REM Results in 'The fat cat' ECHO %a:fat=thin% REM Results in 'The thin cat' </code></pre> <p>Works fine (output is 'The fat cat' and 'The thin cat'</p> <p>However, if 'fat' or 'thin' are in variables, it doesn't work</p> <pre><code>SET b=fat ECHO %a:%c%=thin% REM _Should_ give 'The thin cat'. REM _Actually_ gives '%a:fat=thin%' (the %c% is evaluated, but no further). REM using delayed evaluation doesn't make any difference either ECHO !a:%c%=thin! REM Actual output is now '!a:fat=thin!' </code></pre> <p>I know this can be done as I've seen it in blogs before, but I never saved the link to the blogs.</p> <p>Anyone have any ideas?</p> <p>PS. I'm running the scripts on Windows 7</p> <p>PPS. I know this is easier in Perl/Python/other script language of choice, but I just want to know why something that should be easy is not immediately obvious.</p> <p>PPPS. I've also tried the scripts with delayed expansion explicitly turned on</p> <pre><code>SETLOCAL enabledelayedexpansion </code></pre> <p>This makes no difference.</p>
4,481,648
7
0
null
2010-12-06 14:18:31.99 UTC
1
2017-04-03 03:47:12.073 UTC
2016-07-05 04:04:16.257 UTC
null
3,826,372
null
18,744
null
1
17
windows|batch-file|cmd
49,767
<p>Please try the following:</p> <p>Copy and paste the code into Notepad and save it as a batch file.</p> <pre><code> @echo off setlocal enabledelayedexpansion set str=The fat cat set f=fat echo. echo f = [%f%] echo. echo str = [%str%] set str=!str:%f%=thin! echo str:f=thin = [%str%] </code></pre> <p>I hope you're convinced!</p>
14,853,135
The HTTP request was forbidden with client authentication scheme 'Anonymous'
<p>This seams to be a common problem, and I have looked at all the answers here but none have helped. </p> <p>I am trying to get SSL to work with basichttpbinding and WCF service hosted on iis. I think the problem is in iis or with the certificates. I have created a self signed certificate in iis manager. My certificate is called "mycomputer" and have also been placed under Trusted Root Certification. The client have no problem finding the certificate. </p> <p>My settings in iis are to enable anonymous auth, and disable everything else. Also require SSL and accept client certificate. Is that correct? I get an error if i choose to ignore. </p> <p>I cant see anything wrong with my configs, are these correct?</p> <p>Service config:</p> <pre><code>&lt;system.serviceModel&gt; &lt;services&gt; &lt;service behaviorConfiguration="MyBehaviour" name="BasicHttpSecTest.Service1"&gt; &lt;endpoint name="MyEndPoint" address="https://mycomputer/wp/" binding="basicHttpBinding" bindingConfiguration="ClientCertificateTransportSecurity" contract="BasicHttpSecTest.IService1" /&gt; &lt;!--&lt;endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" /&gt;--&gt; &lt;/service&gt; &lt;/services&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="MyBehaviour"&gt; &lt;serviceMetadata httpsGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="true" /&gt; &lt;serviceCredentials&gt; &lt;clientCertificate&gt; &lt;authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck"/&gt; &lt;/clientCertificate&gt; &lt;/serviceCredentials&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="ClientCertificateTransportSecurity"&gt; &lt;security mode="Transport"&gt; &lt;transport clientCredentialType="Certificate" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; &lt;/bindings&gt; &lt;/system.serviceModel&gt; </code></pre> <p>Client Config:</p> <pre><code>&lt;system.serviceModel&gt; &lt;client&gt; &lt;endpoint address="https://mycomputer/wp/Service1.svc" binding="basicHttpBinding" bindingConfiguration="MyEndPoint" contract="ServiceSSLref.IService1" name="MyEndPoint1" behaviorConfiguration="ClientCertificateCredential"/&gt; &lt;/client&gt; &lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="MyEndPoint"&gt; &lt;security mode="Transport"&gt; &lt;transport clientCredentialType="Certificate" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; &lt;/bindings&gt; &lt;behaviors&gt; &lt;endpointBehaviors&gt; &lt;behavior name="ClientCertificateCredential"&gt; &lt;clientCredentials&gt; &lt;clientCertificate findValue="mycomputer" storeLocation="LocalMachine" storeName="My" x509FindType="FindByIssuerName" /&gt; &lt;serviceCertificate&gt; &lt;authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck"/&gt; &lt;/serviceCertificate&gt; &lt;/clientCredentials&gt; &lt;/behavior&gt; &lt;/endpointBehaviors&gt; &lt;/behaviors&gt; &lt;/system.serviceModel&gt; </code></pre>
14,853,831
1
0
null
2013-02-13 12:02:53.943 UTC
2
2017-12-11 09:32:24.46 UTC
null
null
null
null
1,310,470
null
1
8
wcf|security|https|certificate|transport-security
63,388
<p>I suppose that your problem might be in your client certificate. Setting clientCredentialType="Certificate" you tell WCF, that client must specify a certificate trusted by the server. As I've understood, you have only server-side generated certificate. Try to set</p> <pre><code> &lt;transport clientCredentialType="None" /&gt; </code></pre> <p>This will allow you to send messages without requiring certificate trusted by the server. Or you can try to generate certificate on client side and put it into Trusted folder on your server. Maybe this state will help you <a href="http://msdn.microsoft.com/en-us/library/ms731074.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms731074.aspx</a></p>
14,889,395
Concrete sample merges of git that won't work in SVN
<p><strong>I'm looking for concrete sample merges that will work in git, but will result in a conflict in SVN.</strong> In addition to that, samples of hard/painful SVN merges that you never tried in Git would also be fine.</p> <p>There are mainly four categories of merges I could identify in relation to my question:</p> <ol> <li><a href="https://stackoverflow.com/questions/6172037/really-a-concrete-example-that-merging-in-git-is-easier-than-svn/6172181#6172181">big bang merges</a></li> <li>rename/move related merges</li> <li>created directories/identical files in both branches </li> <li><a href="https://stackoverflow.com/questions/6172037/really-a-concrete-example-that-merging-in-git-is-easier-than-svn/6178091#6178091"><strong>criss cross merges</strong></a> </li> </ol> <p><strong>Did I miss any scenarios here?</strong></p> <p>Finding samples for 1-3 is trivial (Find a sample for 2 in the comments, 3 as part of my answer and 1 is nearly any rebase). <strong>Has anybody a sample</strong> (that doesn't look to academic) <strong>for a successful criss cross merge, which will fail in SVN?</strong></p>
14,891,878
3
14
2013-02-20 14:24:42.917 UTC
2013-02-15 06:29:55.227 UTC
9
2013-03-06 06:17:40.297 UTC
2017-05-23 12:06:12.67 UTC
null
-1
null
638,893
null
1
12
git|svn|merge
1,291
<p>Found an <a href="http://www.laliluna.de/articles/2012/06/15/when-subversion-fails.html" rel="nofollow noreferrer">article</a> with a nice sample. The "team b" branch is only created to show the tree conflict with creating the same directory in two branches. Here is an overview: <img src="https://i.stack.imgur.com/lIe6z.png" alt="Wall sample"></p>
14,643,735
how to generate a unique token which expires after 24 hours?
<p>I have a WCF Webservice which checks if the user is valid. </p> <p>If the user is valid I want to generate a token which expires after 24 hours.</p> <pre><code>public bool authenticateUserManual(string userName, string password,string language,string token) { if (Membership.ValidateUser(userName,password)) { ////////// string token = ???? ////////// return true; } else { return false; } } </code></pre>
14,644,367
6
2
null
2013-02-01 10:00:48.307 UTC
70
2022-02-19 20:15:38.16 UTC
2013-02-01 10:02:37.99 UTC
null
1,916,110
null
1,222,917
null
1
49
c#|asp.net|wcf|authentication|token
128,228
<p>There are two possible approaches; either you create a unique value and store somewhere along with the creation time, for example in a database, or you put the creation time inside the token so that you can decode it later and see when it was created.</p> <p>To create a unique token:</p> <pre><code>string token = Convert.ToBase64String(Guid.NewGuid().ToByteArray()); </code></pre> <p>Basic example of creating a unique token containing a time stamp:</p> <pre><code>byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary()); byte[] key = Guid.NewGuid().ToByteArray(); string token = Convert.ToBase64String(time.Concat(key).ToArray()); </code></pre> <p>To decode the token to get the creation time:</p> <pre><code>byte[] data = Convert.FromBase64String(token); DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0)); if (when &lt; DateTime.UtcNow.AddHours(-24)) { // too old } </code></pre> <p>Note: If you need the token with the time stamp to be secure, you need to encrypt it. Otherwise a user could figure out what it contains and create a false token.</p>
14,570,989
Best practice for storing and protecting private API keys in applications
<p>Most app developers will integrate some third party libraries into their apps. If it's to access a service, such as Dropbox or YouTube, or for logging crashes. The number of third party libraries and services is staggering. Most of those libraries and services are integrated by somehow authenticating with the service, most of the time, this happens through an API key. For security purposes, services usually generate a public and private, often also referred to as secret, key. Unfortunately, in order to connect to the services, this private key must be used to authenticate and hence, probably be part of the application. Needless to say, that this faces in immense security problem. Public and private API keys can be extracted from APKs in a matter of minutes and can easily be automated. </p> <p>Assuming I have something similar to this, how can I protect the secret key:</p> <pre><code>public class DropboxService { private final static String APP_KEY = "jk433g34hg3"; private final static String APP_SECRET = "987dwdqwdqw90"; private final static AccessType ACCESS_TYPE = AccessType.DROPBOX; // SOME MORE CODE HERE } </code></pre> <p>What is in your opinion the best and most secure way to store the private key? Obfuscation, encryption, what do you think?</p>
14,572,051
13
3
null
2013-01-28 20:50:32.847 UTC
208
2022-04-27 12:28:38.067 UTC
2018-02-03 07:40:21.763 UTC
null
940,300
null
940,300
null
1
451
android|reverse-engineering|proguard|api-key
205,015
<ol> <li><p>As it is, your compiled application contains the key strings, but also the constant names APP_KEY and APP_SECRET. Extracting keys from such self-documenting code is trivial, for instance with the standard Android tool dx.</p></li> <li><p>You can apply ProGuard. It will leave the key strings untouched, but it will remove the constant names. It will also rename classes and methods with short, meaningless names, where ever possible. Extracting the keys then takes some more time, for figuring out which string serves which purpose.</p> <p><em>Note that setting up ProGuard shouldn't be as difficult as you fear. To begin with, you only need to enable ProGuard, as documented in project.properties. If there are any problems with third-party libraries, you may need to suppress some warnings and/or prevent them from being obfuscated, in proguard-project.txt. For instance:</em></p> <pre><code>-dontwarn com.dropbox.** -keep class com.dropbox.** { *; } </code></pre> <p><em>This is a brute-force approach; you can refine such configuration once the processed application works.</em></p></li> <li><p>You can obfuscate the strings manually in your code, for instance with a Base64 encoding or preferably with something more complicated; maybe even native code. A hacker will then have to statically reverse-engineer your encoding or dynamically intercept the decoding in the proper place.</p></li> <li><p>You can apply a commercial obfuscator, like ProGuard's specialized sibling <a href="http://www.saikoa.com/dexguard">DexGuard</a>. It can additionally encrypt/obfuscate the strings and classes for you. Extracting the keys then takes even more time and expertise.</p></li> <li><p>You might be able to run parts of your application on your own server. If you can keep the keys there, they are safe.</p></li> </ol> <p>In the end, it's an economic trade-off that you have to make: how important are the keys, how much time or software can you afford, how sophisticated are the hackers who are interested in the keys, how much time will they want to spend, how much worth is a delay before the keys are hacked, on what scale will any successful hackers distribute the keys, etc. Small pieces of information like keys are more difficult to protect than entire applications. Intrinsically, nothing on the client-side is unbreakable, but you can certainly raise the bar.</p> <p>(I am the developer of ProGuard and DexGuard)</p>
24,422,123
Change boot2docker memory assignment
<p>I've been playing around with docker on a mac so I need to install boot2docker to make it work.</p> <p>I have a pretty powerful machine and a very resource hungry app so I want to up the available memory from the default which is <a href="https://github.com/boot2docker/boot2docker/blob/master/doc/FAQ.md">1GB</a> to something like 8GB.</p> <hr> <p><strong>This is what I've tried</strong></p> <p>Booting boot2dock with the --memory param</p> <pre><code>boot2docker --memory=8116 boot </code></pre> <p>Change the config file</p> <pre><code>Verbose = true VBM = "VBoxManage" SSH = "ssh" SSHGen = "ssh-keygen" SSHKey = "/Users/mjsilva/.ssh/id_boot2docker" VM = "boot2docker-vm" Dir = "/Users/mjsilva/.boot2docker" ISO = "/Users/mjsilva/.boot2docker/boot2docker.iso" VMDK = "" DiskSize = 20000 Memory = 8116 SSHPort = 2022 DockerPort = 2375 HostIP = "192.168.59.3" DHCPIP = "192.168.59.99" NetMask = [255, 255, 255, 0] LowerIP = "192.168.59.103" UpperIP = "192.168.59.254" DHCPEnabled = true Serial = false SerialFile = "/Users/mjsilva/.boot2docker/boot2docker-vm.sock" </code></pre> <p>and then booting boot2docker</p> <pre><code>boot2docker boot </code></pre> <p>None of this approaches seem to work. I only end up only having the default memory.</p> <hr> <p>The only way I manage to change was going to virtualbox GUI shutdown boot2docker, change it manually and boot it again.</p> <p>Am I missing something?</p>
24,433,464
6
0
null
2014-06-26 03:56:05.863 UTC
13
2017-12-13 12:27:25.477 UTC
null
null
null
null
223,416
null
1
34
docker|boot2docker
13,667
<p>You will need to re-initialize the boot2docker VM with the new memory settings:</p> <pre><code>$ boot2docker delete $ boot2docker init -m 5555 ... lots of output ... $ boot2docker info { ... "Memory":5555 ...} </code></pre> <p>You can now <code>boot2docker up</code> and the image will always use the configured amount of memory.</p>
30,614,454
How to test a prop update on React component
<p>What is the correct way of unit testing a React component prop update.</p> <p>Here is my test fixture;</p> <pre><code>describe('updating the value', function(){ var component; beforeEach(function(){ component = TestUtils.renderIntoDocument(&lt;MyComponent value={true} /&gt;); }); it('should update the state of the component when the value prop is changed', function(){ // Act component.props.value = false; component.forceUpdate(); // Assert expect(component.state.value).toBe(false); }); }); </code></pre> <p>This works fine and the test passes, however this displays a react warning message</p> <pre><code>'Warning: Dont set .props.value of the React component &lt;exports /&gt;. Instead specify the correct value when initially creating the element or use React.cloneElement to make a new element with updated props.' </code></pre> <p>All i want to test is the update of a property, not to create a new instance of the element with a different property. Is there a better way to do this property update?</p>
35,493,301
9
0
null
2015-06-03 08:15:30.187 UTC
7
2021-08-16 09:29:04.937 UTC
null
null
null
null
2,021,955
null
1
49
unit-testing|jasmine|reactjs
63,834
<p>AirBnB's <a href="http://airbnb.io/enzyme/docs/api/ShallowWrapper/setProps.html" rel="noreferrer">Enzyme</a> library provides an elegant solution to this question.</p> <p>it provides a setProps method, that can be called on either a shallow or jsdom wrapper.</p> <pre><code> it("Component should call componentWillReceiveProps on update", () =&gt; { const spy = sinon.spy(Component.prototype, "componentWillReceiveProps"); const wrapper = shallow(&lt;Component {...props} /&gt;); expect(spy.calledOnce).to.equal(false); wrapper.setProps({ prop: 2 }); expect(spy.calledOnce).to.equal(true); }); </code></pre>
38,709,280
How to limit the number of retries on Spark job failure?
<p>We are running a Spark job via <code>spark-submit</code>, and I can see that the job will be re-submitted in the case of failure.</p> <p>How can I stop it from having attempt #2 in case of yarn container failure or whatever the exception be?</p> <p><a href="https://i.stack.imgur.com/lqdyg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lqdyg.png" alt="enter image description here"></a></p> <p>This happened due to lack of memory and "GC overhead limit exceeded" issue.</p>
38,720,814
4
0
null
2016-08-01 22:52:05.667 UTC
6
2020-07-02 16:57:21.387 UTC
2019-07-01 13:06:55.103 UTC
null
1,305,344
null
1,834,377
null
1
39
apache-spark|hadoop-yarn
51,378
<p>There are two settings that control the number of retries (i.e. the maximum number of <code>ApplicationMaster</code> registration attempts with YARN is considered failed and hence the entire Spark application):</p> <ul> <li><p><code>spark.yarn.maxAppAttempts</code> - Spark's own setting. See <a href="https://github.com/apache/spark/blob/v3.0.0/resource-managers/yarn/src/main/scala/org/apache/spark/deploy/yarn/config.scala#L61-L65" rel="noreferrer">MAX_APP_ATTEMPTS</a>:</p> <pre><code> private[spark] val MAX_APP_ATTEMPTS = ConfigBuilder(&quot;spark.yarn.maxAppAttempts&quot;) .doc(&quot;Maximum number of AM attempts before failing the app.&quot;) .intConf .createOptional </code></pre> </li> <li><p><code>yarn.resourcemanager.am.max-attempts</code> - YARN's own setting with default being 2.</p> </li> </ul> <p>(As you can see in <a href="https://github.com/apache/spark/blob/v3.0.0/resource-managers/yarn/src/main/scala/org/apache/spark/deploy/yarn/YarnRMClient.scala#L124-L133" rel="noreferrer">YarnRMClient.getMaxRegAttempts</a>) the actual number is the minimum of the configuration settings of YARN and Spark with YARN's being the last resort.</p>
54,217,833
is it possible to retrieve engine value from a sql alchemy session
<p>First I create a session as follows: </p> <pre><code>from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker some_engine = create_engine('my_engine_string') Session = sessionmaker(bind=some_engine) session = Session() </code></pre> <p>Then I send this session as an argument to a method</p> <pre><code>def example(session): print("you created a session!") </code></pre> <p>Is it possible to get the value of <code>some_engine</code> from <code>session</code> inside the <code>example</code> method? without actually passing <code>some_engine</code> or <code>my_engine_string</code> to <code>example</code> method.</p> <p>Something as below:</p> <pre><code>def example(session): print("you created a session!") engine = &lt;using session get the value of `some_engine`&gt; print("the engine is retrieved from session") </code></pre>
54,217,893
1
0
null
2019-01-16 13:13:07.19 UTC
null
2020-02-12 22:26:10.643 UTC
null
null
null
null
7,987,878
null
1
36
python|sqlalchemy
8,642
<p><a href="https://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session" rel="noreferrer"><code>Session</code></a>s have the <a href="https://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.get_bind" rel="noreferrer"><code>.get_bind()</code></a> method which in your case will return your <a href="https://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Engine" rel="noreferrer"><code>Engine</code></a> instance.</p> <blockquote> <p>Relevant excerpt from the <a href="https://docs.sqlalchemy.org/" rel="noreferrer"><code>sqlalchemy docs</code></a>:</p> <blockquote> <p>Return a “bind” to which this <a href="https://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session" rel="noreferrer"><code>Session</code></a> is bound.</p> <p>The “bind” is usually an instance of <a href="https://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Engine" rel="noreferrer"><code>Engine</code></a>, except in the case where the <a href="https://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session" rel="noreferrer"><code>Session</code></a> has been explicitly bound directly to a <a href="https://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Connection" rel="noreferrer"><code>Connection</code></a>.</p> </blockquote> </blockquote> <p>Thus your <code>example()</code> function could do something like:</p> <pre><code>def example(session): print("you created a session!") engine = session.get_bind() print("the engine is retrieved from session") </code></pre>
34,458,261
How to get simple dispatch from this.props using connect w/ Redux?
<p>I've got a simple React component that I connect up (mapping a simple array/state over). To keep from referencing the context for store I'd like a way to get "dispatch" directly from props. I've seen others using this approach but don't have access to this for some reason :)</p> <p>Here are the versions of each npm dependency I'm using currently</p> <pre><code>"react": "0.14.3", "react-redux": "^4.0.0", "react-router": "1.0.1", "redux": "^3.0.4", "redux-thunk": "^1.0.2" </code></pre> <p>Here is the component w/ connect method</p> <pre><code>class Users extends React.Component { render() { const { people } = this.props; return ( &lt;div&gt; &lt;div&gt;{this.props.children}&lt;/div&gt; &lt;button onClick={() =&gt; { this.props.dispatch({type: ActionTypes.ADD_USER, id: 4}); }}&gt;Add User&lt;/button&gt; &lt;/div&gt; ); } }; function mapStateToProps(state) { return { people: state.people }; } export default connect(mapStateToProps, { fetchUsers })(Users); </code></pre> <p>If you need to see the reducer (nothing exciting but here it is)</p> <pre><code>const initialState = { people: [] }; export default function(state=initialState, action) { if (action.type === ActionTypes.ADD_USER) { let newPeople = state.people.concat([{id: action.id, name: 'wat'}]); return {people: newPeople}; } return state; }; </code></pre> <p>If you need to see how my router is configured w/ redux</p> <pre><code>const createStoreWithMiddleware = applyMiddleware( thunk )(createStore); const store = createStoreWithMiddleware(reducers); var Route = ( &lt;Provider store={store}&gt; &lt;Router history={createBrowserHistory()}&gt; {Routes} &lt;/Router&gt; &lt;/Provider&gt; ); </code></pre> <p><strong>update</strong></p> <p>looks like if I omit my own dispatch in the connect (currently above I'm showing fetchUsers), I'd get dispatch free (just not sure if this is how a setup w/ async actions would work usually). Do people mix and match or is it all or nothing?</p> <p>[mapDispatchToProps]</p>
34,458,710
3
0
null
2015-12-24 22:00:26.177 UTC
66
2017-06-30 15:17:05.883 UTC
2015-12-24 23:01:06.57 UTC
null
1,248,224
null
2,701
null
1
110
javascript|reactjs|redux
67,189
<p>By default <code>mapDispatchToProps</code> is just <code>dispatch =&gt; ({ dispatch })</code>.<br> So if you don't specify the second argument to <code>connect()</code>, you'll get <code>dispatch</code> injected as a prop in your component.</p> <p>If you pass a custom function to <code>mapDispatchToProps</code>, you can do anything with the function.<br> A few examples:</p> <pre><code>// inject onClick function mapDispatchToProps(dispatch) { return { onClick: () =&gt; dispatch(increment()) }; } // inject onClick *and* dispatch function mapDispatchToProps(dispatch) { return { dispatch, onClick: () =&gt; dispatch(increment()) }; } </code></pre> <p>To save you some typing Redux provides <code>bindActionCreators()</code> that lets you turn this:</p> <pre><code>// injects onPlusClick, onMinusClick function mapDispatchToProps(dispatch) { return { onPlusClick: () =&gt; dispatch(increment()), onMinusClick: () =&gt; dispatch(decrement()) }; } </code></pre> <p>into this:</p> <pre><code>import { bindActionCreators } from 'redux'; // injects onPlusClick, onMinusClick function mapDispatchToProps(dispatch) { return bindActionCreators({ onPlusClick: increment, onMinusClick: decrement }, dispatch); } </code></pre> <p>or even shorter when prop names match action creator names:</p> <pre><code>// injects increment and decrement function mapDispatchToProps(dispatch) { return bindActionCreators({ increment, decrement }, dispatch); } </code></pre> <p>If you'd like you can definitely add <code>dispatch</code> there by hand:</p> <pre><code>// injects increment, decrement, and dispatch itself function mapDispatchToProps(dispatch) { return { ...bindActionCreators({ increment, decrement }), // es7 spread syntax dispatch }; } </code></pre> <p>There's no official advise on whether you should do this or not. <code>connect()</code> usually serves as the boundary between Redux-aware and Redux-unaware components. This is why we usually feel that it doesn't make sense to inject <em>both</em> bound action creators and <code>dispatch</code>. But if you feel like you need to do this, feel free to.</p> <p>Finally, the pattern you are using right now is a shortcut that's even shorter than calling <code>bindActionCreators</code>. When all you do is return <code>bindActionCreators</code>, you can omit the call so instead of doing this:</p> <pre><code>// injects increment and decrement function mapDispatchToProps(dispatch) { return bindActionCreators({ increment, decrement }, dispatch); } export default connect( mapStateToProps, mapDispatchToProps )(App); </code></pre> <p>can be written as this</p> <pre><code>export default connect( mapStateToProps, { increment, decrement } // injects increment and decrement )(App); </code></pre> <p>However you'll have to give up that nice short syntax whenever you want something more custom, like passing <code>dispatch</code> as well.</p>
36,413,476
MVC Core How to force / set global authorization for all actions?
<p><strong>How to force / set global authorization for all actions in MVC Core ?</strong></p> <p>I know how to register global filters - for example I have:</p> <pre><code>Setup.cs services.AddMvc(options =&gt; { options.Filters.Add(new RequireHttpsAttribute()); }); </code></pre> <p>and this works fine, but I can't add the same for Authorize:</p> <p><code>options.Filters.Add(new AuthorizeAttribute());</code></p> <p>I have error:</p> <p><code>Cannot convert from 'Microsoft.AspNet.Authorization.AuthorizeAttribute()' to 'System.Type'</code></p> <p><em>(Method <code>.Add()</code> needs <code>IFilterMetadata</code> type)</em></p> <p><br>I know - from similar questions - that this works on MVC4-5... So something must changed on MVC Core...</p> <p><strong>Someone have any idea?</strong></p>
36,415,213
2
0
null
2016-04-04 21:45:53.643 UTC
9
2019-08-20 08:23:33.753 UTC
2016-07-15 12:11:24.913 UTC
null
6,131,935
null
6,131,935
null
1
61
asp.net-core-mvc|authorize-attribute|asp.net-authorization
21,284
<pre><code>services.AddMvc(config =&gt; { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); </code></pre>
32,035,119
How to solve "clipboard buffer is full and output lost" error in R running in Windows?
<p>I am trying to copy some data directly from R to the clipboard, in my Windows machine. I found in some sites that using file="clipboard" would work. And it does, but for very small datasets.</p> <p>For example:</p> <p>If I copy a small dataset (100 obs), it works smoothly.</p> <pre><code>df1 &lt;- data.frame(x=runif(100)) write.table(df1, file="clipboard", sep="\t", col.names=NA) </code></pre> <p>But if I increase the observations to 10,000, it fails:</p> <pre><code>df1 &lt;- data.frame(x=runif(10000)) write.table(df1, file="clipboard", sep="\t", col.names=NA) </code></pre> <p>The error is:</p> <blockquote> <p>Warning message: In .External2(C_writetable, x, file, nrow(x), p, r</p> </blockquote> <p>Any workaround to this?</p>
32,037,270
2
0
null
2015-08-16 12:32:31.597 UTC
15
2020-09-23 20:51:55.08 UTC
null
null
null
null
4,016,862
null
1
31
r
14,602
<p>If you type <code>?connections</code> you will find your answer.</p> <p>This is the relevant part:</p> <p>"When writing to the clipboard, the output is copied to the clipboard only when the connection is closed or flushed. There is a 32Kb limit on the text to be written to the clipboard. This can be raised by using e.g. file("clipboard-128") to give 128Kb."</p> <p>So, the solution is pretty straigthforward:</p> <pre><code>df1 &lt;- data.frame(x=runif(10000)) write.table(df1, file="clipboard-16384", sep="\t", col.names=NA) </code></pre> <p>Note that the number of Kb is just an example, so you can change it as you need (I put 2^14 that should be more than enough for your data set, but you can increase it even more. Not sure which is the hard limit, though. Maybe physical memory?)</p>
44,438,637
ARG substitution in RUN command not working for Dockerfile
<p>In my Dockerfile I have the following:</p> <pre><code>ARG a-version RUN wget -q -O /tmp/alle.tar.gz http://someserver/server/$a-version/a-server-$a-version.tar.gz &amp;&amp; \ mkdir /opt/apps/$a-version </code></pre> <p>However when building this with:</p> <pre><code>--build-arg http_proxy=http://myproxy","--build-arg a-version=a","--build-arg b-version=b" </code></pre> <p><code>Step 10/15 : RUN wget...</code> is shown with <code>$a-version</code> in the path instead of the substituted value and the build fails.</p> <p>I have followed the instructions shown <a href="https://docs.docker.com/engine/reference/builder/#arg" rel="noreferrer">here</a> but must be missing something else.</p> <blockquote> <p>My questions is, what could be causing this issue and how can i solve it?</p> </blockquote>
44,438,743
8
0
null
2017-06-08 14:34:40.3 UTC
14
2022-02-05 12:14:22.967 UTC
null
null
null
null
3,139,545
null
1
85
docker|dockerfile
55,937
<p>Don't use <code>-</code> in variable names.</p> <p>Docker build will always show you the line as is written down in the Dockerfile, despite the variable value.</p> <p>So use this variable name <code>a_version</code>:</p> <pre><code>ARG a_version </code></pre> <p>See this example:</p> <p>Dockerfile:</p> <pre><code>FROM alpine ARG a_version RUN echo $a_version </code></pre> <p>Build:</p> <pre><code>$ docker build . --build-arg a_version=1234 Sending build context to Docker daemon 2.048 kB Step 1/3 : FROM alpine ---&gt; a41a7446062d Step 2/3 : ARG a_version ---&gt; Running in c55e98cab494 ---&gt; 53dedab7de75 Removing intermediate container c55e98cab494 Step 3/3 : RUN echo $a_version &lt;&lt;&lt; note this &lt;&lt; ---&gt; Running in 56b8aeddf77b 1234 &lt;&lt;&lt;&lt; and this &lt;&lt; ---&gt; 89badadc1ccf Removing intermediate container 56b8aeddf77b Successfully built 89badadc1ccf </code></pre>
5,909,345
Explanation for tiny reads (overlapped, buffered) outperforming large contiguous reads?
<p><em>(apologies for the somewhat lengthy intro)</em></p> <p>During development of an application which prefaults an entire large file (>400MB) into the buffer cache for speeding up the actual run later, I tested whether reading 4MB at a time still had any noticeable benefits over reading only 1MB chunks at a time. Surprisingly, the smaller requests actually turned out to be faster. This seemed counter-intuitive, so I ran a more extensive test.</p> <p>The buffer cache was purged before running the tests (just for laughs, I did one run with the file in the buffers, too. The buffer cache delivers upwards of 2GB/s regardless of request size, though with a surprising +/- 30% random variance).<br> All reads used overlapped ReadFile with the same target buffer (the handle was opened with <code>FILE_FLAG_OVERLAPPED</code> and <em>without</em> <code>FILE_FLAG_NO_BUFFERING</code>). The harddisk used is somewhat elderly but fully functional, NTFS has a cluster size of 8kB. The disk was defragmented after an initial run (6 fragments vs. unfragmented, zero difference). For better figures, I used a larger file too, below numbers are for reading 1GB.</p> <p>The results were really surprising:</p> <pre><code>4MB x 256 : 5ms per request, completion 25.8s @ ~40 MB/s 1MB x 1024 : 11.7ms per request, completion 23.3s @ ~43 MB/s 32kB x 32768 : 12.6ms per request, completion 15.5s @ ~66 MB/s 16kB x 65536 : 12.8ms per request, completion 13.5s @ ~75 MB/s </code></pre> <p>So, this suggests that submitting <em>ten thousands of requests two clusters in length</em> is actually better than submitting a few hundred large, contiguous reads. The submit time (time before ReadFile returns) does go up substantially as the number of requests goes up, but asynchronous completion time nearly halves.<br> Kernel CPU time is around 5-6% in every case (on a quadcore, so one should really say 20-30%) while the asynchronous reads are completing, which is a surprising amount of CPU -- apparently the OS does some non-neglegible amount of busy waiting, too. 30% CPU for 25 seconds at 2.6 GHz, that's quite a few cycles for doing "nothing".</p> <p>Any idea how this can be explained? Maybe someone here has a deeper insight of the inner workings of Windows overlapped IO? Or, is there something substantially wrong with the idea that you can use ReadFile for reading a megabyte of data?</p> <p>I can see how an IO scheduler would be able to optimize multiple requests by minimizing seeks, especially when requests are random access (which they aren't!). I can also see how a harddisk would be able to perform a similar optimization given a few requests in the NCQ.<br> However, we're talking about ridiculous numbers of ridiculously small requests -- which nevertheless outperform what appears to be sensible by a factor of 2.</p> <p><strong>Sidenote:</strong> The clear winner is memory mapping. I'm almost inclined to add "unsurprisingly" because I am a big fan of memory mapping, but in this case, it actually <em>does surprise</em> me, as the "requests" are even smaller and the OS should be even less able to predict and schedule the IO. I didn't test memory mapping at first because it seemed counter-intuitive that it might be able to compete even remotely. So much for your intuition, heh.</p> <p>Mapping/unmapping a view repeatedly at different offsets takes practically zero time. Using a 16MB view and faulting every page with a simple for() loop reading a single byte per page completes in 9.2 secs @ ~111 MB/s. CPU usage is under 3% (one core) at all times. Same computer, same disk, same everything.</p> <p>It also appears that Windows loads 8 pages into the buffer cache at a time, although only one page is actually created. Faulting every 8th page runs at the same speed and loads the same amount of data from disk, but shows lower "physical memory" and "system cache" metrics and only 1/8 of the page faults. Subsequent reads prove that the pages are nevertheless definitively in the buffer cache (no delay, no disk activity).</p> <p>(Possibly very, very distantly related to <a href="https://stackoverflow.com/questions/5257019/memory-mapped-file-is-faster-on-huge-sequential-read-why">Memory-Mapped File is Faster on Huge Sequential Read?</a>)</p> <p>To make it a bit more illustrative:<br> <img src="https://i.stack.imgur.com/Qg8v5.png" alt="enter image description here"></p> <p><strong>Update:</strong></p> <p>Using <code>FILE_FLAG_SEQUENTIAL_SCAN</code> seems to somewhat "balance" reads of 128k, improving performance by 100%. On the other hand, it <em>severely</em> impacts reads of 512k and 256k (you have to wonder why?) and has no real effect on anything else. The MB/s graph of the smaller blocks sizes arguably seems a little more "even", but there is no difference in runtime.</p> <p><img src="https://i.stack.imgur.com/1YJLb.png" alt="enter image description here"></p> <p>I may have found an explanation for smaller block sizes performing better, too. As you know, asynchronous requests may run synchronously if the OS can serve the request immediately, i.e. from the buffers (and for a variety of version-specific technical limitations).</p> <p>When accounting for <em>actual</em> asynchronous vs. "immediate" asyncronous reads, one notices that upwards of 256k, Windows runs every asynchronous request asynchronously. The smaller the blocksize, the more requests are being served "immediately", <em>even when they are not available immediately</em> (i.e. ReadFile simply runs synchronously). I cannot make out a clear pattern (such as "the first 100 requests" or "more than 1000 requests"), but there seems to be an inverse correlation between request size and synchronicity. At a blocksize of 8k, every asynchronous request is served synchronously.<br> Buffered synchronous transfers are, for some reason, twice as fast as asynchronous transfers (no idea why), hence the smaller the request sizes, the faster the overall transfer, because more transfers are done synchronously.</p> <p>For memory mapped prefaulting, FILE_FLAG_SEQUENTIAL_SCAN causes a slightly different shape of the performance graph (there is a "notch" which is moved a bit backwards), but the total time taken is exactly identical (again, this is surprising, but I can't help it).</p> <p><strong>Update 2:</strong></p> <p>Unbuffered IO makes the performance graphs for the 1M, 4M, and 512k request testcases somewhat higher and more "spiky" with maximums in the 90s of GB/s, but with harsh minumums too, the overall runtime for 1GB is within +/- 0.5s of the buffered run (the requests with smaller buffer sizes complete significantly faster, however, that is because with more than 2558 in-flight requests, ERROR_WORKING_SET_QUOTA is returned). Measured CPU usage is zero in all unbuffered cases, which is unsurprising, since any IO that happens runs via DMA.</p> <p>Another very interesting observation with <code>FILE_FLAG_NO_BUFFERING</code> is that it significantly changes API behaviour. <code>CancelIO</code> does not work any more, at least not in a sense of <em>cancelling IO</em>. With unbuffered in-flight requests, <code>CancelIO</code> will simply block until all requests have finished. A lawyer would probably argue that the function cannot be held liable for neglecting its duty, because there are no more in-flight requests left when it returns, so in some way it has done what was asked -- but my understanding of "cancel" is somewhat different.<br> With <em>buffered</em>, overlapped IO, <code>CancelIO</code> will simply cut the rope, all in-flight operations terminate immediately, as one would expect.</p> <p>Yet another funny thing is that the process is <em>unkillable</em> until all requests have finished or failed. This kind of makes sense if the OS is doing DMA into that address space, but it's a stunning "feature" nevertheless.</p>
5,913,089
1
5
null
2011-05-06 09:21:59.053 UTC
10
2011-05-09 10:14:09.1 UTC
2017-05-23 10:27:04.67 UTC
null
-1
null
572,743
null
1
19
windows|winapi|overlapped-io|buffered
2,097
<p>I'm not a filesystem expert but I think there are a couple of things going on here. First off. w.r.t. your comment about memory mapping being the winner. This isn't totally surprising since the NT cache manager is based on memory mapping - by doing the memory mapping yourself, you're duplicating the cache manager's behavior without the additional memory copies.</p> <p>When you read sequentially from the file, the cache manager attempts to pre-fetch the data for you - so it's likely that you are seeing the effect of readahead in the cache manager. At some point the cache manager stops prefetching reads (or rather at some point the prefetched data isn't sufficient to satisfy your reads and so the cache manager has to stall). That may account for the slowdown on larger I/Os that you're seeing.</p> <p>Have you tried adding FILE_FLAG_SEQUENTIAL_SCAN to your CreateFile flags? That instructs the prefetcher to be even more aggressive.</p> <p>This may be counter-intuitive, but traditionally the fastest way to read data off the disk is to use asynchronous I/O and FILE_FLAG_NO_BUFFERING. When you do that, the I/O goes directly from the disk driver into your I/O buffers with nothing to get in the way (assuming that the segments of the file are contiguous - if they're not, the filesystem will have to issue several disk reads to satisfy the application read request). Of course it also means that you lose the built-in prefetch logic and have to roll your own. But with FILE_FLAG_NO_BUFFERING you have complete control of your I/O pipeline.</p> <p>One other thing to remember: When you're doing asynchronous I/O, it's important to ensure that you always have an I/O request oustanding - otherwise you lose potential time between when the last I/O completes and the next I/O is started.</p>
5,624,047
null with PHP < and > operators
<p>Can somebody explain how null is mapped in these statements?</p> <pre><code>null&gt;0; //=&gt; bool(false) null&lt;0; //=&gt; bool(false) null==0; //=&gt; bool(true) </code></pre> <p>but </p> <pre><code>null&lt;-1; // =&gt; bool(true) </code></pre> <p>I assume it's some mapping problem, but can't crack it.</p> <p>Tried with PHP 5.3.5-1 with Suhosin-Patch.</p>
5,624,188
1
3
null
2011-04-11 15:57:20.087 UTC
2
2011-04-12 07:50:54.55 UTC
2011-04-12 07:50:54.55 UTC
null
227,865
null
713,678
null
1
29
php|null|comparison|mapping|operators
5,616
<p>I would point you to a few pages: <a href="http://php.net/manual/en/types.comparisons.php">http://php.net/manual/en/types.comparisons.php</a> <a href="http://php.net/manual/en/language.operators.comparison.php">http://php.net/manual/en/language.operators.comparison.php</a> <a href="http://php.net/manual/en/language.types.boolean.php">http://php.net/manual/en/language.types.boolean.php</a></p> <p>So in your final example: </p> <pre><code>null&lt;-1 =&gt; bool(true) </code></pre> <p>The <code>null</code> is cast to <code>false</code> and the <code>-1</code> is cast to <code>true</code>, <code>false</code> is less than <code>true</code></p> <p>In your first two examples <code>null</code> is cast to <code>false</code> and <code>0</code> is cast to <code>false</code>, <code>false</code> is not less than or greater than <code>false</code> but is equal to it.</p> <p>Ohh the fun of <code>null</code> ! :D</p>
6,120,154
What is difference between different string compare methods
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/44288/differences-in-string-compare-methods-in-c">Differences in string compare methods in C#</a> </p> </blockquote> <p>In .NET there are many string comparison methods, I just want to confirm which one is the best to use considering performance.</p> <pre><code>string.Equals() string.Compare() string.CompareTo() string.CompareOrdinal() string.ReferenceEquals() if (str1 == str2) </code></pre>
6,120,223
1
6
null
2011-05-25 06:00:10.94 UTC
11
2016-07-08 11:48:45.103 UTC
2017-05-23 10:31:06.67 UTC
null
-1
null
450,339
null
1
43
c#|.net|string-comparison
35,406
<p>Ripped from msdn</p> <p><strong><a href="http://msdn.microsoft.com/en-us/library/system.string.equals.aspx" rel="noreferrer">string.Equals</a></strong></p> <p>Determines whether this instance and a specified object, which must also be a String object, have the same value.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.string.compare.aspx" rel="noreferrer"><strong>string.Compare</strong></a> Compares two specified String objects and returns an integer that indicates their relative position in the sort order.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.string.compareto.aspx" rel="noreferrer"><strong>string.CompareTo</strong></a> Compares this instance with a specified object or String and returns an integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified object or String.</p> <p><strong><a href="http://msdn.microsoft.com/en-us/library/af26w0wa.aspx" rel="noreferrer">string.CompareOrdinal</a></strong> Compares two specified String objects by evaluating the numeric values of the corresponding Char objects in each string.</p> <p><strong><a href="http://msdn.microsoft.com/en-us/library/aa664728%28v=vs.71%29.aspx" rel="noreferrer">String equality operators</a></strong> The predefined string equality operators are:</p> <p>bool operator ==(string x, string y); bool operator !=(string x, string y); Two string values are considered equal when one of the following is true:</p> <p>Both values are null. Both values are non-null references to string instances that have identical lengths and identical characters in each character position. The string equality operators compare string values rather than string references. When two separate string instances contain the exact same sequence of characters, the values of the strings are equal, but the references are different. As described in Section 7.9.6, the reference type equality operators can be used to compare string references instead of string values.</p>
51,191,378
what is the point of using pm2 and docker together?
<p>We have been using pm2 quite successfully for running apps on our servers. We are currently moving to docker and we saw <a href="http://pm2.keymetrics.io/docs/usage/docker-pm2-nodejs/" rel="noreferrer">http://pm2.keymetrics.io/docs/usage/docker-pm2-nodejs/</a></p> <p>But what is the point of actually using both together? Does not docker provide everything pm2 does?</p>
55,245,460
2
0
null
2018-07-05 12:30:45.35 UTC
48
2021-06-24 05:56:10.573 UTC
null
null
null
null
1,659,569
null
1
123
docker|pm2
62,266
<p>Usually there is no point in using pm2 inside of a docker.</p> <p>Both PM2 and Docker are process managers and they both can do log forwarding, restart crashed workers and many other things. If you run pm2 inside of a docker container you will hide potential issues with your service, at least following:</p> <p>1) If you run a single process per container with pm2 you will not gain much except for increased memory consumption. Restarts can be done with pure docker with a <a href="https://docs.docker.com/config/containers/start-containers-automatically/" rel="noreferrer">restart policy</a>. Other docker based environments (like ECS or Kubernetes) can also do it.</p> <p>2) If you run multiple processes you will make monitoring harder. CPU/Memory metrics are no longer directly available to your enclosing environment.</p> <p>3) Health checks requests for a single PM2 process will be distributed across workers which is likely to hide unhealthy targets</p> <p>4) Worker crashes are hidden by pm2. You will hardly ever know about them from your monitoring system (like CloudWatch).</p> <p>5) Load balancing becomes more complicated since you're virtually going to have multiple levels of load balancing.</p> <p>Also running multiple processes inside of a docker container contradicts the philosophy of docker to keep a single process per container.</p> <p>One scenario I can think of is if you have very limited control over your docker environment. In this case running pm2 may be the only option to have control over worker scheduling.</p>
51,534,667
PySpark Error When running SQL Query
<p>Due to my lack of knowledge in writing code in pyspark / python, I have decided to write a query in spark.sql. I have written the query in two formats. The first format allows EOL breaks. However, in that format I get an error, see below:</p> <pre><code>results5 = spark.sql("SELECT\ appl_stock.Open\ ,appl_stock.Close\ FROM appl_stock\ WHERE appl_stock.Close &lt; 500") </code></pre> <p>The above format produces the following error:</p> <pre><code>--------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) ~/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/utils.py in deco(*a, **kw) 62 try: ---&gt; 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: ~/spark-2.1.0-bin-hadoop2.7/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 318 "An error occurred while calling {0}{1}{2}.\n". --&gt; 319 format(target_id, ".", name), value) 320 else: Py4JJavaError: An error occurred while calling o19.sql. : org.apache.spark.sql.catalyst.parser.ParseException: mismatched input '.' expecting {&lt;EOF&gt;, ',', 'FROM', 'WHERE', 'GROUP', 'ORDER', 'HAVING', 'LIMIT', 'LATERAL', 'WINDOW', 'UNION', 'EXCEPT', 'MINUS', 'INTERSECT', 'SORT', 'CLUSTER', 'DISTRIBUTE'}(line 1, pos 35) == SQL == SELECT appl_stock.Open appl_stock.CloseFROM appl_stockWHERE appl_stock.Close &lt; 500 -----------------------------------^^^ at org.apache.spark.sql.catalyst.parser.ParseException.withCommand(ParseDriver.scala:197) at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parse(ParseDriver.scala:99) at org.apache.spark.sql.execution.SparkSqlParser.parse(SparkSqlParser.scala:45) at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parsePlan(ParseDriver.scala:53) at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:592) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:280) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:214) at java.lang.Thread.run(Thread.java:748) During handling of the above exception, another exception occurred: ParseException Traceback (most recent call last) &lt;ipython-input-38-4920f7e68c0e&gt; in &lt;module&gt;() ----&gt; 1 results5 = spark.sql("SELECT appl_stock.Open appl_stock.CloseFROM appl_stockWHERE appl_stock.Close &lt; 500") ~/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/session.py in sql(self, sqlQuery) 539 [Row(f1=1, f2=u'row1'), Row(f1=2, f2=u'row2'), Row(f1=3, f2=u'row3')] 540 """ --&gt; 541 return DataFrame(self._jsparkSession.sql(sqlQuery), self._wrapped) 542 543 @since(2.0) ~/spark-2.1.0-bin-hadoop2.7/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py in __call__(self, *args) 1131 answer = self.gateway_client.send_command(command) 1132 return_value = get_return_value( -&gt; 1133 answer, self.gateway_client, self.target_id, self.name) 1134 1135 for temp_arg in temp_args: ~/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/utils.py in deco(*a, **kw) 71 raise AnalysisException(s.split(': ', 1)[1], stackTrace) 72 if s.startswith('org.apache.spark.sql.catalyst.parser.ParseException: '): ---&gt; 73 raise ParseException(s.split(': ', 1)[1], stackTrace) 74 if s.startswith('org.apache.spark.sql.streaming.StreamingQueryException: '): 75 raise StreamingQueryException(s.split(': ', 1)[1], stackTrace) ParseException: "\nmismatched input '.' expecting {&lt;EOF&gt;, ',', 'FROM', 'WHERE', 'GROUP', 'ORDER', 'HAVING', 'LIMIT', 'LATERAL', 'WINDOW', 'UNION', 'EXCEPT', 'MINUS', 'INTERSECT', 'SORT', 'CLUSTER', 'DISTRIBUTE'}(line 1, pos 35)\n\n== SQL ==\nSELECT appl_stock.Open appl_stock.CloseFROM appl_stockWHERE appl_stock.Close &lt; 500\n-----------------------------------^^^\n" </code></pre> <p>Whereas the following code produces a successful result, see below:</p> <pre><code>results6 = spark.sql("SELECT appl_stock.Open ,appl_stock.Close FROM appl_stock WHERE appl_stock.Close &lt; 500") </code></pre> <p>Can someone let me know why the first code doesn't work, but the second does?</p> <p>Cheers</p>
51,534,776
6
0
null
2018-07-26 08:45:19.617 UTC
0
2021-05-10 16:07:29.533 UTC
null
null
null
null
10,061,573
null
1
8
python|pyspark
47,707
<p>Because you are using <code>\</code> in the first one and that's being passed as odd syntax to spark. If you want to write multi-line SQL statements, use triple quotes:</p> <pre><code>results5 = spark.sql("""SELECT appl_stock.Open ,appl_stock.Close FROM appl_stock WHERE appl_stock.Close &lt; 500""") </code></pre>
55,402,751
Angular app has to clear cache after new deployment
<p>We have an Angular 6 application. It’s served on Nginx. And SSL is on.</p> <p>When we deploy new codes, most of new features work fine but not for some changes. For example, if the front-end developers update the service connection and deploy it, users have to open incognito window or clear cache to see the new feature.</p> <p>What type of changes are not updated automatically? Why are they different from others?</p> <p>What’s the common solution to avoid the issue?</p>
55,403,095
3
0
null
2019-03-28 16:37:07.237 UTC
34
2022-07-07 10:27:33.737 UTC
null
null
null
null
7,332,645
null
1
80
javascript|angular|nginx|deployment
124,739
<p>The problem is When a static file gets cached it can be stored for very long periods of time before it ends up expiring. This can be an annoyance in the event that you make an update to a site, however, since the cached version of the file is stored in your visitors’ browsers, they may be unable to see the changes made.</p> <p><a href="https://www.keycdn.com/support/what-is-cache-busting" rel="noreferrer">Cache-busting</a> solves the browser caching issue by using a unique file version identifier to tell the browser that a new version of the file is available. Therefore the browser doesn’t retrieve the old file from cache but rather makes a request to the origin server for the new file.</p> <p>Angular cli resolves this by providing an <code>--output-hashing</code> flag for the build command.</p> <p>Check the official doc : <a href="https://angular.io/cli/build" rel="noreferrer">https://angular.io/cli/build</a></p> <p>Example ( older versions)</p> <pre><code>ng build --prod --aot --output-hashing=all </code></pre> <p>Below are the options you can pass in <code>--output-hashing</code></p> <ul> <li>none: no hashing performed</li> <li>media: only add hashes to files processed via [url|file]-loaders</li> <li>bundles: only add hashes to the output bundles</li> <li>all: add hashes to both media and bundles</li> </ul> <p><strong>Updates</strong></p> <p>For the version of angular ( for example Angular 8,9,10) the command is :</p> <pre><code>ng build --prod --aot --outputHashing=all </code></pre> <p>For the latest version of angular ( from angular 11 to angular 14) the command is reverted back to older format:</p> <pre><code>ng build --aot --output-hashing=all </code></pre>
25,829,296
Exposing multiple ports from Docker within Elastic Beanstalk
<p>From reading the AWS documentation, it appears that when using Docker as the platform on Elastic Beanstalk (EB) (as opposed to Tomcat, etc.), only a single port can be exposed. I'm trying to understand why Amazon created this restriction -- seems that you now can't even serve both HTTP and HTTPS.</p> <p>I'd like to use Docker as the container since it allows me to run several interconnected server processes within the same container, some of which require multiple ports (e.g. RTSP). Are there any workarounds for this kind of application, where say an RTSP and HTTP server can both be running within the same Docker container on EB?</p>
27,675,019
3
0
null
2014-09-14 01:30:57.313 UTC
2
2018-03-10 11:00:47.427 UTC
null
null
null
null
1,176,186
null
1
37
docker|amazon-elastic-beanstalk
12,115
<p>You could write an on-start config file for Elastic Beanstalk's LoadBalancer/ReversProxy to forward the additional ports to its EC2 instance(s). an example from <a href="http://www.delarre.net/posts/elasticbeanstalk-vpc-fun/" rel="nofollow">Ben Delarre</a> :</p> <pre><code>"Resources" : { "AWSEBLoadBalancerSecurityGroup": { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "Enable 80 inbound and 8080 outbound", "VpcId": "vpc-un1que1d", "SecurityGroupIngress" : [ { "IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : "0.0.0.0/0" }], "SecurityGroupEgress": [ { "IpProtocol" : "tcp", "FromPort" : "8080", "ToPort" : "8080", "CidrIp" : "0.0.0.0/0" } ] } }, "AWSEBLoadBalancer" : { "Type" : "AWS::ElasticLoadBalancing::LoadBalancer", "Properties" : { "Subnets": ["subnet-un1que1d2"], "Listeners" : [ { "LoadBalancerPort" : "80", "InstancePort" : "8080", "Protocol" : "HTTP" } ] } } } </code></pre> <p>Ref:</p> <ul> <li>Customizing AWS EB's ENV <a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-resources.html" rel="nofollow">http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-resources.html</a></li> <li><a href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/using-elb-listenerconfig-quickref.html" rel="nofollow">http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/using-elb-listenerconfig-quickref.html</a></li> </ul>
25,810,999
Check if my SSL Certificate is SHA1 or SHA2
<p>I have tried to find the answer to this but I couldn't find an answer...</p> <p>How do I check if my SSL Certificate is using SHA1 or SHA2?</p> <p>Reason I ask is because it might have to do with the certificate not loading on Mozilla Browers....</p> <p>Any ideas? Can I check through cPanel?</p>
25,811,158
5
0
null
2014-09-12 14:47:11.043 UTC
15
2018-02-21 15:16:21.717 UTC
2014-10-29 18:26:36.917 UTC
null
2,619,912
null
2,353,185
null
1
50
sha1|sha2
125,793
<p>You can check by visiting the site in your browser and viewing the certificate that the browser received. The details of how to do that can vary from browser to browser, but generally if you click or right-click on the lock icon, there should be an option to view the certificate details.</p> <p>In the list of certificate fields, look for one called "Certificate Signature Algorithm". (For StackOverflow's certificate, its value is "PKCS #1 SHA-1 With RSA Encryption".)</p>
44,709,096
Pop Up View in Swift
<p>I have a popover view (without a tab bar) that is popped over to a view controller with a tab bar. In the view controller with a tab bar I set up a button to click, so that the view controller pops up: </p> <pre><code> @IBAction func PopUpClicked(_ sender: UIButton) -&gt; Void { let popOverVC = UIStoryboard(name: "SpinningWheel", bundle: nil).instantiateViewController(withIdentifier: "PhotoPopUp") as! PopUpViewController self.addChildViewController(popOverVC) popOverVC.view.frame = self.view.frame self.view.addSubview(popOverVC.view) popOverVC.didMove(toParentViewController: self) } </code></pre> <p>And in the popOver view controller, i animated the pop over. </p> <pre><code>override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black.withAlphaComponent(0.8) self.showAnimate() // Do any additional setup after loading the view. } func showAnimate() { self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0; UIView.animate(withDuration: 0.25, animations: { self.view.alpha = 1.0 self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }); } func removeAnimate() { UIView.animate(withDuration: 0.25, animations: { self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0; }, completion:{(finished : Bool) in if (finished) { self.view.removeFromSuperview() } }); } </code></pre> <p>But when the popover happens, Everything has a faded black background, which I want except for the tab bar. I would like for the pop over View to also pop over the tabbar and for the faded black background to go over it.</p> <p>This is what I want it to look like: <a href="https://i.stack.imgur.com/MRt9p.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MRt9p.png" alt="enter image description here"></a></p> <p>With the black faded background covering the tabbar</p>
44,709,556
2
1
null
2017-06-22 20:46:41.327 UTC
5
2020-07-30 15:37:18.147 UTC
null
null
null
null
7,675,996
null
1
5
ios|swift
47,661
<p>This happens, because you have to present your popover as a modal ViewController. To achieve this you have to set the modal presentation style before presenting your popover from your target ViewController. This code should be called in your presenting ViewController:</p> <pre><code>let vc = YourPopOverViewController(nib: UINib(name: "PopOverViewController", bundle: nil), bundle: nil) vc.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext tabBarController.present(vc, animated: true) </code></pre> <p>EDIT:</p> <p>This should do the trick if you have designed your <code>PopOverViewController</code> as a fullscreen ViewController. I have done this a bunch of times and have left the space which should not be presented as clear background:</p> <pre><code>@IBAction func PopUpClicked(_ sender: UIButton) -&gt; Void { let popOverVC = UIStoryboard(name: "SpinningWheel", bundle: nil).instantiateViewController(withIdentifier: "PhotoPopUp") as! PopUpViewController popOverVc.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext tabBarController.present(popOverVC, animated: true) } </code></pre>
38,518,849
Why and how are Python functions hashable?
<p>I recently tried the following commands in Python:</p> <pre><code>&gt;&gt;&gt; {lambda x: 1: 'a'} {&lt;function __main__.&lt;lambda&gt;&gt;: 'a'} &gt;&gt;&gt; def p(x): return 1 &gt;&gt;&gt; {p: 'a'} {&lt;function __main__.p&gt;: 'a'} </code></pre> <p>The success of both <code>dict</code> creations indicates that both lambda and regular functions are hashable. (Something like <code>{[]: 'a'}</code> fails with <code>TypeError: unhashable type: 'list'</code>).</p> <p>The hash is apparently not necessarily the ID of the function:</p> <pre><code>&gt;&gt;&gt; m = lambda x: 1 &gt;&gt;&gt; id(m) 140643045241584 &gt;&gt;&gt; hash(m) 8790190327599 &gt;&gt;&gt; m.__hash__() 8790190327599 </code></pre> <p>The last command shows that the <code>__hash__</code> method is explicitly defined for <code>lambda</code>s, i.e., this is not some automagical thing Python computes based on the type.</p> <p>What is the motivation behind making functions hashable? For a bonus, what is the hash of a function?</p>
38,518,893
3
4
null
2016-07-22 05:30:35.263 UTC
3
2017-11-03 01:55:48.82 UTC
null
null
null
null
2,988,730
null
1
60
python|hash
7,035
<p>It's nothing special. As you can see if you examine the unbound <code>__hash__</code> method of the function type:</p> <pre><code>&gt;&gt;&gt; def f(): pass ... &gt;&gt;&gt; type(f).__hash__ &lt;slot wrapper '__hash__' of 'object' objects&gt; </code></pre> <p>the <code>of 'object' objects</code> part means it just inherits the default identity-based <code>__hash__</code> from <code>object</code>. Function <code>==</code> and <code>hash</code> work by identity. The difference between <code>id</code> and <code>hash</code> is normal for any type that inherits <code>object.__hash__</code>:</p> <pre><code>&gt;&gt;&gt; x = object() &gt;&gt;&gt; id(x) 40145072L &gt;&gt;&gt; hash(x) 2509067 </code></pre> <hr> <p>You might think <code>__hash__</code> is only supposed to be defined for immutable objects, and you'd be almost right, but that's missing a key detail. <code>__hash__</code> should only be defined for objects where <em>everything involved in <code>==</code> comparisons</em> is immutable. For objects whose <code>==</code> is based on identity, it's completely standard to base <code>hash</code> on identity as well, since even if the objects are mutable, they can't possibly be mutable in a way that would change their identity. Files, modules, and other mutable objects with identity-based <code>==</code> all behave this way.</p>
55,056,513
Vertical align with Tailwind CSS across full screen div
<p>How can I vertically align a div with Tailwind? What I want:</p> <pre><code>----------------------------------- | | | | | | | item1 | | item2 | | | | | | | ----------------------------------- </code></pre> <p>What I currently have:</p> <pre><code>----------------------------------- | item1 | | item2 | | | | | | | | | | | | | ----------------------------------- </code></pre> <p>HTML</p> <pre><code>&lt;div class=&quot;flex flex-col h-screen my-auto items-center bgimg bg-cover&quot;&gt; &lt;h3 class=&quot;text-white&quot;&gt;heading&lt;/h3&gt; &lt;button class=&quot;mt-2 bg-white text-black font-bold py-1 px-8 rounded m-2&quot;&gt; call to action &lt;/button&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code>.bgimg { background-image: url('https://d1ia71hq4oe7pn.cloudfront.net/photo/60021841-480px.jpg'); } </code></pre> <p>I have successfully centered on the secondary axis (left-right) with class <code>items-center</code>. Reading the documentation, I tried <code>align-middle</code> but it does not work. I have confirmed the divs have full height and <code>my-auto</code>.</p> <p>I'm using this version of Tailwind: <a href="https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css" rel="noreferrer">https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css</a></p> <p>Here is a JSFiddle: <a href="https://jsfiddle.net/7xnghf1m/2/" rel="noreferrer">https://jsfiddle.net/7xnghf1m/2/</a></p>
55,174,568
12
1
null
2019-03-08 03:58:50.303 UTC
28
2022-08-18 21:54:01.427 UTC
2021-05-04 16:14:28.547 UTC
null
633,440
null
1,228,951
null
1
101
tailwind-css
159,757
<p>You can also do</p> <pre><code>&lt;div class="flex h-screen"&gt; &lt;div class="m-auto"&gt; &lt;h3&gt;title&lt;/h3&gt; &lt;button&gt;button&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
38,527,828
How to query Wikidata items using its labels?
<p>How can I query Wikidata to get all items that have labels contain a word? I tried this but didn't work; it retrieved nothing.</p> <pre><code>SELECT ?item ?itemLabel WHERE { SERVICE wikibase:label { bd:serviceParam wikibase:language "en". ?item rdfs:label ?itemLabel. } FILTER(CONTAINS(LCASE(?itemLabel), "keyword")) } LIMIT 1000 </code></pre>
39,429,109
4
7
null
2016-07-22 13:33:43.507 UTC
9
2021-08-07 09:49:20.82 UTC
null
null
null
null
1,151,472
null
1
19
sparql|wikidata
8,891
<p>Following your question and the useful comments provided, I ended up with this query</p> <pre><code>SELECT ?item ?itemLabel WHERE { ?item rdfs:label ?itemLabel. FILTER(CONTAINS(LCASE(?itemLabel), "city"@en)). } limit 10 </code></pre> <p>For which I got those results</p> <pre><code>item itemLabel wd:Q515 city wd:Q7930989 city wd:Q15253706 city wd:Q532039 The Eternal City wd:Q1969820 The Eternal City wd:Q3986838 The Eternal City wd:Q7732543 The Eternal City wd:Q7737016 The Golden City wd:Q5119 capital city wd:Q1555 Guatemala City </code></pre> <p><a href="https://query.wikidata.org/#SELECT%20%3Fitem%20%3FitemLabel%20WHERE%20%7B%20%3Fitem%20rdfs%3Alabel%20%3FitemLabel.%20FILTER%28CONTAINS%28LCASE%28%3FitemLabel%29%2C%20%22city%22%40en%29%29.%20%7D%20limit%2010" rel="noreferrer">try it here</a></p>
7,408,980
How can I deprecate an entire protocol?
<p>Is it possible to deprecate an entire protocol? I'm using the GCC compiler that is shipped with iOS SDK 5.0 Beta 7.</p> <p><code>DEPRECATED_ATTRIBUTE</code> doesn't seem to work.</p> <p>For example, the following two statements do not compile.</p> <ul> <li><code>@protocol DEPRECATED_ATTRIBUTE MyProtocol</code></li> <li><code>@protocol MyProtocol DEPRECATED_ATTRIBUTE</code></li> </ul>
7,409,545
1
0
null
2011-09-13 21:49:10.413 UTC
4
2011-09-14 04:46:24.943 UTC
2011-09-14 04:46:24.943 UTC
null
709,202
null
280,825
null
1
31
objective-c|gcc|protocols|deprecated
7,550
<p>I haven't tried this myself, but I think that the following syntax should work.</p> <pre><code>__attribute__ ((deprecated)) @protocol MyProtocol @end </code></pre> <p>This parallels the syntax for deprecating an entire interface as well as a single method.</p> <pre><code>__attribute__ ((deprecated)) @interface MyClass @end @interface MyClass2 - (void) method __attribute__((deprecated)); @end </code></pre>
3,161,989
How do I set the current working directory/drive in a dos batch file?
<p><code>cd d:\projects</code> does not work</p> <p>How can I set the current working drive and directory so that I can run msbuild scripts from there?</p>
3,162,001
3
0
null
2010-07-01 22:01:06.097 UTC
4
2014-12-16 14:15:51.147 UTC
null
null
null
null
57,883
null
1
28
batch-file
67,155
<p>try the following:</p> <pre><code>D: cd \projects </code></pre> <p>or, in a single line (courtesy of <a href="https://stackoverflow.com/questions/3161989/how-do-i-set-the-current-working-directory-drive-in-a-dos-batch-file/3162001#comment3251896_3162001">Kilanash</a>):</p> <pre><code>cd /d D:\projects </code></pre>
2,882,817
How do I redirect to another page with ASP.NET?
<p>I know it's a simple question but I really can't find anything on Google. Sorry if I'm not searching right. I created 2 pages and in the first one I have a button.<br> What should I write in the C# code to change to redirect me on the second page?<br> I usually know my way around C# but I'm totally new in ASP.</p>
2,882,841
4
5
null
2010-05-21 14:15:14.62 UTC
null
2017-11-28 13:49:37.413 UTC
2010-05-21 16:15:25.643 UTC
null
202,919
null
342,307
null
1
10
c#|.net|asp.net|button
61,951
<p>Add the button <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.click.aspx" rel="noreferrer">onclick event handler</a>. </p> <p>In the event handler put: </p> <pre><code>Response.Redirect("YOUR_NEW_PAGE"); </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/ms524309(VS.90).aspx" rel="noreferrer">Response.Redirect</a> or <a href="http://www.developer.com/net/asp/article.php/3299641/ServerTransfer-Vs-ResponseRedirect.htm" rel="noreferrer">Server.Transfer</a> </p> <p><a href="http://msdn.microsoft.com/en-us/library/ms178139.aspx" rel="noreferrer">Slightly more complicated, and probably not what you need a cross page post</a> </p>
2,637,038
How do I open a DWG file extension with Python?
<p>I have a file with extension .dwg (AutoCAD), and I want to call that file from a Python console and present it on the web. Is there a module for the .dwg extension or some other solution?</p>
2,637,212
4
3
null
2010-04-14 11:48:11.053 UTC
9
2021-09-04 07:15:10.457 UTC
2017-04-07 16:34:00.867 UTC
null
63,550
null
248,733
null
1
11
python|dwg
29,530
<p>The best format for displaying these online would (imo) definitely be SVG. Recent browsers support SVG rendering natively; older ones (think IE6) may require an SVG plugin </p> <p>So your best bet is probably using a command line convert tool like <a href="http://etc.nkadesign.com/Download/Cad2svg" rel="noreferrer">cad2svg</a> (this is a free linux command line tool) which converts the DWG files to SVG. You can easily do this that from your Python program (<a href="http://docs.python.org/library/subprocess.html" rel="noreferrer">using</a> <code>subprocess</code>).</p>
2,639,070
Get the full URI from the href property of a link
<p>I would like to have a confirmation on some point.</p> <p>My goal is to always get the same string (which is the URI in my case) while reading the href property from a link. Example:</p> <p><code>&lt;a href="test.htm" /&gt;</code> with base_url = <a href="http://domain.name/" rel="noreferrer">http://domain.name/</a></p> <p><code>&lt;a href="../test.htm" /&gt;</code> with base_url = <a href="http://domain.name/domain/" rel="noreferrer">http://domain.name/domain/</a></p> <p><code>&lt;a href="http://domain.name/test.htm" /&gt;</code> with base_url = any folder from <a href="http://domain.name/" rel="noreferrer">http://domain.name/</a></p> <p>I need to get <code>http://domain.name/test.htm</code> from the 3 situations above (or any other identical string).</p> <p>After some tests, it appears that <code>my_a_dom_node.href</code> always return the full-qualified URI, including the <a href="http://domaine.name" rel="noreferrer">http://domaine.name</a>, which should be okay for what I want. </p> <p>jQuery has a different behaviour and <code>$(my_a_dom_node).attr('href')</code> returns the content (text) that appears inside the HTML. So my trick is to use <code>$(my_a_dom_node).get(0).href</code> to get the full URI.</p> <p>The question is: can I rely on this?</p>
2,639,218
4
1
null
2010-04-14 16:15:17.81 UTC
10
2016-06-09 15:03:56.863 UTC
null
null
null
null
211,204
null
1
25
javascript|hyperlink
31,302
<p>YES, you can rely!</p> <p>Once when people was using simple javascript (no jQuery) many asked the opposite of what you are asking, they wanted to get the real url as written in the href attribute and not the full one, in such case they used to simply do:</p> <pre><code>my_a_dom_node.getAttribute('href', 2); //works both IE/FF </code></pre> <p>Then it came jQuery that helped people not to waste their time in finding out they would need such code and jQuery always returns the real url as written in the href attribute. </p> <p>It's funny that now someone is asking how to get the full url because jQuery returns the one written in the href attribute.</p>
2,773,328
How to find the size of integer array
<p>How to find the size of an integer array in C.</p> <p>Any method available without traversing the whole array once, to find out the size of the array.</p>
2,773,366
4
7
null
2010-05-05 12:54:11.217 UTC
16
2014-04-22 04:16:11.883 UTC
2013-05-14 12:05:29.817 UTC
null
743,214
null
66,593
null
1
27
c|arrays
123,393
<p>If the array is a global, static, or automatic variable (<code>int array[10];</code>), then <code>sizeof(array)/sizeof(array[0])</code> works. </p> <p>If it is a dynamically allocated array (<code>int* array = malloc(sizeof(int)*10);</code>) or passed as a function argument (<code>void f(int array[])</code>), then you cannot find its size at run-time. You will have to store the size somewhere.<br> Note that <code>sizeof(array)/sizeof(array[0])</code> compiles just fine even for the second case, but it will silently produce the wrong result. </p>
29,326,042
Show message Box in .net console application
<p>How to show a message box in a .net c# or vb <strong>console application</strong> ? Something like:</p> <pre><code> Console.WriteLine("Hello World"); MessageBox.Show("Hello World"); </code></pre> <p>or</p> <pre><code>Console.WriteLine("Hello") MsgBox("Hello") </code></pre> <p>in c# and vb respectively.<br> Is it possible?</p>
29,326,043
4
0
null
2015-03-29 05:45:13.72 UTC
5
2022-01-17 18:35:36.31 UTC
2015-03-29 06:59:31.683 UTC
null
4,282,901
null
4,282,901
null
1
37
c#|.net|vb.net|console-application|messagebox
91,362
<p>We can show a message box in a console application. But first include this reference in your vb.net or c# console application</p> <pre><code>System.Windows.Forms; </code></pre> <p><strong>Reference:</strong></p> <p>To add reference in vb.net program right click (in solution explorer) on your project name-&gt; then add reference-&gt; then .Net-&gt; then select System.Windows.Forms.<br /> To add reference in c# program right click in your project folders shown in solution explorer on add references-&gt; .Net -&gt; select System.Windows.Forms.</p> <p>then you can do the below code for c# console application:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace ConsoleApplication6 { class Program { static void Main(string[] args) { MessageBox.Show(&quot;Hello World&quot;); } } } </code></pre> <p>For the vb.net application you can simply code after inclusion of above mentioned reference</p> <pre><code>Module Module1 Sub Main() MsgBox(&quot;Hello&quot;) Console.ReadKey() End Sub End Module </code></pre> <p>Adapted from <a href="https://stackoverflow.com/a/29314811/4282901">this</a> answer to a related question.</p>
28,394,572
Angular.js: Seconds to HH:mm:ss filter
<p>I have a number of seconds count, for example, 713 seconds. How can I implement an Angular.js filter that converts this 713 seconds to HH:mm:ss format? In this case, it should be 00:11:53</p> <pre class="lang-html prettyprint-override"><code>&lt;div&gt; {{ 713 | secondsToHHMMSS }} &lt;!-- Should output 00:11:53 --&gt; &lt;/div&gt; </code></pre>
30,767,487
6
0
null
2015-02-08 13:41:42.353 UTC
4
2020-09-09 08:40:19.913 UTC
2020-09-09 08:40:19.913 UTC
null
2,376,124
null
2,376,124
null
1
26
javascript|angularjs|date|angularjs-filter
48,034
<p>manzapanza's answer only works if the seconds are less than 86400 (1 day). The date object needs to be completely zero. Also, it would be better to return the actual date object so that angularjs does not have to make it again.</p> <pre><code>app.filter('secondsToDateTime', function() { return function(seconds) { var d = new Date(0,0,0,0,0,0,0); d.setSeconds(seconds); return d; }; }); </code></pre> <p>and</p> <pre><code>&lt;b&gt;{{seconds | secondsToDateTime | date:'HH:mm:ss'}}&lt;/b&gt; </code></pre> <hr> <p><strong>Edit:</strong> If you want hours to go above 24 without wrapping to days it is better to not use Date:</p> <pre><code>app.filter('secondsToTime', function() { function padTime(t) { return t &lt; 10 ? "0"+t : t; } return function(_seconds) { if (typeof _seconds !== "number" || _seconds &lt; 0) return "00:00:00"; var hours = Math.floor(_seconds / 3600), minutes = Math.floor((_seconds % 3600) / 60), seconds = Math.floor(_seconds % 60); return padTime(hours) + ":" + padTime(minutes) + ":" + padTime(seconds); }; }); </code></pre> <p>and</p> <pre><code>&lt;b&gt;{{seconds | secondsToTime}}&lt;/b&gt; </code></pre>
37,385,535
Calling method from a Angular 2 class inside template
<p>I have a angular 2 application that has a class called <code>User</code>. This user has a attribute called <code>deleted_at</code> that is either <code>nul</code>l or contains a datetime, obviously the user is deleted if the <code>deleted_at</code> property isn't <code>null</code>. This is how my user.ts file looks:</p> <p><strong>User.ts</strong></p> <pre><code>export class User { id: number; email: string; created_at: string; first_name: string; last_name: string; deleted_at: any; name() { if (this.deleted_at === null) { return this.first_name; } else { return 'DELETED'; } } } </code></pre> <p>Now I expected that I could just call name in my template with a simple line:</p> <pre><code>{{ user.name }} </code></pre> <p>This however returns nothing, how can you call certain functions in the angular 2 template? Or isn't this allowed?</p> <p><strong>Edit:</strong> to clear stuff up a bit, this is a class <code>User</code> that I am using in my component <strong>user-list.component.ts</strong>, multiple users are handled in this component.</p>
37,385,564
2
0
null
2016-05-23 07:55:58.2 UTC
null
2021-04-29 03:19:05.53 UTC
2021-04-29 03:19:05.53 UTC
null
12,488,082
null
3,361,028
null
1
29
angular|angular2-template
65,181
<p>Either you call the method like this:</p> <pre><code>{{user.name()}} // instead of {{user.name}} </code></pre> <p>For this approach you need to be aware that you will lose the execution context (<code>this</code>). See this question for more details:</p> <ul> <li><a href="https://stackoverflow.com/questions/37213908/ng-lightning-data-object-is-undefined-on-lookup/37215762#37215762">ng-lightning - data object is undefined on lookup</a></li> </ul> <p>Or you define your method as a getter so you can use <code>user.name</code> in your template:</p> <pre><code>get name() { if (this.deleted_at === null) { return this.first_name; } else { return 'DELETED'; } } </code></pre>
1,026,635
Setting a style's TargetType property to a base class
<p>I was just poking around a bit in WPF and wanted all elements on my Window to share the same margin. I found that all Controls that are capable of having a margin derive from FrameworkElement so I tried the following:</p> <pre><code>&lt;Window.Resources&gt; &lt;Style TargetType="{x:Type FrameworkElement}"&gt; &lt;Setter Property="Margin" Value="10" /&gt; &lt;/Style&gt; &lt;/Window.Resources&gt; </code></pre> <p>And, this doesn't work. I can apply this to all Buttons, but not to all Elements that derive from Button. Am I missing something or is this simply not possible?</p> <p>Am I the only one feeling like using CSS for WPF would have been a good idea?</p>
1,027,219
2
1
null
2009-06-22 11:26:17.717 UTC
5
2012-09-06 19:23:10.107 UTC
2012-03-15 06:52:20.89 UTC
null
45,382
null
21,699
null
1
45
wpf|styles|targettype
21,663
<p>Unfortunately, you cannot apply styles to the base FrameworkElement type; while WPF will let you write the style, it will not apply it to the controls that derive from it. It appears that this also applies to subtypes of FrameworkElement, e.g. ButtonBase, the supertype of Button/ToggleButton/RepeatButton.</p> <p>You can still use inheritance, but you will have to use the explicit <code>BasedOn</code> syntax to apply it to the control types you want it to apply to.</p> <pre><code>&lt;Window.Resources&gt; &lt;Style TargetType="{x:Type FrameworkElement}"&gt; &lt;Setter Property="Margin" Value="10" /&gt; &lt;/Style&gt; &lt;Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /&gt; &lt;Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /&gt; &lt;Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /&gt; &lt;/Window.Resources&gt; </code></pre> <p></p>
512,487
Checking to see if an optional protocol method has been implemented
<p>Does anyone know the best way to check to see if an optional protocol method has been implemented.</p> <p>I tried this:</p> <pre><code>if ([self.delegate respondsToSelector:@selector(optionalProtocolMethod:)] ) </code></pre> <p>where delegate is:</p> <pre><code>id&lt;MyProtocol&gt; delegate; </code></pre> <p>However, I get an error saying that the function <code>respondsToSelector:</code> is not found in the protocol!</p>
512,630
2
0
null
2009-02-04 17:41:19.733 UTC
10
2015-05-10 07:01:33.537 UTC
2012-10-14 18:12:09.137 UTC
Chris Hanson
249,690
null
1,221,378
null
1
55
iphone|objective-c|delegates|protocols
16,098
<p><code>respondsToSelector:</code> is part of the <code>NSObject</code> protocol. Including <code>NSObject</code> in <code>MyProtocol</code> should solve your problem:</p> <pre><code>@protocol MyProtocol &lt;NSObject&gt; @optional -(void)optionalProtocolMethod:(id)anObject; @end </code></pre>
290,424
Filter a Python list by predicate
<p>I would want to do something like:</p> <pre><code>&gt;&gt;&gt; lst = [1, 2, 3, 4, 5] &gt;&gt;&gt; lst.find(lambda x: x % 2 == 0) 2 &gt;&gt;&gt; lst.findall(lambda x: x % 2 == 0) [2, 4] </code></pre> <p>Is there anything nearing such behavior in Python's standard libraries?</p> <p>I know it's very easy to roll-your-own here, but I'm looking for a more standard way.</p>
290,440
2
0
null
2008-11-14 15:30:00.883 UTC
3
2020-10-21 13:07:44.86 UTC
2016-08-12 16:47:18.57 UTC
eliben
145,976
eliben
8,206
null
1
75
python
89,248
<p>You can use the filter method:</p> <pre><code>&gt;&gt;&gt; lst = [1, 2, 3, 4, 5] &gt;&gt;&gt; filter(lambda x: x % 2 == 0, lst) [2, 4] </code></pre> <p>or a list comprehension:</p> <pre><code>&gt;&gt;&gt; lst = [1, 2, 3, 4, 5] &gt;&gt;&gt; [x for x in lst if x %2 == 0] [2, 4] </code></pre> <p>to find a single element, you could try:</p> <pre><code>&gt;&gt;&gt; next(x for x in lst if x % 2 == 0) 2 </code></pre> <p>Though that would throw an exception if nothing matches, so you'd probably want to wrap it in a try/catch. The () brackets make this a generator expression rather than a list comprehension.</p> <p>Personally though I'd just use the regular filter/comprehension and take the first element (if there is one).</p> <p>These raise an exception if nothing is found</p> <pre><code>filter(lambda x: x % 2 == 0, lst)[0] [x for x in lst if x %2 == 0][0] </code></pre> <p>These return empty lists</p> <pre><code>filter(lambda x: x % 2 == 0, lst)[:1] [x for x in lst if x %2 == 0][:1] </code></pre>
783,584
Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?
<p>I have been unable to find any documentation on the .build method in Rails (i am currently using 2.0.2).</p> <p>Through experimentation it seems you can use the build method to add a record into a <code>has_many</code> relationship before either record has been saved.</p> <p>For example:</p> <pre><code>class Dog &lt; ActiveRecord::Base has_many :tags belongs_to :person end class Person &lt; ActiveRecord::Base has_many :dogs end # rails c d = Dog.new d.tags.build(:number =&gt; "123456") d.save # =&gt; true </code></pre> <p>This will save both the dog and tag with the foreign keys properly. This does not seem to work in a <code>belongs_to</code> relationship.</p> <pre><code>d = Dog.new d.person.build # =&gt; nil object on nil.build </code></pre> <p>I have also tried</p> <pre><code>d = Dog.new d.person = Person.new d.save # =&gt; true </code></pre> <p>The foreign key in <code>Dog</code> is not set in this case due to the fact that at the time it is saved, the new person does not have an id because it has not been saved yet.</p> <p>My questions are:</p> <ol> <li><p>How does build work so that Rails is smart enough to figure out how to save the records in the right order?</p></li> <li><p>How can I do the same thing in a <code>belongs_to</code> relationship?</p></li> <li><p>Where can I find any documentation on this method?</p></li> </ol> <p>Thank you</p>
784,287
2
1
null
2009-04-23 21:23:18.88 UTC
61
2020-12-31 08:49:47.44 UTC
2015-11-21 20:55:57.39 UTC
null
2,680,216
null
72,537
null
1
140
ruby-on-rails|activerecord|foreign-keys
136,028
<p>Where it is documented:</p> <p>From the API documentation under the has_many association in "<a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html" rel="noreferrer">Module ActiveRecord::Associations::ClassMethods</a>"</p> <blockquote> <p>collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!</p> </blockquote> <p>The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,</p> <pre><code>Class Dog has_many :tags belongs_to :person end Class Person has_many :dogs end d = Dog.new d.build_person(:attributes =&gt; "go", :here =&gt; "like normal") </code></pre> <p>or even </p> <pre><code>t = Tag.new t.build_dog(:name =&gt; "Rover", :breed =&gt; "Maltese") </code></pre> <p>You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)</p> <p>How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)</p>
2,749,689
What is the "owning side" in an ORM mapping?
<p>What exactly does the <strong><em>owning side</em></strong> mean? What is an explanation with some mapping examples (<strong><em>one to many, one to one, many to one</em></strong>)?</p> <p>The following text is an excerpt from the description of <strong><em>@OneToOne</em></strong> in Java EE 6 documentation. You can see the concept <strong><em>owning side</em></strong> in it.</p> <blockquote> <p>Defines a single-valued association to another entity that has one-to-one multiplicity. It is not normally necessary to specify the associated target entity explicitly since it can usually be inferred from the type of the object being referenced. If the relationship is bidirectional, <strong><em>the non-owning side</em></strong> must use the mappedBy element of the OneToOne annotation to specify the relationship field or property of the owning side.</p> </blockquote>
21,068,644
5
4
null
2010-05-01 11:11:47.537 UTC
114
2022-04-10 23:51:26.783 UTC
2017-11-13 18:18:20.663 UTC
null
1,788,806
null
170,931
null
1
176
java|hibernate|orm|jpa|mapping
51,084
<p><strong>Why is the notion of a owning side necessary:</strong></p> <p>The idea of a owning side of a bidirectional relation comes from the fact that in relational databases there are no bidirectional relations like in the case of objects. In databases we only have unidirectional relations - foreign keys.</p> <p><strong>What is the reason for the name 'owning side'?</strong></p> <p>The owning side of the relation tracked by Hibernate is the side of the relation that <em>owns</em> the foreign key in the database.</p> <p><strong>What is the problem that the notion of owning side solves?</strong></p> <p>Take an example of two entities mapped <em>without</em> declaring a owning side:</p> <pre><code>@Entity @Table(name=&quot;PERSONS&quot;) public class Person { @OneToMany private List&lt;IdDocument&gt; idDocuments; } @Entity @Table(name=&quot;ID_DOCUMENTS&quot;) public class IdDocument { @ManyToOne private Person person; } </code></pre> <p>From a OO point of view this mapping defines not one bi-directional relation, but <em>two</em> separate uni-directional relations.</p> <p>The mapping would create not only tables <code>PERSONS</code> and <code>ID_DOCUMENTS</code>, but would also create a third association table <code>PERSONS_ID_DOCUMENTS</code>:</p> <pre><code>CREATE TABLE PERSONS_ID_DOCUMENTS ( persons_id bigint NOT NULL, id_documents_id bigint NOT NULL, CONSTRAINT fk_persons FOREIGN KEY (persons_id) REFERENCES persons (id), CONSTRAINT fk_docs FOREIGN KEY (id_documents_id) REFERENCES id_documents (id), CONSTRAINT pk UNIQUE (id_documents_id) ) </code></pre> <p>Notice the primary key <code>pk</code> on <code>ID_DOCUMENTS</code> only. In this case Hibernate tracks both sides of the relation independently: If you add a document to relation <code>Person.idDocuments</code>, it inserts a record in the association table <code>PERSON_ID_DOCUMENTS</code>.</p> <p>On the other hand, if we call <code>idDocument.setPerson(person)</code>, we change the foreign key person_id on table <code>ID_DOCUMENTS</code>. Hibernate is creating <em>two</em> unidirectional (foreign key) relations on the database, to implement <em>one</em> bidirectional object relation.</p> <p><strong>How the notion of owning side solves the problem:</strong></p> <p>Many times what we want is only a foreign key on table <code>ID_DOCUMENTS</code> towards <code>PERSONS</code>and not the extra association table.</p> <p>To solve this we need to configure Hibernate to stop tracking the modifications on relation <code>Person.idDocuments</code>. Hibernate should only track the <em>other</em> side of the relation <code>IdDocument.person</code>, and to do so we add <strong>mappedBy</strong>:</p> <pre><code>@OneToMany(mappedBy=&quot;person&quot;) private List&lt;IdDocument&gt; idDocuments; </code></pre> <p><strong>What does it mean mappedBy ?</strong></p> <blockquote> <p>This means something like: &quot;modifications on this side of the relation are already <strong>Mapped By</strong> the other side of the relation IdDocument.person, so no need to track it here separately in an extra table.&quot;</p> </blockquote> <p><strong>Are there any GOTCHAs, consequences?</strong></p> <p>Using <strong>mappedBy</strong>, If we only call <code>person.getDocuments().add(document)</code>, the foreign key in <code>ID_DOCUMENTS</code> will <strong>NOT</strong> be linked to the new document, because this is not the owning /tracked side of the relation!</p> <p>To link the document to the new person, you need to explicitly call <code>document.setPerson(person)</code>, because that is the <em><strong>owning side</strong></em> of the relation.</p> <p>When using <strong>mappedBy</strong>, it is the responsibility of the developer to know what is the owning side, and update the correct side of the relation in order to trigger the persistence of the new relation in the database.</p>
2,786,303
Offline mode app in a (HTML5) browser possible?
<p>Is it possible to build an application <em>inside</em> in browser? An application means:</p> <p>1 Where there is <strong>connection</strong> (online mode) between the browser and an remote application server:</p> <ul> <li>the application runs in typical web-based mode</li> <li>the application stores <em>necessary</em> data in offline storage, to be used in offline mode (2)</li> <li>the application sync/push data (captured during offline mode) back to the server when it is resumed from offline mode back to online mode</li> </ul> <p>2 Where there is <strong>no connection</strong> (offline mode) between the browser and an remote application server:</p> <ul> <li>the application will still run (javascript?)</li> <li>the application will present data (which is stored offline) to user</li> <li>the application can accept input from user (and store/append in offline storage)</li> </ul> <p>Is this possible? If the answer is a yes, is there any (Ruby/Python/PHP) framework being built?</p> <p>Thanks</p>
2,786,567
6
1
null
2010-05-07 04:55:16.217 UTC
41
2018-06-23 18:33:23.84 UTC
null
null
null
null
88,597
null
1
48
html|offline-mode
41,019
<p>Yes, that is possible. </p> <ul> <li><p>You need to write the application in Javascript, and detect somehow whether the browser is in offline mode (simplest is to poll a server once in a while). (Edit: see comments for a better way to detect offline mode)</p></li> <li><p>Make sure that your application consists of only static HTML, Js and CSS files (or set the caching policy manually in your script so that your browser will remember them in offline mode). Updates to the page are done through JS DOM manipulation, not through the server (a framework such as ExtJS <a href="http://www.extjs.com" rel="noreferrer">http://www.extjs.com</a> will help you here)</p></li> <li><p>For storage, use a module such as PersistJS ( <a href="http://github.com/jeremydurham/persist-js" rel="noreferrer">http://github.com/jeremydurham/persist-js</a> ), which uses the local storage of the browser to keep track of data. When connection is restored, synchronize with the server.</p></li> <li><p>You need to pre-cache images and other assets used, otherwse they will be unavailable in offline mode if you didn't use them before.</p></li> <li><p>Again: the bulk of your app needs to be in javascript, a PHP/Ruby/Python framework will help you little if the server is unreachable. The server is probably kept as simple as possible, a REST-like AJAX API to store and load data.</p></li> </ul>
2,705,394
How can I prevent my asp.net site from being screen scraped?
<p>How can I prevent my asp.net 3.5 website from being screen scraped by my competitor? Ideally, I want to ensure that no webbots or screenscrapers can extract data from my website.</p> <p>Is there a way to detect that there is a webbot or screen scraper running ?</p>
2,705,438
8
1
null
2010-04-24 17:15:59.907 UTC
10
2013-07-17 19:17:32.13 UTC
2010-04-24 17:26:49.197 UTC
null
279,521
null
279,521
null
1
8
asp.net|.net-3.5|screen-scraping
7,382
<p>It is possible to try to detect screen scrapers:</p> <p>Use cookies and timing, this will make it harder for those out of the box screen scrapers. Also check for javascript support, most scrapers do not have it. Check Meta browser data to verify it is really a web browser.</p> <p>You can also check for requests in a minute, a user driving a browser can only make a small number of requests per minute, so logic on the server that detects too many requests per minute could presume that screen scraping is taking place and prevent access from the offending IP address for some period of time. If this starts to affect crawlers, log the users ip that is blocked, and start allowing their IPs as needed.</p> <p>You can use <a href="http://www.copyscape.com/" rel="nofollow noreferrer">http://www.copyscape.com/</a> to proect your content also, this will at least tell you who is reusing your data.</p> <p>See this question also:</p> <p><a href="https://stackoverflow.com/questions/396817/protection-from-screen-scraping">Protection from screen scraping</a></p> <p>Also take a look at</p> <p><a href="http://blockscraping.com/" rel="nofollow noreferrer">http://blockscraping.com/</a></p> <p>Nice doc about screen scraping:</p> <p><a href="http://www.realtor.org/wps/wcm/connect/5f81390048be35a9b1bbff0c8bc1f2ed/scraping_sum_jun_04.pdf?MOD=AJPERES&amp;CACHEID=5f81390048be35a9b1bbff0c8bc1f2ed" rel="nofollow noreferrer">http://www.realtor.org/wps/wcm/connect/5f81390048be35a9b1bbff0c8bc1f2ed/scraping_sum_jun_04.pdf?MOD=AJPERES&amp;CACHEID=5f81390048be35a9b1bbff0c8bc1f2ed</a></p> <p>How to prevent screen scraping:</p> <p><a href="http://mvark.blogspot.com/2007/02/how-to-prevent-screen-scraping.html" rel="nofollow noreferrer">http://mvark.blogspot.com/2007/02/how-to-prevent-screen-scraping.html</a></p>
3,177,241
What is the best way to concatenate two vectors?
<p>I'm using multitreading and want to merge the results. For example:</p> <pre><code>std::vector&lt;int&gt; A; std::vector&lt;int&gt; B; std::vector&lt;int&gt; AB; </code></pre> <p>I want AB to have to contents of A and the contents of B in that order. What's the most efficient way of doing something like this?</p>
3,177,252
11
2
null
2010-07-05 04:36:53.573 UTC
61
2022-05-27 01:00:00.123 UTC
2015-11-24 09:00:49.903 UTC
null
2,476,755
null
146,780
null
1
227
c++|vector
291,397
<pre><code>AB.reserve( A.size() + B.size() ); // preallocate memory AB.insert( AB.end(), A.begin(), A.end() ); AB.insert( AB.end(), B.begin(), B.end() ); </code></pre>
2,827,393
Angles between two n-dimensional vectors in Python
<p>I need to determine the angle(s) between two n-dimensional vectors in Python. For example, the input can be two lists like the following: <code>[1,2,3,4]</code> and <code>[6,7,8,9]</code>.</p>
2,827,475
12
1
null
2010-05-13 14:06:21.343 UTC
45
2022-01-20 16:06:33.26 UTC
2016-01-27 02:45:04.693 UTC
null
1,391,441
null
340,342
null
1
104
python|vector|angle
210,242
<pre><code>import math def dotproduct(v1, v2): return sum((a*b) for a, b in zip(v1, v2)) def length(v): return math.sqrt(dotproduct(v, v)) def angle(v1, v2): return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2))) </code></pre> <p><strong>Note</strong>: this will fail when the vectors have either the same or the opposite direction. The correct implementation is here: <a href="https://stackoverflow.com/a/13849249/71522">https://stackoverflow.com/a/13849249/71522</a></p>
3,038,033
What are good uses for Python3's "Function Annotations"?
<p>Function Annotations: <a href="http://www.python.org/dev/peps/pep-3107/" rel="noreferrer">PEP-3107</a></p> <p>I ran across a snippet of code demonstrating Python3's function annotations. The concept is simple but I can't think of why these were implemented in Python3 or any good uses for them. Perhaps SO can enlighten me?</p> <p>How it works:</p> <pre><code>def foo(a: 'x', b: 5 + 6, c: list) -&gt; max(2, 9): ... function body ... </code></pre> <p>Everything following the colon after an argument is an 'annotation', and the information following the <code>-&gt;</code> is an annotation for the function's return value. </p> <p>foo.func_annotations would return a dictionary:</p> <pre><code>{'a': 'x', 'b': 11, 'c': list, 'return': 9} </code></pre> <p>What's the significance of having this available?</p>
3,038,096
12
5
null
2010-06-14 14:25:51.337 UTC
76
2022-01-12 18:00:56.687 UTC
2021-02-12 00:49:43.733 UTC
null
6,862,601
null
60,739
null
1
171
python|function|annotations|python-3.x
57,177
<p>I think this is actually great.</p> <p>Coming from an academic background, I can tell you that annotations have proved themselves invaluable for enabling smart static analyzers for languages like Java. For instance, you could define semantics like state restrictions, threads that are allowed to access, architecture limitations, etc., and there are quite a few tools that can then read these and process them to provide assurances beyond what you get from the compilers. You could even write things that check preconditions/postconditions.</p> <p>I feel something like this is especially needed in Python because of its weaker typing, but there were really no constructs that made this straightforward and part of the official syntax.</p> <p>There are other uses for annotations beyond assurance. I can see how I could apply my Java-based tools to Python. For instance, I have a tool that lets you assign special warnings to methods, and gives you indications when you call them that you should read their documentation (E.g., imagine you have a method that must not be invoked with a negative value, but it's not intuitive from the name). With annotations, I could technically write something like this for Python. Similarly, a tool that organizes methods in a large class based on tags can be written if there is an official syntax.</p>
2,363,801
What would be the best way to implement change tracking on an object
<p>I have a class which contains 5 properties.</p> <p>If any value is assingned to any of these fields, an another value (for example IsDIrty) would change to true.</p> <pre><code>public class Class1 { bool IsDIrty {get;set;} string Prop1 {get;set;} string Prop2 {get;set;} string Prop3 {get;set;} string Prop4 {get;set;} string Prop5 {get;set;} } </code></pre>
2,363,851
13
0
null
2010-03-02 14:33:32.243 UTC
31
2022-03-31 18:10:49.57 UTC
2019-05-31 09:13:09.663 UTC
null
6,519,111
null
137,348
null
1
47
c#|.net
50,546
<p>To do this you can't really use automatic getter &amp; setters, and you need to set IsDirty in each setter.</p> <p>I generally have a "setProperty" generic method that takes a ref parameter, the property name and the new value. I call this in the setter, allows a single point where I can set isDirty and raise Change notification events e.g.</p> <pre><code>protected bool SetProperty&lt;T&gt;(string name, ref T oldValue, T newValue) where T : System.IComparable&lt;T&gt; { if (oldValue == null || oldValue.CompareTo(newValue) != 0) { oldValue = newValue; PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(name)); isDirty = true; return true; } return false; } // For nullable types protected void SetProperty&lt;T&gt;(string name, ref Nullable&lt;T&gt; oldValue, Nullable&lt;T&gt; newValue) where T : struct, System.IComparable&lt;T&gt; { if (oldValue.HasValue != newValue.HasValue || (newValue.HasValue &amp;&amp; oldValue.Value.CompareTo(newValue.Value) != 0)) { oldValue = newValue; PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(name)); } } </code></pre>
2,752,868
Does JavaScript have classes?
<p>A friend and I had an argument last week. He stated there were no such things as classes in JavaScript.</p> <p>I said there was as you can say <code>var object = new Object()</code></p> <p>He says "as there is no word <code>class</code> used. It's not a class."</p> <p>Who is right?</p> <hr> <p>As a note; For future you needing a succinct Classy JS implement:</p> <p><a href="https://github.com/tnhu/jsface" rel="noreferrer">https://github.com/tnhu/jsface</a></p> <hr> <p><strong>Edit: July 2017</strong></p> <blockquote> <p>JavaScript classes introduced in ECMAScript 2015 are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.</p> </blockquote> <p>- Mozilla ES6 Classes: <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes" rel="noreferrer">https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes</a></p>
2,752,889
13
2
null
2010-05-02 08:37:25.8 UTC
24
2022-03-09 10:06:53.033 UTC
2017-07-27 19:31:12.497 UTC
null
235,146
null
235,146
null
1
79
javascript|oop|class
39,847
<p>Technically, the statement "JavaScript has no classes" is correct.</p> <p>Although JavaScript is object-oriented language, it isn't a <a href="http://en.wikipedia.org/wiki/Class-based_programming" rel="noreferrer">class-based language</a>—it's a <a href="http://en.wikipedia.org/wiki/Prototype-based_programming" rel="noreferrer">prototype-based language</a>. There are differences between these two approaches, but since it is possible to use JavaScript like a class-based language, many people (including myself) often simply refer to the constructor functions as "classes".</p>
25,022,276
Value expression error: "[BC30456] 'RdlObjectModel' is not a member of 'Reporting Services'
<p>Stumbled on an obscure problem. Posting this because my searches of stack overflow did not find my answer. Hopefully this will help someone else.</p> <p>Problem: My reporting services report will compile, but at run-time provides an error along the lines of:</p> <p>[BC30456] 'RdlObjectModel' is not a member of 'Reporting Services'</p> <p>This happened after I copy/pasted an entire tablix over from one report to another.<br> After I reversed the change and removed the tablix, it worked again.<br> The original report with the tablix I'm copy/pasting works fine.</p>
25,022,277
3
0
null
2014-07-29 18:17:08.383 UTC
10
2020-07-10 04:49:57.193 UTC
2019-06-27 03:11:53.467 UTC
null
1,555,612
null
2,880,223
null
1
31
reporting-services|ssrs-2008
20,188
<p>Found this bug report which exactly explains the problem I had:</p> <p><a href="http://connect.microsoft.com/SQLServer/feedback/details/757358/pasting-objects-with-expressions-pastes-fully-qualified-functions" rel="noreferrer">http://connect.microsoft.com/SQLServer/feedback/details/757358/pasting-objects-with-expressions-pastes-fully-qualified-functions</a></p> <p>Summary of the above: When you copy/paste reporting services expressions from one place to another (I copied an entire tablix, with expressions in it) all the pieces of that expression get expanded to their full names. There is a bug specific to when you copy/paste an expression containing "Cstr()". It gets a full name that does not resolve correctly.</p> <p>Fortunately this is easy to fix, even if you have a ton of such expressions in your report. --Go to View > Code Do a find for "RdlObjectModel" or "Cstr". You are looking for something like this:</p> <pre><code>Microsoft.ReportingServices.RdlObjectModel.ExpressionParser.VBFunctions.Cstr([your expression here]) </code></pre> <p>-Remove everything from "Microsoft" to "Cstr" so it looks like this:</p> <pre><code>Cstr([your expression here]) </code></pre> <p>-Save. You have essentially undone what Reporting services so "helpfully" tried to do when you copied/pasted the expresion in the first place. </p>
10,590,998
How to get all of a user's public github commits
<p>Regardless of project, I'd like to know if there's an easy way of getting all commits to all public repositories for a single username.</p> <p>Since I belong to multiple organizations, I'm trying to compile a list of the projects on which I'm a contributor, as well as projects that I have accepted pull requests.</p> <p>So far my google-fu and looking through the github api docs has proved insufficient.</p>
10,669,967
6
0
null
2012-05-14 21:01:52.177 UTC
8
2022-08-15 18:59:47.043 UTC
null
null
null
null
814,123
null
1
34
github|github-api
10,179
<p><a href="https://connectionrequired.com/gitspective" rel="nofollow noreferrer">https://connectionrequired.com/gitspective</a> is your friend. :-) Filter out all but &quot;Push&quot;, and you have your view, albeit without the coding work to implement it yourself first.</p> <p>Inspecting what goes on with the Chrome DevTools &quot;Network&quot; tab might help you mimic the API queries, if you want to redo the work yourself.</p>
58,784,499
System.Text.Json.JsonSerializer.Serialize returns empty Json object "{}"
<p>Environment: Visual Studio 2019 16.3.8, .NET 3.0.100, .NET Core 3.0 unit test.</p> <p>All 3 calls below to System.Text.Json.JsonSerializer.Serialize return empty objects: "{}"</p> <p>I must be doing something wrong ... but I just don't see it?</p> <pre><code>public class MyObj { public int myInt; } [TestMethod] public void SerializeTest() { var myObj = new MyObj() { myInt = 99 }; var txt1 = System.Text.Json.JsonSerializer.Serialize(myObj); var txt2 = System.Text.Json.JsonSerializer.Serialize(myObj, typeof(MyObj)); var txt3 = System.Text.Json.JsonSerializer.Serialize&lt;MyObj&gt;(myObj); } </code></pre>
58,784,566
1
0
null
2019-11-09 23:35:01.31 UTC
1
2019-11-10 04:47:27.263 UTC
null
null
null
null
5,248,400
null
1
30
c#|json|serialization|.net-core
15,067
<p>im pretty sure the serializer doesn't work with fields. so use a property instead.</p> <pre><code>public int MyInt { get; set; } </code></pre>
40,906,322
How to abort 'git commit --amend'?
<p>I accidentally used <code>git commit --amend</code>. My text editor is open and waiting for input. I know, that when I close it now (not changing the existing commit message) the commit will be amended. What can I do to abort the process? </p> <p><a href="https://romanofskiat.wordpress.com/2014/02/12/abort-a-git-commit-amend/" rel="noreferrer">This blog article</a> says that I can simply delete the commit message and the commit will then not be valid and ignored. Is that correct? Are there alternatives?</p>
40,906,340
7
1
null
2016-12-01 09:00:15.627 UTC
9
2022-05-13 20:55:59.817 UTC
2017-10-21 08:10:02.323 UTC
null
3,257,186
null
3,257,186
null
1
106
git
29,236
<p>That is correct. Saving the file with no contents will abort the amend.</p>
34,013,299
Web API Authentication Basic vs Bearer
<p>I have created JWT based Authentication in my Web API application. I am not able to figure out the difference between</p> <ol> <li>Basic Token</li> <li>Bearer Token</li> </ol> <p>Can someone please help me?</p>
34,022,350
2
0
null
2015-12-01 05:33:07.083 UTC
47
2020-01-09 18:38:38.41 UTC
2016-05-31 15:30:55.947 UTC
null
4,751,310
null
3,675,978
null
1
142
basic-authentication|jwt|bearer-token
76,199
<p>The Basic and Digest authentication schemes are dedicated to the authentication using a username and a secret (see <a href="https://www.rfc-editor.org/rfc/rfc7616" rel="noreferrer">RFC7616</a> and <a href="https://www.rfc-editor.org/rfc/rfc7617" rel="noreferrer">RFC7617</a>).</p> <p>The Bearer authentication scheme is dedicated to the authentication using a token and is described by the <a href="https://www.rfc-editor.org/rfc/rfc6750" rel="noreferrer">RFC6750</a>. Even if this scheme comes from an OAuth2 specification, you can still use it in any other context where tokens are exchange between a client and a server.</p> <p>Concerning the JWT authentication and as it is a token, the best choice is the Bearer authentication scheme. Nevertheless, nothing prevent you from using a custom scheme that could fit on your requirements.</p>
35,504,194
What features do Progressive Web Apps have vs. native apps and vice-versa, on Android
<p>In 2015 Google introduced a new approach for developing web apps for Android: <a href="https://developers.google.com/web/progressive-web-apps">progressive web apps</a>. One can create an application that will look like a native application, will be able to use device's hardware like camera and accelerometers, receive push notifications, have a launcher icon, work in offline, store local data, etc.</p> <p>On Android, what features do native apps provide that progressive web apps do not support, and vice versa.</p>
39,027,789
2
0
null
2016-02-19 11:27:27.003 UTC
71
2018-07-04 20:12:58.71 UTC
2016-08-19 21:44:01.533 UTC
null
1,269,037
null
170,842
null
1
116
android|google-chrome|firefox|progressive-web-apps
68,791
<p>TL;DR - As of Feb 2017, Progressive Web Apps are a sufficiently powerful platform that <a href="https://twitter.com/necolas/status/829128165314306048" rel="noreferrer">Twitter has moved all of their mobile web traffic to a React PWA</a>.</p> <p>As of August 2016, Progressive Web Apps actually offer more hardware access than commonly thought. Here's a screenshot of <a href="http://whatwebcando.today" rel="noreferrer">whatwebcando.today</a> from my Chrome 52 stable on Android:</p> <p><a href="https://i.stack.imgur.com/Elwzn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Elwzn.png" alt="What Web Can Do Today - Chrome 52 on Android"></a></p> <h1>Hardware access includes</h1> <ul> <li><a href="http://caniuse.com/#feat=geolocation" rel="noreferrer">geolocation</a> - supported in the vast majority of browsers</li> <li>camera and microphone via the <a href="http://caniuse.com/#feat=stream" rel="noreferrer">getUserMedia/Stream</a> and the upcoming <a href="https://www.w3.org/TR/image-capture/" rel="noreferrer">MediaStream Image Capture</a> APIs</li> <li>device <a href="http://caniuse.com/#feat=vibration" rel="noreferrer">vibration</a></li> <li>screen <a href="http://caniuse.com/#feat=deviceorientation" rel="noreferrer">orientation and accelerometer</a> access, including <a href="https://www.w3.org/TR/orientation-event/#introduction" rel="noreferrer">compass and gyroscope</a></li> <li><a href="http://caniuse.com/#feat=battery-status" rel="noreferrer">battery status</a></li> </ul> <h1>Upcoming hardware access</h1> <p>These features are being implemented or already work in some browsers:</p> <ul> <li>Bluetooth via <a href="http://caniuse.com/#feat=web-bluetooth" rel="noreferrer">Web Bluetooth</a> API</li> <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/B2G_OS/API/NFC_API" rel="noreferrer">NFC</a></li> <li><a href="http://caniuse.com/#feat=ambient-light" rel="noreferrer">ambient light sensor</a> (<a href="https://lh3.googleusercontent.com/y8B_G25tYklJPI4bq1oy9xT-ob1VXqVUCk1ldFTECofXU9ASgIvAI3yLPBLE-9l6yuVNY4kvypZ2UEBGON8CgOxFEgZPJ2MpNFpBeyW5zsouqxFDd6g0cJd8yH1v0gee9Dg3male1nsFkE-BESi1SRRPqd7hLwT6w9kXF2aoPOgvG0fuEQLBGPwetGV5gvCzoR-Zj_e9hTbxKktC6zEDY_sJsH5aPvqTGPvvKdXTs6y-en6jLR6frJNfOdQXRWkWJLC0pNg-K7gphBuGvHTGjiQgEVgq4O8lBcvo1QD6CchKr2gM05vK3KklRvt9A_IziezJEWFXbmN1yZYOrwyhzNkjSiS9hoPOaD9msBH9xyULVDr10G4HzA5R8bveEwXwb6hyn40UmjBi8JCZaMQcxeic_SEf6Ix5-f2wwHRHXJpC29qpA_f2Afw8PI2f45yNWMy-yMIfN6egAva3nUs_NBlj9nQrgyjAIIE3nMdUP-YKFUF30sshwAsGu4VecR2jqYTkRB9DJeWbaVNqymy93QZVyHwXM62wCUYEvsBrKITpNvxBSrvDZ1u9tJSxSnLZ4KkME69dLEIjpkqioTan3AIlzyjb1zM=w605-h1075-no" rel="noreferrer">works</a> in Firefox 48+)</li> <li><a href="http://caniuse.com/#feat=proximity" rel="noreferrer">proximity sensor</a> (<a href="https://lh3.googleusercontent.com/y8B_G25tYklJPI4bq1oy9xT-ob1VXqVUCk1ldFTECofXU9ASgIvAI3yLPBLE-9l6yuVNY4kvypZ2UEBGON8CgOxFEgZPJ2MpNFpBeyW5zsouqxFDd6g0cJd8yH1v0gee9Dg3male1nsFkE-BESi1SRRPqd7hLwT6w9kXF2aoPOgvG0fuEQLBGPwetGV5gvCzoR-Zj_e9hTbxKktC6zEDY_sJsH5aPvqTGPvvKdXTs6y-en6jLR6frJNfOdQXRWkWJLC0pNg-K7gphBuGvHTGjiQgEVgq4O8lBcvo1QD6CchKr2gM05vK3KklRvt9A_IziezJEWFXbmN1yZYOrwyhzNkjSiS9hoPOaD9msBH9xyULVDr10G4HzA5R8bveEwXwb6hyn40UmjBi8JCZaMQcxeic_SEf6Ix5-f2wwHRHXJpC29qpA_f2Afw8PI2f45yNWMy-yMIfN6egAva3nUs_NBlj9nQrgyjAIIE3nMdUP-YKFUF30sshwAsGu4VecR2jqYTkRB9DJeWbaVNqymy93QZVyHwXM62wCUYEvsBrKITpNvxBSrvDZ1u9tJSxSnLZ4KkME69dLEIjpkqioTan3AIlzyjb1zM=w605-h1075-no" rel="noreferrer">works</a> in Firefox 48+)</li> <li><a href="https://w3c.github.io/accelerometer/" rel="noreferrer">accelerometer</a>, <a href="https://w3c.github.io/magnetometer/" rel="noreferrer">magnetometer</a> and <a href="https://w3c.github.io/gyroscope/" rel="noreferrer">gyroscope</a> sensor access</li> <li><a href="https://www.chromestatus.com/feature/4757990523535360" rel="noreferrer">shape detection API</a></li> </ul> <p>Another important point to note is that the <a href="https://github.com/jpchase/OriginTrials" rel="noreferrer">Origin Trials</a> Framework (<a href="https://www.chromestatus.com/feature/6331324939894784" rel="noreferrer">implemented in Chrome</a>) enables manufacturers to expose and test hardware (or software) capabilities without having to go through the standardization process. For example, a phone maker could expose an API for reading the values of a pressure sensor, refine it, then submit it for consideration to the W3C.</p> <p>Besides hardware access, there are also software features traditionally employed by native apps that are now available to web apps.</p> <h1>Traditionally native features that PWAs can also use</h1> <ul> <li>push notifications</li> <li>working offline</li> <li><a href="https://developers.google.com/web/fundamentals/engage-and-retain/app-install-banners/images/add-to-home-screen.gif" rel="noreferrer">adding an icon to the home screen</a></li> <li>appearing in the apps list thanks to <a href="https://www.xda-developers.com/deeply-integrated-progressive-web-apps-are-already-live-for-chrome-on-android/" rel="noreferrer">WebAPKs</a> - Progressive Web Apps can now be packaged into actual installable Android packages!</li> <li>launching in <a href="https://developers.google.com/web/updates/2014/11/Support-for-installable-web-apps-with-webapp-manifest-in-chrome-38-for-Android?hl=en" rel="noreferrer">full-screen</a></li> <li><a href="https://github.com/zenorocha/clipboard.js/" rel="noreferrer">clipboard access</a></li> <li><p>hardware-accelerated 2D/3D graphics via HTML5 <a href="http://caniuse.com/#feat=canvas" rel="noreferrer">Canvas</a> or <a href="http://caniuse.com/#feat=webgl" rel="noreferrer">WebGL</a> - check some of the <a href="http://www.kevs3d.co.uk/dev/" rel="noreferrer">HTML5 Canvas demos</a>, <a href="http://www.cssdesignawards.com/articles/30-best-webgl-sites-for-2015/263/" rel="noreferrer">WebGL sites</a> or the <a href="http://threejs.org/" rel="noreferrer">three.js library</a>. A 2014 benchmark of the <a href="https://unity3d.com" rel="noreferrer">Unity cross-platform game engine</a> compared native vs. WebGL rendering performance, and <a href="https://blogs.unity3d.com/2014/10/07/benchmarking-unity-performance-in-webgl/" rel="noreferrer">concluded</a> that</p> <blockquote> <p>"The most important takeaway is, while there are still areas where WebGL is significantly slower than native code, overall you can get expect very decent performance already, and this can only get better in the future."</p> </blockquote> <p><a href="https://blogs.unity3d.com/2015/12/15/updated-webgl-benchmark-results/" rel="noreferrer">The gap has indeed been closing</a>.</p></li> <li><a href="http://caniuse.com/#feat=fileapi" rel="noreferrer">reading</a> user-selected files in any browser</li> <li><a href="https://www.pokedex.org/" rel="noreferrer">slick, smooth UIs</a> with <a href="https://medium.com/engineering-housing/progressing-mobile-web-fac3efb8b454" rel="noreferrer">60fps animations</a></li> </ul> <p>These features cover a lot of use cases, and many popular native apps nowadays could be rewritten as PWAs. Take Slack, for example. Its open source alternative, <a href="https://github.com/RocketChat/Rocket.Chat.PWA" rel="noreferrer">Rocket.Chat, is building a PWA version</a>. For more PWA demos, see <a href="https://pwa.rocks" rel="noreferrer">https://pwa.rocks</a>.</p> <h1>Native-like features coming to PWAs</h1> <ul> <li><a href="https://stackoverflow.com/questions/38189160/can-a-progressive-web-app-be-registered-as-a-share-option-in-android">handling intents</a>  —  for example, <a href="https://paul.kinlan.me/navigator.share/" rel="noreferrer">sharing a page to another app</a>, or being the <a href="https://github.com/WICG/web-share-target" rel="noreferrer">share target</a>, e.g. a PWA chat app that receives an image to set as the user’s avatar</li> </ul> <h1><a href="https://android.stackexchange.com/questions/38388/what-do-android-application-permissions-mean/38389">Native Android features</a> not yet available to PWAs</h1> <ul> <li>access to the fingerprint sensor (<a href="https://crbug.com669913" rel="noreferrer">under development</a>)</li> <li>contacts, calendar and browser bookmarks access (lack of access to these could be viewed as a <a href="https://www.reddit.com/r/programming/comments/4yfpfl/when_progressive_web_apps_are_better_than_native/d6nsug9?st=is6svret&amp;sh=42d74c90" rel="noreferrer">feature</a> by privacy-conscious users)</li> <li>alarms</li> <li>telephony features - intercept SMSes or calls, send SMS/MMS, get the user's phone number, read voice mail, make phone calls without the Dialer dialog</li> <li>low-level access to some hardware features and sensors: flashlight, atmospheric pressure sensor</li> <li>system access: task management, modifying system settings, logs</li> </ul> <h1>Progressive Web Apps offer features that native apps lack</h1> <ul> <li><strong>discoverability</strong> - content in progressive web apps can easily be found by search engines but a content-centric native app like StackOverflow won't show among app store search results for content that it does offer access to, such as "pwa vs. native". This is a problem for communities like Reddit, which can't expose their numerous sub-communities to the app store as individual "apps".</li> <li><strong>linkability</strong> - any page/screen can have a direct link, which can be shared easily</li> <li><strong>bookmarkability</strong> - save that link to access an app's view directly </li> <li><strong>always fresh</strong> - no need to go through the app stores to push updates</li> <li><strong>universal access</strong> - not subject by app stores <a href="https://medium.com/@krave/apple-s-app-store-review-process-is-hurting-users-but-we-re-not-allowed-to-talk-about-it-55d791451b#.s2bse2bai" rel="noreferrer">sometimes arbitrary policies</a> or (unintended) <a href="https://android.stackexchange.com/questions/12538/how-can-i-circumvent-regional-restrictions-in-googles-play-store">geographic restrictions</a></li> <li><strong>large data savings</strong>, extremely important in emerging markets with expensive and/or slow Internet access. For example, e-commerce website Konga <a href="https://developers.google.com/web/showcase/2016/konga" rel="noreferrer">cut data usage by 92% for the first load by migrating to a PWA</a>.</li> <li><strong>low friction of distribution</strong> - if your progressive web app is online, it's already accessible for Android (and other mobile) users. <ul> <li><a href="http://www.businessinsider.com/how-many-apps-people-download-per-month-2014-8" rel="noreferrer">65.5% of US smartphone users don't download any new apps each month</a></li> <li>PWAs eliminate the need to go to the app store, search for the app, click Install, wait for the download, then open the app. <a href="https://www.youtube.com/watch?v=qmE_jpnYXFo&amp;feature=youtu.be&amp;t=96" rel="noreferrer">Each of these steps loses 20% of the potential users.</a></li> </ul></li> </ul> <p>Final note: PWAs run, with the same codebase, on the desktop as well as most mobile devices. On desktop environments (ChromeOS, and <a href="https://developers.google.com/web/updates/2018/05/nic67#desktop-pwas" rel="noreferrer">later</a> Mac and Windows), they're launched in the same way as other apps, and run in a regular app window (no browser tab).</p>
53,036,328
how do I check the file size of a video in flutter before uploading
<p>I want to upload a video file to my cloud storage but I want to check the size of the video file before I upload. how to achieve this</p>
53,040,464
5
1
null
2018-10-28 21:38:53.543 UTC
9
2022-07-11 20:14:45.783 UTC
null
null
null
null
9,398,610
null
1
39
dart|flutter|firebase-storage
34,355
<p>If you have the path of the file, you can use <code>dart:io</code></p> <pre><code>var file = File('the_path_to_the_video.mp4'); </code></pre> <p>You an either use:</p> <pre><code>print(file.lengthSync()); </code></pre> <p>or</p> <pre><code>print (await file.length()); </code></pre> <hr> <p>Note: The size returned is in <code>bytes</code>. </p>
8,586,327
Generate Ascii art text in C
<p>I am trying to generate ascii art text for a fun application. From FIGLET, I got the ASCII pattern. I am using that pattern in a <code>printf</code> statement to print letters. Here is a screenshot of the pattern I got from FIGLET:</p> <p><img src="https://i.stack.imgur.com/4sHpT.png" alt="FIGLET"></p> <p>Here is the code snippet I use to print A:</p> <pre><code>printf(" _/_/\n _/ _/\n _/_/_/_/\n _/ _/\n_/ _/\n"); </code></pre> <p>Now, I take an input text from user, and show it in ASCII art. As I use printf, I can only generate it vertically:</p> <p><img src="https://i.stack.imgur.com/qec7l.png" alt="Vertical image"></p> <p>But I need to do horizontal ASCII art. How to do that ?</p>
8,586,765
4
0
null
2011-12-21 07:25:29.15 UTC
5
2022-04-08 15:33:23.143 UTC
2011-12-21 08:02:21.07 UTC
null
253,056
null
931,436
null
1
7
c|ascii-art
44,550
<p>Yes, this is a well known problem. The last time I solved this is to use an array for each line and rendering each letter separately.</p> <p>Firstly, I would represent each letter in an array. For example your A would be something like this:</p> <pre><code>char* letter[8]; letter[0] = " _/_/ "; letter[1] = " _/ _/"; etc. </code></pre> <p>(Actually a 2D array would be used where each letter is at a different index.)</p> <p>The actual render would be in an array as well, something along the lines of:</p> <p>char* render[8];</p> <p>and then use concatenation to build each line. A simply nested for loop should do the trick:</p> <pre><code>for each line, i to render (i.e the height of the letters) for each letter, j concatenate line i of letter j to the to char* i in the array </code></pre> <p>Finally loop though the array and print each line. Actually, you can skip the render array and simply print each line without a carriage return. Something like the following comes to mind: </p> <pre><code>for each line, i to render : // (i.e the height of the letters) for each letter, j { output line i of letter j } output a carriage return } </code></pre> <p>(My C is a bit rusty, from there the "pseudo" code. However, I think my logic is sound.)</p>
8,558,919
mktime and tm_isdst
<p>I saw a lot of different views so thought of asking here.</p> <p>I read <code>man mktime</code>:</p> <pre><code> (A positive or zero value for tm_isdst causes mktime() to presume initially that summer time (for example, Daylight Saving Time) is or is not in effect for the specified time, respectively. A negative value for tm_isdst causes the mktime() function to attempt to divine whether summer time is in effect for the specified time. </code></pre> <p>My question is, shouldn't <code>tm_isdst</code> be kept as <code>-1</code> to let the system decide if its dst or not and that way the code becomes dst agnostic? </p> <p>Am I missing something?</p>
8,565,660
3
0
null
2011-12-19 08:50:54.273 UTC
6
2019-04-18 21:34:09.383 UTC
2019-04-08 04:30:35.443 UTC
null
212,378
null
358,892
null
1
18
c|unix|time|freebsd|mktime
38,150
<p>I believe the original reason for that is some timezones do not have daylight savings time. Since mktime is not async-safe nor is it re-entrant allows the implementation to store the current value of daylight savings in the POSIX extern char tzname[2], indexed by daylight [0 or 1]. This means tzname[0]="[std TZ name]" and tzname="[daylight TZ name, e.g. EDT]"</p> <p>See your tzset() man page for more information on this. Standards conforming mktime() is required to behave as though it called tzset() anyway. This kind of obviates the use of tm_isdst, IMO.</p> <p>Bottom line: your particular implementation and timezone(s) would dictate whether you would use -1, 0, or 1 for tm_isdst. There is no one default correct way for all implementations.</p>
8,657,908
Deploying Yesod to Heroku, can't build statically
<p>I'm very new to Yesod and I'm having trouble building Yesod statically so I can deploy to Heroku.</p> <p>I have changed the default .cabal file to reflect static compilation</p> <pre><code>if flag(production) cpp-options: -DPRODUCTION ghc-options: -Wall -threaded -O2 -static -optl-static else ghc-options: -Wall -threaded -O0 </code></pre> <p>And it no longer builds. I get a whole bunch of warnings and then a slew of undefined references like this:</p> <pre><code>Linking dist/build/personal-website/personal-website ... /usr/lib/ghc-7.0.3/libHSrts_thr.a(Linker.thr_o): In function `internal_dlopen': Linker.c:(.text+0x407): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/ghc-7.0.3/unix-2.4.2.0/libHSunix-2.4.2.0.a(HsUnix.o): In function `__hsunix_getpwent': HsUnix.c:(.text+0xa1): warning: Using 'getpwent' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/ghc-7.0.3/unix-2.4.2.0/libHSunix-2.4.2.0.a(HsUnix.o): In function `__hsunix_getpwnam_r': HsUnix.c:(.text+0xb1): warning: Using 'getpwnam_r' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/libpq.a(thread.o): In function `pqGetpwuid': (.text+0x15): warning: Using 'getpwuid_r' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/libpq.a(ip.o): In function `pg_getaddrinfo_all': (.text+0x31): warning: Using 'getaddrinfo' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/ghc-7.0.3/site-local/network-2.3.0.2/ libHSnetwork-2.3.0.2.a(BSD__63.o): In function `sD3z_info': (.text+0xe4): warning: Using 'gethostbyname' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/ghc-7.0.3/site-local/network-2.3.0.2/ libHSnetwork-2.3.0.2.a(BSD__164.o): In function `sFKc_info': (.text+0x12d): warning: Using 'getprotobyname' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/ghc-7.0.3/site-local/network-2.3.0.2/ libHSnetwork-2.3.0.2.a(BSD__155.o): In function `sFDs_info': (.text+0x4c): warning: Using 'getservbyname' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/libpq.a(fe-misc.o): In function `pqSocketCheck': (.text+0xa2d): undefined reference to `SSL_pending' /usr/lib/libpq.a(fe-secure.o): In function `SSLerrmessage': (.text+0x31): undefined reference to `ERR_get_error' /usr/lib/libpq.a(fe-secure.o): In function `SSLerrmessage': (.text+0x41): undefined reference to `ERR_reason_error_string' /usr/lib/libpq.a(fe-secure.o): In function `initialize_SSL': (.text+0x2f8): undefined reference to `SSL_check_private_key' /usr/lib/libpq.a(fe-secure.o): In function `initialize_SSL': (.text+0x3c0): undefined reference to `SSL_CTX_load_verify_locations' (... snip ...) </code></pre> <p>If I just compile with just <code>-static</code> and without <code>-optl-static</code> everything builds fine but the application crashes when it tries to start on Heroku.</p> <pre><code>2011-12-28T01:20:51+00:00 heroku[web.1]: Starting process with command `./dist/build/personal-website/personal-website -p 41083` 2011-12-28T01:20:51+00:00 app[web.1]: ./dist/build/personal-website/ personal-website: error while loading shared libraries: libgmp.so.10: cannot open shared object file: No such file or directory 2011-12-28T01:20:52+00:00 heroku[web.1]: State changed from starting to crashed </code></pre> <p>I tried adding libgmp.so.10 to the LD_LIBRARY_PATH as suggested in <a href="http://translate.google.com/translate?hl=en&amp;sl=ja&amp;tl=en&amp;u=http://d.hatena.ne.jp/thimura/20111117/1321480728" rel="noreferrer">here</a> and then got the following error:</p> <pre><code>2011-12-28T01:31:23+00:00 app[web.1]: ./dist/build/personal-website/ personal-website: /lib/libc.so.6: version `GLIBC_2.14' not found (required by ./dist/build/personal-website/personal-website) 2011-12-28T01:31:23+00:00 app[web.1]: ./dist/build/personal-website/ personal-website: /lib/libc.so.6: version `GLIBC_2.14' not found (required by /app/dist/build/personal-website/libgmp.so.10) 2011-12-28T01:31:25+00:00 heroku[web.1]: State changed from starting to crashed 2011-12-28T01:31:25+00:00 heroku[web.1]: Process exited </code></pre> <p>It seems that the version of libc that I'm compiling against is different. I tried also adding libc to the batch of libraries the same way I did for libgmp but this results in a segmentation fault when the application starts on the Heroku side.</p> <p>Everything works fine on my PC. I'm running 64bit archlinux with ghc 7.0.3. <a href="http://www.yesodweb.com/blog/2011/07/haskell-on-heroku" rel="noreferrer">The blog post on the official Yesod blog</a> looked pretty easy but I'm stumped at this point. Anyone have any ideas? If there's a way to get this thing working <em>without</em> building statically I'm open to that too.</p> <p><strong>EDIT</strong></p> <p>Per <code>Employed Russians</code> answer I did the following to fix this.</p> <p>First created a new directory <code>lib</code> under the project directory and copied the missing shared libraries into it. You can get this information by running <code>ldd path/to/executable</code> and <code>heroku run ldd path/to/executable</code> and comparing the output.</p> <p>I then did <code>heroku config:add LD_LIBRARY_PATH=./lib</code> so when the application is started the dynamic linker will look for libraries in the new lib directory.</p> <p>Finally I created an ubuntu 11.10 virtual machine and built and deployed to Heroku from there, this has an old enough glibc that it works on the Heroku host.</p> <p>Edit: I've since written a tutorial on the <a href="https://github.com/yesodweb/yesod/wiki/Deploying-Yesod-Apps-to-Heroku" rel="noreferrer">Yesod wiki</a></p>
8,658,468
4
0
null
2011-12-28 15:40:56.02 UTC
11
2022-03-31 18:19:50.577 UTC
2016-03-02 17:01:51.677 UTC
null
448,496
null
166,732
null
1
31
linux|haskell|heroku|static-linking|yesod
38,439
<p>I have no idea what Yesod is, but I know <em>exactly</em> what each of your other errors means.</p> <p>First, you should <em>not</em> try to link statically. The warning you get is exactly right: <strong>if</strong> you link statically, and use one of the routines for which you are getting the warning, then you must arrange to run on a system with <em>exactly</em> the same version of libc.so.6 as the one you used at build time.</p> <p>Contrary to popular belief, static linking produces <em>less</em>, not more, portable executables on Linux.</p> <p>Your other (static) link errors are caused by missing <code>libopenssl.a</code> at link time.</p> <p>But let's assume that you are going to go the "sane" route, and use dynamic linking.</p> <p>For dynamic linking, Linux (and most other UNIXes) support backward compatibility: an old binary continues to work on newer systems. But they don't support forward compatibility (a binary built on a newer system will generally <em>not</em> run on an older one).</p> <p>But that's what you are trying to do: you built on a system with glibc-2.14 (or newer), and you are running on a system with glibc-2.13 (or older).</p> <p>The other thing you need to know is that glibc is composed of some 200+ binaries that must all match <em>exactly</em>. Two key binaries are <code>/lib/ld-linux.so</code> and <code>/lib/libc.so.6</code> (but there are many more: <code>libpthread.so.0</code>, <code>libnsl.so.1</code>, etc. etc). If some of these binaries came from different versions of glibc, you usually get a crash. And that is exactly what you got, when you tried to place your glibc-2.14 <code>libc.so.6</code> on the <code>LD_LIBRARY_PATH</code> -- it no longer matches the system <code>/lib/ld-linux</code>.</p> <p>So what are the solutions? There are several possibilities (in increasing difficulty):</p> <ol> <li><p>You could copy <code>ld-2.14.so</code> (the target of <code>/lib/ld-linux</code> symlink) to the target system, and invoke it explicitly:</p> <pre><code>/path/to/ld-2.14.so --library-path &lt;whatever&gt; /path/to/your/executable </code></pre> <p>This generally works, but can confuse an application that looks at <code>argv[0]</code>, and breaks for applications that re-exec themselves.</p></li> <li><p>You could build on an older system.</p></li> <li><p>You could use <code>appgcc</code> (this option has disappeared, see <a href="http://web.archive.org/web/20090902074009/http://autopackage.org/apbuild-apgcc.php">this</a> for description of what it used to be).</p></li> <li><p>You could set up a chroot environment matching the target system, and build inside that chroot.</p></li> <li><p>You could build yourself a Linux-to-olderLinux crosscompiler</p></li> </ol>
8,796,988
Binding multiple events to a listener (without JQuery)?
<p>While working with browser events, I've started incorporating Safari's touchEvents for mobile devices. I find that <code>addEventListener</code>s are stacking up with conditionals. <em>This project can't use JQuery.</em></p> <p>A standard event listener:</p> <pre><code>/* option 1 */ window.addEventListener('mousemove', this.mouseMoveHandler, false); window.addEventListener('touchmove', this.mouseMoveHandler, false); /* option 2, only enables the required event */ var isTouchEnabled = window.Touch || false; window.addEventListener(isTouchEnabled ? 'touchmove' : 'mousemove', this.mouseMoveHandler, false); </code></pre> <p>JQuery's <code>bind</code> allows multiple events, like so:</p> <pre><code>$(window).bind('mousemove touchmove', function(e) { //do something; }); </code></pre> <p><strong>Is there a way to combine the two event listeners as in the JQuery example?</strong> ex:</p> <pre><code>window.addEventListener('mousemove touchmove', this.mouseMoveHandler, false); </code></pre> <p>Any suggestions or tips are appreciated!</p>
8,797,106
10
0
null
2012-01-10 00:15:09.397 UTC
47
2022-07-11 20:27:46.267 UTC
null
null
null
null
1,139,837
null
1
195
javascript|jquery|touch|addeventlistener
226,409
<p>In POJS, you add one listener at a time. It is not common to add the same listener for two different events on the same element. You could write your own small function to do the job, e.g.:</p> <pre><code>/* Add one or more listeners to an element ** @param {DOMElement} element - DOM element to add listeners to ** @param {string} eventNames - space separated list of event names, e.g. 'click change' ** @param {Function} listener - function to attach for each event as a listener */ function addListenerMulti(element, eventNames, listener) { var events = eventNames.split(' '); for (var i=0, iLen=events.length; i&lt;iLen; i++) { element.addEventListener(events[i], listener, false); } } addListenerMulti(window, 'mousemove touchmove', function(){…}); </code></pre> <p>Hopefully it shows the concept. </p> <p><strong>Edit 2016-02-25</strong></p> <p>Dalgard's comment caused me to revisit this. I guess adding the same listener for multiple events on the one element is more common now to cover the various interface types in use, and Isaac's answer offers a good use of built–in methods to reduce the code (though less code is, of itself, not necessarily a bonus). Extended with ECMAScript 2015 arrow functions gives:</p> <pre><code>function addListenerMulti(el, s, fn) { s.split(' ').forEach(e =&gt; el.addEventListener(e, fn, false)); } </code></pre> <p>A similar strategy could add the same listener to multiple elements, but the need to do that might be an indicator for event delegation.</p>
27,330,551
Laravel Eloquent ORM - Many to Many Delete Pivot Table Values left over
<p>Using Laravel, I have the following code</p> <pre><code>$review = Review::find(1); $review-&gt;delete(); </code></pre> <p><code>Review</code> has a many to many relationship defined with a <code>Product</code> entity. When I delete a review, I'd expect it to be detached from the associated products in the pivot table, but this isn't the case. When I run the code above, I still see the linking row in the pivot table.</p> <p>Have I missed something out here or is this the way Laravel works? I'm aware of the <code>detach()</code> method, but I thought that deleting an entity would also detach it from any related entities automatically.</p> <p><code>Review</code> is defined like this:</p> <pre><code>&lt;?php class Review extends Eloquent { public function products() { return $this-&gt;belongsToMany('Product'); } } </code></pre> <p><code>Product</code> is defined like this:</p> <pre><code>&lt;?php class Product extends Eloquent { public function reviews() { return $this-&gt;belongsToMany('Review'); } } </code></pre> <p>Thanks in advance.</p>
27,330,924
6
1
null
2014-12-06 10:13:54.403 UTC
7
2022-05-02 09:06:10.647 UTC
null
null
null
null
1,314,874
null
1
42
laravel|orm|many-to-many|eloquent
68,439
<p>The detach method is used to release a relationship from the pivot table, whilst delete will delete the model record itself i.e. the record in the reviews table. My understanding is that delete won't trigger the detach implicitly. You can use <a href="https://laravel.com/docs/9.x/eloquent#events" rel="nofollow noreferrer">model events</a> to trigger a cleanup of the pivot table, though, using something like:</p> <pre><code>protected static function booted() { static::deleting(function ($review) { $review-&gt;product()-&gt;detach() }); } </code></pre> <p>Also, I would suggest that the relationship would be a one to many, as one product would have many reviews, but one review wouldn't belong to many products (usually).</p> <pre><code>class Review extends \Eloquent { public function product() { return $this-&gt;belongsTo('Product'); } } class Product extends \Eloquent { public function reviews() { return $this-&gt;hasMany('Review'); } } </code></pre> <p>Of course, this would then require that you tweak your database structure. If you wanted to leave the database structure and your current relationships as they are, the other option would be to apply a foreign key constraint on the pivot table, such that when either a review or product is removed, you could cascade the delete on the pivot table.</p> <pre><code>// Part of a database migration $table-&gt;foreign('product_id')-&gt;references('id')-&gt;on('products')-&gt;onDelete('cascade'); $table-&gt;foreign('review_id')-&gt;references('id')-&gt;on('reviews')-&gt;onDelete('cascade'); </code></pre> <p>Edit: In adding the constraint, you push the cleanup work onto the database, and don't have to worry about handling it in code.</p>
1,218,580
what does a php function return by default?
<p>If I return nothing explicitly, what does a php function exactly return?</p> <pre><code>function foo() {} </code></pre> <ol> <li><p>What type is it?</p></li> <li><p>What value is it?</p></li> <li><p>How do I test for it exactly with === ?</p></li> <li><p>Did this change from php4 to php5?</p></li> <li><p>Is there a difference between <code>function foo() {}</code> and <code>function foo() { return; }</code></p></li> </ol> <p>(I am not asking how to test it like <code>if (foo() !=0) ...</code>)</p>
1,218,588
3
1
null
2009-08-02 10:05:28.67 UTC
6
2019-05-08 18:49:18.893 UTC
2014-04-09 20:18:57.51 UTC
null
124,946
null
89,021
null
1
81
php|function|variables|language-design
19,771
<ol> <li><code>null</code></li> <li><code>null</code></li> <li><code>if(foo() === null)</code></li> <li>-</li> <li>Nope.</li> </ol> <p>You can try it out by doing:</p> <pre><code>$x = foo(); var_dump($x); </code></pre>
6,690,395
Newtonsoft Object → Get JSON string
<p>I have an object that is created by Newtonsoft's JSON serializer. I need to get the JSON string that was used to create the object. How do I serialize the object into a simple JSON string?</p>
6,810,546
1
0
null
2011-07-14 08:23:55.37 UTC
4
2017-04-27 09:42:35.363 UTC
2017-04-27 09:42:35.363 UTC
null
107,625
null
172,861
null
1
36
json|json.net
46,565
<p>Try this:</p> <pre><code>public string jsonOut() { // Returns JSON string. return JsonConvert.SerializeObject(this); } </code></pre>
36,437,282
Dealing with large file uploads on ASP.NET Core 1.0
<p>When I'm uploading large files to my web api in ASP.NET Core, the runtime will load the file into memory before my function for processing and storing the upload is fired. With large uploads this becomes an issue as it is both slow and requires more memory. For previous versions of ASP.NET <a href="http://www.strathweb.com/2012/09/dealing-with-large-files-in-asp-net-web-api/" rel="noreferrer">there are some articles</a> on how to disable the buffering of requests, but I'm not able to find any information on how to do this with ASP.NET Core. Is it possible to disable the buffering of requests so I don't run out of memory on my server all the time?</p>
36,439,880
3
2
null
2016-04-05 21:21:09.427 UTC
14
2019-01-08 16:28:15.133 UTC
null
null
null
null
1,924,825
null
1
35
c#|asp.net|asp.net-mvc|asp.net-core|asp.net-core-mvc
23,957
<p>Use the <code>Microsoft.AspNetCore.WebUtilities.MultipartReader</code> because it...</p> <blockquote> <p>can parse any stream [with] minimal buffering. It gives you the headers and body of each section one at a time and then you do what you want with the body of that section (buffer, discard, write to disk, etc.).</p> </blockquote> <p>Here is a middleware example.</p> <pre><code>app.Use(async (context, next) =&gt; { if (!IsMultipartContentType(context.Request.ContentType)) { await next(); return; } var boundary = GetBoundary(context.Request.ContentType); var reader = new MultipartReader(boundary, context.Request.Body); var section = await reader.ReadNextSectionAsync(); while (section != null) { // process each image const int chunkSize = 1024; var buffer = new byte[chunkSize]; var bytesRead = 0; var fileName = GetFileName(section.ContentDisposition); using (var stream = new FileStream(fileName, FileMode.Append)) { do { bytesRead = await section.Body.ReadAsync(buffer, 0, buffer.Length); stream.Write(buffer, 0, bytesRead); } while (bytesRead &gt; 0); } section = await reader.ReadNextSectionAsync(); } context.Response.WriteAsync("Done."); }); </code></pre> <p>Here are the helpers. </p> <pre><code>private static bool IsMultipartContentType(string contentType) { return !string.IsNullOrEmpty(contentType) &amp;&amp; contentType.IndexOf("multipart/", StringComparison.OrdinalIgnoreCase) &gt;= 0; } private static string GetBoundary(string contentType) { var elements = contentType.Split(' '); var element = elements.Where(entry =&gt; entry.StartsWith("boundary=")).First(); var boundary = element.Substring("boundary=".Length); // Remove quotes if (boundary.Length &gt;= 2 &amp;&amp; boundary[0] == '"' &amp;&amp; boundary[boundary.Length - 1] == '"') { boundary = boundary.Substring(1, boundary.Length - 2); } return boundary; } private string GetFileName(string contentDisposition) { return contentDisposition .Split(';') .SingleOrDefault(part =&gt; part.Contains("filename")) .Split('=') .Last() .Trim('"'); } </code></pre> <p>External References</p> <ul> <li><a href="https://github.com/aspnet/HttpAbstractions/pull/146" rel="noreferrer">https://github.com/aspnet/HttpAbstractions/pull/146</a></li> <li><a href="https://github.com/aspnet/HttpAbstractions" rel="noreferrer">https://github.com/aspnet/HttpAbstractions</a></li> </ul>
34,891,841
How to get current category in magento2?
<p>How can i get current category in <strong>magento2</strong> ?</p> <p>I want to get category name and category id in custom phtml file.</p>
34,891,868
5
1
null
2016-01-20 04:53:56.357 UTC
4
2021-10-15 19:32:50.03 UTC
null
null
null
null
2,425,135
null
1
11
magento2|magento-2.0
42,613
<p>Try this code. this will definitely help you.</p> <pre><code>&lt;?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $category = $objectManager-&gt;get('Magento\Framework\Registry')-&gt;registry('current_category');//get current category echo $category-&gt;getId(); echo $category-&gt;getName(); ?&gt; </code></pre>
5,801,820
How to solve BiDi bracket issues?
<p>As you might know some languages are written/read from right to left and we are trying to support some RTL languages. For the web UI using dir="rtl" in html does most of the job thanks to algorithms that browsers have. But I came across this issue with brackets in text:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;title&gt;Bracket problems with BiDi&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p style="direction: rtl;"&gt;Bracket problem: hello (world):&lt;/p&gt; &lt;p style="direction: rtl;"&gt;No bracket problem: hello (world) something:&lt;/p&gt; &lt;p style="direction: rtl;"&gt;Bracket problem: (السلام (عليكم &lt;/p&gt; &lt;p style="direction: rtl;"&gt;No bracket problem: السلام (عليكم) عليكم &lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Problem can be seen here:</p> <p><a href="https://i.stack.imgur.com/zJocd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zJocd.png" alt="enter image description here"></a></p> <p>So I want that last bracket stay in the end. What would be your solution?</p>
5,803,400
4
0
null
2011-04-27 09:16:17.917 UTC
18
2019-07-25 11:35:26.573 UTC
2019-07-25 11:35:26.573 UTC
null
1,019,630
null
35,012
null
1
30
html|css|rendering|bidi
10,135
<p>There are many problems here. According to the unicode standard, brackets are neutral, meaning they are not inherently treated as LTR or RTL. They take the direction of their surrounding language. In the examples where it is being incorrectly rendered, the direction of the closing bracket is assumed to be the same as of English, ie LTR. </p> <p>1st problem: You tell the browser that the paragraph should be treated to be RTL. The browser finds English inside, which is LTR, so it thinks English is embedded inside an RTL paragraph, and the last character ")" is treated to be RTL. (the surrounding paragraph is RTL). </p> <p>2nd problem: There is no problem here, from a simple look at the source code you have provided, it appears you have provided the brackets properly. But in fact, the closing bracket which should be after the RTL text and before the closing &lt;/P&gt; is actually before the starting RTL text. If you type it properly, it would look wrong (because the text editor you are using assumes the end bracket is LTR according to unicode). To verify this, copy the contents on to your editor, put your cursor at the end of "problem:", and press the right arrow repeatedly and observe the location of the last bracket. </p> <p>Without giving much more explaination, here are some examples to get this working:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;title&gt;Bracket problems with BiDi&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p style="direction: rtl;"&gt;&lt;span dir="ltr"&gt;Bracket problem no more: hello (world):&lt;/span&gt;&lt;/p&gt; &lt;p style="direction: rtl;"&gt;&lt;span style="direction: ltr; unicode-bidi: embed"&gt;Bracket problem no more: hello (world):&lt;/span&gt;&lt;/p&gt; &lt;p style="direction: rtl;"&gt;Bracket problem no more: السلام (عليكم)&lt;/p&gt; &lt;!-- style for p tag below is ltr by default --&gt; &lt;p&gt;Bracket problem no more: &lt;span dir="rtl"&gt;السلام (عليكم)&lt;/span&gt;&lt;/p&gt; &lt;p&gt;Bracket problem no more: &lt;span style="direction: rtl; unicode-bidi: embed"&gt;السلام (عليكم)&lt;/span&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>There are differences in how style="direction: ltr;" works and dir="ltr" works, so I've given examples of both. Also, because I assume you basically need to get your second problem solved, where you majorly have RTL text in an otherwise LTR document, I've provided the last two examples.</p> <p>NOTE: If the last two examples are what you are looking for, and you are going to use CSS, the unicode-bidi property is required, and that makes all the difference between working and not working.</p>
6,049,523
how to configure spring mvc 3 to not return "null" object in json response?
<p>a sample of json response looks like this:</p> <pre><code>{"publicId":"123","status":null,"partner":null,"description":null} </code></pre> <p>It would be nice to truncate out all null objects in the response. In this case, the response would become <code>{"publicId":"123"}</code>. </p> <p>Any advice? Thanks!</p> <p>P.S: I think I can do that in Jersey. Also I believe they both use Jackson as the JSON processer. </p> <p>Added Later: My configuration:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;!-- Scans the classpath of this application for @Components to deploy as beans --&gt; &lt;context:component-scan base-package="com.SomeCompany.web" /&gt; &lt;!-- Application Message Bundle --&gt; &lt;bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"&gt; &lt;property name="basename" value="/WEB-INF/messages/messages" /&gt; &lt;property name="cacheSeconds" value="0" /&gt; &lt;/bean&gt; &lt;!-- Configures Spring MVC --&gt; &lt;import resource="mvc-config.xml" /&gt; </code></pre> <p></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"&gt; &lt;!-- Configures the @Controller programming model --&gt; &lt;mvc:annotation-driven /&gt; &lt;!-- Forwards requests to the "/" resource to the "welcome" view --&gt; &lt;!--&lt;mvc:view-controller path="/" view-name="welcome"/&gt;--&gt; &lt;!-- Configures Handler Interceptors --&gt; &lt;mvc:interceptors&gt; &lt;!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de --&gt; &lt;bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /&gt; &lt;/mvc:interceptors&gt; &lt;!-- Saves a locale change using a cookie --&gt; &lt;bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" /&gt; &lt;!--&lt;bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"&gt; &lt;property name="mediaTypes"&gt; &lt;map&gt; &lt;entry key="atom" value="application/atom+xml"/&gt; &lt;entry key="html" value="text/html"/&gt; &lt;entry key="json" value="application/json"/&gt; &lt;entry key="xml" value="text/xml"/&gt; &lt;/map&gt; &lt;/property&gt; &lt;property name="viewResolvers"&gt; &lt;list&gt; &lt;bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/WEB-INF/views/"/&gt; &lt;property name="suffix" value=".jsp"/&gt; &lt;/bean&gt; &lt;/list&gt; &lt;/property&gt; &lt;property name="defaultViews"&gt; &lt;list&gt; &lt;bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /&gt; &lt;bean class="org.springframework.web.servlet.view.xml.MarshallingView" &gt; &lt;property name="marshaller"&gt; &lt;bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; --&gt; &lt;!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory --&gt; &lt;bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/WEB-INF/views/"/&gt; &lt;property name="suffix" value=".jsp"/&gt; &lt;/bean&gt; </code></pre> <p>My code: </p> <pre><code>@Controller public class SomeController { @RequestMapping(value = "/xyz", method = {RequestMethod.GET, RequestMethod.HEAD}, headers = {"x-requested-with=XMLHttpRequest","Accept=application/json"}, params = "!closed") public @ResponseBody List&lt;AbcTO&gt; getStuff( ....... } } </code></pre>
6,049,967
4
4
null
2011-05-18 18:42:40.837 UTC
11
2017-11-03 11:38:05.65 UTC
2011-05-18 19:23:45.873 UTC
null
464,253
null
464,253
null
1
30
json|spring-mvc|jackson
33,888
<p>Yes, you can do this for individual classes by annotating them with <code>@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)</code> or you can do it across the board by configuring your <code>ObjectMapper</code>, setting the serialization inclusion to <code>JsonSerialize.Inclusion.NON_NULL</code>.</p> <p>Here is some info from the Jackson FAQ: <a href="http://wiki.fasterxml.com/JacksonAnnotationSerializeNulls" rel="nofollow noreferrer">http://wiki.fasterxml.com/JacksonAnnotationSerializeNulls</a>.</p> <p>Annotating the classes is straightforward, but configuring the <code>ObjectMapper</code> serialization config slightly trickier. There is some specific info on doing the latter <a href="https://stackoverflow.com/questions/4823358/spring-configure-responsebody-json-format">here</a>.</p>
72,853,889
Superclass androidx.core.app.f of androidx.activity.ComponentActivity is declared final
<p>I wanted to update the version of the application in the Play Store, but in the tests I started getting this error.</p> <pre><code>Superclass androidx.core.app.f of androidx.activity.ComponentActivity is declared final </code></pre> <p>According to the <a href="https://issuetracker.google.com/issues/237785592" rel="noreferrer">google issues tracker</a> this is new, maybe someone has a solution to this problem.</p>
73,301,532
7
1
null
2022-07-04 08:39:00.78 UTC
3
2022-08-10 06:21:32.137 UTC
2022-07-09 13:24:40.93 UTC
null
10,871,073
null
11,038,362
null
1
28
android|testing|google-play
1,998
<p>On 27.07.2022 Google team members posted that the bug has been fixed. and on 09.08.2022 they added some explanation that you can find in this <a href="https://issuetracker.google.com/issues/237785592" rel="nofollow noreferrer">link</a>.</p> <p>In two words: In pre-launch testing app-crawler apk and the app apk generated different ‘keep rules’ for shrunk. This will cause ‘no such method’ or ‘superclass will be declared final’.</p>
1,590,337
Using the Google Chrome Sandbox
<p>There are several resources out there that explain how the sandbox in Chrome works and what it does to protect users from malicious code.</p> <p><a href="http://blog.chromium.org/2008/10/new-approach-to-browser-security-google.html" rel="noreferrer">Chromium Blog</a><br> <a href="http://dev.chromium.org/developers/design-documents/sandbox" rel="noreferrer">Chromium Developer Documentation</a><br> <a href="http://dev.chromium.org/developers/design-documents/sandbox/Sandbox-FAQ" rel="noreferrer">Sandbox FAQ</a> </p> <p>That's great, and I like the OS-centric design that they have in place (somewhat of a "The OS probably knows how to secure itself better than we do, so we let it" approach.) They also mention in several places that the sandbox itself was designed to not be dependent on Chrome but instead more-or-less standalone so that theoretically any process could be sandboxed as long as the architecture of the program is compatible (sandboxed code must run as it's own process as a child of a non-sandboxed parent.)</p> <p>I just happen to have an application who's design makes it ripe for sandboxing, and was able to get a parent/child process working with it. I've got the Chromium code and... have no idea what to do next. </p> <p>Has anyone out there actually sandboxed anything with this yet? Are there any resources that document it's usage or APIs? I would imagine it should be pretty simple, but I'm at a loss for where to start.</p> <p>EDIT: My finding below in the answers!</p>
1,647,871
2
3
null
2009-10-19 18:35:16.573 UTC
19
2011-03-28 18:50:43.227 UTC
2009-10-30 03:28:39.233 UTC
null
25,968
null
25,968
null
1
38
c++|google-chrome|sandbox
10,718
<p>Okay, so here's what I found about sandboxing code with Chrome.</p> <p>First off, you'll need to go <a href="http://dev.chromium.org/developers/how-tos/build-instructions-windows" rel="noreferrer">get the chromium source code</a>. This is <em>big</em>, and will take a while to get, but I've yet to find any reliable shortcuts to checkout that still yeild usable results. Alos, it's very important that you follow the instructions on that page VERY CLOSELY. The Google crew knows what they're doing, and aren't keen on useless steps. Everything on that page is necessary. Yes. Everything.</p> <p>Now, once you get the source, you don't actually have to build chrome in it's entirety (which can take hours!) to use the sandbox. Instead they've been nice enough to give you a separate sandbox solution (found in the sandbox folder) that can build standalone. Build this project and make sure everything compiles. If it does, great! If it doesn't, you didn't follow the steps on the build page, did you? Hang your head in shame and go actually do it this time. Don't worry, I'll wait...</p> <p>Now that everything has built your main point of interest is the sandbox_poc project ("poc" = Proof of Concept). This project is basically a minimal GUI wrapper around a sandbox that will launch an arbitrary dll at a given entry point in a sandboxed environment. It shows all the required steps for creating and using a sandbox, and is about the best reference you've got. Refer to it often!</p> <p>As you look through the code you'll probably notice that the code it actually sandboxes is itself. This is very common with all the sandbox examples, and <a href="http://groups.google.com/group/chromium-dev/browse_thread/thread/f6ee308557249e81/e9c1114575b15033" rel="noreferrer">according to this thread</a> (which may be outdated) is possibly the only working way to sandbox at the moment. The thread describes how one would theoretically sandbox a separate process, but I haven't tried it. Just to be safe, though, having a self-calling app is the "known good" method. </p> <p>sandbox_proc includes a great many static libs, but they appear to mostly be for the sample UI they've built. The only ones I've found that seem to be required for a minimal sandbox are:</p> <pre><code>sandbox.lib base.lib dbghelp.lib </code></pre> <p>There's another dependancy that's not entirely obvious from looking at the project though, and it's what I got caught up on the longest. When you built the sandbox solution, one of the output files should be a "<code>wowhelper.exe</code>". Though it's never mentioned anywhere, this file must be copied to the same directory as the executable you are sandboxing! If it's not, your attempts to sandbox your code will always fail with a generic "file not found" error. This can be very frustrating if you don't know what's going on! Now, I'm developing on Windows 7 64bit, which may have something to do with the wowhelper requirement (WOW is a common acronym for interop apps between 16/32/64bit), but I don't have a good way of testing that right now. Please let me know if anyone else finds out more!</p> <p>So that's all the environment stuff, here's a bit of smaple code to get you going! Please note that although I use wcout in the child process here, you can't see any console output when running in the sandbox. Anything like that needs to be communicated to the parent process via IPC.</p> <pre><code>#include &lt;sandbox/src/sandbox.h&gt; #include &lt;sandbox/src/sandbox_factory.h&gt; #include &lt;iostream&gt; using namespace std; int RunParent(int argc, wchar_t* argv[], sandbox::BrokerServices* broker_service) { if (0 != broker_service-&gt;Init()) { wcout &lt;&lt; L"Failed to initialize the BrokerServices object" &lt;&lt; endl; return 1; } PROCESS_INFORMATION pi; sandbox::TargetPolicy* policy = broker_service-&gt;CreatePolicy(); // Here's where you set the security level of the sandbox. Doing a "goto definition" on any // of these symbols usually gives you a good description of their usage and alternatives. policy-&gt;SetJobLevel(sandbox::JOB_LOCKDOWN, 0); policy-&gt;SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_LOCKDOWN); policy-&gt;SetAlternateDesktop(true); policy-&gt;SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); //Add additional rules here (ie: file access exceptions) like so: policy-&gt;AddRule(sandbox::TargetPolicy::SUBSYS_FILES, sandbox::TargetPolicy::FILES_ALLOW_ANY, "some/file/path"); sandbox::ResultCode result = broker_service-&gt;SpawnTarget(argv[0], GetCommandLineW(), policy, &amp;pi); policy-&gt;Release(); policy = NULL; if (sandbox::SBOX_ALL_OK != result) { wcout &lt;&lt; L"Sandbox failed to launch with the following result: " &lt;&lt; result &lt;&lt; endl; return 2; } // Just like CreateProcess, you need to close these yourself unless you need to reference them later CloseHandle(pi.hThread); CloseHandle(pi.hProcess); broker_service-&gt;WaitForAllTargets(); return 0; } int RunChild(int argc, wchar_t* argv[]) { sandbox::TargetServices* target_service = sandbox::SandboxFactory::GetTargetServices(); if (NULL == target_service) { wcout &lt;&lt; L"Failed to retrieve target service" &lt;&lt; endl; return 1; } if (sandbox::SBOX_ALL_OK != target_service-&gt;Init()) { wcout &lt;&lt; L"failed to initialize target service" &lt;&lt; endl; return 2; } // Do any "unsafe" initialization code here, sandbox isn't active yet target_service-&gt;LowerToken(); // This locks down the sandbox // Any code executed at this point is now sandboxed! TryDoingSomethingBad(); return 0; } int wmain(int argc, wchar_t* argv[]) { sandbox::BrokerServices* broker_service = sandbox::SandboxFactory::GetBrokerServices(); // A non-NULL broker_service means that we are not running the the sandbox, // and are therefore the parent process if(NULL != broker_service) { return RunParent(argc, argv, broker_service); } else { return RunChild(argc, argv); } } </code></pre> <p>Hopefully that's enough to get any other curious coders sandboxing! Good luck!</p>