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
44,026,515
Python-redis keys() returns list of bytes objects instead of strings
<p>I'm using the regular <code>redis</code> package in order to connect my Python code to my Redis server.</p> <p>As part of my code I check if a string object is existed in my Redis server keys.</p> <pre><code>string = 'abcde' if string in redis.keys(): do something.. </code></pre> <p>For some reasons, redis.keys() returns a list with bytes objects, such as <code>[b'abcde']</code>, while my string is, of course, a <code>str</code> object.</p> <p>I already tried to set <code>charset</code>, <code>encoding</code> and <code>decode_responses</code> in my redis generator, but it did not help.</p> <p>My goal is to insert the data as string ahead, and not iterate over the keys list and change each element to str() while checking it.</p> <p>Thanks ahead</p>
44,032,018
4
3
null
2017-05-17 13:37:46.62 UTC
13
2021-03-29 20:16:10.967 UTC
null
null
null
null
7,999,670
null
1
56
python|redis
46,323
<p>You can configure the Redis client to automatically convert responses from bytes to strings using the <code>decode_responses</code> argument to the <code>StrictRedis</code> constructor:</p> <pre><code>r = redis.StrictRedis('localhost', 6379, charset=&quot;utf-8&quot;, decode_responses=True) </code></pre> <p>Make sure you are consistent with the <code>charset</code> option between clients.</p> <p><strong>Note</strong></p> <p>You would be better off using the <a href="https://redis.io/commands/exists" rel="noreferrer">EXISTS</a> command and restructuring your code like:</p> <pre><code>string = 'abcde' if redis.exists(string): do something.. </code></pre> <p>The KEYS operation returns every key in your Redis database and will cause serious performance degradation in production. As a side effect you avoid having to deal with the binary to string conversion.</p>
43,079,444
Angular 2: No provider for (injected) service
<p>I have two services in my app - MainService and RightClickService. Only MainService is accessible globally in the application, and RightClickService is injected to MainService. Therefore, I defined the following files as: </p> <p><strong>app.module.ts</strong></p> <pre><code>@NgModule({ declarations: [ AppComponent, ... ], imports: [ BrowserModule, FormsModule, HttpModule ], providers: [MainService], bootstrap: [AppComponent] }) export class AppModule { } </code></pre> <p>RightClickService is not mentioned in app.module.ts.</p> <p><strong>service.ts</strong></p> <pre><code> @Injectable() export class MainService { constructor(private rightClickService: RightClickService) { console.log("Constructor is init"); } } </code></pre> <p>RightClickService exists only in one component named inside the big application RightClickComponent. </p> <p><strong>right-click.component.ts:</strong></p> <pre><code>@Component({ selector: 'right-click', template: ` ... `, styleUrls: ['...'], providers: [RightClickService] }) export class RightClickComponent implements OnInit { constructor(private rightClickService: RightClickService) {} } </code></pre> <p>Still, I get the error:</p> <pre><code>EXCEPTION: No provider for RightClickService! </code></pre> <p>Do you know what I'm doing wrong? </p>
43,080,188
2
8
null
2017-03-28 20:35:04.16 UTC
8
2020-02-26 04:58:38.953 UTC
null
null
null
null
5,402,618
null
1
24
angular|dependency-injection
48,843
<p>In addition to what already said, you must know two things:</p> <ol> <li><p>Your app has only one root injector that contains all providers delcared in <code>@NgModule.providers</code> array of any module in your app including <code>AppModule</code>.</p></li> <li><p>Each Component has its own injector (child injector of the root injector) that contains providers declared in <code>@Component.providers</code> array of the component.</p></li> </ol> <p>when angular want to resolve dependencies (RightClickService) of a <strong>service</strong> (MainService) it looks for it in the root injector which contains providers of all NgModules.</p> <p>When angular want to resolve dependencies (RightClickService) of a <strong>component</strong> (RightClickComponent) it looks for it in the component injector if not found it looks for it in the <strong>parent</strong> component injector if not found he will do the same until he reaches the root injector if not found an error will be thrown.</p> <p>if you want to solve the problem you can do this :</p> <pre><code>function MainServiceFactory(RightClickService) { return new MainService(new RightClickService()); } @NgModule({ declarations: [ AppComponent, ... ], imports: [ BrowserModule, FormsModule, HttpModule ], providers: [ { provide: MainService, useFactory: MainServiceFactory, deps: [RightClickService] } ], bootstrap: [AppComponent] }) export class AppModule { } </code></pre>
3,766,688
Filtering a cursor the right way?
<p>At the moment I need to filter a Cursor/CursorAdapter to only show rows that match a specific condition in the ListView. I don't want to requery the db all the time. I just want to filter the Cursor I got from querying the DB. </p> <p>I have seen the question: <a href="https://stackoverflow.com/questions/3027428">Filter rows from Cursor so they don&#39;t show up in ListView</a></p> <p>But I don't understand how to do the filtering by overwritting the "move" methods in my CursorWrapper. An example would be nice. </p> <p>Thank you very much. </p>
7,343,721
3
1
null
2010-09-22 06:03:09.67 UTC
12
2017-03-22 12:58:21.197 UTC
2017-05-23 12:34:19.433 UTC
null
-1
null
391,216
null
1
13
android
10,726
<p><strong>UPDATE:</strong></p> <p>I have rewritten the source and my employer has made it available as open source software: <a href="https://github.com/clover/android-filteredcursor">https://github.com/clover/android-filteredcursor</a></p> <p>You don't need to override all the move methods in CursorWrapper, you do need to override a bunch though due to the design of the Cursor interface. Let's pretend you want to filter out row #2 and #4 of a 7 row cursor, make a class that extends CursorWrapper and override these methods like so:</p> <pre><code>private int[] filterMap = new int[] { 0, 1, 3, 5, 6 }; private int mPos = -1; @Override public int getCount() { return filterMap.length } @Override public boolean moveToPosition(int position) { // Make sure position isn't past the end of the cursor final int count = getCount(); if (position &gt;= count) { mPos = count; return false; } // Make sure position isn't before the beginning of the cursor if (position &lt; 0) { mPos = -1; return false; } final int realPosition = filterMap[position]; // When moving to an empty position, just pretend we did it boolean moved = realPosition == -1 ? true : super.moveToPosition(realPosition); if (moved) { mPos = position; } else { mPos = -1; } return moved; } @Override public final boolean move(int offset) { return moveToPosition(mPos + offset); } @Override public final boolean moveToFirst() { return moveToPosition(0); } @Override public final boolean moveToLast() { return moveToPosition(getCount() - 1); } @Override public final boolean moveToNext() { return moveToPosition(mPos + 1); } @Override public final boolean moveToPrevious() { return moveToPosition(mPos - 1); } @Override public final boolean isFirst() { return mPos == 0 &amp;&amp; getCount() != 0; } @Override public final boolean isLast() { int cnt = getCount(); return mPos == (cnt - 1) &amp;&amp; cnt != 0; } @Override public final boolean isBeforeFirst() { if (getCount() == 0) { return true; } return mPos == -1; } @Override public final boolean isAfterLast() { if (getCount() == 0) { return true; } return mPos == getCount(); } @Override public int getPosition() { return mPos; } </code></pre> <p>Now the interesting part is creating the filterMap, that's up to you.</p>
22,610,400
Can program developed with Java 8 be run on Java 7?
<p>I am a little confused.</p> <ol> <li><p>Oracle says Java 8 is highly compatible with Java 7 (backward). But, what possibilities exist that Java 8 program can be run on Java 7 successfully (SE/EE)?</p></li> <li><p>If point one was true, Java 8 applications will be deployed and executed on a Java 7 server support? for example, Tomcat 8 or WildFly?</p></li> </ol>
22,610,424
6
10
null
2014-03-24 13:11:21.663 UTC
14
2019-04-01 09:51:18.953 UTC
2019-04-01 09:51:18.953 UTC
null
205,546
null
3,450,297
null
1
53
java|backwards-compatibility|java-8|java-server
50,130
<p>In general, no.</p> <p>The backwards compatibility means that you can run Java 7 program on Java 8 runtime, not the other way around.</p> <p>There are several reasons for that:</p> <ul> <li><p>Bytecode is versioned and JVM checks if it supports the version it finds in .class files. </p></li> <li><p>Some language constructs cannot be expressed in previous versions of bytecode.</p></li> <li><p>There are new classes and methods in newer JRE's which won't work with older ones.</p></li> </ul> <p>If you really, really want (tip: you don't), you can force the compiler to treat the source as one version of Java and emit bytecode for another, using something like this:</p> <pre><code>javac -source 1.8 -target 1.7 MyClass.java </code></pre> <p>(<a href="http://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html">the same for Maven</a>), and compile against JDK7, but in practice it will more often not work than work. <strong>I recommend you don't.</strong> </p> <p><strong>EDIT</strong>: JDK 8 apparently doesn't support this exact combination, so this won't work. Some other combinations of versions do work.</p> <p>There are also programs to convert newer Java programs to work on older JVM's. For converting Java 8 to 5-7, you can try <a href="https://github.com/orfjackal/retrolambda">https://github.com/orfjackal/retrolambda</a> To get lower than 5, you can pick one of these: <a href="http://en.wikipedia.org/wiki/Java_backporting_tools">http://en.wikipedia.org/wiki/Java_backporting_tools</a></p> <p>None of these hacks will give you new Java 8 classes and methods, including functional programming support for collections, streams, time API, unsigned API, and so on. So I'd say it's not worth it.</p> <p>Or, since you want to run your Java 8 JEE applications on an application server, just run your entire server on Java 8, it may work. </p>
10,998,521
Square braces not required in list comprehensions when used in a function
<p>I submitted a pull request with this code:</p> <pre><code>my_sum = sum([x for x in range(10)]) </code></pre> <p>One of the reviewers suggested this instead:</p> <pre><code>my_sum = sum(x for x in range(10)) </code></pre> <p>(the difference is just that the square braces are missing).</p> <p>I was surprised that the second form seems to be identical. But when I tried to use it in other contexts where the first one works, it fails:</p> <pre><code>y = x for x in range(10) ^ SyntaxError !!! </code></pre> <p>Are the two forms identical? Is there any important reason for why the square braces aren't necessary in the function? Or is this just something that I have to know?</p>
10,998,554
4
2
null
2012-06-12 14:14:32.31 UTC
9
2012-06-12 14:41:42.553 UTC
null
null
null
null
894,284
null
1
13
python|syntax|list-comprehension
3,787
<p>This is a generator expression. To get it to work in the standalone case, use braces:</p> <pre><code>y = (x for x in range(10)) </code></pre> <p>and y becomes a generator. You can iterate over generators, so it works where an iterable is expected, such as the <code>sum</code> function.</p> <p><strong>Usage examples and pitfalls:</strong></p> <pre><code>&gt;&gt;&gt; y = (x for x in range(10)) &gt;&gt;&gt; y &lt;generator object &lt;genexpr&gt; at 0x0000000001E15A20&gt; &gt;&gt;&gt; sum(y) 45 </code></pre> <p>Be careful when keeping generators around, you can only go through them once. So after the above, if you try to use <code>sum</code> again, this will happen:</p> <pre><code>&gt;&gt;&gt; sum(y) 0 </code></pre> <p>So if you pass a generator where actually a list or a set or something similar is expected, you have to be careful. If the function or class stores the argument and tries to iterate over it multiple times, you will run into problems. For example consider this:</p> <pre><code>def foo(numbers): s = sum(numbers) p = reduce(lambda x,y: x*y, numbers, 1) print "The sum is:", s, "and the product:", p </code></pre> <p>it will fail if you hand it a generator:</p> <pre><code>&gt;&gt;&gt; foo(x for x in range(1, 10)) The sum is: 45 and the product: 1 </code></pre> <p>You can easily get a list from the values a generator produces:</p> <pre><code>&gt;&gt;&gt; y = (x for x in range(10)) &gt;&gt;&gt; list(y) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre> <p>You can use this to fix the previous example:</p> <pre><code>&gt;&gt;&gt; foo(list(x for x in range(1, 10))) The sum is: 45 and the product: 362880 </code></pre> <p>However keep in mind that if you build a list from a generator, you will need to store every value. This might use a lot more memory in situations where you have lots of items.</p> <p><strong>Why use a generator in your situation?</strong></p> <p>The much lower memory consumption is the reason why <code>sum(generator expression)</code> is better than <code>sum(list)</code>: The generator version only has to store a single value, while the list-variant has to store N values. Therefore you should always use a generator where you don't risk side-effects.</p>
11,421,127
How to trigger events on Leaflet map polygons?
<p>I'm trying to figure out how to manually trigger events for Leaflet polygons (loaded via GeoJSON).</p> <p>In a nutshell, I have a Leaflet map with numerous polygons. I also have a regular hyperlink outside of the map that when clicked, should trigger a mouseover event (or any event really) on a particular polygon.</p> <p><strong>How do I assign ID's to all of my polygons so that I can bind hyperlink(s) to a specific polygon's event? Or is that even the most logical way of doing this?</strong></p> <p>Ultimately, I'm trying to create a map with numerous polygons along with an HTML table of text labels that are associated to each polygon. When clicking on the HTML table text, I'd like to trigger events on the map polygons (and vice versa). I just don't know how to reference each polygon.</p> <p><strong>Here is my very simplified HTML:</strong></p> <pre><code>&lt;body&gt; &lt;div id="map" style="height: 550px; width:940px"&gt;&lt;/div&gt; &lt;a href="#" id="testlink"&gt;Click to trigger a specific polygon mouseover event&lt;/a&gt; &lt;/body&gt; </code></pre> <p><strong>Here is my very simplified JS:</strong></p> <pre><code>$(document).ready(function () { // build the map and polygon layer function buildMap(data) { var map = new L.Map('map'); var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/***yourkeyhere***/66267/256/{z}/{x}/{y}.png', cloudmadeAttribution = '', cloudmade = new L.TileLayer(cloudmadeUrl, {maxZoom: 18, attribution: cloudmadeAttribution}); var mapLoc = new L.LatLng(43.675198,-79.383287); map.setView(mapLoc, 12).addLayer(cloudmade); var geojsonLayer = new L.GeoJSON(null, {}); geojsonLayer.on("featureparse", function (e){ // apply the polygon style e.layer.setStyle(polyStyle); (function(layer, properties) { layer.on("mouseover", function (e) { // change the style to the hover version layer.setStyle(polyHover); }); }); layer.on("mouseout", function (e) { // reverting the style back layer.setStyle(polyStyle); }); layer.on("click", function (e) { // do something here like display a popup console.log(e); }); })(e.layer, e.properties); }); map.addLayer(geojsonLayer); geojsonLayer.addGeoJSON(myPolygons); } // bind the hyperlink to trigger event on specific polygon (by polygon ID?) $('#testlink').click(function(){ // trigger a specific polygon mouseover event here }); }); </code></pre>
11,639,178
3
0
null
2012-07-10 20:08:56.68 UTC
11
2019-04-02 21:54:09.683 UTC
null
null
null
null
623,818
null
1
20
events|map|geojson|leaflet
39,627
<p>OK, I've figured it out.</p> <p>You need to create a click event for each polygon that opens the popup, and assign a unique ID to each polygon so you can reference it later and manually trigger its popup.</p> <p>The following accomplishes this:</p> <pre><code> var polyindex = 0; popup = new L.Popup(); geojsonLayer = new L.GeoJSON(null, {}); geojsonLayer.on("featureparse", function (e){ (function(layer, properties) { //click event that triggers the popup and centres it on the polygon layer.on("click", function (e) { var bounds = layer.getBounds(); var popupContent = "popup content here"; popup.setLatLng(bounds.getCenter()); popup.setContent(popupContent); map.openPopup(popup); }); })(e.layer, e.properties); //assign polygon id so we can reference it later e.layer._leaflet_id = 'polyindex'+polyindex+''; //increment polyindex used for unique polygon id's polyindex++; }); //add the polygon layer map.addLayer(geojsonLayer); geojsonLayer.addGeoJSON(neighbourhood_polygons); </code></pre> <p>Then to manually trigger a specific layers click event, simply call it like this:</p> <pre><code>map._layers['polyindex0'].fire('click'); </code></pre> <p>Everything between the square brackets is the unique ID of the layer you want to trigger. In this case, I'm firing the click event of layer ID polyindex0.</p> <p>Hope this info helps somebody else out!</p>
11,444,640
Add a class to a DIV with javascript
<p>Example HTML:</p> <pre><code>&lt;div id="foo" class="class_one"&gt;&lt;/div&gt; </code></pre> <p>How can I add the class <code>class_two</code> without replacing <code>class_one</code>?</p> <p>end result:</p> <pre><code>&lt;div id="foo" class="class_one class_two"&gt;&lt;/div&gt; </code></pre>
11,444,643
4
0
null
2012-07-12 03:28:56.877 UTC
9
2021-03-03 03:05:41.73 UTC
2016-10-13 08:08:06.67 UTC
null
4,792,869
null
1,497,460
null
1
22
javascript|html|css
108,464
<p>See deekshith's answer below if you only need to support new browsers</p> <p>Standard javascript:</p> <pre><code>document.getElementById('foo').className += ' class_two' </code></pre> <p>or JQuery:</p> <pre><code>$('#foo').addClass('class_two'); </code></pre>
11,300,650
How to scale axes in mplot3d
<p>I can't seem to find documentation regarding the ability to scale axes in a 3d image using matplotlib.</p> <p>For example, I have the image:</p> <p><img src="https://i.stack.imgur.com/VlQWg.png" alt="3dplot"> And the axes have different scales. I would like them to be uniform.</p>
11,300,758
2
0
null
2012-07-02 20:24:10.913 UTC
4
2021-12-06 12:57:43.55 UTC
2012-07-02 20:26:26.217 UTC
null
487,339
null
1,481,457
null
1
26
python|numpy|matplotlib
65,638
<p>Usually it is easiest for you to include some of the code that generated the image, so we can see what you've tried and also the general setup of your code. That being said, the inclusion of the following should work:</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt fig = plt.figure() ax = Axes3D(fig) ax.set_xlim3d(0, 1000) ax.set_ylim3d(0, 1000) ax.set_zlim3d(0, 1000) </code></pre>
11,189,729
Using AutoMapper to map the property of an object to a string
<p>I have the following model:</p> <pre><code>public class Tag { public int Id { get; set; } public string Name { get; set; } } </code></pre> <p>I want to be able to use AutoMapper to map the <code>Name</code> property of the <code>Tag</code> type to a string property in one of my viewmodels.</p> <p>I have created a custom resolver to try to handle this mapping, using the following code:</p> <pre><code>public class TagToStringResolver : ValueResolver&lt;Tag, string&gt; { protected override string ResolveCore(Tag source) { return source.Name ?? string.Empty; } } </code></pre> <p>I am mapping using the following code:</p> <pre><code>Mapper.CreateMap&lt;Tag, String&gt;() .ForMember(d =&gt; d, o =&gt; o.ResolveUsing&lt;TagToStringResolver&gt;()); </code></pre> <p>When I run the application I get the error:</p> <blockquote> <p>Custom configuration for members is only supported for top-level individual members on a type.</p> </blockquote> <p>What am I doing wrong?</p>
11,191,415
2
0
null
2012-06-25 12:51:13.73 UTC
6
2012-11-30 19:33:15.72 UTC
null
null
null
null
197,415
null
1
44
c#|.net|mapping|automapper|automapper-2
28,309
<p>This is because you are trying to map to the actual destination type rather than a property of the destination type. You can achieve what you want with:</p> <pre><code>Mapper.CreateMap&lt;Tag, string&gt;().ConvertUsing(source =&gt; source.Name ?? string.Empty); </code></pre> <p>although it would be a lot simpler just to override ToString on the Tag class.</p>
11,173,447
How can I set up autocompletion for Git commands?
<p>I have Git (version 1.7.2.5) bash compeletion working on my Debian squeeze (6.0). Git was installed with aptitude and I am using standard debian's <code>bash</code>, which supports command line autocompletion.</p> <p>Now, I just installed Git (1.5.6.5) on an other machine (Lenny/Debian 5.0) and the there is no autocompletion. </p> <ol> <li><p>Why is Git autocomplete not working on the second machine? How do I diagnose this?</p></li> <li><p>What is making completion work on my machine? I have looked for the file <code>git-completion.bash</code> but it doesn't seem to be on my machine. How does Git complete ever work?</p></li> <li><p>How can I bring git complete to the other machine?</p></li> </ol>
11,173,550
10
8
null
2012-06-23 22:21:47.997 UTC
13
2021-10-19 07:53:33.53 UTC
2015-09-06 14:55:19.023 UTC
null
2,541,573
null
353,985
null
1
53
linux|git|bash|debian
41,793
<p>You need to <code>source /etc/bash_completion.d/git</code> to enable git auto-completion.</p> <p>In my <code>.bashrc</code> it's done with:</p> <pre><code>for file in /etc/bash_completion.d/* ; do source "$file" done </code></pre>
11,333,354
How can I test fragments with Robolectric?
<p>I know there is a <code>Robolectric.shadowOf(Fragment)</code> method and a <code>ShadowFragment</code> class, thought they aren't listed on the docs, but I can't make it work.</p> <pre><code>myFragment = new MyFragment(); myFragment.onCreateView(LayoutInflater.from(activity), (ViewGroup) activity.findViewById(R.id.container), null); myFragment.onAttach(activity); myFragment.onActivityCreated(null); </code></pre> <p>I'm working with API level 13 (Honeycomb).</p> <p>Thanks.</p>
12,903,280
7
0
null
2012-07-04 17:30:45.92 UTC
19
2020-02-28 07:23:22.697 UTC
2015-01-10 19:38:48.303 UTC
null
950,427
null
397,244
null
1
58
android|robolectric
50,996
<p><strong>Edit #4 &amp; #5</strong>: In <a href="https://github.com/robolectric/robolectric/wiki/2.4-to-3.0-Upgrade-Guide" rel="noreferrer">Robolectric 3.*</a>, they split up the fragment starting functions.</p> <p>For support fragments, you will need to add a <a href="https://bintray.com/bintray/jcenter/org.robolectric%3Ashadows-supportv4/view" rel="noreferrer">dependency</a> to your <code>build.gradle</code>:</p> <pre><code>testCompile "org.robolectric:shadows-supportv4:3.8" </code></pre> <p>Import: <a href="http://robolectric.org/javadoc/3.0/org/robolectric/shadows/support/v4/SupportFragmentTestUtil.html" rel="noreferrer"><code>org.robolectric.shadows.support.v4.SupportFragmentTestUtil.startFragment;</code></a></p> <p>For platform fragments, you don't need this dependency. Import: <a href="http://robolectric.org/javadoc/3.0/org/robolectric/util/FragmentTestUtil" rel="noreferrer"><code>import static org.robolectric.util.FragmentTestUtil.startFragment; </code></a></p> <p>They both use the same name of <code>startFragment()</code>.</p> <pre><code>import static org.robolectric.shadows.support.v4.SupportFragmentTestUtil.startFragment; @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class) public class YourFragmentTest { @Test public void shouldNotBeNull() throws Exception { YourFragment fragment = YourFragment.newInstance(); startFragment( fragment ); assertNotNull( fragment ); } } </code></pre> <p><strong>Edit #3</strong>: Robolectric 2.4 has an <a href="http://robolectric.org/javadoc/2.4/org/robolectric/util/FragmentTestUtil.html" rel="noreferrer">API for support and regular fragments</a>. You can either use the <code>newInstance()</code> pattern or use the constructor when constructing your <code>Fragment</code>'s.</p> <pre><code>import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertNotNull; import static org.robolectric.util.FragmentTestUtil.startFragment; @RunWith(RobolectricGradleTestRunner.class) public class YourFragmentTest { @Test public void shouldNotBeNull() throws Exception { YourFragment fragment = new YourFragment(); startFragment( fragment ); assertNotNull( fragment ); } } </code></pre> <p><strong>Edit #2</strong>: There's a new helper if you're using support fragments (<a href="https://github.com/robolectric/robolectric/blob/master/src/main/java/org/robolectric/util/FragmentTestUtil.java" rel="noreferrer">one that supports regular activities/fragments should be in the next release</a>):</p> <pre><code>import static org.robolectric.util.FragmentTestUtil.startFragment; @Before public void setUp() throws Exception { fragment = YourFragment.newInstance(); startFragment( fragment ); } </code></pre> <p><strong>Edit</strong>: If you upgraded to Robolectric 2.0:</p> <pre><code>public static void startFragment( Fragment fragment ) { FragmentActivity activity = Robolectric.buildActivity( FragmentActivity.class ) .create() .start() .resume() .get(); FragmentManager fragmentManager = activity.getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add( fragment, null ); fragmentTransaction.commit(); } </code></pre> <p><strong>Original answer</strong></p> <p>As the other commenter suggested, you do need to use the fragment manager (instead of calling the lifecycle methods you listed above).</p> <pre><code>@RunWith(MyTestRunner.class) public class YourFragmentTest { @Test public void shouldNotBeNull() throws Exception { YourFragment yourFragment = new YourFragment(); startFragment( yourFragment ); assertNotNull( yourFragment ); } </code></pre> <p>I create a test runner and have a function that starts up a fragment for me so I can use it everywhere.</p> <pre><code>public class MyTestRunner extends RobolectricTestRunner { public MyTestRunner( Class&lt;?&gt; testClass ) throws InitializationError { super( testClass ); } public static void startFragment( Fragment fragment ) { FragmentManager fragmentManager = new FragmentActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add( fragment, null ); fragmentTransaction.commit(); } } </code></pre>
13,014,704
How to work out if a file has been modified?
<p>I'm writing a back up solution (of sorts). Simply it copies a file from location C:\ and pastes it to location Z:\</p> <p>To ensure the speed is fast, before copying and pasting it checks to see if the original file exists. If it does, it performs a few 'calculations' to work out if the copy should continue or if the backup file is up to date. It is these calculations I'm finding difficult.</p> <p>Originally, I compared the file size but this is not good enough because it would be very possible to change a file and it to be the same size (for example saving the character C in notepad is the same size as if I saved the Character T). </p> <p>So, I need to find out if the modified date differs. At the moment, I get the file info using the <code>FileInfo</code> class but after reviewing all the fields there is nothing which appears to be suitable. </p> <p>How can I check to ensure that I'm copying files which have been modified?</p> <p><strong>EDIT</strong> I have seen suggestions on SO to use MD5 checksums, but I'm concerned this may be a problem as some of the files I'm comparing will be up to 10GB</p>
13,014,813
6
10
null
2012-10-22 15:31:06.247 UTC
9
2021-09-03 19:20:30.47 UTC
2012-10-22 15:41:45.48 UTC
null
337,759
null
1,221,410
null
1
20
c#
34,805
<p>Going by modified date will be unreliable - the computer clock can go backwards when it synchronizes, or when manually adjusted. Some programs might not behave well when modifying or copying files in terms of managing the modified date.</p> <p>Going by the archive bit might work in a controlled environment but what happens if another piece of software is running that uses the archive bit as well?</p> <p><a href="http://www.computerworld.com/article/2598081/data-center/the-windows-archive-bit-is-evil-and-must-be-stopped.html" rel="noreferrer">The Windows archive bit is evil and must be stopped</a></p> <p>If you want (almost) complete reliability then what you should do is store a hash value of the last backed up version using a good hashing function like SHA1, and if the hash value changes then you upload the new copy. </p> <p>Here is the SHA1 class along with a code sample on the bottom:</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha1.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha1.aspx</a></p> <p>Just run the file bytes through it and store the hash value. Pass a <code>FileStream</code> to it instead of loading your file into memory with a byte array to reduce memory usage, especially for large files.</p> <p>You can combine this with modified date in various ways to tweak your program as needed for speed and reliability. For example, you can check modified dates for most backups and periodically run a hash checker that runs while the system is idle to make sure nothing got missed. Sometimes the modified date will change but the file contents are still the same (i.e. got overwritten with the same data), in which case you can avoid resending the whole file after you recompute the hash and realize it is still the same.</p> <p>Most version control systems use some kind of combined approach with hashes and modified dates.</p> <p>Your approach will generally involve some kind of risk management with a compromise between performance and reliability if you don't want to do a full backup and send all the data over each time. It's important to do "full backups" once in a while for this reason.</p>
13,222,858
Android - default button style
<p><strong>Question:</strong> Where can I find default styles xml with hexadecimal codes of colors?</p> <p>I'm looking for Style 'buttonStyle' and other default styles witch affect aspects like TextViews, Buttons etc (if you dont change the style of aspect)</p> <p>I looked up in <code>&lt;instalation_folder&gt;\android-sdk\platforms\android-&lt;versio&gt;\data\res\values</code> and <code>&lt;instalation_folder&gt;\android-sdk\platforms\android-&lt;version&gt;\data\res\colors</code> but I didn't actually find what I was looking for.</p> <p>Hope my question is clear.</p> <p><hr> Due to low reputation I cant answer this question yet. Here is answer</p> <p><strong>Answer</strong></p> <p>With a bit of googling I found 'buttonStyle' is actually 'Widget.Button' - <a href="http://www.therealjoshua.com/2012/01/styling-android-with-defaults/">Styling Android With Defaults</a></p> <p>This is how it works:</p> <ul> <li>As I said 'buttonStyle' style is accualy 'Widget.Button' style defined in <code>\android-sdk\platforms\android-&lt;version&gt;\data\res\values\styles.xml</code>. Background is set to: <code>@android:drawable/btn_default</code></li> <li><code>\android-sdk\platforms\android-&lt;version&gt;\data\res\drawable\btn_default.xml</code> defines background color of button as selector. Color actually depends on button's state. Default color is set to <code>@drawable/btn_default_normal</code></li> <li>With a bit of searching I found, that btn_default_normal is png image located in <code>\android-sdk\platforms\android-&lt;version&gt;\data\res\drawable-mdpi</code></li> </ul> <p>I find it a bit confusing, but I hope it will help someone, maybe...</p>
13,223,330
2
0
null
2012-11-04 20:57:44.613 UTC
29
2012-11-04 22:25:06.857 UTC
2012-11-04 21:47:02.78 UTC
null
1,784,053
null
1,784,053
null
1
50
java|android|button|styles
66,590
<p>Understanding how Android styles do work can be a little bit messy.</p> <p>I will try to explain how the basic work flow would be, based on an example.</p> <p>Let's assume you want to know what the default background for buttons is. This can be either a simple color (unlikely) or a drawable (there are many different types of drawables).</p> <p>Android has Themes. A theme basically defines which style is applied to which widget. Therefore, our first step is to find the default android theme.</p> <p>You find it under <code>android-sdk\platforms\android-15\data\res\values\themes.xml</code></p> <p>In this theme file, search for <code>button</code>.</p> <p>You will find something like this:</p> <pre><code>&lt;!-- Button styles --&gt; &lt;item name="buttonStyle"&gt;@android:style/Widget.Button&lt;/item&gt; </code></pre> <p>This means that the theme applies the style <code>Widget.Button</code> to buttons.</p> <p>Ok, now let's find the style <code>Widget.Button</code>. </p> <p>All default Android style are defined in the file <code>android-sdk\platforms\android-15\data\res\values\styles.xml</code></p> <p>Now search for <code>Widget.Button</code></p> <p>You will find something like this:</p> <pre><code>&lt;style name="Widget.Button"&gt; &lt;item name="android:background"&gt;@android:drawable/btn_default&lt;/item&gt; &lt;item name="android:focusable"&gt;true&lt;/item&gt; &lt;item name="android:clickable"&gt;true&lt;/item&gt; &lt;item name="android:textAppearance"&gt;?android:attr/textAppearanceSmallInverse&lt;/item&gt; &lt;item name="android:textColor"&gt;@android:color/primary_text_light&lt;/item&gt; &lt;item name="android:gravity"&gt;center_vertical|center_horizontal&lt;/item&gt; &lt;/style&gt; </code></pre> <p>The interesting line is: </p> <p><code>&lt;item name="android:background"&gt;@android:drawable/btn_default&lt;/item&gt;</code></p> <p>This means that there is a drawable called <code>btn_default</code> set as button background.</p> <p>Now we need to find a file named <code>btn_default.*</code> in one of the drawable folders under <code>android-sdk\platforms\android-15\data\res</code>.</p> <p>This can be either an image (very unlikely) or a xml file like <code>btn_default.xml</code>.</p> <p>After a little bit searching you will find the file <code>android-sdk\platforms\android-15\data\res\drawable\btn_default.xml</code></p> <p>It contains something like this:</p> <pre><code>&lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:state_window_focused="false" android:state_enabled="true" android:drawable="@drawable/btn_default_normal" /&gt; &lt;item android:state_window_focused="false" android:state_enabled="false" android:drawable="@drawable/btn_default_normal_disable" /&gt; &lt;item android:state_pressed="true" android:drawable="@drawable/btn_default_pressed" /&gt; &lt;item android:state_focused="true" android:state_enabled="true" android:drawable="@drawable/btn_default_selected" /&gt; &lt;item android:state_enabled="true" android:drawable="@drawable/btn_default_normal" /&gt; &lt;item android:state_focused="true" android:drawable="@drawable/btn_default_normal_disable_focused" /&gt; &lt;item android:drawable="@drawable/btn_default_normal_disable" /&gt; &lt;/selector&gt; </code></pre> <p>Now you have to understand that this is a selector drawable (one of the many drawable types). This selector chooses different backgrounds, based on the buttons state. For example, if the buttons is pressed, it has a different background.</p> <p>No let's look at the default state.</p> <p><code>&lt;item android:state_enabled="true" android:drawable="@drawable/btn_default_normal" /&gt;</code></p> <p>It applies a drawable called <code>btn_default_normal</code>.</p> <p>Now we need to find this drawable.</p> <p>Again, we need to find a file named <code>btn_default_normal.*</code> in one of the drawable folders under <code>android-sdk\platforms\android-15\data\res</code>.</p> <p>This can be again either an image or a xml file like <code>btn_default_normal.xml</code>.</p> <p>You will find multiple files called 'btn_default_normal.9.png' in different drawable folders for different resolutions. </p> <p>:) Now you know that <code>btn_default_normal.9.png</code> is set as button background.</p>
13,046,192
Changing default shell in Linux
<p>How is it possible to change the default shell? The <code>env</code> command currently says:</p> <pre><code>SHELL=/bin/tcsh </code></pre> <p>and I want to change that to Bash.</p>
13,046,283
3
2
null
2012-10-24 09:15:37.913 UTC
91
2019-01-26 11:51:11.667 UTC
2019-01-26 11:51:11.667 UTC
null
775,954
null
859,227
null
1
353
linux|bash|shell|environment|tcsh
606,179
<p>Try linux command <code>chsh</code>.</p> <p>The detailed command is <code>chsh -s /bin/bash</code>. It will prompt you to enter your password. Your default login shell is <code>/bin/bash</code> now. <strong>You must log out and log back in to see this change.</strong></p> <p>The following is quoted from man page:</p> <blockquote> <p>The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account</p> </blockquote> <p>This command will change the default login shell permanently.</p> <p>Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use <code>chsh</code>. </p>
12,961,514
How to use Bitbucket and GitHub at the same time for one project?
<p>I have one repository which I want to push into Bitbucket and GitHub. It is vital for my repository to be hosted by both.</p> <p>Is there a way to do this in Git?</p>
12,961,543
4
1
null
2012-10-18 18:40:19.463 UTC
75
2022-02-08 17:09:05.143 UTC
2016-09-29 20:15:00.197 UTC
null
6,199,855
null
648,896
null
1
105
git|github|bitbucket
38,742
<p>You can use multiple remote repositories with git. But you'll have to push separately into 2 of your remotes I believe.</p> <p>For example, if your project currently points to github, you can rename your current remote repository to <code>github</code>:</p> <pre><code>$ git remote rename origin github </code></pre> <p>You can then add another remote repository, say <code>bitbucket</code>:</p> <pre><code>$ git remote add bitbucket [email protected]:your_user/your_repo.git </code></pre> <p>Now in order to push changes to corresponding branch on github or bitbucket you can do this:</p> <pre><code>$ git push github HEAD $ git push bitbucket HEAD </code></pre> <p>Same rule applies to pulling: you need to specify which remote you want to pull from:</p> <pre><code>$ git pull github your_branch $ git pull bitbucket your_branch </code></pre>
30,514,995
What is the difference between a lambda and a method reference at a runtime level?
<p>I've experienced a problem that was happening using a method reference but not with lambdas. That code was the following:</p> <pre><code>(Comparator&lt;ObjectNode&gt; &amp; Serializable) SOME_COMPARATOR::compare </code></pre> <p>or, with lambda,</p> <pre><code>(Comparator&lt;ObjectNode&gt; &amp; Serializable) (a, b) -&gt; SOME_COMPARATOR.compare(a, b) </code></pre> <p>Semantically, it is strictly the same, but in practice it is different as in the first case I get an exception in one of the Java serialization classes. My question is not about this exception, because the actual code is running in a more complicated context that has proved to have strange behaviour with serialization, so it would just make it too difficult to answer if I gave any more details.</p> <p>What I want to understand is the difference between those two ways of creating a lambda expression.</p>
30,574,381
2
11
null
2015-05-28 18:59:04.437 UTC
21
2019-01-16 17:47:34.167 UTC
2019-01-16 17:47:34.167 UTC
null
452,775
null
3,895,960
null
1
41
java|serialization|lambda|java-8
3,046
<h2>Getting Started</h2> <p>To investigate this we start with the following class:</p> <pre><code>import java.io.Serializable; import java.util.Comparator; public final class Generic { // Bad implementation, only used as an example. public static final Comparator&lt;Integer&gt; COMPARATOR = (a, b) -&gt; (a &gt; b) ? 1 : -1; public static Comparator&lt;Integer&gt; reference() { return (Comparator&lt;Integer&gt; &amp; Serializable) COMPARATOR::compare; } public static Comparator&lt;Integer&gt; explicit() { return (Comparator&lt;Integer&gt; &amp; Serializable) (a, b) -&gt; COMPARATOR.compare(a, b); } } </code></pre> <p>After compilation, we can disassemble it using:</p> <blockquote> <p>javap -c -p -s -v Generic.class</p> </blockquote> <p>Removing the irrelevant parts (and some other clutter, such as fully-qualified types and the initialisation of <code>COMPARATOR</code>) we are left with</p> <pre><code> public static final Comparator&lt;Integer&gt; COMPARATOR; public static Comparator&lt;Integer&gt; reference(); 0: getstatic #2 // Field COMPARATOR:LComparator; 3: dup 4: invokevirtual #3 // Method Object.getClass:()LClass; 7: pop 8: invokedynamic #4, 0 // InvokeDynamic #0:compare:(LComparator;)LComparator; 13: checkcast #5 // class Serializable 16: checkcast #6 // class Comparator 19: areturn public static Comparator&lt;Integer&gt; explicit(); 0: invokedynamic #7, 0 // InvokeDynamic #1:compare:()LComparator; 5: checkcast #5 // class Serializable 8: checkcast #6 // class Comparator 11: areturn private static int lambda$explicit$d34e1a25$1(Integer, Integer); 0: getstatic #2 // Field COMPARATOR:LComparator; 3: aload_0 4: aload_1 5: invokeinterface #44, 3 // InterfaceMethod Comparator.compare:(LObject;LObject;)I 10: ireturn BootstrapMethods: 0: #61 invokestatic invoke/LambdaMetafactory.altMetafactory:(Linvoke/MethodHandles$Lookup;LString;Linvoke/MethodType;[LObject;)Linvoke/CallSite; Method arguments: #62 (LObject;LObject;)I #63 invokeinterface Comparator.compare:(LObject;LObject;)I #64 (LInteger;LInteger;)I #65 5 #66 0 1: #61 invokestatic invoke/LambdaMetafactory.altMetafactory:(Linvoke/MethodHandles$Lookup;LString;Linvoke/MethodType;[LObject;)Linvoke/CallSite; Method arguments: #62 (LObject;LObject;)I #70 invokestatic Generic.lambda$explicit$df5d232f$1:(LInteger;LInteger;)I #64 (LInteger;LInteger;)I #65 5 #66 0 </code></pre> <p>Immediately we see that the bytecode for the <code>reference()</code> method is different to the bytecode for <code>explicit()</code>. However, the notable difference <a href="http://www.benf.org/other/cfr/java8lambda_instancemethodref_getclass.html" rel="noreferrer">isn't actually relevant</a>, but the bootstrap methods are interesting.</p> <blockquote> <p>An invokedynamic call site is linked to a method by means of a <em>bootstrap method</em>, which is a method specified by the compiler for the dynamically-typed language that is called once by the JVM to link the site. </p> </blockquote> <p>(<a href="http://docs.oracle.com/javase/8/docs/technotes/guides/vm/multiple-language-support.html#challenges" rel="noreferrer">Java Virtual Machine Support for Non-Java Languages</a>, emphasis theirs)</p> <p>This is the code responsible for creating the <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/invoke/CallSite.html" rel="noreferrer">CallSite</a> used by the lambda. The <code>Method arguments</code> listed below each bootstrap method are the values passed as the variadic parameter (i.e. <code>args</code>) of <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/invoke/LambdaMetafactory.html#altMetafactory-java.lang.invoke.MethodHandles.Lookup-java.lang.String-java.lang.invoke.MethodType-java.lang.Object...-" rel="noreferrer">LambdaMetaFactory#altMetaFactory</a>.</p> <h2>Format of the Method arguments</h2> <ol> <li>samMethodType - Signature and return type of method to be implemented by the function object.</li> <li>implMethod - A direct method handle describing the implementation method which should be called (with suitable adaptation of argument types, return types, and with captured arguments prepended to the invocation arguments) at invocation time.</li> <li>instantiatedMethodType - The signature and return type that should be enforced dynamically at invocation time. This may be the same as samMethodType, or may be a specialization of it.</li> <li>flags indicates additional options; this is a bitwise OR of desired flags. Defined flags are FLAG_BRIDGES, FLAG_MARKERS, and FLAG_SERIALIZABLE.</li> <li>bridgeCount is the number of additional method signatures the function object should implement, and is present if and only if the FLAG_BRIDGES flag is set.</li> </ol> <p>In both cases here <code>bridgeCount</code> is 0, and so there is no 6, which would otherwise be <code>bridges</code> - a variable-length list of additional methods signatures to implement (given that <code>bridgeCount</code> is 0, I'm not entirely sure why FLAG_BRIDGES is set).</p> <p>Matching the above up with our arguments, we get:</p> <ol> <li>The function signature and return type <code>(Ljava/lang/Object;Ljava/lang/Object;)I</code>, which is the return type of <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#compare-T-T-" rel="noreferrer">Comparator#compare</a>, because of generic type erasure.</li> <li>The method being called when this lambda is invoked (which is different).</li> <li>The signature and return type of the lambda, which will be checked when the lambda is invoked: <code>(LInteger;LInteger;)I</code> (note that these aren't erased, because this is part of the lambda specification).</li> <li>The flags, which in both cases is the composition of <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/invoke/LambdaMetafactory.html#FLAG_BRIDGES" rel="noreferrer">FLAG_BRIDGES</a> and <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/invoke/LambdaMetafactory.html#FLAG_SERIALIZABLE" rel="noreferrer">FLAG_SERIALIZABLE</a> (i.e. 5).</li> <li>The amount of bridge method signatures, 0.</li> </ol> <p>We can see that FLAG_SERIALIZABLE is set for both lambdas, so it's not that.</p> <h2>Implementation methods</h2> <p>The implementation method for the method reference lambda is <code>Comparator.compare:(LObject;LObject;)I</code>, but for the explicit lambda it's <code>Generic.lambda$explicit$df5d232f$1:(LInteger;LInteger;)I</code>. Looking at the disassembly, we can see that the former is essentially an inlined version of the latter. The only other notable difference is the method parameter types (which, as mentioned earlier, is because of generic type erasure).</p> <h2>When is a lambda actually serializable?</h2> <blockquote> <p>You can serialize a lambda expression if its target type and its captured arguments are serializable.</p> </blockquote> <p><a href="http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#serialization" rel="noreferrer">Lambda Expressions (The Java™ Tutorials)</a></p> <p>The important part of that is "captured arguments". Looking back at the disassembled bytecode, the invokedynamic instruction for the method reference certainly looks like it's capturing a Comparator (<code>#0:compare:(LComparator;)LComparator;</code>, in contrast to the explicit lambda, <code>#1:compare:()LComparator;</code>).</p> <h2>Confirming capturing is the issue</h2> <p><code>ObjectOutputStream</code> contains an <code>extendedDebugInfo</code> field, which we can set using the <code>-Dsun.io.serialization.extendedDebugInfo=true</code> VM argument:</p> <blockquote> <p>$ java -Dsun.io.serialization.extendedDebugInfo=true Generic</p> </blockquote> <p>When we try to serialize the lambdas again, this gives a very satisfactory</p> <pre><code>Exception in thread "main" java.io.NotSerializableException: Generic$$Lambda$1/321001045 - element of array (index: 0) - array (class "[LObject;", size: 1) /* ! */ - field (class "invoke.SerializedLambda", name: "capturedArgs", type: "class [LObject;") // &lt;--- !! - root object (class "invoke.SerializedLambda", SerializedLambda[capturingClass=class Generic, functionalInterfaceMethod=Comparator.compare:(LObject;LObject;)I, implementation=invokeInterface Comparator.compare:(LObject;LObject;)I, instantiatedMethodType=(LInteger;LInteger;)I, numCaptured=1]) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1182) /* removed */ at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348) at Generic.main(Generic.java:27) </code></pre> <h2>What's actually going on</h2> <p>From the above, we can see that the explicit lambda is <strong>not</strong> capturing anything, whereas the method reference lambda is. Looking over the bytecode again makes this clear:</p> <pre><code> public static Comparator&lt;Integer&gt; explicit(); 0: invokedynamic #7, 0 // InvokeDynamic #1:compare:()LComparator; 5: checkcast #5 // class java/io/Serializable 8: checkcast #6 // class Comparator 11: areturn </code></pre> <p>Which, as seen above, has an implementation method of:</p> <pre><code> private static int lambda$explicit$d34e1a25$1(java.lang.Integer, java.lang.Integer); 0: getstatic #2 // Field COMPARATOR:Ljava/util/Comparator; 3: aload_0 4: aload_1 5: invokeinterface #44, 3 // InterfaceMethod java/util/Comparator.compare:(Ljava/lang/Object;Ljava/lang/Object;)I 10: ireturn </code></pre> <p>The explicit lambda is actually calling <code>lambda$explicit$d34e1a25$1</code>, which in turn calls the <code>COMPARATOR#compare</code>. This layer of indirection means it's not capturing anything that isn't <code>Serializable</code> (or anything at all, to be precise), and so is safe to serialize. The method reference expression <strong>directly</strong> uses <code>COMPARATOR</code> (the value of which is then passed to the bootstrap method):</p> <pre><code> public static Comparator&lt;Integer&gt; reference(); 0: getstatic #2 // Field COMPARATOR:LComparator; 3: dup 4: invokevirtual #3 // Method Object.getClass:()LClass; 7: pop 8: invokedynamic #4, 0 // InvokeDynamic #0:compare:(LComparator;)LComparator; 13: checkcast #5 // class java/io/Serializable 16: checkcast #6 // class Comparator 19: areturn </code></pre> <p>The lack of indirection means that <code>COMPARATOR</code> must be serialized along with the lambda. As <code>COMPARATOR</code> does not refer to a <code>Serializable</code> value, this fails.</p> <h2>The fix</h2> <p>I hesitate to call this a compiler bug (I expect the lack of indirection serves as an optimisation), although it is very strange. The fix is trivial, but ugly; adding the explicit cast for <code>COMPARATOR</code> at declaration:</p> <pre><code>public static final Comparator&lt;Integer&gt; COMPARATOR = (Serializable &amp; Comparator&lt;Integer&gt;) (a, b) -&gt; a &gt; b ? 1 : -1; </code></pre> <p>This makes everything perform correctly on Java 1.8.0_45. It's also worth noting that the eclipse compiler produces that layer of indirection in the method reference case as well, and so the original code in this post does not require modification to execute correctly.</p>
16,627,476
PHP resize image proportionally with max width or weight
<p>There is any php script that resize image proportionally with max widht or height??</p> <p>Ex: I upload image and this original size is w:500 h:1000. But, I want to resize this thats max height is width and height is 500... That the script resize the image for w: 250 h: 500</p>
16,627,743
2
7
null
2013-05-18 18:16:34.647 UTC
7
2013-05-18 18:46:58.08 UTC
2013-05-18 18:20:55.383 UTC
null
625,782
null
1,785,897
null
1
23
php
80,958
<p>All you need is the aspect ratio. Something along these lines:</p> <pre><code>$fn = $_FILES['image']['tmp_name']; $size = getimagesize($fn); $ratio = $size[0]/$size[1]; // width/height if( $ratio &gt; 1) { $width = 500; $height = 500/$ratio; } else { $width = 500*$ratio; $height = 500; } $src = imagecreatefromstring(file_get_contents($fn)); $dst = imagecreatetruecolor($width,$height); imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]); imagedestroy($src); imagepng($dst,$target_filename_here); // adjust format as needed imagedestroy($dst); </code></pre> <p>You'll need to add some error checking, but this should get you started.</p>
16,767,415
How do I find out why I couldn't #destroy() a record?
<pre><code>person = Person.find(4123) person.destroy #=&gt; false </code></pre> <p>What ways do I have to find out why the record wasn't deleted? The model has two validations, both trigger on create only. It has one callback, but the callback doesn't block if it fails.</p> <p>I have no traceback or errors to look at.</p>
71,524,304
6
1
null
2013-05-27 06:23:37.353 UTC
11
2022-03-18 08:37:23.623 UTC
null
null
null
null
414,329
null
1
47
ruby-on-rails|activerecord
15,347
<p>Had the exact same error right now. I didn't get any backtrace, because it was a logic error.</p> <p>In my case my models had a conflicting <code>dependent: destroy</code> in the relations in the model. That means my model wanted to delete a parent model which was already deleted before hand.</p> <p>I think it's a bit confusing, i'll make it clear by declaring the models:</p> <pre><code>class Section &lt; ApplicationRecord has_many :contents, dependent: :destroy class Content &lt; ApplicationRecord belongs_to :section has_many :quizzes, dependent: :destroy class Quiz &lt; ApplicationRecord belongs_to :content, dependent: :destroy </code></pre> <p>I deleted the Section <code>section.destroy</code> and got the error. The error was the <code>dependent: destroy</code> in the relation :content in the <code>Quiz</code>-model, because the content was already deleted by the <code>dependent: destroy</code> in the section model. I hope this will help to find the problem :)</p>
26,804,651
How to access files from assets folder during tests execution?
<p>How to access files from assets folder during unit tests execution? My project is build using Gradle, I use Robolectric to run tests. It seems like gradle is being recognizing the <code>assets</code>:</p> <p><img src="https://i.stack.imgur.com/SOcT1.png" alt="enter image description here"></p> <p>This is how I'm struggling to read the file:</p> <pre><code>public String readFileFromAssets(String fileName) throws IOException { InputStream stream = getClass().getClassLoader().getResourceAsStream("assets/" + fileName); Preconditions.checkNotNull(stream, "Stream is null"); BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); return IOUtils.toString(reader); } </code></pre> <p>But <code>stream</code> is always <code>null</code>. I tried it many different ways, i.e. defined path to a file using different approaches.</p> <p>Thank you very much in advance.</p>
26,968,924
9
5
null
2014-11-07 15:33:47.297 UTC
9
2022-04-05 23:04:38.963 UTC
2014-11-12 13:57:58.573 UTC
null
972,684
null
397,991
null
1
23
android|gradle|robolectric|android-assets
23,563
<p>Basically you have to use <code>Context</code> to read assets. You can not load assets with <code>ClassLoader</code> since it is not in a classpath. I am not sure how you run Robolectric test cases. Here are how I can achieve in both Android studio and gralde command.</p> <p>I added separate app-unit-test module to run Robolectric test cases in app project. With proper build configuration and custom <code>RobolectricTestRunner</code>, following test case will pass.</p> <pre><code>@Config @RunWith(MyRobolectricTestRunner.class) public class ReadAssetsTest { @Test public void test_ToReadAssetsFileInAndroidTestContext() throws IOException { ShadowApplication application = Robolectric.getShadowApplication(); Assert.assertNotNull(application); InputStream input = application.getAssets().open("b.xml"); Assert.assertNotNull(input); } } </code></pre> <p>app-unit-test/build.gradle</p> <pre><code>buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:0.14.1' } } apply plugin: 'java' evaluationDependsOn(':app') sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 repositories { maven { url "$System.env.ANDROID_HOME/extras/android/m2repository" } // Fix 'com.android.support:*' package not found issue mavenLocal() mavenCentral() jcenter() } dependencies { testCompile 'junit:junit:4.8.2' testCompile('org.robolectric:robolectric:2.4') { exclude module: 'classworlds' exclude module: 'commons-logging' exclude module: 'httpclient' exclude module: 'maven-artifact' exclude module: 'maven-artifact-manager' exclude module: 'maven-error-diagnostics' exclude module: 'maven-model' exclude module: 'maven-project' exclude module: 'maven-settings' exclude module: 'plexus-container-default' exclude module: 'plexus-interpolation' exclude module: 'plexus-utils' exclude module: 'wagon-file' exclude module: 'wagon-http-lightweight' exclude module: 'wagon-provider-api' exclude group: 'com.android.support', module: 'support-v4' } testCompile('com.squareup:fest-android:1.0.+') { exclude group: 'com.android.support', module: 'support-v4' } testCompile 'org.mockito:mockito-core:1.10.10' def appModule = project(':app') testCompile(appModule) { exclude group: 'com.google.android' exclude module: 'dexmaker-mockito' } testCompile appModule.android.applicationVariants.toList().first().javaCompile.classpath testCompile appModule.android.applicationVariants.toList().first().javaCompile.outputs.files testCompile 'com.google.android:android:4.1.1.4' /* FIXME : prevent Stub! error testCompile files(appModule.plugins.findPlugin("com.android.application").getBootClasspath()) */ compile project(':app') } </code></pre> <p>Add custom RobolectricTestRunner to adjust file paths. Look at the assets path.</p> <pre><code>public class MyRobolectricTestRunner extends RobolectricTestRunner { private static final String APP_MODULE_NAME = "app"; /** * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file * and res directory by default. Use the {@link org.robolectric.annotation.Config} annotation to configure. * * @param testClass the test class to be run * @throws org.junit.runners.model.InitializationError if junit says so */ public MyRobolectricTestRunner(Class&lt;?&gt; testClass) throws InitializationError { super(testClass); System.out.println("testclass="+testClass); } @Override protected AndroidManifest getAppManifest(Config config) { String userDir = System.getProperty("user.dir", "./"); File current = new File(userDir); String prefix; if (new File(current, APP_MODULE_NAME).exists()) { System.out.println("Probably running on AndroidStudio"); prefix = "./" + APP_MODULE_NAME; } else if (new File(current.getParentFile(), APP_MODULE_NAME).exists()) { System.out.println("Probably running on Console"); prefix = "../" + APP_MODULE_NAME; } else { throw new IllegalStateException("Could not find app module, app module should be \"app\" directory in the project."); } System.setProperty("android.manifest", prefix + "/src/main/AndroidManifest.xml"); System.setProperty("android.resources", prefix + "/src/main/res"); System.setProperty("android.assets", prefix + "/src/androidTest/assets"); return super.getAppManifest(config); } } </code></pre> <p>I followed this blog to do it.</p> <ul> <li><a href="http://blog.blundellapps.com/android-gradle-app-with-robolectric-junit-tests/" rel="noreferrer">http://blog.blundellapps.com/android-gradle-app-with-robolectric-junit-tests/</a></li> <li><a href="http://blog.blundellapps.com/how-to-run-robolectric-junit-tests-in-android-studio/" rel="noreferrer">http://blog.blundellapps.com/how-to-run-robolectric-junit-tests-in-android-studio/</a></li> </ul> <p>Full example codes are <a href="https://github.com/sh1nj1/exercise-andy/tree/master/app-unit-test" rel="noreferrer">here</a>.</p>
9,961,949
PlaySound in C++ Console application?
<p>EDITED SO THE CODE IS CORRECT (THANKS TO ta.speot.is) - NEW QUESTION AT BOTTOM</p> <p>So I have been playing with the console as I am at that level, and we have been asked to make our first &quot;project&quot; for a assessment. I have the basic application all done.. but i wanted to jaz it up a bit and add some sounds. Sounds that will play from the console.</p> <p>This test works(kind of), as it will play a sound file, but there are 2 problems...</p> <ol> <li><p>When the sound starts playing, the application freezes until it finishes playing.</p> </li> <li><p>When I try to compile as a &quot;release&quot; it errors with a &quot;linking error&quot; - fatal error LNK1120: 1 unresolved externals.</p> </li> </ol> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;windows.h&gt; #include &lt;mmsystem.h&gt; using namespace std; int main(){ //PlaySound(TEXT(&quot;mywavsound.wav&quot;), NULL, SND_FILENAME); - My erroring code PlaySound(TEXT(&quot;mywavsound.wav&quot;), NULL, SND_FILENAME | SND_ASYNC);// - the correct code int test = 0; cin&gt;&gt;test; return 0; } </code></pre> <p>So my questions are...</p> <ol> <li><p><em>How can I play sounds without freezing the console, so I can for example play looping music file while the project is running? Also it would be great if I could play other sounds on top of it, for example when you press enter it will plays a sound without stopping the music.</em></p> </li> <li><p><em>How do I add the wav file so it compiles as a release?</em></p> </li> </ol> <p><strong>EDIT</strong></p> <p>I know about the <code>SND_ASYNC</code> thing but I do not know how to use it, I can't seem to use it without the thing not compiling.. does anyone have an example of a code using <code>SND_ASYNC</code>?</p> <p><strong>EDIT 2</strong></p> <p>So I have this working now.... using the</p> <pre class="lang-cpp prettyprint-override"><code>PlaySound(TEXT(&quot;mysound.wav&quot;), NULL, SND_FILENAME | SND_ASYNC); </code></pre> <p>Now I am wondering how I can get 1 or more sounds to play at once, for if I call <code>PlaySound()</code> twice with that flag it will stop the 1st one and play the 2nd.. <em>Is there a way to play 2 sounds at once?</em></p>
9,961,965
6
0
null
2012-04-01 04:37:00.547 UTC
3
2022-05-23 12:34:05.327 UTC
2021-06-02 16:12:07.6 UTC
null
65,863
null
1,260,774
null
1
5
c++|audio|console
60,897
<blockquote> <p>How can I play sounds without freezing the console?</p> </blockquote> <p>If you Google for <code>PlaySound</code> <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd743680.aspx" rel="nofollow noreferrer">this is the first result</a>:</p> <blockquote> <h1><code>fdwSound</code></h1> <p>...</p> <p><code>SND_ASYNC</code> The sound is played asynchronously and <code>PlaySound</code> returns immediately after beginning the sound. To terminate an asynchronously played waveform sound, call <code>PlaySound</code> with <code>pszSound</code> set to <code>NULL</code>.</p> </blockquote> <p>You should familiarise yourself with search engines and what they are capable of.</p> <blockquote> <p>How do I add the wav file so it compiles as a release?</p> </blockquote> <p>You need to link <code>winmm.lib</code> in both Release and Debug configurations. Alternatively, add</p> <pre><code>#pragma comment(lib, &quot;winmm.lib&quot;) </code></pre> <p>to the top of your source code.</p>
9,766,168
java.sql.SQLException: Io exception: Broken pipe how to recover without restart?
<p>In my application I use connection to Oracle, when connection lost and I try to re-connect I receive exception:</p> <pre><code>java.sql.SQLException: Io exception: Broken pipe at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:124) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:161) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:273) at oracle.jdbc.driver.T4CStatement.fetch(T4CStatement.java:540) at oracle.jdbc.driver.OracleResultSetImpl.close_or_fetch_from_next(OracleResultSetImpl.java:264) at oracle.jdbc.driver.OracleResultSetImpl.next(OracleResultSetImpl.java:196) </code></pre> <p>For recover I need to restart application, does it possible recover without restart? Thanks.</p>
9,767,173
1
0
null
2012-03-19 06:58:56.06 UTC
1
2012-03-19 08:46:27.793 UTC
null
null
null
null
710,818
null
1
10
java|oracle|connection|recover|disconnected
41,848
<p>Followings could be the possibilities which could be causing the exception:</p> <ol> <li><p>Network problem: That is the network between the database and application server causing the physical connection to be dropped after a period of time. It's probably due to a firewall running behind the network which is configured to kill db connections after a specified period of time. You may consider a workaround to maintain the connection alive all the time simply by re-configuring your application server. For Tomcat, you may try adding <code>validationQuery="select 'validationQuery' from dua</code>l in the Tomcat datasource conf file (context.xml)</p></li> <li><p>The connections to the database server are being reset and the client is not notified by the database driver. The problem in this case is that the Oracle driver is discovering that it's socket to the DBMS somehow (firewall again, maybe?) has been closed by the other end. You may consider setting your connection timeout (in the pool) shorter than the network/DB server timeout as a solution. </p></li> </ol>
9,972,743
Creating a FORTRAN interface to a C function that returns a char*
<p>I've been held up on this for about a week, now, and have searched forum after forum for a clear explanation of how to send a char* from C to FORTRAN. To make the matter more frustrating, sending a char* argument from FORTRAN to C was straight-forward...</p> <p>Sending a char* argument from FORTRAN to C (this works fine):</p> <pre><code>// The C header declaration (using __cdecl in a def file): extern "C" double GetLoggingValue(char* name); </code></pre> <p>And from FORTRAN:</p> <pre><code>! The FORTRAN interface: INTERFACE REAL(8) FUNCTION GetLoggingValue [C, ALIAS: '_GetLoggingValue'] (name) USE ISO_C_BINDING CHARACTER(LEN=1, KIND=C_CHAR), DIMENSION(*), INTENT(IN) :: name END FUNCTION GetLoggingValue END INTERFACE ! Calling the function: GetLoggingValue(user_name) </code></pre> <p>When trying to use analogous logic to return a char* from C, I get problem after problem. One attempt that I felt should work is:</p> <pre><code>// The C declaration header (using __cdecl in a def file): extern "C" const char* GetLastErrorMessage(); </code></pre> <p>And the FORTRAN interface:</p> <pre><code>INTERFACE FUNCTION GetLastErrorMessage [C, ALIAS: '_GetLastErrorMessage'] () USE ISO_C_BINDING CHARACTER(LEN=1, KIND=C_CHAR), DIMENSION(255), :: GetLastErrorMessage END FUNCTION GetLastErrorMessage END INTERFACE </code></pre> <p>(I can't literally use the DIMENSION(*), so I've gone oversize to 255.)</p> <p>This <em>should</em> return a pointer to an array of 255 C-style characters - but if it does, I've been unable to convert this to a meaningful string. In practice, it returns a random set of characters, anywhere from Wingdings to the 'bell' character...</p> <p>I've also attempted to return:</p> <ul> <li>A pointer to CHARACTER(LEN=255, KIND=C_CHAR).</li> <li>Literally CHARACTER(LEN=255, KIND=C_CHAR).</li> <li>A INTEGER(C_SIZE_T), and tried to finesse that into a pointer to a string array.</li> <li>A CHARACTER.</li> <li>etc.</li> </ul> <p>If anybody can give me an example of how to do this, I would be very grateful...</p> <p>Best regards,</p> <p>Mike</p>
9,973,852
7
2
null
2012-04-02 07:58:57.85 UTC
8
2018-07-23 00:39:45.527 UTC
2013-01-03 06:36:36.687 UTC
null
187,997
null
1,297,496
null
1
11
c|interface|char|fortran|fortran-iso-c-binding
8,113
<p>Strings of dynamic length are always a bit tricky with the C interaction. A possible solution is to use pointers.</p> <p>First a simple case, where you have to hand over a null-character terminated string to a C-Function. If you really pass the string only in, you have to ensure to finalize it with the c_null_char, thus this direction is pretty straight forward. Here are examples from a <a href="https://bitbucket.org/haraldkl/aotus/src/c5a20699579b/LuaFortran/flu_binding.f90">LuaFortran Interface</a>:</p> <pre><code>subroutine flu_getfield(L, index, k) type(flu_State) :: L integer :: index character(len=*) :: k integer(kind=c_int) :: c_index character(len=len_trim(k)+1) :: c_k c_k = trim(k) // c_null_char c_index = index call lua_getfield(L%state, c_index, c_k) end subroutine flu_getfield </code></pre> <p>And the <a href="https://bitbucket.org/haraldkl/aotus/src/c5a20699579b/LuaFortran/lua_fif.f90">interface</a> of lua_getfield looks like:</p> <pre><code>subroutine lua_getfield(L, index, k) bind(c, name="lua_getfield") use, intrinsic :: iso_c_binding type(c_ptr), value :: L integer(kind=c_int), value :: index character(kind=c_char), dimension(*) :: k end subroutine lua_getfield </code></pre> <p>And the C-Code interface is:</p> <pre><code>void lua_getfield (lua_State *L, int idx, const char *k) </code></pre> <p>Now the little more complex case, where we have to deal with a returned string from C with a dynamic length. The most portable solution I found so far is using pointers. Here is an example with a pointer, where the string is given by the C-Routine (also from the Aotus library mentioned above):</p> <pre><code>function flu_tolstring(L, index, len) result(string) type(flu_State) :: L integer :: index integer :: len character,pointer,dimension(:) :: string integer :: string_shape(1) integer(kind=c_int) :: c_index integer(kind=c_size_t) :: c_len type(c_ptr) :: c_string c_index = index c_string = lua_tolstring(L%state, c_index, c_len) len = int(c_len,kind=kind(len)) string_shape(1) = len call c_f_pointer(c_string, string, string_shape) end function flu_tolstring </code></pre> <p>where lua_tolstring has the following <a href="https://bitbucket.org/haraldkl/aotus/src/c5a20699579b/LuaFortran/lua_fif.f90">interface</a>:</p> <pre><code>function lua_tolstring(L, index, len) bind(c, name="lua_tolstring") use, intrinsic :: iso_c_binding type(c_ptr), value :: L integer(kind=c_int), value :: index integer(kind=c_size_t) :: len type(c_ptr) :: lua_tolstring end function lua_tolstring </code></pre> <p>Finally, here is an attempt to clarify how a c_ptr can be interpreted as a Fortran character string: Assume you got a c_ptr pointing to the string:</p> <pre><code>type(c_ptr) :: a_c_string </code></pre> <p>And the length of it is given by a len variable with the following type:</p> <pre><code>integer(kind=c_size_t) :: stringlen </code></pre> <p>You want to get this string in a pointer to a character string in Fortran:</p> <pre><code>character,pointer,dimension(:) :: string </code></pre> <p>So you do the mapping:</p> <pre><code>call c_f_pointer(a_c_string, string, [ stringlen ]) </code></pre>
9,717,852
How to pass object created in FXML Controller1 to Controller2 of inner FXML control
<p>I have a JavaFX 2.0 application, which consists of two FXML files, and two controllers for them + one &quot;main&quot; .java file.</p> <p>At the start time, FXML1 is initialized, like this:</p> <pre><code>public void start(Stage stage) throws Exception { stage.setTitle(&quot;Demo Jabber JavaFX Chat&quot;); Parent root = FXMLLoader.load(getClass().getResource(&quot;fxml_example.fxml&quot;), ResourceBundle.getBundle(&quot;fxmlexample.fxml_example&quot;)); Scene scene = new Scene(root, 226, 264); stage.setScene(scene); scene.getStylesheets().add(&quot;fxmlexample/fxmlstylesheet.css&quot;); stage.show(); } </code></pre> <p>Then, when a button from scene1 is clicked, in its event handler in Controller1 class, I change scene1 root, to show new gui-view for a user. And in this controller I initialize some object. For example, like this:</p> <pre><code>public class FXMLExampleController { //some fields... private MySuperObject c; @FXML protected void handleSubmitButtonAction(ActionEvent event) { //some fields... c = new MySuperObject(); //here i initialize my object, i'm interested in try { c.login(username, password); // some actions with this object, which i need to make. Scene cc = buttonStatusText.getScene(); Parent root = null; try { //changing a scene content... root = FXMLLoader.load(getClass().getResource(&quot;fxml_example2.fxml&quot;), ResourceBundle.getBundle(&quot;fxmlexample.fxml_example&quot;)); } catch (IOException ex) { Logger.getLogger(FXMLExampleController.class.getName()).log(Level.SEVERE, null, ex); } cc.setRoot(root); } </code></pre> <p>And, after that, I have to do some work with that object on the next scene, and it must be NOT a new instance of the same class, but the object which I have initialized on the first one scene.</p> <p>I understand how to make these all using &quot;standard java&quot;, but I'm kind of confused on this task using JavaFX + FXML.</p>
10,718,683
2
0
null
2012-03-15 10:27:18.527 UTC
12
2020-11-17 06:09:18.59 UTC
2020-11-17 06:09:18.59 UTC
null
4,076,315
null
1,267,404
null
1
15
javafx-2|fxml
28,832
<p>In FX 2.2 new API for controller-node was introduced:</p> <pre><code>// create class which is both controller and node public class InnerFxmlControl extends HBox implements Initializable { @FXML public ComboBox cb; public InnerFxmlControl () { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml_example2.fxml")); fxmlLoader.setRoot(this); fxmlLoader.setController(this); try { fxmlLoader.load(); } catch (IOException exception) { throw new RuntimeException(exception); } } </code></pre> <p>with next fxml (note tag <code>fx:root</code>):</p> <pre><code>&lt;fx:root type="javafx.scene.layout.HBox" xmlns:fx="http://javafx.com/fxml"&gt; &lt;children&gt; &lt;ComboBox fx:id="cb" /&gt; &lt;/children&gt; &lt;/fx:root&gt; </code></pre> <p>By this you've created a new control, which you can use as regular JavaFX controls. E.g. in your case:</p> <pre><code>@FXML protected void handleSubmitButtonAction(ActionEvent event) { // you just create new control, all fxml tricks are encapsulated InnerFxmlControl root = new InnerFxmlControl(); // and you can access all its' methods and fields including matched by @FXML tag: root.cb.getItems().add("new item"); Scene cc = buttonStatusText.getScene(); cc.setRoot(root); } </code></pre> <p>and in fxml:</p> <pre><code>&lt;InnerFxmlControl /&gt; </code></pre>
9,656,362
Div horizontally center and vertically middle
<p>I want to align a div horizontally center and vertically middle of the <code>body</code> of a page.</p> <p>The css:</p> <pre><code>.loginBody { width: 100%; height: 100%; margin: 0; padding: 0; background: #999; /* for non-css3 browsers */ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#000000'); /* for IE */ background: -webkit-gradient(linear, left top, left bottom, from(#ccc), to(#000)); /* for webkit browsers */ background: -moz-linear-gradient(top, #ccc, #000); /* for firefox 3.6+ */ } .loginDiv { position: absolute; left: 35%; top: 35%; text-align: center; background-image: url('Images/loginBox.png'); width:546px; height:265px; } </code></pre> <p>And I have this html:</p> <pre><code>&lt;body class="loginBody"&gt; &lt;form id="form1"&gt; &lt;div class="loginDiv"&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p>Now it is behaving as I want it to, but if I resize the browser, it became completely distorted, perhaps this is because the absolute positioning. I am showing some of the screenshots: in resized firefox: <img src="https://i.stack.imgur.com/cffpL.png" alt="enter image description here"></p> <p>in resized chrome: <img src="https://i.stack.imgur.com/jPSsl.png" alt="enter image description here"></p> <p>in resized ie: <img src="https://i.stack.imgur.com/srf4I.png" alt="enter image description here"></p> <p>in maximized window it is: <img src="https://i.stack.imgur.com/IlnsO.png" alt="enter image description here"></p> <p>Is there any way to solve this problem and achieve this centered alignment using relative positioning? </p> <p>Thanks.</p> <hr> <p>Edit:</p> <p>In firefox no scrollbar appears while resizing but it appears in other browsers. <img src="https://i.stack.imgur.com/1K4Or.png" alt="enter image description here"></p>
9,656,391
3
0
null
2012-03-11 15:43:03.497 UTC
5
2020-02-13 10:31:29.407 UTC
2012-03-11 15:53:53.023 UTC
null
576,758
null
576,758
null
1
18
html|css|vertical-alignment|alignment
59,751
<p>Try this:</p> <pre class="lang-css prettyprint-override"><code>.loginDiv { position: absolute; left: 50%; top: 50%; text-align: center; background-image: url('Images/loginBox.png'); width:546px; height:265px; margin-left: -273px; /*half width*/ margin-top: -132px; /*half height*/ } </code></pre> <p>You move it to the center, and than back left and up by half the dimensions - that will center it even on resize</p>
10,001,310
Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc
<p>I've looked at similar questions on SO, but nothing quite matches my issue as far as I can tell.</p> <p>The exception message:</p> <blockquote> <p>Could not load file or assembly 'CrystalDecisions.ReportAppServer.ClientDoc, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The system cannot find the file specified.</p> </blockquote> <p>The file is in my GAC. I am developing on a 32 bit machine (Windows 7) running VS2010, everything is .NET4. The target hosting machine is 64-bit Win 2008 R2. My local machine has the CR installation for VS2010; the hosting machine has the 64-bit runtimes for VS2010. I am compiling all my code in "Any CPU" mode for this web application.</p> <p>It is blowing my mind that it cannot find the file in the GAC. This is an IIS application; is there some sort of permissions issue? I would think IIS would have access to the GAC.</p> <p>Some suggestions of what to do would be appreciated.</p>
10,013,181
4
2
null
2012-04-03 21:00:20.237 UTC
1
2017-06-06 20:29:34 UTC
2012-04-03 21:01:08.43 UTC
null
732,284
null
610,217
null
1
23
c#|asp.net-mvc|crystal-reports
134,438
<p>It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.</p> <p>In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.</p> <p>It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.</p>
10,031,929
What are the pros and cons of writing C#/XAML vs. C++/XAML WinRT applications in Windows8?
<p>I'd like to go down the route of porting a WPF/Silverlight component to Windows 8. For a bit of context, the component is a <a href="http://www.scichart.com" rel="noreferrer">real-time WPF Chart</a>, which uses a mixture of WPF/XAML and bitmap rendering to achieve high performance. </p> <p>I'd like the component to be Metro compatible, e.g. used in metro mode as well as desktop mode. I read a lot about creating <a href="http://www.codeproject.com/Articles/262151/Visual-Cplusplus-and-WinRT-Metro-Some-fundamentals" rel="noreferrer">C++/WinRT</a> applications in Windows 8 as well as <a href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/br229571.aspx" rel="noreferrer">C#/XAML</a> applications, but what are the differences between the two frameworks? </p> <p>Are there limitations if you choose C#/XAML over C++/XAML? Also consider the porting from C#/Xaml in .NET4.0 to Windows8 would be far easier if I could stick to C#/XAML, however will I be able to create a fully featured Metro component using this method? </p> <p>Your comments/suggestions appreciated. </p> <p><strong>Edit:</strong> </p> <p>If you're voting to close this thread, please post a comment why. Its a valid question, has +6 votes, four answers and one favourite. Seems reasonable to keep it to me!</p>
10,035,507
4
5
null
2012-04-05 15:57:35.273 UTC
13
2015-03-25 02:07:07.883 UTC
2015-03-25 02:07:07.883 UTC
null
918,624
null
303,612
null
1
34
c#|c++|xaml|windows-8|microsoft-metro
11,470
<p>I see the difference as a design choice, than a personal preference of language. Preference would be more related to VB vs C#. And generally it's the same differences you get in any application where you choose C++ or .NET.</p> <p>C++ will give you faster startup times. IIRC, .NET 4.5 has auto NGENing abilities (not sure how it related to metro apps), so this may help mitigate typical slow startup times of .NET applications.</p> <p>C++ will give you lower general memory usage as it does not use a garbage collector. This becomes increasingly more important on resource constrained devices such as tablets. IIRC, .NET 4.5 has more mitigations into GC pauses (which can cause the UI to studder), they are still a reality with managed code.</p> <p>Since .NET and C++ use the same WinRT framework, there probably won't be too much difference in interacting with the XAML/WinRT platform (technically faster interacting with WinRT objects via C++ but the hit is really small), but of course your user code will generally be faster with C++ than .NET. </p> <p>C++ is generally more difficult to reverse engineer, even when compared with obfuscated .NET code. Though sly thieves can steal your IP regardless.</p> <p>Since .NET was created first for the convenience of the developer and developer productivity, you will have more convenience options in architecting your applications (eg, reflection based tools such as DI/IoC).</p> <p>Iterating application code may be easier via .NET as .NET compiles quicker than C++, but correctly created C++ projects this can be mitigated substantially.</p> <p>Pure .NET projects can support "Any CPU", which means your application can run on all supported WinRT platforms. C++ projects you will simply have to recompile to support ARM, x86/64. If you .NET application depends on a custom C++ component, you will have to compile for each architecture.</p> <p>Because WinRT was created from the ground up to support many languages, my suggestion to devs that arent comfortable with C++ is to stick with .NET but explore areas that benefit from C++. Microsoft has done a great job with the /CX projections and most C# devs should be able to find their way around. My suggestion to C++ devs is to stick with C++ and get all the benefits of C++.</p>
9,885,748
C# Select elements in list as List of string
<p>In C# i need to get all values of a particular property from an object list into list of string </p> <pre><code>List&lt;Employee&gt; emplist = new List&lt;Employee&gt;() { new Employee{ EID=10, Ename="John"}, new Employee{ EID=11, Ename="Adam"}, new Employee{ EID=12, Ename="Ram"} }; List&lt;string&gt; empnames = emplist.//get all Enames in 'emplist' object into list //using linq or list functions or IENumerable functions </code></pre> <p>I am familiar with the foreach method to extract the value but I want to know <strong>if \ how its possible use linq or IENumerable functions</strong> or some shorter code to extract values from the list object property values into a string object.</p> <p>My query is Similar to <a href="https://stackoverflow.com/questions/2616891/c-sharp-select-elements-from-ilist">C# select elements from IList</a> but i want the the result as list of string</p>
9,885,766
2
0
null
2012-03-27 08:22:13.277 UTC
8
2021-09-13 12:31:42.667 UTC
2017-05-23 11:54:34.61 UTC
null
-1
null
193,061
null
1
45
c#|linq
163,103
<pre><code>List&lt;string&gt; empnames = emplist.Select(e =&gt; e.Ename).ToList(); </code></pre> <p>This is an example of <a href="http://msdn.microsoft.com/en-us/library/bb738447.aspx">Projection in Linq</a>. Followed by a <code>ToList</code> to resolve the <code>IEnumerable&lt;string&gt;</code> into a <code>List&lt;string&gt;</code>.</p> <p>Alternatively in Linq syntax (head compiled):</p> <pre><code>var empnamesEnum = from emp in emplist select emp.Ename; List&lt;string&gt; empnames = empnamesEnum.ToList(); </code></pre> <p>Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).</p> <p>For example, you can project an enumerable of <code>Employee</code> to an enumerable of <code>Tuple&lt;int, string&gt;</code> like so:</p> <pre><code>var tuples = emplist.Select(e =&gt; new Tuple&lt;int, string&gt;(e.EID, e.Ename)); </code></pre>
9,737,352
What is the apply function in Scala?
<p>I never understood it from the contrived unmarshalling and verbing nouns ( an <code>AddTwo</code> class has an <code>apply</code> that adds two!) examples.</p> <p>I understand that it's syntactic sugar, so (I deduced from context) it must have been designed to make some code more intuitive.</p> <p>What meaning does a class with an <code>apply</code> function give? What is it used for, and what purposes does it make code better (unmarshalling, verbing nouns etc)?</p> <p>how does it help when used in a companion object?</p>
9,738,862
7
5
null
2012-03-16 12:36:39.217 UTC
150
2022-07-07 06:37:26.023 UTC
null
null
null
null
604,511
null
1
353
scala
145,783
<p>Mathematicians have their own little funny ways, so instead of saying "then we call function <code>f</code> passing it <code>x</code> as a parameter" as we programmers would say, they talk about "applying function <code>f</code> to its argument <code>x</code>". </p> <blockquote> <p>In mathematics and computer science, Apply is a function that applies functions to arguments.<br> <em><a href="http://en.wikipedia.org/wiki/Apply" rel="noreferrer"> Wikipedia</a></em></p> </blockquote> <p><code>apply</code> serves the purpose of closing the gap between Object-Oriented and Functional paradigms in Scala. Every function in Scala can be represented as an object. Every function also has an OO type: for instance, a function that takes an <code>Int</code> parameter and returns an <code>Int</code> will have OO type of <code>Function1[Int,Int]</code>.</p> <pre><code> // define a function in scala (x:Int) =&gt; x + 1 // assign an object representing the function to a variable val f = (x:Int) =&gt; x + 1 </code></pre> <p>Since everything is an object in Scala <code>f</code> can now be treated as a reference to <code>Function1[Int,Int]</code> object. For example, we can call <code>toString</code> method inherited from <code>Any</code>, that would have been impossible for a pure function, because functions don't have methods:</p> <pre><code> f.toString </code></pre> <p>Or we could define another <code>Function1[Int,Int]</code> object by calling <code>compose</code> method on <code>f</code> and chaining two different functions together:</p> <pre><code> val f2 = f.compose((x:Int) =&gt; x - 1) </code></pre> <p>Now if we want to actually execute the function, or as mathematician say "apply a function to its arguments" we would call the <code>apply</code> method on the <code>Function1[Int,Int]</code> object:</p> <pre><code> f2.apply(2) </code></pre> <p>Writing <code>f.apply(args)</code> every time you want to execute a function represented as an object is the Object-Oriented way, but would add a lot of clutter to the code without adding much additional information and it would be nice to be able to use more standard notation, such as <code>f(args)</code>. That's where Scala compiler steps in and whenever we have a reference <code>f</code> to a function object and write <code>f (args)</code> to apply arguments to the represented function the compiler silently expands <code>f (args)</code> to the object method call <code>f.apply (args)</code>.</p> <p>Every function in Scala can be treated as an object and it works the other way too - every object can be treated as a function, provided it has the <code>apply</code> method. Such objects can be used in the function notation:</p> <pre><code>// we will be able to use this object as a function, as well as an object object Foo { var y = 5 def apply (x: Int) = x + y } Foo (1) // using Foo object in function notation </code></pre> <p>There are many usage cases when we would want to treat an object as a function. The most common scenario is a <a href="http://en.wikipedia.org/wiki/Factory_method_pattern" rel="noreferrer">factory pattern</a>. Instead of adding clutter to the code using a factory method we can <code>apply</code> object to a set of arguments to create a new instance of an associated class:</p> <pre><code>List(1,2,3) // same as List.apply(1,2,3) but less clutter, functional notation // the way the factory method invocation would have looked // in other languages with OO notation - needless clutter List.instanceOf(1,2,3) </code></pre> <p>So <code>apply</code> method is just a handy way of closing the gap between functions and objects in Scala.</p>
9,831,594
Apache and Node.js on the Same Server
<p>I want to use Node because it's swift, uses the same language I am using on the client side, and it's non-blocking by definition. But the guy who I hired to write the program for file handling (saving, editing, renaming, downloading, uploading files, etc.), he wants to use apache. So, I must:</p> <ol> <li><p>Convince him to use Node (he's giving up little ground on that)</p></li> <li><p>Figure out how to upload, download, rename, save, etc. files in node or</p></li> <li><p>I must install apache and node on the same server.</p></li> </ol> <p>Which is the most favorable situation, and how do I implement that?</p>
18,604,082
10
0
null
2012-03-22 22:37:41.353 UTC
325
2021-03-31 22:07:14.843 UTC
2015-10-08 16:20:25.3 UTC
null
542,517
null
1,024,501
null
1
392
apache|node.js
278,275
<p><strong>Great question!</strong></p> <p>There are many websites and free web apps implemented in PHP that run on Apache, lots of people use it so you can mash up something pretty easy and besides, its a no-brainer way of serving static content. Node is fast, powerful, elegant, and a sexy tool with the raw power of V8 and a flat stack with no in-built dependencies. </p> <p>I also want the ease/flexibility of Apache and yet the grunt and elegance of Node.JS, <em>why can't I have both</em>?</p> <p>Fortunately with the <a href="http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypass" rel="noreferrer">ProxyPass</a> directive in the Apache <code>httpd.conf</code> its not too hard to pipe all requests on a particular URL to your Node.JS application.</p> <pre><code>ProxyPass /node http://localhost:8000 </code></pre> <p>Also, make sure the following lines are NOT commented out so you get the right proxy and submodule to reroute http requests:</p> <pre><code>LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so </code></pre> <p>Then run your Node app on port 8000!</p> <pre><code>var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Apache!\n'); }).listen(8000, '127.0.0.1'); </code></pre> <p>Then you can access all Node.JS logic using the <code>/node/</code> path on your url, the rest of the website can be left to Apache to host your existing PHP pages:</p> <p><img src="https://i.stack.imgur.com/xmjco.png" alt="enter image description here"></p> <p>Now the only thing left is convincing your hosting company let your run with this configuration!!!</p>
8,143,370
document.getElementById("…").className = "…"; Not working in IE
<p>I created a business generator here: <a href="http://minespress.net/web_apps/business-cards/" rel="nofollow">http://minespress.net/web_apps/business-cards/</a></p> <p>I created a preview pane using <code>document.getElementById("…").className = "…";</code> which switches the background image onClick (of the thumbnail) and also moves around the text divs depending on the design of the business card. This works flawlessly in FF, Chrome and Safari. When I tried it in IE nothing happened onClick. </p> <p>I should also mention that my thumbs are radio buttons that need to change the form action based whether or not they are checked. Once again works fine in other browsers besides IE. Is there some IE bug or am I just doing something completely wrong? </p> <p>Here is an example of my code:</p> <pre><code>&lt;input style="display:none" checked="checked" name="group1" id="2" value='http://minespress.net/web_apps/business-cards/img/twinkle-blue.jpg' type="radio" onclick="document.getElementById('card').className ='Default'; document.getElementById('compname').className ='', document.getElementById('slogan').className ='', document.getElementById('leftinfo').className ='', document.getElementById('rightinfo').className =''" /&gt; </code></pre>
8,154,525
3
0
null
2011-11-15 21:28:27.91 UTC
null
2011-11-16 15:51:51.73 UTC
2011-11-15 21:39:38.99 UTC
null
416,224
null
1,048,476
null
1
2
javascript|internet-explorer|getelementbyid|classname
47,236
<p>IE 8 does not support images as labels for input fields. This is why my radio buttons do not work. Now I just need to figure out how to work around this. </p>
8,064,937
What is the best opensource dbf driver for java?
<p>Can anybody please mention the best available opensource odbc:jdbc driver to read / write dbf.? I have a dbf file which I would like to query (select/update) via a web application (Tomcat app).</p> <p>Any help/tips would be appreciative.</p> <p>Thank you.</p>
8,079,987
3
2
null
2011-11-09 12:20:30.847 UTC
11
2013-04-25 13:37:54.253 UTC
null
null
null
null
559,944
null
1
20
java|dbf|jdbc-odbc
31,318
<pre><code>try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String connString="jdbc:odbc:Driver={Microsoft dBASE Driver (*.dbf)};DefaultDir=E:\\db";//DeafultDir indicates the location of the db Connection connection=DriverManager.getConnection(connString); String sql="SELECT * FROM table_name where condition";// usual sql query Statement stmt=connection.createStatement(); ResultSet resultSet=stmt.executeQuery(sql); while(resultSet.next()) { System.out.println(); } System.out.println(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } </code></pre> <p>It works. And I guess there will be no need to explore for other (open/closed) apis as Java has provided an excellent way to read/write dbf.</p> <p>Thank you all.</p>
11,813,720
Search for a string in a Worksheet using VBA
<p>I am trying to search for a particular string "ERROR" in all the worksheets in the workbook and make it bold and color the found cell red.</p> <p>I am able to parse through each worksheet. I am not able to use the <code>Find</code> function of VBA.</p>
11,813,968
3
5
null
2012-08-05 03:29:00.17 UTC
2
2019-11-19 07:50:13.303 UTC
2019-11-19 07:50:13.303 UTC
null
-1
null
276,859
null
1
4
excel|vba
59,883
<p>Here's an example of using <code>Find</code> and formatting the found cells</p> <pre><code>Sub FindERROR() Dim SearchString As String Dim SearchRange As Range, cl As Range Dim FirstFound As String Dim sh As Worksheet ' Set Search value SearchString = "ERROR" Application.FindFormat.Clear ' loop through all sheets For Each sh In ActiveWorkbook.Worksheets ' Find first instance on sheet Set cl = sh.Cells.Find(What:=SearchString, _ After:=sh.Cells(1, 1), _ LookIn:=xlValues, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False) If Not cl Is Nothing Then ' if found, remember location FirstFound = cl.Address ' format found cell Do cl.Font.Bold = True cl.Interior.ColorIndex = 3 ' find next instance Set cl = sh.Cells.FindNext(After:=cl) ' repeat until back where we started Loop Until FirstFound = cl.Address End If Next End Sub </code></pre>
11,606,504
Registering beans(prototype) at runtime in Spring
<p>Just need something evaluated by the community. Following is a snippet of code, which is a simple factory that creates instances of a particular type. The method will register the bean in the context as a prototype and return the instance. This is the first time I am configuring beans at run time. Could you kindly evaluate and provide feedback? thank you in advance.</p> <pre><code>package au.com.flexcontacts.flexoperations; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.support.AbstractApplicationContext; import au.com.flexcontacts.exceptions.SyncClassCreactionError; /** * @author khushroo.mistry * Class purpose: Simple Factory to create an * instance of SynchroniseContactsService and register it in the Spring IoC. */ public final class FLEXSyncFactory implements ApplicationContextAware { private static AbstractApplicationContext context; /** * @param username * @param password * @param syncType * @return the correct service class * @throws SyncClassCreactionError * The method registers the classes dynamically into the Spring IoC */ public final SynchroniseContactsService createSyncService(String username, String password, SyncType syncType) throws SyncClassCreactionError { DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory(); try { //Register the bean in the IoC BeanDefinition bdb = new GenericBeanDefinition(); bdb.setBeanClassName(syncType.getClassName()); bdb.setScope("prototype"); ConstructorArgumentValues constructor = bdb.getConstructorArgumentValues(); constructor.addIndexedArgumentValue(0, username); constructor.addIndexedArgumentValue(1, password); beanFactory.registerBeanDefinition(syncType.getInstanceName(), bdb); //Return instance of bean return (SynchroniseContactsService) beanFactory.getBean(syncType.getInstanceName()); } catch (Exception e) { e.printStackTrace(); throw new SyncClassCreactionError("Error: Illegal Handler"); } } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = (AbstractApplicationContext) applicationContext; } } </code></pre> <p>FLEX Sync factory has been configured in the IoC container as a singleton. So to create a new sync manager I do the following:</p> <pre><code>flexSyncFactory.createSyncService(userName, password, SyncType.FULL); </code></pre> <p>I am using Spring 3.1. Please review and provide your valuable feedback.</p> <p>kind regards.</p>
11,751,503
3
0
null
2012-07-23 04:28:06.927 UTC
15
2016-05-20 14:21:33.613 UTC
2016-05-20 14:21:33.613 UTC
null
960,875
null
765,908
null
1
21
java|spring|spring-mvc|dependency-injection
49,839
<p>This is purely my opinion, not an expert view:</p> <p>Spring provides two mechanisms for custom modification of an application context - using <a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/beans/factory/config/BeanFactoryPostProcessor.html" rel="noreferrer">BeanFactoryPostProcessor</a> which allows for modification of existing bean definitions or adding new bean definitions, and <a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/beans/factory/config/BeanPostProcessor.html" rel="noreferrer">BeanPostProcessors</a> which allows for modification of bean instances(wrapping them around proxy etc). </p> <p>Spring does not provide any other native way to dynamically add bean definitions or bean instances at runtime, but like you have done by getting hold of the underlying bean factory instances and adding in bean definitions is one way to go. It works, but there are risks:</p> <ul> <li><p>What happens if you overwrite an existing bean name with a new type, how are places where this bean is already injected handled. Also, what happens if a existing bean name is overwritten with a totally different type!</p></li> <li><p>This newly registered bean will not have any fields autowired in, and will not be injected into other beans also - so essentially the bean factory is purely acting as a registry for holding the bean, not really a dependency injection functionality!</p></li> <li><p>if a <code>refresh()</code> is called on the application context then the backing bean factory will be overwritten and a new one created, thus any bean instances registered against the bean factory directly will be lost.</p></li> </ul> <p>If the objective is purely to create beans which has been autowired by Spring, I would go for something like <a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/beans/factory/annotation/Configurable.html" rel="noreferrer">@Configurable</a>. If the risks above are acceptable also your approach should work. </p>
11,477,145
Open Source Neural Network Library
<p>I am looking for an open source neural network library. So far, I have looked at FANN, WEKA, and OpenNN. Are the others that I should look at? The criteria, of course, is documentation, examples, and ease of use. </p>
11,477,815
4
3
null
2012-07-13 19:32:11.557 UTC
38
2020-04-01 21:41:52.427 UTC
2014-08-31 18:12:41.203 UTC
null
-1
null
1,299,585
null
1
64
machine-learning|artificial-intelligence|neural-network
54,156
<p><strong>Last update: 2020/03/24</strong> (I will update this answer from time to time...)</p> <h1>Simple Implementations of Neural Networks</h1> <ul> <li><a href="http://leenissen.dk/fann/wp/" rel="nofollow noreferrer">FANN</a> is a very popular implementation in C/C++ and has bindings for many other languages.</li> <li>In scikit-learn (Python) 0.18 (current developement version) there will be an implementation of feed-forward neural networks (<a href="http://scikit-learn.org/dev/modules/classes.html#module-sklearn.neural_network" rel="nofollow noreferrer">API documentation</a>).</li> <li>And I must mention my own project, which is called <a href="https://github.com/OpenANN/OpenANN" rel="nofollow noreferrer">OpenANN</a> (<a href="http://openann.github.io/OpenANN-apidoc/" rel="nofollow noreferrer">Documentation</a>). It is written in C++ and has Python bindings.</li> </ul> <h1>Deep Learning</h1> <p>Because neural networks are quite popular in research and industry at the moment ("deep learning") there are many research libraries available. Most of them are kind of easy to set up, integrate, and use. Although not as easy as the libraries mentioned above. They provide leading edge functionality and high performance (with GPUs etc.). Most of these libraries also have automatic differentiation. You can easily specify new architectures, loss functions etc. and don't have to specify the backpropagation manually.</p> <ul> <li><a href="https://github.com/tensorflow/tensorflow" rel="nofollow noreferrer">TensorFlow</a> from Google (C++/Python)</li> <li><a href="http://pytorch.org/" rel="nofollow noreferrer">PyTorch</a> from Facebook, in Python, can be extended with C/C++</li> <li><a href="https://github.com/dmlc/mxnet" rel="nofollow noreferrer">mxnet</a> (C++, Python, R, Scala, Julia, Matlab, Javascript)</li> <li><a href="http://deeplearning4j.org/" rel="nofollow noreferrer">Deeplearning4j</a> (Java)</li> <li><a href="https://github.com/Microsoft/CNTK" rel="nofollow noreferrer">CNTK</a> from Microsoft (training in Python / evaluation in C++/C#/Java/Python)</li> <li><a href="https://github.com/pfnet/chainer" rel="nofollow noreferrer">Chainer</a> (Python)</li> <li><a href="https://github.com/baidu/Paddle" rel="nofollow noreferrer">PaddlePaddle</a> from Baidu in CUDA/C++ with Python bindings</li> <li><a href="https://github.com/sony/nnabla" rel="nofollow noreferrer">NNabla</a> from Sony in Cuda/C++11 with Python bindings</li> </ul> <p>A performance comparison for GPU-accelerated libraries can be found <a href="https://github.com/soumith/convnet-benchmarks" rel="nofollow noreferrer">here</a> (a bit outdated unfortunately). A comparison of GPUs and library versions can be found <a href="https://github.com/jcjohnson/cnn-benchmarks" rel="nofollow noreferrer">here</a>.</p> <p>Inactive:</p> <ul> <li><a href="https://github.com/fchollet/keras" rel="nofollow noreferrer">Keras</a>: It could use <a href="https://github.com/tensorflow/tensorflow" rel="nofollow noreferrer">Tensorflow</a>, <a href="http://deeplearning.net/software/theano/" rel="nofollow noreferrer">Theano</a>, and <a href="https://github.com/Microsoft/CNTK" rel="nofollow noreferrer">CNTK</a> as a backend. (Now part of tensorflow as its high-level interface.)</li> <li><a href="http://caffe.berkeleyvision.org/" rel="nofollow noreferrer">Caffe</a> from Berkeley Vision and Learning Center in C++ with Python bindings</li> <li><a href="https://github.com/pjreddie/darknet" rel="nofollow noreferrer">Darknet</a>: CNNs in C, known for the implementations of the YOLO object detector.</li> <li><a href="https://github.com/NervanaSystems/neon" rel="nofollow noreferrer">Neon</a> from Intel Nervana provides very efficient implementations (Python)</li> <li><a href="http://www.vlfeat.org/matconvnet/" rel="nofollow noreferrer">MatConvNet</a> (Matlab)</li> <li><a href="http://deeplearning.net/software/theano/" rel="nofollow noreferrer">Theano</a> (Python) and its high-level APIs: <ul> <li><a href="http://deeplearning.net/software/pylearn2/" rel="nofollow noreferrer">Pylearn 2</a></li> <li><a href="https://github.com/lmjohns3/theano-nets" rel="nofollow noreferrer">Theanets</a></li> <li><a href="https://github.com/aigamedev/scikit-neuralnetwork" rel="nofollow noreferrer">scikit-neuralnetwork</a></li> <li><a href="https://github.com/Lasagne/Lasagne" rel="nofollow noreferrer">Lasagne</a></li> <li><a href="http://blocks.readthedocs.org/en/latest/" rel="nofollow noreferrer">Blocks</a> based on Theano (Python)</li> </ul></li> <li><a href="https://github.com/akrizhevsky/cuda-convnet2" rel="nofollow noreferrer">cuda-convnet2</a> in CUDA/C++ with Python bindings</li> <li><a href="https://github.com/hannes-brt/hebel" rel="nofollow noreferrer">Hebel</a> (Python)</li> <li><a href="https://caffe2.ai/" rel="nofollow noreferrer">Caffe2</a> from Facebook in C++ with Python bindings; has been joined with PyTorch</li> <li><a href="https://github.com/torch/nn" rel="nofollow noreferrer">Neural Networks</a> for Torch 7 (Lua, Torch 7 is a "Matlab-like environment", <a href="https://github.com/torch/torch7/wiki/Cheatsheet#machine-learning" rel="nofollow noreferrer">overview of machine learning algorithms in Torch</a>)</li> <li><a href="http://pybrain.org/" rel="nofollow noreferrer">PyBrain</a> (Python) contains different types of neural networks and training methods.</li> <li><a href="http://www.heatonresearch.com/encog" rel="nofollow noreferrer">Encog</a> (Java and C#)</li> </ul>
11,969,208
Non-Generic TaskCompletionSource or alternative
<p>I'm working with an alert window (Telerik WPF) that is normally displayed asynchronously ( code continues running while it is open) and I want to make it synchronous by using async/await.</p> <p>I have this working with <code>TaskCompletionSource</code> but that class is generic and returns an object like <code>Task&lt;bool&gt;</code> when all I want is a plain <code>Task</code> with no return value.</p> <pre><code>public Task&lt;bool&gt; ShowAlert(object message, string windowTitle) { var dialogParameters = new DialogParameters { Content = message }; var tcs = new TaskCompletionSource&lt;bool&gt;(); dialogParameters.Closed += (s, e) =&gt; tcs.TrySetResult(true); RadWindow.Alert(dialogParameters); return tcs.Task; } </code></pre> <p>The code that calls that method is</p> <pre><code>await MessageBoxService.ShowAlert("The alert text.") </code></pre> <p>How can I return a non-generic Task that functions similarly which I can await until the <code>dialogParameters.Closed</code> event fires? I understand that I could just ignore the <code>bool</code> that is being returned in this code. I am looking for a different solution than that.</p>
11,969,255
5
0
null
2012-08-15 12:24:28.71 UTC
6
2020-08-12 08:20:07.623 UTC
2016-06-01 18:45:40.267 UTC
null
713,428
null
713,428
null
1
85
c#|.net|async-await
28,227
<p>The method can be changed to:</p> <pre><code>public Task ShowAlert(object message, string windowTitle) </code></pre> <p><code>Task&lt;bool&gt;</code> inherits from <code>Task</code> so you can return <code>Task&lt;bool&gt;</code> while only exposing <code>Task</code> to the caller</p> <p><strong>Edit:</strong></p> <p>I found a Microsoft document, <a href="http://www.microsoft.com/en-us/download/details.aspx?id=19957" rel="noreferrer">http://www.microsoft.com/en-us/download/details.aspx?id=19957</a>, by Stephen Toub titled 'The Task-based Asynchronous pattern' and it has the following excerpt that recommends this same pattern.</p> <blockquote> <p>There is no non-generic counterpart to TaskCompletionSource&lt;TResult>. However, Task&lt;TResult> derives from Task, and thus the generic TaskCompletionSource&lt;TResult> can be used for I/O-bound methods that simply return a Task by utilizing a source with a dummy TResult (Boolean is a good default choice, and if a developer is concerned about a consumer of the Task downcasting it to a Task&lt;TResult>, a private TResult type may be used)</p> </blockquote>
11,889,243
What is the best way to remove all subviews from you self.view?
<p>I was thinking maybe something like this might work:</p> <pre><code>for (UIView* b in self.view.subviews) { [b removeFromSuperview]; } </code></pre> <p>I want to remove every kind of subview. UIImages, Buttons, Textfields etc.</p>
11,889,296
5
7
null
2012-08-09 17:55:50.243 UTC
29
2022-01-12 09:20:04.337 UTC
2022-01-12 09:20:04.337 UTC
null
1,265,393
user440096
null
null
1
89
iphone|objective-c|ios|uikit
46,172
<pre><code>[self.view.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)]; </code></pre> <p>It's identical to your variant, but slightly shorter.</p>
3,294,027
Crystal Reports - Suppress a Page Header if the page has 0 records
<p>I'd like to suppress a page header if the page has no data records.</p> <p><strong>Notes</strong></p> <ul> <li>The page may still need to display in order to show the group or report footers.</li> <li>I'm interested in the case where there are no records for the details section of the report for the current page. I'm referring to a situation where all details records have been displayed for a group, but the group footer wraps to the next page.</li> </ul>
3,307,962
5
3
null
2010-07-20 20:20:54.92 UTC
2
2019-11-18 15:52:50.35 UTC
2012-05-11 17:31:47.447 UTC
null
127,880
null
127,880
null
1
7
crystal-reports
42,551
<p>Assuming you have Keep Together checked for the group footer, try entering the following in the conditional suppress formula for the page header section in the section expert:</p> <pre><code>OnLastRecord or {GROUP FIELD NAME} &lt;&gt; Next({GROUP FIELD NAME}) </code></pre> <p>where {GROUP FIELD NAME} is the name of the grouping field.</p> <p>OnLastRecord <strong>must</strong> come first in the formula, because if the last page of the report has no detail records (so that the page header should be suppressed), then Next({GROUP FIELD NAME}) evaluates as NULL and all conditions that come after it are also evaluated as NULL.</p>
3,441,396
Defining custom attrs
<p>I need to implement my own attributes like in <code>com.android.R.attr</code></p> <p>Found nothing in official documentation so I need information about how to define these attrs and how to use them from my code.</p>
3,441,986
6
3
null
2010-08-09 15:08:49.403 UTC
314
2022-06-15 02:16:07.37 UTC
2017-02-11 09:25:17.403 UTC
null
3,681,880
null
218,783
null
1
517
android|android-resources|android-attributes
293,534
<p>Currently the best documentation is the source. You can take a look at it <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/attrs.xml" rel="noreferrer">here (attrs.xml)</a>. </p> <p>You can define attributes in the top <code>&lt;resources&gt;</code> element or inside of a <code>&lt;declare-styleable&gt;</code> element. If I'm going to use an attr in more than one place I put it in the root element. Note, all attributes share the same global namespace. That means that even if you create a new attribute inside of a <code>&lt;declare-styleable&gt;</code> element it can be used outside of it and you cannot create another attribute with the same name of a different type.</p> <p>An <code>&lt;attr&gt;</code> element has two xml attributes <code>name</code> and <code>format</code>. <code>name</code> lets you call it something and this is how you end up referring to it in code, e.g., <code>R.attr.my_attribute</code>. The <code>format</code> attribute can have different values depending on the 'type' of attribute you want. </p> <ul> <li>reference - if it references another resource id (e.g, "@color/my_color", "@layout/my_layout")</li> <li>color</li> <li>boolean</li> <li>dimension</li> <li>float</li> <li>integer</li> <li>string</li> <li>fraction</li> <li>enum - normally implicitly defined</li> <li>flag - normally implicitly defined</li> </ul> <p>You can set the format to multiple types by using <code>|</code>, e.g., <code>format="reference|color"</code>.</p> <p><code>enum</code> attributes can be defined as follows:</p> <pre><code>&lt;attr name="my_enum_attr"&gt; &lt;enum name="value1" value="1" /&gt; &lt;enum name="value2" value="2" /&gt; &lt;/attr&gt; </code></pre> <p><code>flag</code> attributes are similar except the values need to be defined so they can be bit ored together:</p> <pre><code>&lt;attr name="my_flag_attr"&gt; &lt;flag name="fuzzy" value="0x01" /&gt; &lt;flag name="cold" value="0x02" /&gt; &lt;/attr&gt; </code></pre> <p>In addition to attributes there is the <code>&lt;declare-styleable&gt;</code> element. This allows you to define attributes a custom view can use. You do this by specifying an <code>&lt;attr&gt;</code> element, if it was previously defined you do not specify the <code>format</code>. If you wish to reuse an android attr, for example, android:gravity, then you can do that in the <code>name</code>, as follows.</p> <p>An example of a custom view <code>&lt;declare-styleable&gt;</code>:</p> <pre><code>&lt;declare-styleable name="MyCustomView"&gt; &lt;attr name="my_custom_attribute" /&gt; &lt;attr name="android:gravity" /&gt; &lt;/declare-styleable&gt; </code></pre> <p>When defining your custom attributes in XML on your custom view you need to do a few things. First you must declare a namespace to find your attributes. You do this on the root layout element. Normally there is only <code>xmlns:android="http://schemas.android.com/apk/res/android"</code>. You must now also add <code>xmlns:whatever="http://schemas.android.com/apk/res-auto"</code>.</p> <p>Example:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:whatever="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;org.example.mypackage.MyCustomView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" whatever:my_custom_attribute="Hello, world!" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>Finally, to access that custom attribute you normally do so in the constructor of your custom view as follows.</p> <pre><code>public MyCustomView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0); String str = a.getString(R.styleable.MyCustomView_my_custom_attribute); //do something with str a.recycle(); } </code></pre> <p>The end. :)</p>
3,624,332
How do you remove all the alphabetic characters from a string?
<p>I have a string containg alphabetic characters, for example:</p> <ol> <li><strong>254.69 meters</strong></li> <li><strong>26.56 cm</strong></li> <li><strong>23.36 inches</strong></li> <li><strong>100.85 ft</strong></li> </ol> <p>I want to remove all the alphabetic characters (units) from the above mentioned strings so that I can call the <code>double.Parse()</code> method.</p>
3,624,357
6
0
null
2010-09-02 06:38:30.317 UTC
11
2020-06-07 13:32:19.903 UTC
2019-03-18 12:19:03.597 UTC
null
1,694,368
null
134,202
null
1
79
c#|.net
85,619
<p>This should work:</p> <pre><code>// add directive at the top using System.Text.RegularExpressions; string numberOnly = Regex.Replace(s, "[^0-9.]", "") </code></pre>
3,682,615
How to fix the session_register() deprecated issue?
<p>How to fix the <code>session_register()</code> deprecated problem in PHP 5.3</p>
3,682,629
7
0
null
2010-09-10 06:23:23.17 UTC
12
2019-12-28 02:26:43.947 UTC
2014-04-23 09:31:16.81 UTC
null
1,003,917
null
669,388
null
1
44
php|session|deprecated
196,937
<p>Don't use it. The description says:</p> <blockquote> <p>Register one or more global variables with the current session.</p> </blockquote> <p>Two things that came to my mind:</p> <ol> <li>Using global variables is not good anyway, find a way to avoid them.</li> <li>You can still set variables with <code>$_SESSION['var'] = "value"</code>.</li> </ol> <p>See also the warnings from the <a href="http://php.net/manual/en/function.session-register.php" rel="noreferrer">manual</a>:</p> <blockquote> <p>If you want your script to work regardless of <code>register_globals</code>, you need to instead use the <code>$_SESSION</code> array as <code>$_SESSION</code> entries are automatically registered. If your script uses <code>session_register()</code>, it will <strong>not</strong> work in environments where the PHP directive <code>register_globals</code> is disabled.</p> </blockquote> <p>This is pretty important, because the <code>register_globals</code> directive <a href="http://php.net/manual/en/ini.core.php" rel="noreferrer">is set to <code>False</code> by default!</a></p> <p>Further:</p> <blockquote> <p>This registers a <code>global</code> variable. If you want to register a session variable from within a <strong>function</strong>, you need to make sure to make it global using the <code>global</code> keyword or the <code>$GLOBALS[]</code> array, or use the special session arrays as noted below.</p> </blockquote> <p>and </p> <blockquote> <p>If you are using <code>$_SESSION</code> (or <code>$HTTP_SESSION_VARS</code>), do not use <code>session_register()</code>, <code>session_is_registered()</code>, and <code>session_unregister()</code>.</p> </blockquote>
3,822,745
Rename files to lowercase in Powershell
<p>I am trying to rename a bunch of files recursively using Powershell 2.0. The directory structure looks like this:</p> <pre><code>Leaflets + HTML - File1 - File2 ... + HTMLICONS + IMAGES - Image1 - Image2 - File1 - File2 ... + RTF - File1 - File2 ... + SGML - File1 - File2 ... </code></pre> <p>I am using the following command:</p> <pre><code>get-childitem Leaflets -recurse | rename -newname { $_.name.ToLower() } </code></pre> <p>and it seems to rename the files, but complains about the subdirectories:</p> <pre><code>Rename-Item : Source and destination path must be different. </code></pre> <p>I reload the data monthly using robocopy, but the directories do not change, so I can rename them by hand. Is there any way to get <code>get-children</code> to skip the subdirectories (like <code>find Leaflets -type f ...</code>)?</p> <p>Thanks.</p> <p><strong>UPDATE:</strong> It appears that the problem is with files that are already all lower case. I tried changing the command to:</p> <pre><code>get-childitem Leaflets -recurse | if ($_.name -ne $_name.ToLower()) rename -newname { $_.name.ToLower() } </code></pre> <p>but now Powershell complains that <code>if</code> is not a cmdlet, function, etc. Can I pipe the output of <code>get-childitem</code> to an <code>if</code> statement?</p> <p><strong>UPDATE 2</strong>: This works:</p> <pre><code>$files=get-childitem Leaflets -recurse foreach ($file in $files) { if ($file.name -ne $file.name.ToLower()) { rename -newname { $_.name.ToLower() } } } </code></pre>
3,823,567
8
1
null
2010-09-29 14:44:47.223 UTC
9
2022-01-03 20:53:28.25 UTC
2010-09-29 15:09:04.487 UTC
null
96,233
null
96,233
null
1
26
powershell|rename|recursive-descent
29,928
<p>Even though you have already posted your own answer, here is a variation:</p> <pre><code>dir Leaflets -r | % { if ($_.Name -cne $_.Name.ToLower()) { ren $_.FullName $_.Name.ToLower() } } </code></pre> <p>Some points:</p> <ul> <li><strong>dir</strong> is an alias for <strong>Get-ChildItem</strong> (and -r is short for -Recurse).</li> <li><strong>%</strong> is an alias for <strong>ForEach-Object</strong>.</li> <li><strong>-cne</strong> is a case-sensitive comparison. <strong>-ne</strong> ignores case differences.</li> <li><strong>$_</strong> is how you reference the current item in the ForEach-Object loop.</li> <li><strong>ren</strong> is an alias for <strong>Rename-Item</strong>.</li> <li><strong>FullName</strong> is probably preferred as it ensures you will be touching the right file.</li> </ul> <p>If you wanted to excludes directories from being renamed, you could include something like:</p> <pre><code>if ((! $_.IsPsContainer) -and $_.Name -cne $_.Name.ToLower()) { ... } </code></pre> <p>Hopefully this is helpful in continuing to learn and explore PowerShell.</p>
3,395,359
Difference between SRC and HREF
<p>The <code>SRC</code> and <code>HREF</code> attributes are used to include some external entities like an image, a CSS file, a HTML file, any other web page or a JavaScript file.</p> <p>Is there a clear differentiation between <code>SRC</code> and <code>HREF</code>? Where or when to use <code>SRC</code> or <code>HREF</code>? I think they can't be used interchangeably.</p> <p>I'm giving below few examples where these attributes are used:</p> <ul> <li>To refer a CSS file: <code>href="cssfile.css"</code> inside the link tag.</li> <li>To refer a JS file: <code>src="myscript.js"</code> inside the script tag.</li> <li>To refer an image file: <code>src="mypic.jpg"</code> inside an image tag.</li> <li>To refer another webpage: <code>href="http://www.webpage.com"</code> inside an anchor tag.</li> </ul>
7,794,936
15
2
null
2010-08-03 09:52:44.617 UTC
121
2021-12-23 18:44:27.153 UTC
2013-08-18 22:00:38.353 UTC
null
1,494,454
null
384,231
null
1
194
html
146,573
<p><strong>NOTE:</strong> @John-Yin's <a href="https://stackoverflow.com/a/21549827/69310">answer</a> is more appropriate considering the changes in the specs.</p> <hr /> <p>Yes. There is a differentiation between <strong>src</strong> and <strong>href</strong> and they can't be used interchangeably. We use <strong>src</strong> for <em><a href="https://web.archive.org/web/20160526203403/http://reference.sitepoint.com/css/replacedelements" rel="nofollow noreferrer">replaced</a></em> elements while <strong>href</strong> for establishing a relationship between the referencing document and an external resource.</p> <p><strong>href</strong> (Hypertext Reference) attribute specifies the location of a Web resource thus defining a link or relationship between the current element (in case of anchor <code>a</code>) or current document (in case of <code>link</code>) and the destination anchor or resource defined by this attribute. When we write:</p> <pre><code>&lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot; /&gt; </code></pre> <p>The browser understands that this resource is a stylesheet and the <del>processing</del> parsing of the page is <strong>not</strong> paused (rendering might be paused since the browser needs the style rules to paint and render the page). It is <strong>not</strong> similar to dumping the contents of the css file inside the <code>style</code> tag. (Hence it is advisable to use <code>link</code> rather than <code>@import</code> for attaching stylesheets to your html document.)</p> <p><strong>src</strong> (Source) attribute just embeds the resource in the current document at the location of the element's definition. For eg. When the browser finds</p> <pre><code>&lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt; </code></pre> <p>The loading and processing of the page is paused until this the browser fetches, compiles and executes the file. It is similar to dumping the contents of the js file inside the <code>script</code> tag. Similar is the case with <code>img</code> tag. It is an empty tag and the content, that should come inside it, is defined by the <code>src</code> attribute. The browser pauses the loading until it fetches and loads the image. [so is the case with <code>iframe</code>]</p> <p>This is the reason why it is advisable to load all JavaScript files at the bottom (before the <code>&lt;/body&gt;</code> tag)</p> <hr /> <p><strong>update</strong> : Refer @John-Yin's <a href="https://stackoverflow.com/a/21549827/69310">answer</a> for more info on how it is implemented as per HTML 5 specs.</p>
3,218,910
Rename a file in C#
<p>How do I rename a file using C#?</p>
3,218,923
20
1
null
2010-07-10 11:05:54.027 UTC
78
2022-02-03 13:32:35.693 UTC
2013-01-23 10:02:17.843 UTC
null
238,902
null
43,907
null
1
744
c#|file|rename
728,609
<p>Take a look at <a href="http://msdn.microsoft.com/en-us/library/system.io.file.move.aspx" rel="noreferrer">System.IO.File.Move</a>, "move" the file to a new name.</p> <pre><code>System.IO.File.Move("oldfilename", "newfilename"); </code></pre>
8,283,714
What is the result of NULL + int?
<p>I have seen the following macro being used in OpenGL VBO implementations:</p> <pre><code>#define BUFFER_OFFSET(i) ((char *)NULL + (i)) //... glNormalPointer(GL_FLOAT, 32, BUFFER_OFFSET(x)); </code></pre> <p>Could you provide a little detail on how this macro works? Can it be replaced with a function? More exactly, what is the result of incrementing a NULL pointer?</p>
8,283,855
4
0
null
2011-11-27 04:49:12.187 UTC
19
2021-10-04 14:49:55.42 UTC
2011-11-27 05:16:45.35 UTC
null
598,465
null
598,465
null
1
22
c|opengl|pointers|null|pointer-arithmetic
6,147
<p>Let's take a trip back through the sordid history of OpenGL. Once upon a time, there was OpenGL 1.0. You used <code>glBegin</code> and <code>glEnd</code> to do drawing, and that was all. If you wanted fast drawing, you stuck things in a display list.</p> <p>Then, somebody had the bright idea to be able to just take arrays of objects to render with. And thus was born OpenGL 1.1, which brought us such functions as <code>glVertexPointer</code>. You might notice that this function ends in the word &quot;Pointer&quot;. That's because it takes pointers to actual memory, which will be accessed when one of the <code>glDraw*</code> suite of functions is called.</p> <p>Fast-forward a few more years. Now, graphics cards have the ability to perform vertex T&amp;L on their own (up until this point, fixed-function T&amp;L was done by the CPU). The most efficient way to do that would be to put vertex data in GPU memory, but display lists are not ideal for that. Those are too hidden, and there's no way to know whether you'll get good performance with them. Enter buffer objects.</p> <p>However, because the ARB had an absolute policy of making everything as backwards compatible as possible (no matter how silly it made the API look), they decided that the best way to implement this was to just use the same functions again. Only now, there's a global switch that changes <code>glVertexPointer</code>'s behavior from &quot;takes a pointer&quot; to &quot;takes a byte offset from a buffer object.&quot; That switch being whether or not a buffer object is bound to <code>GL_ARRAY_BUFFER</code>.</p> <p>Of course, as far as C/C++ is concerned, the function still takes a <em>pointer</em>. And the rules of C/C++ do not allow you to pass an integer as a pointer. Not without a cast. Which is why macros like <code>BUFFER_OBJECT</code> exist. It's one way to convert your integer byte offset into a pointer.</p> <p>The <code>(char *)NULL</code> part simply takes the NULL pointer (which is usually a <code>void*</code> in C and the literal 0 in C++) and turns it into a <code>char*</code>. The <code>+ i</code> just does pointer arithmetic on the <code>char*</code>. Because the null pointer usually has a zero address, adding <code>i</code> to it will increment the byte offset by <code>i</code>, thus generating a pointer who's value is the byte offset you passed in.</p> <p>Of course, the C++ specification lists the results of BUFFER_OBJECT as <em>undefined behavior</em>. By using it, you're really relying on the compiler to do something reasonable. After all, <code>NULL</code> does not <em>have</em> to be zero; all the specification says is that it is an implementation-defined null pointer constant. It doesn't have to have the value of zero at all. On most real systems, it will. But it doesn't <em>have</em> to.</p> <p>That's why I just use a cast.</p> <pre><code>glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, (void*)48); </code></pre> <p>It's not guaranteed behavior either way (int-&gt;ptr-&gt;int conversions are conditionally supported, not required). But it's also shorter than typing &quot;BUFFER_OFFSET&quot;. GCC and Visual Studio seem to find it reasonable. And it doesn't rely on the value of the NULL macro.</p> <p>Personally, if I were more C++ pedantic, I'd use a <code>reinterpret_cast&lt;void*&gt;</code> on it. But I'm not.</p> <p>Or you can ditch the old API and <a href="https://stackoverflow.com/q/37972229/734069">use <code>glVertexAttribFormat</code> et. al.</a>, which is better in every way.</p>
7,752,273
How to save a string to a .txt file in Delphi?
<p>I need to make a program that generates a password that is saved in a text file format in a specific destination I set and the user needs to open the .txt to get the password to 'unlock' another program. </p> <p>I have already got the code to generate the password in the string sPass and now I need to use the SaveToFile function to save it into the text file I created called Password.txt but I cannot find the general form to use the SaveTo File Function in Delphi and I do not know where to put the sPass and Password.txt in the function. </p> <p>It should be something like : SaveToFile(...) but I do not know how to save sPass in Password.txt</p> <p>Edit :</p> <p>Just one more question, how do you delete what is previously stored in Password.txt before you add the string to it so that Password.txt is blank before the string is added ? Thanks</p>
7,752,456
4
0
null
2011-10-13 09:47:48.733 UTC
6
2014-01-04 08:53:06.11 UTC
2011-10-13 10:44:43.173 UTC
null
993,150
null
993,150
null
1
24
string|delphi|delphi-7|text-files
79,077
<p>The modern way is to create a stringlist and save that to file.</p> <pre><code>procedure MakeAStringlistAndSaveThat; var MyText: TStringlist; begin MyText:= TStringlist.create; try MyText.Add('line 1'); MyText.Add('line 2'); MyText.SaveToFile('c:\folder\filename.txt'); finally MyText.Free end; {try} end; </code></pre> <p>Note that Delphi already has a related class that does everything you want: TInifile.<br> It stores values and keys in a <code>key = 'value'</code> format. </p> <pre><code>passwordlist:= TInifile.Create; try passwordlist.LoadFromFile('c:\folder\passwords.txt'); //Add or replace a password for `user1` passwordlist.WriteString('sectionname','user1','topsecretpassword'); passwordlist.SaveToFile('c:\folder\passwords.txt'); finally passwordlist.Free; end; {try} </code></pre> <p><strong>Warning</strong><br> Note that saving unecrypted passwords in a textfile is a security-leak. It's better to hash your passwords using a hashfunction, see: <a href="https://stackoverflow.com/questions/133393/password-encryption-in-delphi">Password encryption in Delphi</a><br> For tips on how to save passwords in a secure way. </p>
8,114,809
Tracking offline event with Google Analytics
<p>I tried to track user activity in my site such as click or mouse over and different kind of events.... Is there any solution to track events even when users are working offline... Can I store them in something like cookie and send them to the server when find active internet connection?</p> <p>Is that possible?</p> <p>Thank you</p>
8,114,887
5
0
null
2011-11-13 21:17:15.05 UTC
12
2016-08-30 08:14:38.16 UTC
2011-11-13 21:43:42.75 UTC
null
182,668
null
398,805
null
1
9
javascript|google-analytics|google-analytics-api
8,041
<p>Depends on what browser types you're targeting. Are these for HTML5 offline webapps? </p> <p>If they <a href="https://developer.mozilla.org/en/Online_and_offline_events" rel="noreferrer">support <code>ononline</code> and <code>onoffline</code> events</a>, you can implement this yourself fairly trivially. </p> <p>Some potentially workable code, using offline events, native JSON and HTML5 Local Storage:</p> <pre><code>if(!localStorage.getItem("offlineGA")){ localStorage.setItem("offlineGA","[]"); } var _ogaq = { push : function(arr){ if(navigator.onLine || !("onLine" in navigator)){ // if online or if browser doesn't support onLine/offLine detection. _gaq.push(arr); } else{ var stored = JSON.parse(localStorage.getItem("offlineGA")); stored.push(arr); localStorage.setItem("offlineGA", JSON.stringify(stored)); } } }; $(window).bind("online", function(){ // if you don't have jQuery, you can do window.ononline instead _gaq.push( JSON.parse(localStorage.getItem("offlineGA")) ); localStorage.setItem("offlineGA","[]"); //empty it }); </code></pre> <p>Then you would just use <code>_ogaq</code> as a wrapper for <code>_gaq</code>.</p> <p>ie:</p> <pre><code>_ogaq.push(["_trackEvent","Category", "Action"]); </code></pre>
7,928,803
Background music Android
<p>Okey, this is my problem. I have one service class where Ive managed to create media player to play music in background all time. Here is code:</p> <pre><code>package com.test.brzoracunanje; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; public class BackgroundSoundService extends Service { private static final String TAG = null; MediaPlayer player; public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); player = MediaPlayer.create(this, R.raw.test_cbr); player.setLooping(true); // Set looping player.setVolume(100,100); player.start(); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } protected void onNewIntent() { player.pause(); } } </code></pre> <p>But now I have problem when I click on <code>HOME</code>, or <code>BACK</code> button. It still plays music. Does anyone knows how to solve that problem?</p> <p>And here is code how i call this service on class where I want to play music;</p> <pre><code> Intent svc=new Intent(this, BackgroundSoundService.class); startService(svc); </code></pre>
7,928,911
9
2
null
2011-10-28 11:47:22.627 UTC
8
2019-08-03 17:07:23.62 UTC
2019-01-02 14:42:05.69 UTC
null
2,266,772
null
955,836
null
1
10
android|playback
47,854
<p>If you want to play background music for your app only, then play it in a thread launched from your app/use AsyncTask class to do it for you.</p> <p>The concept of services is to run in the background; By background, the meaning is usually when your app UI is <strong>NOT VISIBLE</strong>. True, it can be used just like you have (If you remember to stop it) but its just not right, and it consumes resources you shouldn't be using.</p> <p>If you want to peform tasks on the background of your <strong>activity</strong>, use AsyncTask.</p> <p>By the way, <code>onStart</code> is deprecated. When you do use services, implement <code>onStartCommand</code>.</p> <p><strong>UPDATE:</strong></p> <p>I think this code will work for you. Add this class (Enclosed in your activity class).</p> <pre><code>public class BackgroundSound extends AsyncTask&lt;Void, Void, Void&gt; { @Override protected Void doInBackground(Void... params) { MediaPlayer player = MediaPlayer.create(YourActivity.this, R.raw.test_cbr); player.setLooping(true); // Set looping player.setVolume(1.0f, 1.0f); player.start(); return null; } } </code></pre> <p>Now, in order to control the music, save your BackgroundSound object instead of creating it annonymously. Declare it as a field in your activity:</p> <pre><code>BackgroundSound mBackgroundSound = new BackgroundSound(); </code></pre> <p>On your activity's onResume method, start it:</p> <pre><code>public void onResume() { super.onResume(); mBackgroundSound.execute(null); } </code></pre> <p>And on your activity's onPause method, stop it:</p> <pre><code>public void onPause() { super.onPause(); mBackgroundSound.cancel(true); } </code></pre> <p>This will work.</p>
4,789,045
How can I set up MongoDB on a Node.js server using node-mongodb-native in an EC2 environment?
<p>I got help from many people here, and now I want to contribute back. For those who are having trouble making a Node.js server work with MongoDB, here is what I've done.</p>
4,831,463
3
5
null
2011-01-25 01:12:47.52 UTC
9
2012-01-08 20:32:50.103 UTC
2011-01-28 17:57:19.107 UTC
null
122,607
null
196,874
null
1
12
mongodb|node.js
12,047
<p><em>This was originally posted by the question asker. A mod asked him in the comments to post it as an answer, but got no response. So, I cleaned it up and am posting it myself.</em></p> <p>When you look at the code, you will notice that the <code>createServer</code> code is inside <code>db.open</code>. It won't work if you reverse it. Also, <strong>do not close</strong> the db connection. Otherwise, after the first time, the db connection will not be opened again. (Of course, <code>db.open</code> is declared outside of <code>createServer</code>.) I have no clue why <code>createServer</code> is inside <code>db.open</code>. I guess it may have to do with not opening too many db connections?</p> <p>Also, one problem I face is that when I run it via SSH, even if I run the server in the background (e.g. <code>$ node server.js &amp;</code>), after 2.5 hours, the server dies (not the instance though). I am not sure if it is because of terminal connection or what.</p> <p><strong>Here is the procedure &amp; code</strong></p> <p>Environment: EC2, AMS-Linux-AMI</p> <p>Purpose: Take an HTTP request and log the query, IP and timestamp into MongoDB.</p> <p><strong>Steps</strong></p> <p>1) After creating the instance (server), install gcc. </p> <pre><code>$ yum install gcc-c++ </code></pre> <p>2) Download Node.js files and unzip them. (I used version 2.6.)</p> <pre><code>$ curl -O http://nodejs.org/dist/node-v0.2.6.tar.gz $ tar -xzf node-v0.2.6.tar.gz </code></pre> <p>I renamed the unzipped folder to just "nodejs"</p> <pre><code>$ cd nodejs $ sudo ./configure --without-ssl $ sudo make $ sudo make install </code></pre> <p><code>make</code> takes a long while.... After that you can try running the sample in nodejs.org</p> <p>3) Install MongoDB. I installed version 1.6.5, not 1.7.</p> <pre><code>$ curl -O http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-1.6.5.tgz $ tar -xzf mongodb-linux-x86_64-1.6.5.tgz $ sudo mkdir /data/db/r01/ </code></pre> <p>I renamed the folder to "mongodb"</p> <p>Run the db process:</p> <pre><code>$ ./mongodb/bin/mongod --dbpath /data/db/r01/ </code></pre> <p>Then if you like, you can run and try out the command line. Refer to MongoDB's website.</p> <p>4) I recommend that you create your own AIM based on your instance. It will take 20 minutes. Then, recreate the install and run MongoDB again.</p> <p>5) Install <code>node-mongodb-native</code></p> <pre><code>$ curl -O https://download.github.com/christkv-node-mongodb-native-V0.8.1-91-g54525d8.tar.gz $ tar -xzf christkv-node-mongodb-native-V0.8.1-91-g54525d8.tar.gz </code></pre> <p>I renamed the folder to <code>node-mongodb-native</code></p> <pre><code>$ cd node-mongodb-native $ make </code></pre> <p>6) Here is the code for the server:</p> <pre><code>GLOBAL.DEBUG = true; global.inData = ''; var http = require('http'); sys = require("sys"); /* set up DB */ var Db = require('./node-mongodb-native/lib/mongodb').Db, Connection = require('./node-mongodb-native/lib/mongodb').Connection, Server = require('./node-mongodb-native/lib/mongodb').Server, BSON = require('./node-mongodb-native/lib/mongodb').BSONNative; var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; var db = new Db('test01', new Server(host, port, {}), {native_parser:true}); db.open(function(err, db) { http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); global.inData = {'p':'', 'url':''}; // get IP address var ipAddress = req.connection.remoteAddress; global.inData.ip = ipAddress; // date time var d = new Date(); var ts = d.valueOf(); global.inData.ts = ts; // get the http query var qs = {}; qs = require('url').parse(req.url, true); if (qs.query !== null) { for (var key in qs.query) { if (key == 'p') { global.inData.p = qs.query[key]; } if (key == 'url') { global.inData.url = qs.query[key]; } } } if (global.inData.p == '' &amp;&amp; global.inData.url == '') { res.end(""); } else { db.collection('clickCount', function(err, collection) { if (err) { console.log('is error \n' + err); } collection.insert({'p':global.inData.p, 'url':global.inData.url, 'ip':global.inData.ip, 'ts':global.inData.ts}); res.end(""); //db.close(); // DO NOT CLOSE THE CONNECTION }); } }).listen(8080); }); console.log('Server running at whatever host :8080'); </code></pre> <p>This may not be <em>perfect</em> code, but it runs. I'm still not used to the "nested" or LISP kind of coding style. That's why I cheated and used <code>global.inData</code> to pass data along. :)</p> <p>Don't forget to put <code>res.end("")</code> in the appropriate location (where you think the HTTP request call should be ended).</p>
4,616,132
How to append \line into RTF using RichTextBox control
<p>When using the Microsoft RichTextBox control it is possible to add new lines like this...</p> <pre><code>richtextbox.AppendText(System.Environment.NewLine); // appends \r\n </code></pre> <p>However, if you now view the generated rtf the \r\n characters are converted to \par not \line</p> <p>How do I insert a \line control code into the generated RTF?</p> <p><b>What does't work:</B></p> <p><b>Token Replacement</b></p> <p>Hacks like inserting a token at the end of the string and then replacing it after the fact, so something like this:</p> <pre><code>string text = "my text"; text = text.Replace("||" "|"); // replace any '|' chars with a double '||' so they aren't confused in the output. text = text.Replace("\r\n", "_|0|_"); // replace \r\n with a placeholder of |0| richtextbox.AppendText(text); string rtf = richtextbox.Rtf; rtf.Replace("_|0|_", "\\line"); // replace placeholder with \line rtf.Replace("||", "|"); // set back any || chars to | </code></pre> <p>This almost worked, it breaks down if you have to support right to left text as the right to left control sequence always ends up in the middle of the placeholder.</p> <p><b>Sending Key Messages</b></p> <pre><code>public void AppendNewLine() { Keys[] keys = new Keys[] {Keys.Shift, Keys.Return}; SendKeys(keys); } private void SendKeys(Keys[] keys) { foreach(Keys key in keys) { SendKeyDown(key); } } private void SendKeyDown(Keys key) { user32.SendMessage(this.Handle, Messages.WM_KEYDOWN, (int)key, 0); } private void SendKeyUp(Keys key) { user32.SendMessage(this.Handle, Messages.WM_KEYUP, (int)key, 0); } </code></pre> <p>This also ends up being converted to a \par</p> <p>Is there a way to post a messaged directly to the msftedit control to insert a control character?</p> <p>I am totally stumped, any ideas guys? Thanks for your help!</p>
8,771,870
3
1
null
2011-01-06 14:47:15.537 UTC
4
2014-09-16 12:22:25.693 UTC
2011-01-06 14:49:10.02 UTC
null
41,956
null
314,014
null
1
18
c#|richtextbox
68,462
<p>Adding a Unicode "Line Separator" (U+2028) does work as far as my testing showed:</p> <pre><code>private void Form_Load(object sender, EventArgs e) { richText.AppendText("Hello, World!\u2028"); richText.AppendText("Hello, World!\u2028"); string rtf = richText.Rtf; richText.AppendText(rtf); } </code></pre> <p>When I run the program, I get:</p> <pre><code>Hello, World! Hello, World! {\rtf1\ansi\ansicpg1252\deff0\deflang1031{\fonttbl{\f0\fnil\fcharset0 Courier New;}} {\colortbl ;\red255\green255\blue255;} \viewkind4\uc1\pard\cf1\f0\fs17 Hello, World!\line Hello, World!\line\par } </code></pre> <p>It did add <code>\line</code> instead of <code>\par</code>.</p>
4,585,345
Phpunit testing with database
<p>I am trying to focus a bit on unit testing using PHPunit.</p> <p>I have found a very good tutorial over here <a href="http://blog.nickbelhomme.com/php/phpunit-training-course-for-free_282" rel="noreferrer">http://blog.nickbelhomme.com/php/phpunit-training-course-for-free_282</a></p> <p>But there is something I'm missing and don't yet understand how to do.</p> <p>I have a user module which maintains all information about users. And there is a function save which saves the user in the database. So I have a testFunction</p> <pre><code>public function testCanCreateUser() { $userData = array( 'userName' =&gt; 'User1', 'firstName' =&gt; 'Joey', 'lastName' =&gt; 'Hendricks', 'email' =&gt; '[email protected]', 'password' =&gt; 'f$tfe8F' ); $user = new Model_User($userData); $user-&gt;save(); } </code></pre> <p>The first time when I will run my test this will work. Since the database is empty. But When I run my tests for the second time it won't work since my system doesn't allow the same user twice in the db. So In order to do this I have to recreate my testdatabase every time before I run my tests. What is the best way to do this?</p> <p>Or is this problem to be solved on a different way?</p>
4,585,539
3
0
null
2011-01-03 14:40:47.49 UTC
14
2020-08-04 04:14:35.53 UTC
2020-08-04 04:14:35.53 UTC
null
214,143
null
80,040
null
1
20
php|unit-testing|zend-framework|phpunit
37,121
<p><strong>If you want to test your business logic:</strong> Mock away the Database class and return fake data</p> <p><strong>If you want to test the class that fires the SQL statements</strong> (and imho you could test that too since I kinda wanna know if my code works fine with a real db in the backend) it gets a little complicated but there are ways to do it:</p> <ul> <li><p>Using setUp() and tearDown() to get a consistent state for your data before running your tests is (imho) a fine way to write db-driven unittests. It can get annoying to write lots of custom sql by hand though.</p></li> <li><p>To make your life a little easier you can look into the <a href="https://phpunit.de/manual/current/en/database.html" rel="nofollow noreferrer">DbUnit extension</a> and see if that works for your Application.</p></li> <li><p>If you <em>really</em> want to dive into Unittesting database interactions the best read on the subject is (imho) the chapter on db-unittesting in <a href="https://rads.stackoverflow.com/amzn/click/com/0470872497" rel="nofollow noreferrer" rel="nofollow noreferrer">Sebastian Bergmanns phpqa book</a>.</p></li> <li><p>Could your application allow for a custom database name and automated setup of all tables it may also be possible to set the db up once with a lot of testdata and use that data in all your tests. You could be carefull so though that one test doesn't rely on data written by another one.</p></li> </ul>
4,185,010
Navigate to specific page in scrollView with paging, programmatically
<p>How do I navigate to a specific page programmatically. Basically I have an app with a scrollView populated with a bunch of subviews (tableViews in this case). When clicking on a subview it zooms in and the user can edit and navigate the table, however when I zoom back out I reload the entire view in case there were any changed made by the user. Of course reloading the view sends the user back to page 0. I've tried setting the pageControl.currentpage property but all that does is change the dot of the pageControl. Does that mean that something is wrong or do I need to do something else as well??</p> <p>All that is controlling the page scrolling is this method:</p> <pre><code>- (void)scrollViewDidScroll:(UIScrollView *)sender { CGFloat pageWidth = self.scrollView.frame.size.width; int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1; self.pageControl.currentPage = page; NSString *listName = [self.wishLists objectAtIndex:self.pageControl.currentPage]; self.labelListName.text = listName; } </code></pre>
4,185,027
3
1
null
2010-11-15 13:55:08.623 UTC
1
2020-05-04 02:41:19.83 UTC
2017-04-25 16:55:41.757 UTC
null
1,033,581
null
443,152
null
1
29
iphone|uiscrollview|uipagecontrol
15,753
<p>You have to calculate the corresponding scroll position manually. To scroll to page i:</p> <pre><code>[scrollView setContentOffset:CGPointMake(scrollView.frame.size.width*i, 0.0f) animated:YES]; </code></pre>
4,088,862
Android List view refresh
<p>I have one ListView which is showing me some data through an array (which is in another class and I'm accessing it through it's object). </p> <p>Whenever I delete an element from the ListView through context menu, the list is not refreshing but the element is deleted from the array. How can I refresh the list to show this?</p> <p>Code:</p> <pre><code> public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { if (v.getId()==R.id.mainListView) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo; post=info.position; menu.setHeaderTitle(stocks[info.position]); String[] menuItems = stt; for (int i = 0; i&lt;menuItems.length; i++) { menu.add(Menu.NONE, i, i, menuItems[i]); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); int menuItemIndex = item.getItemId(); String[] menuItems = stt; String menuItemName = menuItems[menuItemIndex]; listItemName = stocks[info.position]; stockname.remove(post-1); return true; } </code></pre>
4,088,889
5
0
null
2010-11-03 15:47:46.523 UTC
7
2017-08-02 22:28:29.58 UTC
2014-02-17 04:56:10.36 UTC
null
1,965,587
null
383,597
null
1
16
android|dom|xml-parsing|android-listview
64,135
<p>You have to notify your ListView adapter that the data has changed.</p> <pre><code>listViewAdapater.notifyDataSetChanged(); </code></pre> <p>If that for some reason doesn't work and there are some wierd situations where it seems like it wasn't notifying, you can just reassign your adapter via the constructor with the updated array.</p>
4,477,082
What is a JPA implementation?
<p>I'm getting started with JPA, and I'm confused as to what exactly the JPA implementation(EclipseLink, TopLink, Hibernate, etc.) does. </p> <p>I understand the theoretical role of JPA, but what is the purpose of the various implementations? Are there significant differences between these choices, as there is with say, DB connectors/drivers? Which is the best one for a beginner?</p> <p>I'll probably go with EclipseLink because that is what most of the literature I've read uses.</p>
4,477,349
5
1
null
2010-12-18 07:11:51.353 UTC
18
2017-11-07 14:47:15.14 UTC
2017-11-07 14:47:15.14 UTC
null
4,813,586
null
262,525
null
1
40
java|eclipse|jpa|eclipselink
25,115
<p><img src="https://i.stack.imgur.com/4sVPQ.png" alt="JPA"></p> <p>JPA is just an API (hence Java Persistence <strong>API</strong>) that requires an implementation to use.</p> <p>An analogy would be using JDBC. JDBC is an API for accessing databases, but you need an implementation (a driver jar file) to be able to connect to a database. On its own, without a driver, you cannot do anything with a database.</p> <p>With JPA, as I said, you need an implementation, a set of classes that lie "below" JPA, and such an implementation will do what you want.</p> <p>Your application uses the JPA API (this wording is a bit cubersome, but I hope you get the idea), which then communicates with the underlying implementation.</p> <p>Popular implementations include <a href="http://www.hibernate.org/" rel="noreferrer">Hibernate</a>, <a href="http://www.eclipse.org/eclipselink/" rel="noreferrer">EclipseLink</a>, <a href="http://openjpa.apache.org/" rel="noreferrer">OpenJPA</a> and others.</p> <p>Every one of them implement the JPA API, so if you use only JPA, every implementation should act the same.</p> <p>But! The functionality provided by these implementations might go beyond the standard JPA API.</p> <p>If you want to use this particular functionality, you will have to use vendor specific API that will not be compatible with others.</p> <p>For example, even though JPA defines the <code>@Id</code> annotation with ID generation options, when using Hibernate, you can use also <code>@org.hibernate.annotations.GenericGenerator</code> for Hibernate specific generation strategies.</p> <p>Using this annotation will not work unless you're using Hibernate as the underlying implementation.</p> <p>The bottom line is: JPA is the "least common denominator" which every vendor implements, and every implementation might have some more advanced features that aren't standard.</p> <p>If you want your application to be portable, use only JPA. If you are sure you won't change your mind later on and switch implementations, use JPA + vendor specific features.</p>
4,096,506
How to find user id from session_data from django_session table?
<p>In <code>django_session</code> table <code>session_data</code> is stored which is first pickled using pickle module of Python and then encoded in base64 by using base64 module of Python.</p> <p>I got the decoded pickled <code>session_data</code>.</p> <p><code>session_data</code> from <code>django_session</code> table:</p> <pre><code>gAJ9cQEoVQ9fc2Vzc2lvbl9leHBpcnlxAksAVRJfYXV0aF91c2VyX2JhY2tlbmRxA1UpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBFUNX2F1dGhfdXNlcl9pZHEFigECdS5iZmUwOWExOWI0YTZkN2M0NDc2MWVjZjQ5ZDU0YjNhZA== </code></pre> <p>after decoding it by base64.decode(session_data):</p> <pre><code> \x80\x02}q\x01(U\x0f_session_expiryq\x02K\x00U\x12_auth_user_backendq\x03U)django.contrib.auth.backends.ModelBackendq\x04U\r_auth_user_idq\x05\x8a\x01\x02u.bfe09a19b4a6d7c44761ecf49d54b3ad </code></pre> <p>I want to find out the value of <code>auth_user_id</code> from <code>auth_user_idq\x05\x8a\x01\x02u</code>.</p>
12,056,240
6
0
null
2010-11-04 12:13:51.147 UTC
9
2021-08-25 20:41:43.667 UTC
2021-08-25 20:41:43.667 UTC
null
11,573,842
null
494,907
null
1
28
python|django|pickle
15,970
<p>I had trouble with Paulo's method (see my comment on his answer), so I ended up using this method from a <a href="http://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/">scottbarnham.com blog post</a>:</p> <pre><code>from django.contrib.sessions.models import Session from django.contrib.auth.models import User session_key = '8cae76c505f15432b48c8292a7dd0e54' session = Session.objects.get(session_key=session_key) uid = session.get_decoded().get('_auth_user_id') user = User.objects.get(pk=uid) print user.username, user.get_full_name(), user.email </code></pre>
4,605,270
Add item to array in VBScript
<p>How do you add an item to an existing array in VBScript?</p> <p>Is there a VBScript equivalent to the push function in Javascript?</p> <p>i.e.</p> <p>myArray has three items, "Apples", "Oranges", and "Bananas" and I want to add "Watermelons" to the end of the array.</p>
4,605,331
7
0
null
2011-01-05 14:40:27.54 UTC
12
2018-10-26 15:15:36.553 UTC
null
null
null
null
252,529
null
1
49
arrays|vbscript
149,841
<p>Arrays are not very dynamic in VBScript. You'll have to use the <a href="http://msdn.microsoft.com/en-us/library/c850dt17%28v=vs.85%29.aspx">ReDim Preserve</a> statement to grow the existing array so it can accommodate an extra item:</p> <pre><code>ReDim Preserve yourArray(UBound(yourArray) + 1) yourArray(UBound(yourArray)) = "Watermelons" </code></pre>
4,109,798
Convert DateTime.Now to Seconds
<p>I am trying to write a function that will convert a DateTime.Now instance to the number of seconds it represents so that I can compare that to another DateTime instance. Here is what I currently have:</p> <pre><code>public static int convertDateTimeToSeconds(DateTime dateTimeToConvert) { int secsInAMin = 60; int secsInAnHour = 60 * secsInAMin; int secsInADay = 24 * secsInAnHour; double secsInAYear = (int)365.25 * secsInADay; int totalSeconds = (int)(dateTimeToConvert.Year * secsInAYear) + (dateTimeToConvert.DayOfYear * secsInADay) + (dateTimeToConvert.Hour * secsInAnHour) + (dateTimeToConvert.Minute * secsInAMin) + dateTimeToConvert.Second; return totalSeconds; } </code></pre> <p>I realize that I am truncating the calculation for seconds in a year, but I don't need my calculation to be precise. I'm really looking to know if the method that I am using to calculate seconds is correct.</p> <p>Does anyone have anything that could better compute seconds given from a DateTime object? </p> <p>Also, Should the return type be int64 if I am coding in C# if I am going to calculate all the seconds since 0 AD?</p>
4,109,825
9
2
null
2010-11-05 20:30:05.973 UTC
2
2018-06-04 21:14:45.213 UTC
2010-11-07 10:07:48.553 UTC
null
228,755
null
411,494
null
1
18
c#|.net|.net-3.5|.net-4.0
95,632
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx" rel="noreferrer">DateTime</a> type supports <a href="http://msdn.microsoft.com/en-us/library/ff986512.aspx" rel="noreferrer">comparison operators</a>:</p> <pre><code>if (dateTimeA &gt; dateTimeB) { ... </code></pre> <p>This also works for <a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx" rel="noreferrer">DateTime</a> values returned by <a href="http://msdn.microsoft.com/en-us/library/system.datetime.addseconds.aspx" rel="noreferrer">DateTime.AddSeconds</a>:</p> <pre><code>if (dateTimeA.AddSeconds(42) &gt; dateTimeB) { ... </code></pre> <hr> <p>If you really want the number of seconds that elapsed since <em>01/01/0001 00:00:00</em>, you can calculate the difference between the two DateTime values. The resulting <a href="http://msdn.microsoft.com/en-us/library/system.timespan.aspx" rel="noreferrer">TimeSpan</a> value has a <a href="http://msdn.microsoft.com/en-us/library/system.timespan.totalseconds.aspx" rel="noreferrer">TotalSeconds</a> property:</p> <pre><code>double result = DateTime.Now.Subtract(DateTime.MinValue).TotalSeconds; </code></pre>
4,198,842
Wordpress Search Function to only search posts
<p>I want to use the wordpress search function but I want it to only search my blog posts and exclude my static pages from the query. How to do this? I am not opposed to using a plugin.</p>
4,198,894
10
1
null
2010-11-16 20:54:31.127 UTC
4
2020-11-22 07:42:52.583 UTC
2017-11-30 21:07:47.247 UTC
null
4,040,525
null
194,832
null
1
22
php|wordpress|search
65,880
<p>This wp forum page has a bunch of different examples of how to do this depending on where you want to edit your site (index.php or wp-includes/query.php are your options I believe):</p> <p><a href="http://wordpress.org/support/topic/possible-search-only-posts-exclude-pages" rel="nofollow noreferrer">http://wordpress.org/support/topic/possible-search-only-posts-exclude-pages</a></p>
4,421,400
How to get 0-padded binary representation of an integer in java?
<p>for example, for <code>1, 2, 128, 256</code> the output can be (16 digits):</p> <pre><code>0000000000000001 0000000000000010 0000000010000000 0000000100000000 </code></pre> <p>I tried</p> <pre><code>String.format("%16s", Integer.toBinaryString(1)); </code></pre> <p>it puts spaces for left-padding:</p> <pre><code>` 1' </code></pre> <p>How to put <code>0</code>s for padding. I couldn't find it in <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax" rel="noreferrer">Formatter</a>. Is there another way to do it?</p> <p>P.S. <a href="https://stackoverflow.com/questions/473282/left-padding-integers-with-zeros-in-java">this post</a> describes how to format integers with left 0-padding, but it is not for the binary representation.</p>
4,421,438
17
3
null
2010-12-12 11:30:59.35 UTC
41
2020-04-27 01:43:43.123 UTC
2019-04-03 16:31:16.067 UTC
null
4,348,556
null
493,928
null
1
142
java|binary|string-formatting
156,331
<p>I think this is a suboptimal solution, but you could do</p> <pre><code>String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0') </code></pre>
14,515,200
Python Opencv SolvePnP yields wrong translation vector
<p>I am attempting to calibrate and find the location and rotation of a single virtual camera in Blender 3d using homography. I am using Blender so that I can double check my results before I move on to the real world where that is more difficult.</p> <p>I rendered ten pictures of a chess board in various locations and rotations in the view of my stationary camera. With OpenCV's Python, I used <code>cv2.calibrateCamera</code> to find the intrinsic matrix from the detected corners of the chess board in the ten images and then used that in <code>cv2.solvePnP</code> to find the extrinsic parameters(translation and rotation).</p> <p>However, though the estimated parameters were close to the actual ones, there is something fishy going on. My initial estimation of the translation was <code>(-0.11205481,-0.0490256,8.13892491)</code>. The actual location was <code>(0,0,8.07105)</code>. Pretty close right?</p> <p>But, when I moved and rotated the camera slightly and rerendered the images, the estimated translation became farther off. Estimated: <code>(-0.15933154,0.13367286,9.34058867)</code>. Actual: <code>(-1.7918,-1.51073,9.76597)</code>. The Z value is close, but the X and the Y are not.</p> <p>I am utterly confused. If anybody can help me sort through this, I would be highly grateful. Here is the code (it's based off of the Python2 calibrate example supplied with OpenCV):</p> <pre><code>#imports left out USAGE = ''' USAGE: calib.py [--save &lt;filename&gt;] [--debug &lt;output path&gt;] [--square_size] [&lt;image mask&gt;] ''' args, img_mask = getopt.getopt(sys.argv[1:], '', ['save=', 'debug=', 'square_size=']) args = dict(args) try: img_mask = img_mask[0] except: img_mask = '../cpp/0*.png' img_names = glob(img_mask) debug_dir = args.get('--debug') square_size = float(args.get('--square_size', 1.0)) pattern_size = (5, 8) pattern_points = np.zeros( (np.prod(pattern_size), 3), np.float32 ) pattern_points[:,:2] = np.indices(pattern_size).T.reshape(-1, 2) pattern_points *= square_size obj_points = [] img_points = [] h, w = 0, 0 count = 0 for fn in img_names: print 'processing %s...' % fn, img = cv2.imread(fn, 0) h, w = img.shape[:2] found, corners = cv2.findChessboardCorners(img, pattern_size) if found: if count == 0: #corners first is a list of the image points for just the first image. #This is the image I know the object points for and use in solvePnP corners_first = [] for val in corners: corners_first.append(val[0]) np_corners_first = np.asarray(corners_first,np.float64) count+=1 term = ( cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1 ) cv2.cornerSubPix(img, corners, (5, 5), (-1, -1), term) if debug_dir: vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) cv2.drawChessboardCorners(vis, pattern_size, corners, found) path, name, ext = splitfn(fn) cv2.imwrite('%s/%s_chess.bmp' % (debug_dir, name), vis) if not found: print 'chessboard not found' continue img_points.append(corners.reshape(-1, 2)) obj_points.append(pattern_points) print 'ok' rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h)) print "RMS:", rms print "camera matrix:\n", camera_matrix print "distortion coefficients: ", dist_coefs.ravel() cv2.destroyAllWindows() np_xyz = np.array(xyz,np.float64).T #xyz list is from file. Not shown here for brevity camera_matrix2 = np.asarray(camera_matrix,np.float64) np_dist_coefs = np.asarray(dist_coefs[:,:],np.float64) found,rvecs_new,tvecs_new = cv2.solvePnP(np_xyz, np_corners_first,camera_matrix2,np_dist_coefs) np_rodrigues = np.asarray(rvecs_new[:,:],np.float64) print np_rodrigues.shape rot_matrix = cv2.Rodrigues(np_rodrigues)[0] def rot_matrix_to_euler(R): y_rot = asin(R[2][0]) x_rot = acos(R[2][2]/cos(y_rot)) z_rot = acos(R[0][0]/cos(y_rot)) y_rot_angle = y_rot *(180/pi) x_rot_angle = x_rot *(180/pi) z_rot_angle = z_rot *(180/pi) return x_rot_angle,y_rot_angle,z_rot_angle print "Euler_rotation = ",rot_matrix_to_euler(rot_matrix) print "Translation_Matrix = ", tvecs_new </code></pre>
14,543,277
1
7
null
2013-01-25 04:11:00.147 UTC
16
2019-11-19 12:02:24.717 UTC
2019-06-19 05:11:26.967 UTC
null
752,843
null
1,713,402
null
1
17
python|opencv|camera-calibration
14,744
<p>I think you may be thinking of <code>tvecs_new</code> as the camera position. Slightly confusingly that is not the case! In fact it is the position of the world origin in camera co-ords. To get the camera pose in the object/world co-ords, I believe you need to </p> <pre class="lang-py prettyprint-override"><code>-np.matrix(rotation_matrix).T * np.matrix(tvecs_new) </code></pre> <p>And you can get the Euler angles using <code>cv2.decomposeProjectionMatrix(P)[-1]</code> where <code>P</code> is the <code>[r|t]</code> 3 by 4 extrinsic matrix.</p> <p>I found <a href="https://ksimek.github.com/2012/08/22/extrinsic/" rel="noreferrer">this</a> to be a pretty good article about the intrinsics and extrinsics...</p>
14,770,312
How to achieve chamfered CSS Border Corners rather than rounded corners?
<p>With the CSS <code>border-radius</code> property I can have a curvy, rounded border corner at the end.</p> <pre class="lang-css prettyprint-override"><code>.boxLeft{ border-right: 1px dashed #333; border-bottom: 1px dashed #333; border-radius: 0 0 10px 0; } .boxRight{ border-left: 1px dashed #333; border-bottom: 1px dashed #333; border-radius: 0 0 0 10px; } </code></pre> <p>But I want a border corner like the image below. If I have two boxes (Yellow &amp; Pink) meeting each other and I want a harsh corner at the bottom meeting point (dotted corner), what should I do?</p> <p><img src="https://i.stack.imgur.com/IzYHA.jpg" alt="enter image description here"></p> <p>Is that possible using CSS?</p>
14,770,752
8
2
null
2013-02-08 10:19:14.347 UTC
15
2020-05-13 08:42:49.757 UTC
2014-09-11 08:19:18.123 UTC
null
1,811,992
null
1,743,124
null
1
22
border|css|css-shapes
38,832
<p>Here's a way, although it does have some shortcomings, like no borders and it isn't transparent:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.left, .right { width: 100px; height: 100px; float: left; position: relative; } .left { background: lightpink; } .right { background: lightblue; } .right::after, .left::after { width: 0px; height: 0px; background: #fff; content: ''; position: absolute; bottom: 0; } .right::after { left: 0; border-top: 10px solid lightblue; border-right: 10px solid lightblue; border-left: 10px solid white; border-bottom: 10px solid white; } .left::after { right: 0; border-top: 10px solid lightpink; border-right: 10px solid white; border-left: 10px solid lightpink; border-bottom: 10px solid white; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="left"&gt;&lt;/div&gt; &lt;div class="right"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p><strong>RESULT:</strong></p> <p><img src="https://i.stack.imgur.com/wsRKv.png" alt="enter image description here"></p> <p><a href="http://jsfiddle.net/thordarson/ytb3dg0u/" rel="nofollow noreferrer">Here's a fiddle.</a></p>
14,412,752
django applying a style class based on a conditional
<p>I am displaying a list of images. If the user has uploaded an image, I want to keep its opacity 0.5 and in the list of images, the images uploaded by others should have full opacity. I have done it as follows, is there a better way to do it??</p> <pre><code>{% if request.user == obj.shared_by %} &lt;div class="item-image" style="opacity:0.5;filter:alpha(opacity=50);"&gt; {% else %} &lt;div class="item-image"&gt; {% endif %} ......Some code here.... &lt;/div&gt; </code></pre> <p>Thanks!</p>
14,412,777
2
0
null
2013-01-19 09:03:35.273 UTC
12
2019-03-03 21:28:45.367 UTC
null
null
null
null
648,866
null
1
47
django|django-templates
26,854
<p>I normally go for:</p> <pre><code>&lt;div class="item-image{% if foo %} own-image{% endif %}"&gt;...&lt;/div&gt; </code></pre> <p>but switching out the entire <code>div</code> tag may be more readable.</p> <p>Either way I'd do the styling with another class, not with inline css.</p>
14,874,208
How to access and test an internal (non-exports) function in a node.js module?
<p>I'm trying to figure out on how to test internal (i.e. not exported) functions in nodejs (preferably with mocha or jasmine). And i have no idea!</p> <p>Let say I have a module like that:</p> <pre><code>function exported(i) { return notExported(i) + 1; } function notExported(i) { return i*2; } exports.exported = exported; </code></pre> <p>And the following test (mocha):</p> <pre><code>var assert = require('assert'), test = require('../modules/core/test'); describe('test', function(){ describe('#exported(i)', function(){ it('should return (i*2)+1 for any given i', function(){ assert.equal(3, test.exported(1)); assert.equal(5, test.exported(2)); }); }); }); </code></pre> <p>Is there any way to unit test the <code>notExported</code> function without actually exporting it since it's not meant to be exposed?</p>
30,794,280
10
3
null
2013-02-14 11:50:43.753 UTC
55
2022-01-07 08:59:09.647 UTC
2015-09-22 09:14:46.32 UTC
null
1,066,031
null
572,543
null
1
230
node.js|unit-testing|jasmine|mocha.js
93,551
<p>The <a href="https://github.com/jhnns/rewire" rel="noreferrer">rewire</a> module is definitely the answer.</p> <p>Here's my code for accessing an unexported function and testing it using Mocha.</p> <p>application.js:</p> <pre><code>function logMongoError(){ console.error('MongoDB Connection Error. Please make sure that MongoDB is running.'); } </code></pre> <p>test.js:</p> <pre><code>var rewire = require('rewire'); var chai = require('chai'); var should = chai.should(); var app = rewire('../application/application.js'); var logError = app.__get__('logMongoError'); describe('Application module', function() { it('should output the correct error', function(done) { logError().should.equal('MongoDB Connection Error. Please make sure that MongoDB is running.'); done(); }); }); </code></pre>
2,606,653
Connecting to SQL Server 2008 from Java
<p>I am trying to connect to SQL Server 2008 server from Java </p> <p>here is a program</p> <pre><code>import java.sql.*; public class connectURL { public static void main(String[] args) { // Create a variable for the connection string. String connectionUrl = "jdbc:sqlserver://localhost/SQLEXPRESS/Databases/HelloWorld:1433;";// + //"databaseName=HelloWorld;integratedSecurity=true;"; // Declare the JDBC objects. Connection con = null; Statement stmt = null; ResultSet rs = null; try { // Establish the connection. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con = DriverManager.getConnection(connectionUrl); // Create and execute an SQL statement that returns some data. String SQL = "SELECT TOP 10 * FROM Person.Contact"; stmt = con.createStatement(); rs = stmt.executeQuery(SQL); // Iterate through the data in the result set and display it. while (rs.next()) { System.out.println(rs.getString(4) + " " + rs.getString(6)); } } // Handle any errors that may have occurred. catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) try { rs.close(); } catch(Exception e) {} if (stmt != null) try { stmt.close(); } catch(Exception e) {} if (con != null) try { con.close(); } catch(Exception e) {} } } } </code></pre> <p>But it shows error as </p> <pre><code>com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost/SQLEXPRESS/Databases/HelloWorld, port 1433 has failed. Error: "null. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.". at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:170) at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1049) at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:833) at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:716) at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at connectURL.main(connectURL.java:43) </code></pre> <p>I have given followed all the instructions as given in <a href="http://teamtutorials.com/database-tutorials/configuring-and-creating-a-database-in-ms-sql-2008" rel="nofollow noreferrer">http://teamtutorials.com/database-tutorials/configuring-and-creating-a-database-in-ms-sql-2008</a></p> <p>What can be the problem ?</p>
2,606,712
3
1
null
2010-04-09 10:31:12.757 UTC
4
2012-12-22 06:45:40.703 UTC
2010-04-12 15:08:11.873 UTC
null
13,302
null
138,604
null
1
4
java|sql-server-2008
38,237
<p>I thing the connection URL may be wrong. Then try following connection,</p> <pre><code> String Connectionurl="jdbc:sqlserver://localhost:1433;DatabaseName=YourDBName;user=UserName;Password=YourPassword" </code></pre>
38,539,417
Validating Password And Confirm Password Fields Whenever One Or The Other Fields Model Changes (Each Keystroke) With Angular Directive
<p>I currently have an Angular Directive that validates a password and confirm password field as matching. It works to a point, it does throw an error when the passwords do not match. However, it doesn't throw the error until you have entered data in both fields. How can I make it so the error for mismatched passwords is thrown as soon as you enter data in one field or the other?</p> <p>Here is the directive (it has to be added to both fields that need to match):</p> <pre><code>.directive('passwordVerify', function() { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, elem, attrs, ngModel) { //if (!ngModel) return; // do nothing if no ng-model // watch own value and re-validate on change scope.$watch(attrs.ngModel, function() { validate(); }); // observe the other value and re-validate on change attrs.$observe('passwordVerify', function(val) { validate(); }); var validate = function() { // values var val1 = ngModel.$viewValue; var val2 = attrs.passwordVerify; // set validity ngModel.$setValidity('passwordVerify', !val1 || !val2 || val1 === val2); }; } }; }); </code></pre> <p>And here is the directive in my form:</p> <pre><code>&lt;div class="small-5 columns"&gt; &lt;div class="small-12 columns"&gt; &lt;label&gt; Password &lt;input ng-class="{ notvalid: submitted &amp;&amp; add_user_form.user_password.$invalid }" class="instructor-input" id="user_password" type="password" name='user_password' placeholder="password" value='' required ng-model="user.user_password" password-verify="[[user.confirm_password]]" &gt; &lt;/label&gt; &lt;p class="help-text"&gt; &lt;span class=" "&gt;Required&lt;/span&gt; &lt;/p&gt; &lt;div class="help-block" ng-messages="add_user_form.user_password.$error" ng-show="add_user_form.user_password.$touched || add_user_form.user_password.$dirty" &gt; &lt;span class="red"&gt; &lt;div ng-messages-include="/app/views/messages.html" &gt;&lt;/div&gt; &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="small-12 columns"&gt; &lt;label&gt; Confirm Password &lt;input ng-class="{ notvalid: submitted &amp;&amp; add_user_form.confirm_password.$invalid }" class="instructor-input" id="confirm_password" ng-model="user.confirm_password" name="confirm_password" type="password" placeholder="confirm password" name="user_confirm_passsword" required password-verify="[[user.user_password]]" &gt; &lt;/label&gt; &lt;p class="help-text"&gt; &lt;span class=" "&gt; Enter matching password &lt;/span&gt; &lt;/p&gt; &lt;div class="help-block" ng-messages="add_user_form.confirm_password.$error" ng-show="add_user_form.confirm_password.$dirty || add_user_form.confirm_password.$touched " &gt; &lt;span class="red"&gt; &lt;div ng-messages-include="/app/views/messages.html" &gt;&lt;/div&gt; &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
38,546,955
6
5
null
2016-07-23 07:41:23.277 UTC
2
2019-10-02 10:45:12.103 UTC
2018-04-19 08:18:44.29 UTC
null
366,664
null
5,831,695
null
1
6
angularjs|angularjs-directive
43,425
<p>Just change the last check:</p> <pre><code>ngModel.$setValidity('passwordVerify', !val1 || !val2 || val1 === val2); </code></pre> <p><strong>to:</strong></p> <pre><code>ngModel.$setValidity('passwordVerify', val1 === val2); </code></pre> <p>Here's a <em>working</em> version:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>(function() { "use strict"; angular .module('app', ['ngMessages']) .controller('mainCtrl', mainCtrl) .directive('passwordVerify', passwordVerify); function mainCtrl($scope) { // Some code } function passwordVerify() { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, elem, attrs, ngModel) { if (!ngModel) return; // do nothing if no ng-model // watch own value and re-validate on change scope.$watch(attrs.ngModel, function() { validate(); }); // observe the other value and re-validate on change attrs.$observe('passwordVerify', function(val) { validate(); }); var validate = function() { // values var val1 = ngModel.$viewValue; var val2 = attrs.passwordVerify; // set validity ngModel.$setValidity('passwordVerify', val1 === val2); }; } } } })();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html ng-app="app"&gt; &lt;head&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" /&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.5.7/angular-messages.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body ng-controller="mainCtrl"&gt; &lt;form name="add_user_form"&gt; &lt;div class="col-md-12"&gt; &lt;div class="form-group" ng-class="{ 'has-error' : add_user_form.user_password.$dirty &amp;&amp; add_user_form.user_password.$invalid }"&gt; &lt;p class="help-text"&gt;Enter password&lt;/p&gt; &lt;input type="password" class="form-control" id="user_password" name="user_password" placeholder="password" required ng-model="user.user_password" password-verify="{{user.confirm_password}}"&gt; &lt;div class="help-block" ng-messages="add_user_form.user_password.$error" ng-if="add_user_form.user_password.$dirty"&gt; &lt;p ng-message="required"&gt;This field is required&lt;/p&gt; &lt;p ng-message="minlength"&gt;This field is too short&lt;/p&gt; &lt;p ng-message="maxlength"&gt;This field is too long&lt;/p&gt; &lt;p ng-message="required"&gt;This field is required&lt;/p&gt; &lt;p ng-message="passwordVerify"&gt;No match!&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group" ng-class="{ 'has-error' : add_user_form.confirm_password.$dirty &amp;&amp; add_user_form.confirm_password.$invalid }"&gt; &lt;p class="help-text"&gt;Enter matching password&lt;/p&gt; &lt;input class="form-control" id="confirm_password" ng-model="user.confirm_password" name="confirm_password" type="password" placeholder="confirm password" required password-verify="{{user.user_password}}"&gt; &lt;div class="help-block" ng-messages="add_user_form.confirm_password.$error" ng-if="add_user_form.confirm_password.$dirty"&gt; &lt;p ng-message="required"&gt;This field is required&lt;/p&gt; &lt;p ng-message="minlength"&gt;This field is too short&lt;/p&gt; &lt;p ng-message="maxlength"&gt;This field is too long&lt;/p&gt; &lt;p ng-message="required"&gt;This field is required&lt;/p&gt; &lt;p ng-message="passwordVerify"&gt;No match!&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>I hope it helps.</p>
44,104,241
postgreSQL error initdb: command not found
<p>i was installing postgresql on ubuntu using linuxbrew:</p> <pre><code>brew install postgresql </code></pre> <p>it seems to work fine but after that because i was installing PostgreSQL for the first time i tried creating a database:</p> <pre><code>initdb /usr/local/var/postgres -E utf8 </code></pre> <p>but it returned as:</p> <pre><code>initdb: command not found </code></pre> <p>i tried running the command with <code>sudo but that doesn't helped</code></p>
44,106,963
5
0
null
2017-05-22 03:31:22.987 UTC
3
2022-09-11 14:56:55.277 UTC
null
null
null
null
5,226,912
null
1
17
database|postgresql|ubuntu
53,068
<p>run <code>locate initdb</code> it should give you the list to chose. smth like:</p> <pre><code>MacBook-Air:~ vao$ locate initdb /usr/local/Cellar/postgresql/9.5.3/bin/initdb /usr/local/Cellar/postgresql/9.5.3/share/doc/postgresql/html/app-initdb.html /usr/local/Cellar/postgresql/9.5.3/share/man/man1/initdb.1 /usr/local/Cellar/postgresql/9.6.1/bin/initdb /usr/local/Cellar/postgresql/9.6.1/share/doc/postgresql/html/app-initdb.html /usr/local/Cellar/postgresql/9.6.1/share/man/man1/initdb.1 /usr/local/bin/initdb /usr/local/share/man/man1/initdb.1 </code></pre> <p>So in my case I want to run </p> <pre><code>/usr/local/Cellar/postgresql/9.6.1/bin/initdb </code></pre> <p>If you don't have mlocate installed, either install it or use </p> <pre><code>sudo find / -name initdb </code></pre>
2,719,330
Why does Heroku log using the server time rather than the Rails time zone?
<p>UPDATE: Ok, I didn't formulate a good Q to be answered. I still struggle with heroku being on -07:00 UTC and I at +02:00 UTC.</p> <p><strong>Q: How do I get the log written in the correct Time.zone ?</strong> The 9 hours difference, heroku (us west) - norway, is distracting to work with. I get this in my production.log (using <code>heroku logs</code>):</p> <blockquote> <p>Processing ProductionController#create to xml (for 81.26.51.35 at <strong>2010-04-28 23:00:12</strong>) [POST]</p> </blockquote> <p>How do I get it to write <code>2010-04-29 08:00:12 +02:00 GMT</code> ?</p> <p>Note that I'm running at heroku and cannot set the server time myself, as one could do at your amazon EC2 servers. Below is my previous question, I'll leave it be as it holds some interesting information about time and zones.</p> <hr> <p>Why does <code>Time.now</code> yield the server local time when I have set the another time zone in my <code>environment.rb</code></p> <pre><code>config.time_zone = 'Copenhagen' </code></pre> <p>I've put this in a view</p> <pre><code>&lt;p&gt; Time.zone &lt;%= Time.zone %&gt; &lt;/p&gt; &lt;p&gt; Time.now &lt;%= Time.now %&gt; &lt;/p&gt; &lt;p&gt; Time.now.utc &lt;%= Time.now.utc %&gt; &lt;/p&gt; &lt;p&gt; Time.zone.now &lt;%= Time.zone.now %&gt; &lt;/p&gt; &lt;p&gt; Time.zone.today &lt;%= Time.zone.today %&gt; &lt;/p&gt; </code></pre> <p>rendering this result on my app at <strong>heroku</strong> </p> <blockquote> <p>Time.zone (GMT+01:00) Copenhagen</p> <p>Time.now Mon Apr 26 08:28:21 -0700 2010</p> <p>Time.now.utc Mon Apr 26 15:28:21 UTC 2010</p> <p>Time.zone.now 2010-04-26 17:28:21 +0200</p> <p>Time.zone.today 2010-04-26</p> </blockquote> <p><code>Time.zone.now</code> yields the correct result. Do I have to switch from <code>Time.now</code> to <code>Time.zone.now</code>, everywhere? Seems cumbersome. I truly don't care what the local time of the server is, it's giving me loads of trouble due to extensive use of <code>Time.now</code>. Am I misunderstanding anything fundamental here?</p>
2,954,105
3
2
null
2010-04-27 07:04:59.45 UTC
19
2018-07-03 23:03:20.93 UTC
2012-08-22 21:28:55.403 UTC
null
146,764
null
252,799
null
1
35
ruby-on-rails|logging|time|timezone|heroku
11,535
<p>After some further investigation into my own Heroku timezone problems, I found a post which indicates that you actually <em>can</em> specify the timezone at an application level, using the following command:</p> <pre><code>heroku config:add TZ=Europe/Oslo </code></pre> <p>I believe this may be the answer to all your troubles. Courtesy of <a href="http://www.reality.hk/articles/2010/01/07/1319/" rel="noreferrer">http://www.reality.hk/articles/2010/01/07/1319/</a> (<strong>Edit:</strong> Broken link as of 2012.08.23. <a href="http://web.archive.org/web/20100525142324/http://www.reality.hk/articles/2010/01/07/1319/" rel="noreferrer">Archived copy</a>.)</p>
2,405,120
How to start an Intent by passing some parameters to it?
<p>I would like to pass some variables in the constructor of my ListActivity </p> <p>I start activity via this code:</p> <pre><code>startActivity(new Intent (this, viewContacts.class)); </code></pre> <p>I would like to use similar code, but to pass two strings to the constructor. How is possible?</p>
11,821,596
3
1
null
2010-03-08 22:01:31.033 UTC
29
2020-10-15 11:08:04.02 UTC
null
null
null
null
243,782
null
1
114
android|constructor|android-intent
165,270
<p>In order to pass the parameters you create new intent and put a parameter map:</p> <pre><code>Intent myIntent = new Intent(this, NewActivityClassName.class); myIntent.putExtra("firstKeyName","FirstKeyValue"); myIntent.putExtra("secondKeyName","SecondKeyValue"); startActivity(myIntent); </code></pre> <p>In order to get the parameters values inside the started activity, you must call the <code>get[type]Extra()</code> on the same intent:</p> <pre><code>// getIntent() is a method from the started activity Intent myIntent = getIntent(); // gets the previously created intent String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue" String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue" </code></pre> <p>If your parameters are ints you would use <code>getIntExtra()</code> instead etc. Now you can use your parameters like you normally would. </p>
2,631,975
Using consts in static classes
<p>I was plugging away on <a href="http://code.google.com/p/noda-time/" rel="noreferrer">an open source project</a> this past weekend when I ran into <a href="http://code.google.com/p/noda-time/source/browse/src/NodaTime/Format/FormatUtils.cs" rel="noreferrer">a bit of code that confused me</a> to look up the usage in the <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx" rel="noreferrer">C# specification</a>.</p> <p>The code in questions is as follows:</p> <pre><code>internal static class SomeStaticClass { private const int CommonlyUsedValue = 42; internal static string UseCommonlyUsedValue(...) { // some code value = CommonlyUsedValue + ...; return value.ToString(); } } </code></pre> <p>I was caught off guard because this appears to be a non static field being used by a static function which some how compiled just fine in a static class!</p> <p>The specification states (§10.4):</p> <blockquote> <p>A constant-declaration may include a set of attributes (§17), a new modifier (§10.3.4), and a valid combination of the four access modifiers (§10.3.5). The attributes and modifiers apply to all of the members declared by the constant-declaration. <strong>Even though constants are considered static members, a constant-declaration neither requires nor allows a static modifier.</strong> It is an error for the same modifier to appear multiple times in a constant declaration.</p> </blockquote> <p>So now it makes a little more sense because <em>constants are considered static members</em>, but the rest of the sentence is a bit surprising to me. Why is it that <em>a constant-declaration neither requires nor allows a static modifier</em>? Admittedly I did not know the spec well enough for this to immediately make sense in the first place, but <strong>why was the decision made to not force constants to use the static modifier if they are considered static?</strong></p> <p>Looking at the last sentence in that paragraph, I cannot figure out if it is regarding the previous statement directly and there is some implicit static modifier on constants to begin with, or if it stands on its own as another rule for constants. Can anyone help me clear this up?</p>
2,632,001
4
2
null
2010-04-13 18:08:10.763 UTC
7
2022-07-14 23:29:32.523 UTC
2017-07-06 19:02:30.41 UTC
null
41,956
null
178,082
null
1
33
c#|static|constants
19,672
<p>Basically, <strong>const</strong> implies <strong>static</strong> already, since the value cannot be changed at runtime. There's no reason for you to ever declare <em>static const</em>, since it's already implied, and the language designers decided to make the language syntax reflect that.</p> <p>The specification language is basically saying "Const is always static, so you can't explicitly say static and const since it's redundant."</p>
37,639,496
How can I check the version of sed in OS X?
<p>I know if <code>sed</code> is GNU version, version check can be done like</p> <pre><code>$ sed --version </code></pre> <p>But this doesn't work in OS X. How can I do that?</p>
37,639,736
3
0
null
2016-06-05 07:28:55.497 UTC
4
2022-02-08 16:40:14.123 UTC
2016-11-17 21:09:01.447 UTC
null
55,075
null
5,444,860
null
1
29
shell|command-line|sed
14,808
<p>This probably isn't the answer you're looking for, but you can't. Mac OS X <code>sed</code> has no option to show the version number.</p> <p>There is not even a version number in the binary:</p> <pre><code>$ strings $(which sed) $FreeBSD: src/usr.bin/sed/compile.c,v 1.28 2005/08/04 10:05:11 dds Exp $ $FreeBSD: src/usr.bin/sed/main.c,v 1.36 2005/05/10 13:40:50 glebius Exp $ $FreeBSD: src/usr.bin/sed/misc.c,v 1.10 2004/08/09 15:29:41 dds Exp $ $FreeBSD: src/usr.bin/sed/process.c,v 1.39 2005/04/09 14:31:41 stefanf Exp $ @(#)PROGRAM:sed PROJECT:text_cmds-88 malloc %lu: %s: unexpected EOF (pending }'s) 0123456789/\$ %lu: %s: command expected %lu: %s: invalid command code %c %lu: %s: command %c expects up to %d address(es), found %d %lu: %s: unexpected } %lu: %s: extra characters at the end of %c command %lu: %s: command %c expects \ followed by text %lu: %s: extra characters after \ at the end of %c command %lu: %s: filename expected w command read command branch label %lu: %s: empty label %lu: %s: substitute pattern can not be delimited by newline or backslash %lu: %s: unterminated substitute pattern %lu: %s: extra text at the end of a transform command %lu: %s: unterminated regular expression %lu: %s: expected context address realloc %lu: %s: whitespace after %s %lu: %s: duplicate label '%s' %lu: %s: RE error: %s %lu: %s: \ can not be used as a string delimiter %lu: %s: newline can not be used as a string delimiter %lu: %s: unbalanced brackets ([]) bin/sed Unix2003 123456789 %lu: %s: \%c not defined in the RE %lu: %s: unescaped newline inside substitute pattern %lu: %s: unterminated substitute in regular expression %lu: %s: more than one number or 'g' in substitute flags %lu: %s: overflow in the 'N' substitute flag %lu: %s: no wfile specified %lu: %s: bad flag in substitute command: '%c' %lu: %s: transform pattern can not be delimited by newline or backslash %lu: %s: unterminated transform source string %lu: %s: unterminated transform target string %lu: %s: transform strings are not the same length %lu: %s: undefined label '%s' %lu: %s: unused label '%s' Eae:f:i:ln setlinebuf() failed stdout "%s" ..." -i may not be used with stdin stdin rename() %s: %s %s in-place editing only works for regular files %s: name too long %s/.!%ld!%s %s: %s usage: sed script [-Ealn] [-i extension] [file ...] sed [-Ealn] [-i extension] [-e script] ... [-f script_file] ... [file ...] first RE may not be empty RE error: %s %lu: %s: \%d not defined in the RE COLUMNS \abfrtv \%03o </code></pre>
33,791,069
Quick way to get AWS Account number from the AWS CLI tools?
<p>Looking for a quick way to pull my account number, I had originally thought of using <code>aws iam get-account-authorization-details --max-items 1</code> but there are several issues with doing it this way. Is there a way to do this that might not cross account origins?</p>
40,121,084
4
0
null
2015-11-18 21:48:39.9 UTC
26
2020-10-19 18:57:11.88 UTC
2019-03-11 15:32:32.367 UTC
null
411,141
null
411,141
null
1
145
amazon-web-services|aws-cli|amazon-iam|aws-sts
59,714
<p>You can get the account number from the <a href="https://docs.aws.amazon.com/cli/latest/reference/sts/" rel="noreferrer">Secure Token Service</a> subcommand <a href="https://docs.aws.amazon.com/cli/latest/reference/sts/get-caller-identity.html" rel="noreferrer"><code>get-caller-identity</code></a> using the following:</p> <pre><code>aws sts get-caller-identity --query Account --output text </code></pre>
52,163,500
.NET core web api with queue processing
<p>How to setup a .NET core web api that</p> <ul> <li>accepts a string value, </li> <li>puts into a queue </li> <li>and return flag that message is accepted (regardless it is processed).</li> </ul> <p>Also, a routine which keeps checking the queue, and process the messages one by one. </p> <p>As per the requirement, the api is going to act as the receiver of messages which may get hits as much as hundreds of times in a minute, while the messages it receives should be processed one by one. I am bit new to web apis, so wonder if such setup is good to have and if yes how to put together different components.</p> <p>Thanks in advance..</p>
52,163,745
2
0
null
2018-09-04 09:49:05.943 UTC
9
2022-08-10 07:34:46.137 UTC
null
null
null
null
2,470,926
null
1
6
asp.net-core|queue|asp.net-web-api2
15,945
<p>Honestly, I don't think that it makes sense to receive and process messages in one process, so I would recommend to use external messaging system like <a href="https://www.rabbitmq.com/" rel="noreferrer">RabbitMQ</a> or <a href="https://kafka.apache.org/" rel="noreferrer">Kafka</a> or any other existing system of your preference, where you can put your messages and another process would consume it. It's quite big topic, you can start from <a href="https://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html" rel="noreferrer">this tutorial</a></p> <p>If you still want to have it in one process it's also possible, you can create a background task queue, put there your messages and create <a href="https://blogs.msdn.microsoft.com/cesardelatorre/2017/11/18/implementing-background-tasks-in-microservices-with-ihostedservice-and-the-backgroundservice-class-net-core-2-x/" rel="noreferrer">background task</a> which will consume them from that queue.</p> <pre class="lang-cs prettyprint-override"><code>public interface IBackgroundTaskQueue { void QueueBackgroundWorkItem(Func&lt;CancellationToken, Task&gt; workItem); Task&lt;Func&lt;CancellationToken, Task&gt;&gt; DequeueAsync( CancellationToken cancellationToken); } public class BackgroundTaskQueue : IBackgroundTaskQueue { private ConcurrentQueue&lt;Func&lt;CancellationToken, Task&gt;&gt; _workItems = new ConcurrentQueue&lt;Func&lt;CancellationToken, Task&gt;&gt;(); private SemaphoreSlim _signal = new SemaphoreSlim(0); public void QueueBackgroundWorkItem( Func&lt;CancellationToken, Task&gt; workItem) { if (workItem == null) { throw new ArgumentNullException(nameof(workItem)); } _workItems.Enqueue(workItem); _signal.Release(); } public async Task&lt;Func&lt;CancellationToken, Task&gt;&gt; DequeueAsync( CancellationToken cancellationToken) { await _signal.WaitAsync(cancellationToken); _workItems.TryDequeue(out var workItem); return workItem; } } </code></pre> <p>Background task:</p> <pre class="lang-cs prettyprint-override"><code>public class QueuedHostedService : BackgroundService { private readonly ILogger _logger; public QueuedHostedService(IBackgroundTaskQueue taskQueue, ILoggerFactory loggerFactory) { TaskQueue = taskQueue; _logger = loggerFactory.CreateLogger&lt;QueuedHostedService&gt;(); } public IBackgroundTaskQueue TaskQueue { get; } protected async override Task ExecuteAsync( CancellationToken cancellationToken) { _logger.LogInformation("Queued Hosted Service is starting."); while (!cancellationToken.IsCancellationRequested) { var workItem = await TaskQueue.DequeueAsync(cancellationToken); try { await workItem(cancellationToken); } catch (Exception ex) { _logger.LogError(ex, $"Error occurred executing {nameof(workItem)}."); } } _logger.LogInformation("Queued Hosted Service is stopping."); } } </code></pre> <p>Registration:</p> <pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services) { services.AddHostedService&lt;QueuedHostedService&gt;(); services.AddSingleton&lt;IBackgroundTaskQueue, BackgroundTaskQueue&gt;(); } </code></pre> <p>Inject to controller:</p> <pre class="lang-cs prettyprint-override"><code>public class ApiController { private IBackgroundTaskQueue queue; public ApiController(IBackgroundTaskQueue queue) { this.queue = queue; } public IActionResult StartProcessing() { queue.QueueBackgroundWorkItem(async token =&gt; { // put processing code here } return Ok(); } } </code></pre> <p>You can modify BackgroundTaskQueue to fit your requirements, but I hope you understand the idea behind this.</p>
31,999,269
how to setup sqlalchemy session in celery tasks with no global variable
<p>Summary: I want to use a sqlalchemy session in celery tasks without having a global variable containing that session.</p> <p>I am using SQLAlchemy in a project with celery tasks, and I'm having </p> <p>Currently, I have a global variable 'session' defined along with my celery app setup (celery.py), with a worker signal to set it up.</p> <pre><code>session = scoped_session(sessionmaker()) @celeryd_init.connect def configure_workers(sender=None, conf=None, **kwargs): # load the application configuration # db_uri = conf['db_uri'] engine = create_engine(db_uri) session.configure(bind=engine) </code></pre> <p>In the module defining the tasks, I simply import 'session' and use it. Tasks are defined with a custom class that closes the session after returning:</p> <pre><code>class DBTask(Task): def after_return(self, *args, **kwargs): session.remove() </code></pre> <p>That works well, however: when unit testing with CELERY_ALWAYS_EAGER=True, the session won't be configured. The only solution I've found so far is to mock that 'session' variable when running a task in a unit test:</p> <pre><code>with mock.patch('celerymodule.tasks.session', self.session): do_something.delay(...) </code></pre> <p>While it works, I don't want to do that.</p> <p>Is there any way to setup a session that will no be a global variable, that will work both for normal asynchronous behavior and without workers with CELERY_ALWAYS_EAGER=True?</p>
32,019,510
1
0
null
2015-08-13 22:10:03.32 UTC
8
2015-08-15 08:06:14.877 UTC
2015-08-15 08:06:14.877 UTC
null
1,200,503
null
1,200,503
null
1
15
python|sqlalchemy|celery
10,511
<p>The answer was right under my nose in the official documentation about <a href="http://celery.readthedocs.org/en/latest/userguide/tasks.html#instantiation" rel="noreferrer">custom task classes</a>.</p> <p>I modified the custom task class that I use for tasks accessing the database:</p> <pre><code>class DBTask(Task): _session = None def after_return(self, *args, **kwargs): if self._session is not None: self._session.remove() @property def session(self): if self._session is None: _, self._session = _get_engine_session(self.conf['db_uri'], verbose=False) return self._session </code></pre> <p>I define my tasks this way:</p> <pre><code>@app.task(base=DBTask, bind=True) def do_stuff_with_db(self, conf, some_arg): self.conf = conf thing = self.session.query(Thing).filter_by(arg=some_arg).first() </code></pre> <p>That way, the SQLAlchemy session will only be created once for each celery worker process, and I don't need any global variable.</p> <p>This solves the problem with my unit tests, since the SQLAlchemy session setup is now independant from the celery workers.</p>
27,932,345
Downloading folders from aws s3, cp or sync?
<p>If I want to download all the contents of a directory on S3 to my local PC, which command should I use cp or sync ? </p> <p>Any help would be highly appreciated.</p> <p>For example,</p> <p>if I want to download all the contents of "this folder" to my desktop, would it look like this ?</p> <pre><code> aws s3 sync s3://"myBucket"/"this folder" C:\\Users\Desktop </code></pre>
27,935,645
6
0
null
2015-01-13 22:04:03.09 UTC
27
2022-09-24 01:04:41.243 UTC
2017-10-31 06:23:07.873 UTC
null
1,939,568
null
4,122,396
null
1
182
windows|amazon-web-services|amazon-s3
214,643
<p>Using <code>aws s3 cp</code> from the <a href="http://aws.amazon.com/cli/" rel="nofollow noreferrer">AWS Command-Line Interface (CLI)</a> will require the <code>--recursive</code> parameter to copy multiple files.</p> <pre><code>aws s3 cp s3://myBucket/dir localdir --recursive </code></pre> <p>The <code>aws s3 sync</code> command will, by default, copy a whole directory. It will only copy new/modified files.</p> <pre><code>aws s3 sync s3://mybucket/dir localdir </code></pre> <p>Just experiment to get the result you want.</p> <p>Documentation:</p> <ul> <li><a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3/cp.html" rel="nofollow noreferrer">cp command</a></li> <li><a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3/sync.html" rel="nofollow noreferrer">sync command</a></li> </ul>
22,594,567
SQL Server : on update set current timestamp
<p>I need a timestamp field which updates every time the user modifies the record.</p> <p>So far I used MySql in which I can even use this in the field creation:</p> <pre><code>ALTER TABLE myTable ADD `last_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP </code></pre> <p>I couldn't find this possibility in SQL Server.</p> <p>Then I tried writing a trigger - in a MySql trigger this is simple:</p> <pre><code>SET new.last_time = CURRENT_TIMESTAMP(); </code></pre> <p>SQL Server doesn't seem to know neither new, nor old syntax, it gave me error on compilation.</p> <p>This:</p> <pre><code>UPDATE myTable SET last_time = CURRENT_TIMESTAMP; </code></pre> <p>worked, but it updated all the rows instead of the current.</p> <p>Isn't there a way the tell SQL Server to update the current record? Should I use <code>UPDATE .... WHERE myid = something</code> ?</p> <p>Doesn't SQL Server know which is the actual record it is processing?</p>
22,594,779
2
0
null
2014-03-23 17:42:12.15 UTC
5
2021-12-21 11:35:04.303 UTC
2021-12-21 11:35:04.303 UTC
null
13,302
null
3,238,140
null
1
11
sql-server
92,724
<p>And if you really need a timestamp - then make a trigger on insert and update that updates the column with the current timestmap.</p> <pre><code>CREATE TRIGGER dbo.trgAfterUpdate ON dbo.YourTable AFTER INSERT, UPDATE AS UPDATE dbo.YourTable SET last_changed = GETDATE() FROM Inserted i </code></pre> <p>To update a single row (which has been edited or inserted) you should use</p> <pre><code>CREATE TRIGGER dbo.trgAfterUpdate ON dbo.YourTable AFTER INSERT, UPDATE AS UPDATE f set LastUpdate=GETDATE() FROM dbo.[YourTable] AS f INNER JOIN inserted AS i ON f.rowID = i.rowID; </code></pre> <p>These should be all you need. GETUTCDATE() if you want it in UTC (which I prefer)</p> <p>SQL Server absolutely knows the rows it processes</p> <blockquote> <p>update myTable set last_time =CURRENT_TIMESTAMP ; worked, but it updated all the rows instead of the current.</p> </blockquote> <p>Yeah, guess what - because that is exactly what you tell SQL Server: Update all rows in the table.</p> <blockquote> <p>Doesn't Sql Server know which is the actual record it is processing?</p> </blockquote> <p>Sets have no current row ;) That is where the problem starts.</p> <p>The only way to do that exactly as you want is up in my answer on the beginning: a timestamp. Due to the misconceptions, though, I add an advice: get a book about SQL basics.</p>
22,721,630
The mcrypt extension is missing. Please check your PHP configuration
<p>I just followed the tutorial located at <a href="https://www.digitalocean.com/community/articles/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu" rel="noreferrer">https://www.digitalocean.com/community/articles/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu</a> while fixing multiple other errors that I came across along the way and I'm stuck with one last error. When I log in to phpMyAdmin, there's a huge red error at the bottom saying "The mcrypt extension is missing. Please check your PHP configuration.". I installed everything listed in the tutorial on Ubuntu 13.10 via putty.</p>
22,730,185
7
0
null
2014-03-28 19:32:28.257 UTC
19
2015-07-18 11:53:38.24 UTC
2014-07-28 04:37:10.773 UTC
null
168,868
null
3,344,396
null
1
50
ubuntu|phpmyadmin|ubuntu-13.10|linux-mint
75,881
<p>Try this:</p> <pre><code>sudo apt-get install php5-mcrypt sudo ln -s /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available sudo php5enmod mcrypt sudo service apache2 restart </code></pre>
47,638,636
How does AWS FIFO SQS deduplication ID work?
<p>I'm trying to use the AWS SQS FIFO service together with an Elastic Beanstalk worker environment.</p> <p>Let's say I send a message with <code>MessageDeduplicationId</code> <code>test</code>, if I continue sending this exact message in the next 5 minutes, the message will be ignored, correct?</p> <p>What happens if I send a message with <code>MessageDeduplicationId</code> <code>test</code> , the consumer processes the message and deletes it, then, in about 1 minute, I send the exact same message again. Will this message be ignored?</p> <p>My question is, does deduplication occur as long as the same <code>MessageDeduplicationId</code> <strong>is still in queue/flight?</strong> Or is the id banner forever, no other message with the same id can be sent.</p> <p>Thanks.</p>
51,725,094
2
0
null
2017-12-04 17:19:05.423 UTC
9
2021-09-12 23:22:07.087 UTC
2021-09-12 23:22:07.087 UTC
null
74,089
null
3,438,712
null
1
23
amazon-web-services|duplicates|amazon-sqs
15,710
<p><em>What happens if I send message with MessageDeduplicationId test , the consumer processes the message and the deletes it, then, in about 1 minute, I send the exact same message again. Will this message be ignored?</em></p> <p>Answer seems to be: <strong>Yes</strong></p> <blockquote> <p>Amazon SQS continues to keep track of the message deduplication ID even after the message is received and deleted.</p> </blockquote> <p><a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/using-messagededuplicationid-property.html" rel="noreferrer">https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/using-messagededuplicationid-property.html</a></p>
47,938,265
Does Spring create new thread per request in rest controllers?
<p>I wanted to learn non blocking REST, but first I wrote blocking controller for comparison. To my surprise Spring doesn't block incoming requests.</p> <p>Simple blocking service:</p> <pre><code>@Service public class BlockingService { public String blocking() { try { Thread.sleep(10000L); } catch (InterruptedException ign) {} return &quot;Blocking response&quot;; } } </code></pre> <p>Simple REST controller:</p> <pre><code>@Slf4j @RestController public class BlockingRestController { private final BlockingService blockingService; @Autowired public BlockingRestController(BlockingService blockingService) { this.blockingService = blockingService; } @GetMapping(&quot;blocking&quot;) public String blocking() { log.info(&quot;Starting blocking request processing...&quot;); return blockingService.blocking(); } } </code></pre> <p>And I was thinking that when I send 4 requests using curl from 4 separated terminals I get:</p> <pre><code>1. Starting blocking request processing... (console where spring is running) 2. (4 terminals waiting) 3. &quot;Blocking response&quot; (in 1st terminal) 4. Starting blocking request processing... (console where spring is running) 5. (3 terminals waiting) 6. &quot;Blocking response&quot; (in 2nd terminal) And so on... </code></pre> <p>But to my surprise I got:</p> <pre><code>1. Starting blocking request processing... (console where spring is running) 2. Starting blocking request processing... (console where spring is running) 3. Starting blocking request processing... (console where spring is running) 4. Starting blocking request processing... (console where spring is running) 5. &quot;Blocking response&quot; (in 1st terminal) 6. &quot;Blocking response&quot; (in 2nd terminal) 7. &quot;Blocking response&quot; (in 3rd terminal) 8. &quot;Blocking response&quot; (in 4th terminal) </code></pre> <p>Why first request doesn't block processing requests? Yet I don't create new threads and I don't process anything asynchronous?</p> <p>Why do I ask about it? Because I want to learn how to use <code>DeferredResult</code>, but now I don't see a need.</p>
47,938,357
2
0
null
2017-12-22 08:37:24.867 UTC
4
2021-06-10 07:45:34.717 UTC
2021-02-22 07:07:02.11 UTC
null
4,433,222
null
6,590,294
null
1
31
spring|spring-mvc|spring-restcontroller|spring-rest
16,524
<p>It's blocking in the sense that it blocks <strong>one</strong> thread: the thread taken out of the pool of threads by the servlet container (Tomcat, Jetty, etc., <strong>not</strong> Spring) to handle your request. Fortunately, many threads are used concurrently to handle requests, otherwise the performance of any Java web application would be dramatic.</p> <p>If you have, let's say, 500 concurrent requests all taking 1 minute to complete, and the pool of threads has 300 threads, then 200 requests will be queued, waiting for one of the threads to become available.</p>
31,269,958
FloatingActionButton doesn't hide
<p>I am trying to hide my FloatingActionButton <code>fabLocation</code> programmatically with :</p> <pre><code>fabLocation.setVisibility(View.GONE) </code></pre> <p>but it does not work.</p> <p>If I add <code>android:visibility="gone"</code> in my XML layout, <code>fabLocation</code> is hidden when I run my activity but it reappears when I scroll.</p> <p>Here is my layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"&gt; &lt;android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:fitsSystemWindows="true" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"&gt; &lt;android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collapsing_toolbar" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:contentScrim="@color/colorOverlay" app:expandedTitleMarginEnd="64dp" app:expandedTitleMarginStart="48dp" app:layout_scrollFlags="scroll|exitUntilCollapsed"&gt; &lt;ImageView android:id="@+id/img_couverture" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:scaleType="centerCrop" android:src="@drawable/bg_navigation_drawer_header" app:layout_collapseMode="parallax" /&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /&gt; &lt;/android.support.design.widget.CollapsingToolbarLayout&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"&gt; &lt;android.support.v7.widget.CardView android:layout_marginTop="8dp" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp"&gt; &lt;TextView android:id="@+id/tv_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" /&gt; &lt;View android:background="@drawable/separator_orange_gradient" android:layout_marginTop="8dp" android:layout_marginBottom="16dp" android:layout_width="match_parent" android:layout_height="2dp"/&gt; &lt;TextView android:id="@+id/tv_history" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="@style/TextAppearance.RobotoLight" /&gt; &lt;/LinearLayout&gt; &lt;/android.support.v7.widget.CardView&gt; &lt;/LinearLayout&gt; &lt;/android.support.v4.widget.NestedScrollView&gt; &lt;android.support.design.widget.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" android:clickable="true" android:id="@+id/fab_location" android:src="@drawable/ic_fab_location_24dp" app:backgroundTint="@color/colorOrange" app:layout_anchor="@id/appbar" app:layout_anchorGravity="bottom|right|end" /&gt; </code></pre> <p></p>
31,270,083
17
0
null
2015-07-07 13:29:45.2 UTC
11
2020-08-04 08:16:43.7 UTC
2015-07-07 13:40:16.857 UTC
null
4,288,782
null
2,179,993
null
1
50
android|material-design|android-design-library|floating-action-button
53,380
<p>It is due to the <code>app:layout_anchor</code> attribute. You must get rid of the anchor before changing visibility:</p> <pre><code>CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fab.getLayoutParams(); p.setAnchorId(View.NO_ID); fab.setLayoutParams(p); fab.setVisibility(View.GONE); </code></pre>
6,164,370
Check what version of the app is being used
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1492351/how-to-display-the-current-project-version-of-my-app-to-the-user">How to display the current project version of my App to the user?</a> </p> </blockquote> <p>Is there a way to check the version number of my app? Is it supplied somewhere once the app is in the App Store?</p>
6,164,392
1
0
null
2011-05-28 21:10:29.35 UTC
9
2011-05-28 21:24:18.137 UTC
2017-05-23 11:33:26.943 UTC
null
-1
null
437,247
null
1
42
objective-c|cocoa-touch|ios|version-numbering
23,117
<p>I believe this is included in your <a href="http://www.innerexception.com/2008/10/iphone-app-version-and-build-numbers.html" rel="noreferrer">info.plist</a> file, and can be retrieved with code like this:</p> <pre><code>[NSString stringWithFormat:@"Version %@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]]; </code></pre>
37,806,762
How to disable CSRF Token in Laravel and why we have to disable it?
<p>I want to see how I can disable CSRF token in Laravel and where I have to disable it. Is this good to disable it or not?</p>
37,806,818
8
0
null
2016-06-14 08:27:41.667 UTC
9
2022-04-22 08:32:01.27 UTC
null
null
null
null
6,400,599
null
1
47
laravel
108,624
<p>You can Disable CSRF on few routes by editing.</p> <pre><code>App\Http\Middleware\VerifyCsrfToken </code></pre> <p>and add your own routes name in protected </p> <pre><code>$except = [] array. </code></pre> <p>It does not seems to be good practice as by doing this we are removing security feature of Laravel.</p>
56,441,825
How to fix 'button' interactive role must be focusable
<p>I have list of dropdown options which user can select.</p> <p>optinos in dropdown are made with tag: &lt; a href>:</p> <pre><code>&lt;a onClick={() =&gt; handleSelect(filter)} role="button"&gt; {filter.name} &lt;/a&gt; </code></pre> <p>Problem is cus I must add <code>tabIndex="0" or -1</code>, to fix error from Eslint. </p> <p>But When I add <code>tabIndex=0</code>, my button does not work anymore. </p> <p>Is there are any other way to fix this error?</p> <p>This is how looks dropdown component:</p> <pre><code>&lt;ul name="filters" className="dropdown"&gt; {filterOptions.map((filter) =&gt; ( &lt;li key={filter.id} defaultChecked={filter.name} name={filter.name} className={`option option-${filter.selected ? 'selected' : 'unselected'}`} &gt; &lt;span className={`option-${filter.selected ? 'checked-box' : 'unchecked-box'} `} /&gt; &lt;a onClick={() =&gt; handleSelect(filter)} role="button"&gt; {filter.name} &lt;/a&gt; &lt;/li&gt; ))} &lt;/ul&gt; </code></pre>
58,980,034
2
0
null
2019-06-04 10:13:39.637 UTC
3
2020-01-23 07:12:15.943 UTC
2019-06-04 10:31:26.267 UTC
null
11,220,076
null
11,220,076
null
1
55
javascript|html|reactjs|eslint
58,710
<blockquote> <p>Buttons are interactive controls and thus focusable. If the button role is added to an element that is not focusable by itself (such as <code>&lt;span&gt;</code>, <code>&lt;div&gt;</code> or <code>&lt;p&gt;</code>) then, the tabindex attribute has to be used to make the button focusable.</p> </blockquote> <p><a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role#Accessibility_concerns" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role#Accessibility_concerns</a></p> <blockquote> <p>The HTML attribute <code>tabindex</code> corresponds to the attribute <code>tabIndex</code> in React.</p> </blockquote> <p><a href="https://reactjs.org/docs/dom-elements.html" rel="noreferrer">https://reactjs.org/docs/dom-elements.html</a></p> <p>So I think @S.. answer is correct:</p> <pre><code>&lt;a onClick={() =&gt; handleSelect(filter)} role="button" tabIndex={0} &gt; {filter.name} &lt;/a&gt; </code></pre>
28,755,517
Max and min values on Google Charts
<p>How can I set a max and a min value on a Google Chart?</p> <p>I've tried this without success:</p> <pre><code>vAxis: { viewWindowMode:'explicit', viewWindow: { max:3000, min:500 } } </code></pre> <p>This is all the code I'm using:</p> <pre><code>&lt;script type="text/javascript" src="https://www.google.com/jsapi"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; google.load("visualization", "1.1", {packages:["bar"]}); google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Year', 'Sales', 'Expenses', 'Profit'], ['2014', 1000, 400, 200], ['2015', 1170, 460, 250], ['2016', 660, 1120, 300], ['2017', 1030, 540, 350] ]); var options = { chart: { title: 'Company Performance', subtitle: 'Sales, Expenses, and Profit: 2014-2017', }, vAxis: { viewWindowMode:'explicit', viewWindow: { max:3000, min:500 } }, bars: 'vertical' // Required for Material Bar Charts. }; var chart = new google.charts.Bar(document.getElementById('barchart_material')); chart.draw(data, options); } &lt;/script&gt; </code></pre> <p>(example from <a href="https://developers.google.com/chart/interactive/docs/gallery/barchart">https://developers.google.com/chart/interactive/docs/gallery/barchart</a>)</p> <p>Thks in advance.</p>
28,772,325
1
0
null
2015-02-27 00:35:21.02 UTC
4
2015-02-27 18:58:28.113 UTC
null
null
null
null
4,301,970
null
1
21
google-visualization
52,739
<p>With the release of Material Charts, Google is modifying how the options are specified. The structure for these options is not yet finalized, so Google provides a converter function for the classic options structure into the new one, and it is recommended that you use it instead of using options that may change in the future.</p> <p>So you could fix your problem in one of two ways:</p> <ol> <li>You could use the conversion function, as Google recommends (you can see this method demonstrated in <a href="http://jsfiddle.net/x8dafm9u/">this jsfiddle</a> or <a href="https://developers.google.com/chart/interactive/docs/gallery/columnchart#Material">Google's official documentation</a> (note the note right at the bottom of the linked heading))</li> </ol> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> google.load("visualization", "1.0", {packages:["bar"]}); google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Year', 'Sales', 'Expenses', 'Profit'], ['2014', 1000, 400, 200], ['2015', 1170, 460, 250], ['2016', 660, 1120, 300], ['2017', 1030, 540, 350] ]); var options = { chart: { title: 'Company Performance', subtitle: 'Sales, Expenses, and Profit: 2014-2017', }, vAxis: { viewWindowMode:'explicit', viewWindow: { max:3000, min:500 } }, bars: 'vertical', // Required for Material Bar Charts. width: 800, height: 600 }; var chart = new google.charts.Bar(document.getElementById('barchart_material')); chart.draw(data, google.charts.Bar.convertOptions(options)); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"&gt;&lt;/script&gt; &lt;div id="barchart_material"&gt;&lt;/div&gt; </code></pre> </div> </div> </p> <ol start="2"> <li>You could continue using options that may change in the future. If you do not care about your charts breaking, the option you are looking for is axes.y.all.range.{min,max}. You can see that option in action in <a href="http://jsfiddle.net/x8dafm9u/2/">this jsfiddle</a>.</li> </ol> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>google.load("visualization", "1.0", { packages: ["bar"] }); google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Year', 'Sales', 'Expenses', 'Profit'], ['2014', 1000, 400, 200], ['2015', 1170, 460, 250], ['2016', 660, 1120, 300], ['2017', 1030, 540, 350] ]); var options = { chart: { title: 'Company Performance', subtitle: 'Sales, Expenses, and Profit: 2014-2017', }, axes: { y: { all: { range: { max: 3000, min: 500 } } } }, bars: 'vertical', // Required for Material Bar Charts. width: 800, height: 600 }; var chart = new google.charts.Bar(document.getElementById('barchart_material')); chart.draw(data, options); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"&gt;&lt;/script&gt; &lt;div id="barchart_material"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>Source: I work on Google Charts.</p>
24,985,716
In Swift how to call method with parameters on GCD main thread?
<p>In my app I have a function that makes an NSRURLSession and sends out an NSURLRequest using</p> <pre><code>sesh.dataTaskWithRequest(req, completionHandler: {(data, response, error) </code></pre> <p>In the completion block for this task, I need to do some computation that adds a UIImage to the calling viewcontroller. I have a func called</p> <pre><code>func displayQRCode(receiveAddr, withAmountInBTC:amountBTC) </code></pre> <p>that does the UIImage-adding computation. If I try to run the view-adding code inside of the completion block, Xcode throws an error saying that I can't use the layout engine while in a background process. So I found some code on SO that tries to queue a method on the main thread:</p> <pre><code>let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.0 * Double(NSEC_PER_MSEC))) dispatch_after(time, dispatch_get_main_queue(), { let returned = UIApplication.sharedApplication().sendAction("displayQRCode:", to: self.delegate, from: self, forEvent: nil) }) </code></pre> <p>However, I don't know how to add the parameters "receiveAddr" and "amountBTC" to this function call. How would I do this, or can someone suggest an optimal way for adding a method call to the application's main queue?</p>
24,985,766
11
0
null
2014-07-27 21:12:47.91 UTC
35
2022-07-22 12:49:58.207 UTC
2021-11-08 08:35:23.84 UTC
null
8,090,893
null
1,484,555
null
1
205
ios|swift|cocoa-touch|parameters|grand-central-dispatch
186,404
<p>Modern versions of Swift use <code>DispatchQueue.main.async</code> to dispatch to the main thread:</p> <pre><code>DispatchQueue.main.async { // your code here } </code></pre> <p>To <em>dispatch after</em> on the main queue, use:</p> <pre><code>DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { // your code here } </code></pre> <p>Older versions of Swift used:</p> <pre><code>dispatch_async(dispatch_get_main_queue(), { let delegateObj = UIApplication.sharedApplication().delegate as YourAppDelegateClass delegateObj.addUIImage("yourstring") }) </code></pre>
23,586,031
Calling activity class method from Service class
<p>I have seen many posts in SO regarding this but could not get the exact and most easy way to call an activity method from service class. Is broadcast receiver only the option? No easy way out ? I just need to call the following method in Activity class after the media player is prepared in Service class .</p> <p>Activity class:</p> <pre><code> public void updateProgress() { // set Progress bar values songProgressBar.setProgress(0); songProgressBar.setMax(100); // Updating progress bar updateProgressBar(); } </code></pre> <p>Service class:</p> <pre><code> @Override public IBinder onBind(Intent intent) { Log.d(this.getClass().getName(), "BIND"); return musicBind; } @Override public boolean onUnbind(Intent intent) { return false; } @Override public void onPrepared(MediaPlayer mp) { try { mp.start(); } catch (IllegalStateException e) { e.printStackTrace(); } // updateProgress();// Need to call the Activity method here } </code></pre>
23,587,641
7
0
null
2014-05-10 20:34:11.147 UTC
34
2021-04-29 13:11:16.787 UTC
null
null
null
null
3,375,361
null
1
57
android|service
76,649
<p>Define an interface your Service will use to communicate events:</p> <pre><code>public interface ServiceCallbacks { void doSomething(); } </code></pre> <p>Write your Service class. Your Activity will bind to this service, so follow the <a href="http://developer.android.com/guide/components/bound-services.html#Binder">sample shown here</a>. In addition, we will add a method to set the <code>ServiceCallbacks</code>.</p> <pre><code>public class MyService extends Service { // Binder given to clients private final IBinder binder = new LocalBinder(); // Registered callbacks private ServiceCallbacks serviceCallbacks; // Class used for the client Binder. public class LocalBinder extends Binder { MyService getService() { // Return this instance of MyService so clients can call public methods return MyService.this; } } @Override public IBinder onBind(Intent intent) { return binder; } public void setCallbacks(ServiceCallbacks callbacks) { serviceCallbacks = callbacks; } } </code></pre> <p>Write your Activity class following the same guide, but also make it implement your ServiceCallbacks interface. When you bind/unbind from the Service, you will register/unregister it by calling <code>setCallbacks</code> on the Service.</p> <pre><code>public class MyActivity extends Activity implements ServiceCallbacks { private MyService myService; private boolean bound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(...); } @Override protected void onStart() { super.onStart(); // bind to Service Intent intent = new Intent(this, MyService.class); bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // Unbind from service if (bound) { myService.setCallbacks(null); // unregister unbindService(serviceConnection); bound = false; } } /** Callbacks for service binding, passed to bindService() */ private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // cast the IBinder and get MyService instance LocalBinder binder = (LocalBinder) service; myService = binder.getService(); bound = true; myService.setCallbacks(MyActivity.this); // register } @Override public void onServiceDisconnected(ComponentName arg0) { bound = false; } }; /* Defined by ServiceCallbacks interface */ @Override public void doSomething() { ... } } </code></pre> <p>Now when your service wants to communicate back to the activity, just call one of the interface methods from earlier. Inside your service:</p> <pre><code>if (serviceCallbacks != null) { serviceCallbacks.doSomething(); } </code></pre>
56,047,659
Multiple Props Options for Styled Components
<p>I have a navbar component that I have created using Styled Components. I would like to create some props that change the background-color and/or text color.</p> <p>For instance: <code>&lt;Navbar dark&gt;</code> should have the following CSS:</p> <pre><code>background: #454545; color: #fafafa; </code></pre> <p>Whereas <code>&lt;Navbar light&gt;</code> should be the opposite:</p> <pre><code>background: #fafafa; color: #454545; </code></pre> <p>If, however, neither prop is used, then I want to have a default background and text color -- say (for demo purposes), something like this:</p> <pre><code>background: #eee; color: #333; </code></pre> <p>Now, my question is how to set this up in Styled Components.</p> <p>I can do the following: </p> <pre><code>background: ${props =&gt; props.dark ? #454545 : '#eee'} background: ${props =&gt; props.dark ? #fafafa : '#eee'} background: #eee; </code></pre> <p>And something similar for color.</p> <p>But this is redundant and not very elegant. I would like some sort of if/else statement:</p> <pre><code>background: ${ props =&gt; { if (props.dark) { #454545 } elseif (props.light) { #fafafa } else { #eee } } </code></pre> <p>But I don't know how to set something like that up in Styled Components.</p> <p>Any suggestions?</p> <p>Thanks in advance.</p>
56,098,044
7
0
null
2019-05-08 19:19:43.03 UTC
9
2022-02-24 02:27:06.22 UTC
null
null
null
null
7,477,670
null
1
14
reactjs|styled-components|css-in-js
28,254
<p>This is the solution I ended up using:</p> <pre><code>export const Navbar = styled.nav` width: 100%; ... // rest of the regular CSS code ${props =&gt; { if (props.dark) { return ` background: ${colors.dark}; color: ${colors.light}; ` } else if (props.light) { return ` background: ${colors.light}; color: ${colors.dark}; ` } else { return ` background: ${colors.light}; color: ${colors.dark}; ` } }} ` </code></pre>
52,711,326
Kubernetes - How to know latest supported API version
<p>Is there a table that will tell me which set of API versions I should be using, given a k8s cluster version? Kubernetes docs always assume I always have a nice, up-to-date cluster (1.12 at time of writing) but platform providers don't always live on this bleeding edge so it can get frustrating quite quickly.</p> <p>Better yet, is there a <code>kubectl</code> command I can run that will let me cluster tell me each resource type and its latest supported API version?</p>
52,711,746
6
0
null
2018-10-08 23:25:53.733 UTC
8
2022-05-19 13:32:02.677 UTC
2018-10-09 00:12:01.143 UTC
null
2,989,261
null
2,340,636
null
1
33
kubernetes|kubectl
24,751
<p>For getting a list of all the resource types and their latest supported version, run the following:</p> <pre><code>for kind in `kubectl api-resources | tail +2 | awk '{ print $1 }'`; do kubectl explain $kind; done | grep -e "KIND:" -e "VERSION:" </code></pre> <p>It should produce output like</p> <pre><code>KIND: Binding VERSION: v1 KIND: ComponentStatus VERSION: v1 KIND: ConfigMap VERSION: v1 KIND: Endpoints VERSION: v1 KIND: Event VERSION: v1 ... </code></pre> <p>As @Rico mentioned, they key is in the <code>kubectl explain</code> command. This may be a little fragile since it depends on the format of the printed output, but it works for kubernetes 1.9.6</p> <p>Also, the information can be gathered in a less efficient way from the kubernetes API docs (with links for each version) found here - <a href="https://kubernetes.io/docs/reference/#api-reference" rel="noreferrer">https://kubernetes.io/docs/reference/#api-reference</a> </p>
2,483,124
Remove C# attribute of a property dynamically
<p>I have a class with a set of properties As given below.</p> <pre><code>class ContactInfo { [ReadOnly(true)] [Category("Contact Info")] public string Mobile { get; set; } [Category("Contact Info")] public string Name{ get; set; } } </code></pre> <p>The objects of this class is being assigned to a property grid, so that the users can <strong>update an existing contact</strong>. you can see that Mobile is marked as ReadOnly.</p> <p>But, when I want to add an <strong>entirely new Contact</strong>, I would want the users to be able to edit the contact Mobile also. For that I need to <strong>remove the Readonly property dynamically</strong> from the Type, before assigning the object to the property grid. Is it possible?</p>
2,483,193
5
0
null
2010-03-20 13:11:37.513 UTC
5
2012-12-13 10:16:40.303 UTC
2010-03-20 14:20:56.673 UTC
null
23,659
null
284,277
null
1
13
c#|.net|propertygrid
66,603
<p>You can not remove the attribute at runtime, but you can use reflection to change the ReadOnly attribute's ReadOnly private backing field to False. Making it the equivalent of [ReadOnly(false)]</p> <p>See this article for details: </p> <p><a href="http://codinglight.blogspot.com/2008/10/changing-attribute-parameters-at.html" rel="noreferrer">http://codinglight.blogspot.com/2008/10/changing-attribute-parameters-at.html</a></p> <p>Edit: fixed link</p>
2,782,915
What should I know about Structured Exceptions (SEH) in C++?
<p>What important points about Structured Exceptions should every C++ developer know?</p>
2,782,968
5
0
2010-05-06 17:02:04.737 UTC
2010-05-06 17:01:57.763 UTC
23
2020-05-01 10:21:54.357 UTC
null
null
null
null
13,543
null
1
49
c++|exception|exception-handling|seh|structured-exception
38,087
<p>They are the Win32 equivalent to Unix signals, and let you catch CPU exceptions such as access violation, illegal instruction, divide by zero.</p> <p>With the right compiler options (/EHa for Visual C++), C++ exceptions use the same mechanism as stack unwinding works properly for both C++ (user) exceptions and SEH (OS) exceptions.</p> <p>Unlike C++ exceptions, SEH are not typed but all share the same data structure which has an exception code (the cause) and additional information on what code faulted and what the CPU registers held at the time of the fault. See <a href="http://msdn.microsoft.com/en-us/library/ms679356(VS.85).aspx" rel="noreferrer"><code>GetExceptionCode</code></a> and <a href="http://msdn.microsoft.com/en-us/library/ms679357(v=VS.85).aspx" rel="noreferrer"><code>GetExceptionInformation</code></a> for more details on this.</p> <p>Also, SEH has "first-chance" handling, which allows you to log or otherwise handle the exception <em>before</em> unwinding destroys all the local variables.</p>
2,557,937
How do I get column names to print in this C# program?
<p>I've cobbled together a C# program that takes a <code>.csv</code> file and writes it to a <code>DataTable</code>. Using this program, I can loop through each row of the <code>DataTable</code> and print out the information contained in the row. The console output looks like this:</p> <pre><code>--- Row --- Item: 1 Item: 545 Item: 507 Item: 484 Item: 501 </code></pre> <p>I'd like to print the column name beside each value, as well, so that it looks like this:</p> <pre><code>--- Row --- Item: 1 Hour Item: 545 Day1 KW Item: 507 Day2 KW Item: 484 Day3 KW Item: 501 Day4 KW </code></pre> <p>Can someone look at my code and tell me what I can add so that the column names will print? I am very new to C#, so please forgive me if I've overlooked something. </p> <p>Here is my code:</p> <pre><code>// Write load_forecast data to datatable. DataTable loadDT = new DataTable(); StreamReader sr = new StreamReader(@"c:\load_forecast.csv"); string[] headers = sr.ReadLine().Split(','); foreach (string header in headers) { loadDT.Columns.Add(header); // I've added the column headers here. } while (sr.Peek() &gt; 0) { DataRow loadDR = loadDT.NewRow(); loadDR.ItemArray = sr.ReadLine().Split(','); loadDT.Rows.Add(loadDR); } foreach (DataRow row in loadDT.Rows) { Console.WriteLine("--- Row ---"); foreach (var item in row.ItemArray) { Console.Write("Item:"); Console.WriteLine(item); // Can I add something here to also print the column names? } } </code></pre>
2,557,943
5
0
null
2010-04-01 03:14:37.877 UTC
8
2018-06-14 09:31:24.547 UTC
2015-11-18 09:33:27.717 UTC
null
2,279,200
null
295,265
null
1
74
c#|datatable|datarow|datacolumn
325,035
<p>You need to loop over <code>loadDT.Columns</code>, like this:</p> <pre><code>foreach (DataColumn column in loadDT.Columns) { Console.Write("Item: "); Console.Write(column.ColumnName); Console.Write(" "); Console.WriteLine(row[column]); } </code></pre>
2,758,080
How to sort an STL vector?
<p>I would like to sort a <code>vector</code> </p> <pre><code>vector&lt;myClass&gt; object; </code></pre> <p>Where <code>myclass</code> contains many <code>int</code> variables. How can I sort my <code>vector</code> on any specific data variable of <code>myClass</code>.</p>
2,758,100
5
0
null
2010-05-03 12:48:12.36 UTC
20
2017-08-09 06:28:46.787 UTC
2017-08-09 06:28:46.787 UTC
null
3,580,365
null
330,731
null
1
81
c++|sorting|stl
159,203
<p>Overload less than operator, then sort. This is an example I found off the web...</p> <pre><code>class MyData { public: int m_iData; string m_strSomeOtherData; bool operator&lt;(const MyData &amp;rhs) const { return m_iData &lt; rhs.m_iData; } }; std::sort(myvector.begin(), myvector.end()); </code></pre> <p>Source: <a href="http://www.codeguru.com/forum/showthread.php?t=366064" rel="noreferrer">here</a></p>
2,676,872
How to parse malformed HTML in python, using standard libraries
<p>There are so many <a href="http://docs.python.org/library/markup.html" rel="noreferrer">html and xml libraries built into python</a>, that it's hard to believe there's no support for real-world HTML parsing.</p> <p>I've found plenty of great third-party libraries for this task, but this question is about the python standard library.</p> <p>Requirements:</p> <ul> <li>Use only Python standard library components (any 2.x version)</li> <li>DOM support</li> <li>Handle HTML entities (<code>&amp;nbsp;</code>)</li> <li>Handle partial documents (like: <code>Hello, &lt;i>World&lt;/i>!</code>)</li> </ul> <p>Bonus points:</p> <ul> <li>XPATH support</li> <li>Handle unclosed/malformed tags. (<code>&lt;big>does anyone here know &lt;html ???</code></li> </ul> <hr> <p>Here's my 90% solution, as requested. This works for the limited set of HTML I've tried, but as everyone can plainly see, this isn't exactly robust. Since I did this by staring at the docs for 15 minutes and one line of code, I thought I would be able to consult the stackoverflow community for a similar but better solution...</p> <pre><code>from xml.etree.ElementTree import fromstring DOM = fromstring("&lt;html&gt;%s&lt;/html&gt;" % html.replace('&amp;nbsp;', '&amp;#160;')) </code></pre>
2,680,724
6
12
null
2010-04-20 16:29:21.227 UTC
11
2017-03-17 12:42:03.16 UTC
2010-04-21 04:47:01.02 UTC
null
146,821
null
146,821
null
1
38
python|html|dom|parsing|html-parsing
12,387
<p>Parsing HTML reliably is a relatively modern development (weird though that may seem). As a result there is definitely nothing in the standard library. <a href="http://docs.python.org/library/htmlparser.html" rel="noreferrer">HTMLParser</a> may <em>appear</em> to be a way to handle HTML, but it's not -- it fails on lots of very common HTML, and though you can work around those failures there will always be another case you haven't thought of (if you actually succeed at handling every failure you'll have basically recreated BeautifulSoup).</p> <p>There are really only 3 reasonable ways to parse HTML (as it is found on the web): <a href="http://codespeak.net/lxml//lxmlhtml.html" rel="noreferrer">lxml.html</a>, <a href="http://www.crummy.com/software/BeautifulSoup/" rel="noreferrer">BeautifulSoup</a>, and <a href="http://code.google.com/p/html5lib/" rel="noreferrer">html5lib</a>. lxml is the fastest by far, but can be a bit tricky to install (and impossible in an environment like App Engine). html5lib is based on how HTML 5 specifies parsing; though similar in practice to the other two, it is perhaps more "correct" in how it parses broken HTML (they all parse pretty-good HTML the same). They all do a respectable job at parsing broken HTML. BeautifulSoup can be convenient though I find its API unnecessarily quirky.</p>
2,951,273
pure-specifier on function-definition
<p>While compiling on GCC I get the <strong>error: pure-specifier on function-definition</strong>, but not when I compile the same code using VS2005.</p> <pre><code>class Dummy { //error: pure-specifier on function-definition, VS2005 compiles virtual void Process() = 0 {}; }; </code></pre> <p>But when the definition of this pure virtual function is not inline, it works:</p> <pre><code>class Dummy { virtual void Process() = 0; }; void Dummy::Process() {} //compiles on both GCC and VS2005 </code></pre> <p>What does the error means? Why cannot I do it inline? Is it legal to evade the compile issue as shown in the second code sample?</p>
2,951,294
6
1
null
2010-06-01 15:56:10.667 UTC
6
2019-09-25 11:40:37.337 UTC
2010-06-01 16:46:40.9 UTC
anon
null
null
355,581
null
1
38
c++|abstract-class|pure-virtual
19,407
<p>Ok, I've just learned something. A pure virtual function must be declared as follows:</p> <pre><code> class Abstract { public: virtual void pure_virtual() = 0; }; </code></pre> <p>It may have a body, although it is illegal to include it at the point of declaration. This means that to have a body the pure virtual function must be defined outside the class. Note that even if it has a body, the function must still be overridden by any concrete classes derived from <code>Abstract</code>. They would just have an option to call <code>Abstract::pure_virtual()</code> explicitly if they need to.</p> <p>The details are <a href="http://en.wikipedia.org/wiki/Virtual_function#C.2B.2B_2" rel="noreferrer">here</a>.</p>
2,426,103
Asking browsers to cache as aggressively as possible
<p>This is about a web app that serves images. Since the same request will always return the same image, I want the accessing browsers to cache the images as aggressively as possible. I pretty much want to tell the browser</p> <blockquote> <p>Here's your image. Go ahead and keep it; it's really not going to change for the next couple of days. No need to come back. Really. I promise.</p> </blockquote> <p>I do, so far, set </p> <pre>Cache-Control: public, max-age=86400 Last-Modified: (some time ago) Expires: (two days from now)</pre> <p>and of course return a <code>304 not modified</code> if the request has the appropriate <code>If-Modified-Since</code> header.</p> <p>Is there anything else I can do (or anything I should do differently) to get my message across to the browsers?</p> <p>The app is hosted on the Google App Engine, in case that matters.</p>
2,426,266
7
3
null
2010-03-11 15:16:44.19 UTC
16
2010-03-20 14:11:07.037 UTC
2010-03-12 15:37:08.673 UTC
null
115,866
null
115,866
null
1
34
http|browser|caching|http-headers
6,411
<p>You may be interested in checking out the following Google Code article:</p> <ul> <li><a href="http://code.google.com/speed/page-speed/docs/caching.html#LeverageBrowserCaching" rel="noreferrer">Optimize caching: Leverage browser caching</a></li> </ul> <p>In a nutshell, all modern browsers should be able to cache your images appropriately as instructed, with those HTTP headers.</p>
2,468,412
Finding a prime number after a given number
<p>How can I find the least prime number greater than a given number? For example, given 4, I need 5; given 7, I need 11.</p> <p>I would like to know some ideas on best algorithms to do this. One method that I thought of was generate primes numbers through the Sieve of Eratosthenes, and then find the prime after the given number.</p>
2,475,255
8
0
null
2010-03-18 08:44:36.207 UTC
13
2022-01-18 15:05:56.153 UTC
2010-03-24 18:47:23.067 UTC
null
164,901
null
169,210
null
1
42
algorithm|primes
65,144
<p>Some other methods have been suggested and I think that they are good, but it really depends on how much you want to have to store or compute on the spot. For instance if you are looking for the next prime after a very large number, then using the Sieve of Eratosthenes might not be so great because of the number of bits you would need to store. </p> <p>Alternatively, you could check all odd integers between (and including) 3 and sqrt(N) on every number odd number N greater than the input number until you find the correct number. Of course you can stop checking when you find it is composite. </p> <p>If you want a different method, then I would suggest using the <a href="http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test" rel="noreferrer">Miller-Rabin primality test</a> on all odd numbers above the input number (assuming the input is > 1) until a prime is found. If you follow the list, located at the bottom of the page, of numbers <code>a</code> to check for the given ranges, you can significantly cut down on the number of <code>a</code>s you need to check. Of course, you might want to check at least a few of the smaller primes (3,5,7,11 for instance) before checking with Miller-Rabin. </p>
2,898,897
How can I use "<" and ">" in javadoc without formatting?
<p>If I write <code>&lt;xmlElement&gt;</code> in a javadoc, it does not appear, because tags have special functions on formatting texts.</p> <p>How can I show this chars in a javadoc?</p>
2,898,955
9
1
null
2010-05-24 17:27:13.96 UTC
16
2021-10-18 09:23:58.75 UTC
2017-01-01 10:15:30.623 UTC
null
1,033,581
null
287,316
null
1
139
java|javadoc
55,711
<p>You can use <code>&amp;lt;</code> for <strong>&lt;</strong> and <code>&amp;gt;</code> for <strong>></strong> .</p>
2,484,980
Why is volatile not considered useful in multithreaded C or C++ programming?
<p>As demonstrated in <a href="https://stackoverflow.com/questions/2478397/atomic-swap-in-gnu-c/2478520#2478520">this answer</a> I recently posted, I seem to be confused about the utility (or lack thereof) of <code>volatile</code> in multi-threaded programming contexts.</p> <p>My understanding is this: any time a variable may be changed outside the flow of control of a piece of code accessing it, that variable should be declared to be <code>volatile</code>. Signal handlers, I/O registers, and variables modified by another thread all constitute such situations.</p> <p>So, if you have a global int <code>foo</code>, and <code>foo</code> is read by one thread and set atomically by another thread (probably using an appropriate machine instruction), the reading thread sees this situation in the same way it sees a variable tweaked by a signal handler or modified by an external hardware condition and thus <code>foo</code> should be declared <code>volatile</code> (or, for multithreaded situations, accessed with memory-fenced load, which is probably a better a solution).</p> <p>How and where am I wrong?</p>
2,485,177
9
6
null
2010-03-20 22:10:27.36 UTC
131
2019-07-24 22:01:03.01 UTC
2017-05-23 11:33:14.057 UTC
null
-1
null
1,385,039
null
1
179
c++|c|multithreading|volatile|c++-faq
65,796
<p>The problem with <code>volatile</code> in a multithreaded context is that it doesn't provide <em>all</em> the guarantees we need. It does have a few properties we need, but not all of them, so we can't rely on <code>volatile</code> <em>alone</em>.</p> <p>However, the primitives we'd have to use for the <em>remaining</em> properties also provide the ones that <code>volatile</code> does, so it is effectively unnecessary.</p> <p>For thread-safe accesses to shared data, we need a guarantee that:</p> <ul> <li>the read/write actually happens (that the compiler won't just store the value in a register instead and defer updating main memory until much later)</li> <li>that no reordering takes place. Assume that we use a <code>volatile</code> variable as a flag to indicate whether or not some data is ready to be read. In our code, we simply set the flag after preparing the data, so all <em>looks</em> fine. But what if the instructions are reordered so the flag is set <em>first</em>?</li> </ul> <p><code>volatile</code> does guarantee the first point. It also guarantees that no reordering occurs <em>between different volatile reads/writes</em>. All <code>volatile</code> memory accesses will occur in the order in which they're specified. That is all we need for what <code>volatile</code> is intended for: manipulating I/O registers or memory-mapped hardware, but it doesn't help us in multithreaded code where the <code>volatile</code> object is often only used to synchronize access to non-volatile data. Those accesses can still be reordered relative to the <code>volatile</code> ones.</p> <p>The solution to preventing reordering is to use a <em>memory barrier</em>, which indicates both to the compiler and the CPU that <em>no memory access may be reordered across this point</em>. Placing such barriers around our volatile variable access ensures that even non-volatile accesses won't be reordered across the volatile one, allowing us to write thread-safe code.</p> <p>However, memory barriers <em>also</em> ensure that all pending reads/writes are executed when the barrier is reached, so it effectively gives us everything we need by itself, making <code>volatile</code> unnecessary. We can just remove the <code>volatile</code> qualifier entirely.</p> <p>Since C++11, atomic variables (<code>std::atomic&lt;T&gt;</code>) give us all of the relevant guarantees.</p>
2,384,592
Is there a way to force all referenced assemblies to be loaded into the app domain?
<p>My projects are set up like this:</p> <ul> <li>Project "Definition"</li> <li>Project "Implementation"</li> <li>Project "Consumer"</li> </ul> <p>Project "Consumer" references both "Definition" and "Implementation", but does not statically reference any types in "Implementation".</p> <p>When the application starts, Project "Consumer" calls a static method in "Definition", which needs to find types in "Implementation"</p> <p>Is there a way I can force any referenced assembly to be loaded into the App Domain without knowing the path or name, and preferably without having to use a full-fledged IOC framework?</p>
2,384,679
10
4
null
2010-03-05 04:40:15.617 UTC
30
2022-08-29 13:41:05.447 UTC
2014-10-10 19:52:00.85 UTC
null
41,956
null
2,596
null
1
88
c#|assemblies|appdomain
81,012
<p>This seemed to do the trick:</p> <pre class="lang-cs prettyprint-override"><code>var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList(); var loadedPaths = loadedAssemblies.Select(a =&gt; a.Location).ToArray(); var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, &quot;*.dll&quot;); var toLoad = referencedPaths.Where(r =&gt; !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList(); toLoad.ForEach(path =&gt; loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path)))); </code></pre> <p><a href="https://stackoverflow.com/a/2384608/3195477">As Jon noted</a>, the ideal solution would need to recurse into the dependencies for each of the loaded assemblies, but in my specific scenario I don't have to worry about it.</p> <hr /> <p><strong>Update:</strong> The Managed Extensibility Framework (System.ComponentModel) included in .NET 4 has much better facilities for accomplishing things like this.</p>
2,980,763
Javascript objects: get parent
<p>I have the following (nested) object:</p> <pre><code>obj: { subObj: { foo: 'hello world' } }; </code></pre> <p>Next thing I do is to reference the subobject like this:</p> <pre><code>var s = obj.subObj; </code></pre> <p>Now what I would like to do is to get a reference to the object <code>obj</code> out of the variable <code>s</code>. Something like:</p> <pre><code>var o = s.parent; </code></pre> <p>Is this somehow possible?</p>
2,980,771
12
12
null
2010-06-05 14:37:26.233 UTC
38
2017-09-09 05:23:39.08 UTC
2017-09-09 05:23:39.08 UTC
user663031
null
null
251,861
null
1
153
javascript
300,418
<p>No. There is no way of knowing which object it came from.</p> <p><code>s</code> and <code>obj.subObj</code> both simply have references to the same object.</p> <p>You could also do:</p> <pre><code>var obj = { subObj: {foo: 'hello world'} }; var obj2 = {}; obj2.subObj = obj.subObj; var s = obj.subObj; </code></pre> <p>You now have three references, <code>obj.subObj</code>, <code>obj2.subObj</code>, and <code>s</code>, to the same object. None of them is special.</p>
2,672,085
What is the difference between Static and Dynamic arrays in C++?
<p>I have to do an assignment for my class and it says not to use Static arrays, only Dynamic arrays. I've looked in the book and online, but I don't seem to understand.</p> <p>I thought Static was created at <em>compile time</em> and Dynamic at <em>runtime</em>, but I might be mistaking this with memory allocation.</p> <p>Can you explain the difference between static array and dynamic array in C++?</p>
2,672,106
13
3
null
2010-04-20 02:03:40.033 UTC
50
2022-09-19 09:40:16.293 UTC
2022-07-11 00:00:35.593 UTC
null
5,780,109
null
69,514
null
1
106
c++|arrays|dynamic-memory-allocation|static-memory-allocation
273,429
<p>Static arrays are created on the <em>stack</em>, and have automatic storage duration: you don't need to manually manage memory, but they get destroyed when the function they're in ends. They necessarily have a fixed size at <em>compile time</em>:</p> <pre><code>int foo[10]; </code></pre> <p>Arrays created with <code>operator new[]</code> have dynamic storage duration and are stored on the <em>heap</em> (technically the &quot;free store&quot;). They can have any size during <em>runtime</em>, but you need to allocate and free them yourself since they're not part of the stack frame:</p> <pre><code>int* foo = new int[10]; delete[] foo; </code></pre>
2,557,480
Refresh (reload) a page once using jQuery?
<p>I'm wondering how to refresh/reload a page (or even specific div) once(!) using jQuery? </p> <p>Ideally in a way right after the <code>DOM structure</code> is available (cf. <code>onload</code> event) and not negatively affecting <code>back button</code> or <code>bookmark</code> functionality. </p> <p>Please, note: <code>replace()</code> is not allowed due to third-party restrictions. </p>
2,557,515
14
3
null
2010-04-01 00:47:14.13 UTC
22
2018-09-20 05:12:12.683 UTC
2014-12-16 18:28:01.277 UTC
null
2,619,912
null
306,485
null
1
84
jquery|refresh|reload
411,166
<p>Alright, I think I got what you're asking for. Try this</p> <pre><code>if(window.top==window) { // You're not in a frame, so you reload the site. window.setTimeout('location.reload()', 3000); //Reloads after three seconds } else { //You're inside a frame, so you stop reloading. } </code></pre> <hr> <p>If it is once, then just do</p> <pre><code>$('#div-id').triggerevent(function(){ $('#div-id').html(newContent); }); </code></pre> <p>If it is periodically</p> <pre><code>function updateDiv(){ //Get new content through Ajax ... $('#div-id').html(newContent); } setInterval(updateDiv, 5000); // That's five seconds </code></pre> <p>So, every five seconds the div #div-id content will refresh. Better than refreshing the whole page.</p>