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
4,825,907
Convert Int to Guid
<p>I have to convert Convert Int32 into Guids and this is what I came up with.</p> <pre><code>public static class IntExtensions { public static Guid ToGuid(this Int32 value) { if (value &gt;= 0) // if value is positive return new Guid(string.Format("00000000-0000-0000-0000-00{0:0000000000}", value)); else if (value &gt; Int32.MinValue) // if value is negative return new Guid(string.Format("00000000-0000-0000-0000-01{0:0000000000}", Math.Abs(value))); else //if (value == Int32.MinValue) return new Guid("00000000-0000-0000-0000-012147483648"); // Because Abs(-12147483648) generates a stack overflow due to being &gt; 12147483647 (Int32.Max) } } </code></pre> <p>But it’s somehow ugly. Has anybody a better idea?</p> <p>Update:</p> <p>Yes I know the whole thing is ugly but I am a loss of Ideas. The problem is. I am getting data and have to store it into a Table I cannot change. The sending data primary key is a Int and the table primary key I have to store it is a Guid. The problem is I have to understand what object the sender is talking about but can only store it as a Guid.</p> <p>Update 2:</p> <p>Okay I see I have to provide more info here. I am a Webservice receiving data and have to pass along data to an Interface I also can not control. So I neither can model the data received nor the (Interface)database where I have to send the data. Additionally, I have somehow have to map these two things in a way so I somehow can update an item. <em>sigh</em></p>
4,826,200
5
7
null
2011-01-28 07:34:56.39 UTC
11
2020-06-12 15:01:19.263 UTC
2017-01-20 12:16:44.833 UTC
null
996,815
null
213,722
null
1
55
c#
58,694
<p>Here is a simple way to do it:</p> <pre><code>public static Guid ToGuid(int value) { byte[] bytes = new byte[16]; BitConverter.GetBytes(value).CopyTo(bytes, 0); return new Guid(bytes); } </code></pre> <p>You can change where the copy will happen (vary the index from 0 to 12). It really depends on how you want to define this unusual "int to Guid" conversion.</p>
4,349,075
BitmapFactory.decodeResource returns a mutable Bitmap in Android 2.2 and an immutable Bitmap in Android 1.6
<p>I am developing an application and testing it on my device running Android 2.2. In my code, I make use of a Bitmap that I retrieve using BitmapFactory.decodeResource, and I am able to make changes by calling <code>bitmap.setPixels()</code> on it. When I test this on a friend's device running Android 1.6, I get an <code>IllegalStateException</code> in the call to <code>bitmap.setPixels</code>. Documentation online says an <code>IllegalStateException</code> is thrown from this method when the bitmap is immutable. The documentation doesn't say anything about <code>decodeResource</code> returning an immutable bitmap, but clearly that must be the case.</p> <p>Is there a different call I can make to get a mutable bitmap reliably from an application resource without needing a second <code>Bitmap</code> object (I could create a mutable one the same size and draw into a Canvas wrapping it, but that would require two bitmaps of equal size using up twice as much memory as I had intended)?</p>
9,194,259
7
0
null
2010-12-03 19:19:39.867 UTC
26
2021-05-21 10:39:33.69 UTC
2013-05-01 08:29:43.073 UTC
null
1,618,135
null
53,501
null
1
43
java|android|bitmap
59,219
<p>You can convert your immutable bitmap to a mutable bitmap.</p> <p>I found an acceptable solution that uses only the memory of one bitmap. </p> <p>A source bitmap is raw saved (RandomAccessFile) on disk (no ram memory), then source bitmap is released, (now, there's no bitmap at memory), and after that, the file info is loaded to another bitmap. This way is possible to make a bitmap copy having just one bitmap stored in ram memory per time.</p> <p>See the full solution and implementation here: <a href="http://sudarnimalan.blogspot.com/2011/09/android-convert-immutable-bitmap-into.html">Android: convert Immutable Bitmap into Mutable</a></p> <p>I add a improvement to this solution, that now works with any type of Bitmaps (ARGB_8888, RGB_565, etc), and deletes the temp file. See my method:</p> <pre><code>/** * Converts a immutable bitmap to a mutable bitmap. This operation doesn't allocates * more memory that there is already allocated. * * @param imgIn - Source image. It will be released, and should not be used more * @return a copy of imgIn, but muttable. */ public static Bitmap convertToMutable(Bitmap imgIn) { try { //this is the file going to use temporally to save the bytes. // This file will not be a image, it will store the raw image data. File file = new File(Environment.getExternalStorageDirectory() + File.separator + "temp.tmp"); //Open an RandomAccessFile //Make sure you have added uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" //into AndroidManifest.xml file RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); // get the width and height of the source bitmap. int width = imgIn.getWidth(); int height = imgIn.getHeight(); Config type = imgIn.getConfig(); //Copy the byte to the file //Assume source bitmap loaded using options.inPreferredConfig = Config.ARGB_8888; FileChannel channel = randomAccessFile.getChannel(); MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, imgIn.getRowBytes()*height); imgIn.copyPixelsToBuffer(map); //recycle the source bitmap, this will be no longer used. imgIn.recycle(); System.gc();// try to force the bytes from the imgIn to be released //Create a new bitmap to load the bitmap again. Probably the memory will be available. imgIn = Bitmap.createBitmap(width, height, type); map.position(0); //load it back from temporary imgIn.copyPixelsFromBuffer(map); //close the temporary file and channel , then delete that also channel.close(); randomAccessFile.close(); // delete the temp file file.delete(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return imgIn; } </code></pre>
4,371,724
Having to restart tomcat whenever you make a change
<p>Is there a way around having to restart tomcat every time a small change is made in java code?</p>
4,371,821
8
1
null
2010-12-06 22:49:11.433 UTC
14
2016-05-06 05:56:02.267 UTC
2010-12-07 00:57:04.29 UTC
null
495,341
null
495,341
null
1
25
java|tomcat
29,720
<p>Set <code>reloadable</code> attribute of <a href="http://tomcat.apache.org/tomcat-6.0-doc/config/context.html" rel="noreferrer"><code>&lt;Context&gt;</code></a> element in <code>context.xml</code> to <code>true</code>.</p> <pre><code>&lt;Context reloadable="true"&gt; </code></pre> <p>Then Tomcat will monitor changes in <code>/WEB-INF/classes</code> and <code>/WEB-INF/lib</code> and reload whenever appropriate. </p> <p>If you're using an IDE, this is configureable as server setting as well. Here's how it look like in Eclipse:</p> <p><img src="https://i.stack.imgur.com/hQK08.png" alt="alt text"></p>
4,156,055
static linking only some libraries
<p>How can I statically link only a some specific libraries to my binary when linking with GCC?</p> <p><code>gcc ... -static ...</code> tries to statically link <strong>all</strong> the linked libraries, but I haven't got the static version of some of them (eg: libX11).</p>
4,156,190
8
1
null
2010-11-11 15:28:47.363 UTC
57
2018-02-26 16:53:03.087 UTC
2018-02-26 16:53:03.087 UTC
null
13,860
null
300,805
null
1
126
gcc|linker|static-libraries
166,342
<p><code>gcc -lsome_dynamic_lib code.c some_static_lib.a</code></p>
4,137,824
How to elegantly rename all keys in a hash in Ruby?
<p>I have a Ruby hash:</p> <pre><code>ages = { "Bruce" =&gt; 32, "Clark" =&gt; 28 } </code></pre> <p>Assuming I have another hash of replacement names, is there an elegant way to rename all the keys so that I end up with:</p> <pre><code>ages = { "Bruce Wayne" =&gt; 32, "Clark Kent" =&gt; 28 } </code></pre>
4,137,966
11
0
null
2010-11-09 19:48:32.813 UTC
46
2021-06-25 20:05:19.05 UTC
2016-03-28 23:08:17.447 UTC
null
128,421
null
497,469
null
1
101
ruby|hash|key
59,850
<pre><code>ages = { 'Bruce' =&gt; 32, 'Clark' =&gt; 28 } mappings = { 'Bruce' =&gt; 'Bruce Wayne', 'Clark' =&gt; 'Clark Kent' } ages.transform_keys(&amp;mappings.method(:[])) #=&gt; { 'Bruce Wayne' =&gt; 32, 'Clark Kent' =&gt; 28 } </code></pre>
4,418,708
What's the rationale for null terminated strings?
<p>As much as I love C and C++, I can't help but scratch my head at the choice of null terminated strings:</p> <ul> <li>Length prefixed (i.e. Pascal) strings existed before C</li> <li>Length prefixed strings make several algorithms faster by allowing constant time length lookup.</li> <li>Length prefixed strings make it more difficult to cause buffer overrun errors.</li> <li>Even on a 32 bit machine, if you allow the string to be the size of available memory, a length prefixed string is only three bytes wider than a null terminated string. On 16 bit machines this is a single byte. On 64 bit machines, 4GB is a reasonable string length limit, but even if you want to expand it to the size of the machine word, 64 bit machines usually have ample memory making the extra seven bytes sort of a null argument. I know the original C standard was written for insanely poor machines (in terms of memory), but the efficiency argument doesn't sell me here.</li> <li>Pretty much every other language (i.e. Perl, Pascal, Python, Java, C#, etc) use length prefixed strings. These languages usually beat C in string manipulation benchmarks because they are more efficient with strings.</li> <li>C++ rectified this a bit with the <code>std::basic_string</code> template, but plain character arrays expecting null terminated strings are still pervasive. This is also imperfect because it requires heap allocation.</li> <li>Null terminated strings have to reserve a character (namely, null), which cannot exist in the string, while length prefixed strings can contain embedded nulls.</li> </ul> <p>Several of these things have come to light more recently than C, so it would make sense for C to not have known of them. However, several were plain well before C came to be. Why would null terminated strings have been chosen instead of the obviously superior length prefixing?</p> <p><strong>EDIT</strong>: Since some asked for <em>facts</em> (and didn't like the ones I already provided) on my efficiency point above, they stem from a few things:</p> <ul> <li>Concat using null terminated strings requires O(n + m) time complexity. Length prefixing often require only O(m).</li> <li>Length using null terminated strings requires O(n) time complexity. Length prefixing is O(1).</li> <li>Length and concat are by far the most common string operations. There are several cases where null terminated strings can be more efficient, but these occur much less often.</li> </ul> <p>From answers below, these are some cases where null terminated strings are more efficient:</p> <ul> <li>When you need to cut off the start of a string and need to pass it to some method. You can't really do this in constant time with length prefixing even if you are allowed to destroy the original string, because the length prefix probably needs to follow alignment rules.</li> <li>In some cases where you're just looping through the string character by character you might be able to save a CPU register. Note that this works only in the case that you haven't dynamically allocated the string (Because then you'd have to free it, necessitating using that CPU register you saved to hold the pointer you originally got from malloc and friends).</li> </ul> <p>None of the above are nearly as common as length and concat.</p> <p>There's one more asserted in the answers below:</p> <ul> <li>You need to cut off the end of the string</li> </ul> <p>but this one is incorrect -- it's the same amount of time for null terminated and length prefixed strings. (Null terminated strings just stick a null where you want the new end to be, length prefixers just subtract from the prefix.)</p>
4,418,774
20
43
null
2010-12-11 20:13:28.317 UTC
101
2021-12-28 03:41:57.023 UTC
2017-03-21 19:44:47.827 UTC
null
7,392,286
null
82,320
null
1
302
c++|c|string|null-terminated
30,475
<p>From the <a href="https://www.bell-labs.com/usr/dmr/www/chist.html" rel="noreferrer">horse's mouth</a> </p> <blockquote> <p>None of BCPL, B, or C supports character data strongly in the language; each treats strings much like vectors of integers and supplements general rules by a few conventions. In both BCPL and B a string literal denotes the address of a static area initialized with the characters of the string, packed into cells. In BCPL, the first packed byte contains the number of characters in the string; in B, there is no count and strings are terminated by a special character, which B spelled <code>*e</code>. This change was made partially to avoid the limitation on the length of a string caused by holding the count in an 8- or 9-bit slot, and partly because maintaining the count seemed, in our experience, less convenient than using a terminator.</p> </blockquote> <p><sub>Dennis M Ritchie, <em>Development of the C Language</em></sub></p>
14,473,488
Is String a primitive or an Object in Android or Java?
<p>In the Android API <a href="http://developer.android.com/guide/topics/data/data-storage.html#pref" rel="noreferrer">http://developer.android.com/guide/topics/data/data-storage.html#pref</a> </p> <p>It says:</p> <blockquote> <p>Shared Preference allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings.</p> </blockquote> <p>Is String a primitive data type or an Object?</p>
14,473,567
6
6
null
2013-01-23 06:08:57.097 UTC
6
2018-10-11 08:22:55.947 UTC
2015-02-09 15:43:44.553 UTC
null
445,131
null
804,486
null
1
21
java|android|string|sharedpreferences|primitive
45,585
<p>As far as <code>Java</code> programming language is considered,</p> <blockquote> <p>A primitive type is predefined by the language and is named by a reserved keyword.</p> <p>In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the <code>java.lang.String</code> class.</p> </blockquote> <p>—— from <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html" rel="nofollow noreferrer">The Java™ Tutorials - Primitive Data Types</a></p> <p>So, as such in <code>Java</code> books, it's not a keyword and not a primitive either. <code>SharedPreferences</code> may still call it one of the primitives, but that's not from the book of <code>Java</code> as such, it could be because it's one of the set of basic types like int, float, char etc we come across.</p>
14,654,998
How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?
<p>I've done a lot of googling but not had much luck with my issues. I am new to network programming and trying to learn, I've attempted to set up a simple server &amp; client that communicate (following an online tutorial located here -> <a href="http://tech.pro/tutorial/704/csharp-tutorial-simple-threaded-tcp-server" rel="noreferrer">http://tech.pro/tutorial/704/csharp-tutorial-simple-threaded-tcp-server</a>)</p> <p>The issue I'm having is that I keep getting the exception "Only one usage of each socket address (protocol/network address/port) is normally permitted" when trying to start the TcpListener on the server.</p> <p>I've tried disabling my firewall, changing the port to be used, moving variables around but to no avail (the client works fine, but it obviously can't find the server because I cannot launch it).</p> <p>I've seen solutions describing the use of Socket.Poll() but since I'm only using the TcpListener object, I have no idea how to make use of the Poll function.</p> <p>My code: </p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Net; using System.Threading; using System.Text; namespace ServerTutorial { class Server { private readonly Thread m_listenThread; public Server() { m_listenThread = new Thread(new ThreadStart(ListenForClients)); m_listenThread.Start(); } public void ListenForClients() { var listener = new TcpListener(IPAddress.Any, 3000); listener.Start(); while (true) { //Blocks until a client has connected to the server TcpClient client = listener.AcceptTcpClient(); //Send a message to the client var encoder = new ASCIIEncoding(); NetworkStream clientStream = client.GetStream(); byte[] buffer = encoder.GetBytes("Hello Client!"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); //Create a thread to handle communication with the connected client var clientThread = new Thread(new ParameterizedThreadStart(HandleClient)); clientThread.Start(client); } } private void HandleClient(object clientObj) { //Param thread start can only accept object types, hence the cast var client = (TcpClient) clientObj; NetworkStream clientStream = client.GetStream(); var message = new byte[4096]; while (true) { int bytesRead = 0; try { //Block until a client sends a message bytesRead = clientStream.Read(message, 0, 4096); } catch { //A socket error has occurred System.Diagnostics.Debug.WriteLine("A socket error has occured"); break; } if (bytesRead == 0) { //The client has disconnected from the server System.Diagnostics.Debug.WriteLine("A client has disconnected from the server"); client.Close(); break; } //Message has been received var encoder = new ASCIIEncoding(); System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead)); } } } } </code></pre> <p>In my main method:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ServerTutorial { class Program { static void Main(string[] args) { var server = new Server(); server.ListenForClients(); } } } </code></pre> <p>Any help is hugely appreciated!</p>
14,655,041
3
1
null
2013-02-01 21:03:00.907 UTC
7
2018-07-16 03:25:24.277 UTC
2017-05-30 09:40:58.69 UTC
null
133
null
1,319,751
null
1
43
c#|exception|networking|tcplistener
114,115
<p><code>ListenForClients</code> is getting invoked twice (on two different threads) - once from the constructor, once from the explicit method call in <code>Main</code>. When two instances of the <code>TcpListener</code> try to listen on the same port, you get that error.</p>
14,778,364
Select All checkboxes using jQuery
<p>I have the following html code:</p> <pre><code> &lt;input type="checkbox" id="ckbCheckAll" /&gt; &lt;p id="checkBoxes"&gt; &lt;input type="checkbox" class="checkBoxClass" id="Checkbox1" /&gt; &lt;br /&gt; &lt;input type="checkbox" class="checkBoxClass" id="Checkbox2" /&gt; &lt;br /&gt; &lt;input type="checkbox" class="checkBoxClass" id="Checkbox3" /&gt; &lt;br /&gt; &lt;input type="checkbox" class="checkBoxClass" id="Checkbox4" /&gt; &lt;br /&gt; &lt;input type="checkbox" class="checkBoxClass" id="Checkbox5" /&gt; &lt;br /&gt; &lt;/p&gt; </code></pre> <p>When user checks <code>ckbCheckAll</code> all checkboxes must be checked. Also I have following jquery code:</p> <pre><code> $(document).ready(function () { $("#ckbCheckAll").click(function () { $(".checkBoxClass").attr('checked', this.checked); }); }); </code></pre> <p>When I see my page in the browser I get the following result: In the first click on <code>ckbCheckAll</code> all checkboxes were checked (which is correct). In the second click on <code>ckbCheckAll</code> all checkboxes were unchecked (which is correct). But in 3rd attempt nothing happened! also in 4th attempt nothing happened and so on.</p> <p>Where is the problem?</p>
14,778,444
16
1
null
2013-02-08 17:47:15.41 UTC
8
2021-02-07 13:17:26.587 UTC
2018-01-10 16:35:37.497 UTC
null
55,075
null
953,975
null
1
50
javascript|jquery
141,282
<p>Use prop</p> <pre><code>$(".checkBoxClass").prop('checked', true); </code></pre> <p>or to uncheck:</p> <pre><code>$(".checkBoxClass").prop('checked', false); </code></pre> <p><a href="http://jsfiddle.net/sVQwA/">http://jsfiddle.net/sVQwA/</a></p> <pre><code>$("#ckbCheckAll").click(function () { $(".checkBoxClass").prop('checked', $(this).prop('checked')); }); </code></pre> <p>Updated JSFiddle Link: <a href="http://jsfiddle.net/sVQwA/1/">http://jsfiddle.net/sVQwA/1/</a></p>
14,882,642
Scala: Why mapValues produces a view and is there any stable alternatives?
<p>Just now I am surprised to learn that <code>mapValues</code> produces a view. The consequence is shown in the following example:</p> <pre><code>case class thing(id: Int) val rand = new java.util.Random val distribution = Map(thing(0) -&gt; 0.5, thing(1) -&gt; 0.5) val perturbed = distribution mapValues { _ + 0.1 * rand.nextGaussian } val sumProbs = perturbed.map{_._2}.sum val newDistribution = perturbed mapValues { _ / sumProbs } </code></pre> <p>The idea is that I have a distribution, which is perturbed with some randomness then I renormalize it. The code actually fails in its original intention: since <code>mapValues</code> produces a <code>view</code>, <code>_ + 0.1 * rand.nextGaussian</code> is always re-evaluated whenever <code>perturbed</code> is used.</p> <p>I am now doing something like <code>distribution map { case (s, p) =&gt; (s, p + 0.1 * rand.nextGaussian) }</code>, but that's just a little bit verbose. So the purpose of this question is:</p> <ol> <li>Remind people who are unaware of this fact.</li> <li>Look for reasons why they make <code>mapValues</code> output <code>view</code>s.</li> <li>Whether there is an alternative method that produces concrete <code>Map</code>.</li> <li>Are there any other commonly-used collection methods that have this trap.</li> </ol> <p>Thanks.</p>
14,883,167
3
6
null
2013-02-14 19:34:03.383 UTC
8
2019-11-11 15:45:25.567 UTC
null
null
null
null
1,830,538
null
1
63
scala|map
9,378
<p>There's a ticket about this, <a href="https://issues.scala-lang.org/browse/SI-4776" rel="noreferrer">SI-4776</a> (by YT).</p> <p>The commit that introduces it has this to say:</p> <blockquote> <p>Following a suggestion of jrudolph, made <code>filterKeys</code> and <code>mapValues</code> transform abstract maps, and duplicated functionality for immutable maps. Moved <code>transform</code> and <code>filterNot</code> from immutable to general maps. Review by phaller.</p> </blockquote> <p>I have not been able to find the original suggestion by jrudolph, but I assume it was done to make <code>mapValues</code> more efficient. Give the question, that may come as a surprise, but <code>mapValues</code> <em>is</em> more efficient if you are not likely to iterate over the values more than once.</p> <p>As a work-around, one can do <code>mapValues(...).view.force</code> to produce a new <code>Map</code>.</p>
23,896,690
Securing OAuth clientId/clientSecret in AngularJS application
<p>I know this is probably an age-old question, but...are there any best practices for securing client secrets for performing OAuth2 authentication in AngularJS applications? I've been racking my brain trying to think of a solution to providing truly secure access to an API from modern style web applications (they need not necessarily be AngularJS.) In my experience, adding layers of abstraction and obfuscation really don't do anything to improve security...they just make cracking the security egg more difficult for any prospective hackers (however many of them prefer a good challenge, so all your really doing is just making the hack more fun.)</p> <p>Aside from the obvious ineffective solutions such as obfuscation and convolution of code and things like that, are there any best practices for securing client secrets in modern day web applications? I know these questions arose with desktop client apps, and I don't believe there was ever a solution beyond "Might as well obfuscate, that'll slow hackers down". Are we in the same boat with web apps? Is there no real solution to this problem?</p> <p>If there is not a solution...is there even really any point in securing REST APIs with OAuth?</p>
24,621,760
2
0
null
2014-05-27 18:40:54.14 UTC
8
2016-03-14 08:10:14.117 UTC
null
null
null
null
111,554
null
1
15
angularjs|security|oauth|token|secret-key
12,918
<p>Remember that <em><strong>OAuth</strong></em> is less about protecting against impersonation and more about protecting credentials. 3rd parties authenticated a user's identity for you without exposing the user's credentials. Since Tokens are not credentials, the amount of harm a hacker can do and his window to act are limited.</p> <p>But <em><strong>OAuth</strong></em> is not inherently more secure for your application than regular username/pwd authentication. And on client-side apps, all your code is available for the world to see! As you mentioned, client-side encryption is a questionable strategy.</p> <hr /> <p><strong>While there aren't established best practices for protecting client interactions, here are some approaches to minimize your exposure:</strong></p> <p><strong>1) SSL:</strong> Silver bullet? Maybe. The more you can use <em><strong>SSL</strong></em> in your site and your requests, the safer your users' requests will be. I honestly believe all privileged requests should be made by encrypted requests.</p> <p><strong>2) Short Token Life-Span:</strong> The shorter the life-span of your Token, the less incentive/advantage of sniffing it.</p> <p>OAuth 2.0 creates a constant chatter out of authentication by exchanging Authentication Tokens for Refresh Tokens for Authentication Tokens. You, as the developer are now developing a chatty app that does a lot of &quot;what's your token, here's another token, ask me for a token, here's your new token... so what do you want?&quot; ... &quot;oops, time's up, where's your Refresh Token?&quot;</p> <p>If that sounds like a pain, it kind of is. OAuth 2.0 is designed to make the process easier for you the developer. But the important point is, the shorter the life span of your tokens, the harder for a hacker to maintain a fraudulent identity. <strong><a href="https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-22#section-1.5" rel="nofollow noreferrer">Refresh Token reference</a></strong></p> <p><strong>3) Enforce your Domain:</strong> Want to give sniffers less chance of abusing the chinks in your armor? Don't allow Cross Domain Requests!</p> <p>Sure, we often have distributed environments. But if your Facade is on the Client's Domain, your exposure is lessened (word choice questionable).</p> <p>Force the hacker to use your domain, limit their creativity.</p> <p><strong>4) Use 3rd party API's for maintaining you access as often as possible:</strong> <em><strong>Google</strong></em> and <em><strong>Facebook</strong></em> API's and Services have been unit tested, battle tested, and evolved. The more you can lean on them to maintain your user's Identity, the less work you will do and fewer chances you take.</p> <p><strong>5) Check IP addresses:</strong> Almost anything can be faked, but the hacker must know that IP Address is part of your validation. This is the least assured of all practices, but combined with 1,2, or more, the gaps for hackers to exploit get smaller and the payoffs for effort fade.</p> <p><strong>6) Use a &quot;Secret&quot; or 2nd parameter:</strong> You can pass your users more than tokens. You can pass your own Alter-Token.</p> <p>Pretend it's an ID data being passed back and forth. Name the param in a non-obvious way. Make it a number (e.g. age, height, address). The important point is, your hacker knows little or nothing of what's being asked for on the other side!</p> <p>You can throw a serious monkey-wrench by having 3 params that act as security.</p> <p><strong>7)</strong> Don't give error messages to inform the hacker they've been caught. Give timeout msgs rather than &quot;Got You!&quot; If the invaders don't realize the fraud was caught they don't adapt as well.</p> <hr /> <p><strong>I can't say it enough -- SSL saves a lot of trouble.</strong></p> <p><strong>Note:</strong> All client Providers I have seen allow access to their API's without exposing Secret. <strong>Secret should never be exposed on client.</strong></p> <ul> <li>Any data exposed on client can be gleamed</li> <li>Any encryption algorithm you use, will be exposed on the client.</li> </ul>
45,655,019
How do I add SSL with Firebase Hosting?
<p>I uploaded my angular 4 project to Firebase Hosting and it works well on Firebase's domain. However, when I connect it to my custom domain it should use SSL but as you can see on the image below, SSL is not active.</p> <p><a href="https://i.stack.imgur.com/bPZs9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bPZs9.png" alt="SSL Error" /></a></p> <p>How do I set up SSL with Firebase Hosting?</p>
45,656,420
1
0
null
2017-08-12 21:17:20.37 UTC
5
2020-09-17 16:17:19.42 UTC
2020-09-17 16:17:19.42 UTC
null
10,871,073
null
8,310,147
null
1
30
firebase|firebase-hosting
21,842
<p>Firebase Hosting will only serve traffic over SSL. However it may take a bit of time before your custom domain propagates. During this time, you'll see the "not secure" warning and may even see a different domain name when you click it.</p> <p>If the problem persists and you're not able/willing to share the domain name here, <a href="https://firebase.google.com/support/contact/troubleshooting/" rel="noreferrer">reach out to Firebase support</a> for personalized help in troubleshooting</p>
3,000,653
Using NLog as a rollover file logger
<p>How - if possible - can I use NLog as a rollover file logger? as if:</p> <p>I want to have at most 31 files for 31 days and when a new day started, if there is an old day log file ##.log, then it should be deleted but during that day all logs are appended and will be there at least for 27 days.</p>
17,743,051
2
0
null
2010-06-08 19:39:11.22 UTC
13
2016-11-26 01:14:19.123 UTC
null
null
null
null
54,467
null
1
24
c#|.net|nlog
32,401
<p>Finally I have settled with <a href="https://github.com/nlog/NLog/wiki/File-target#size-based-file-archival" rel="noreferrer">size-based file archival</a>. I use a trick to name the file after just the day of month and I needed the size-based file archival because it really helps when you logs begin to grow beyond some hundred mega-bytes. It helps to make - for example - 20 MB chunks of log, so one can easily take a quick look at it with a light weight tool like Notepad++.</p> <p>It is working for almost a year now. Here is a simplified version of my <code>NLog.config</code> file:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;nlog autoReload="true" throwExceptions="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;variable name="LogDir" value="${specialfolder:folder=MyDocuments}/MyApp/Log"/&gt; &lt;variable name="LogDay" value="${date:format=dd}"/&gt; &lt;targets&gt; &lt;target name="LogTarget1" xsi:type="File" fileName="${LogDir}/${LogDay}.log" encoding="utf-8" maxArchiveFiles="10" archiveNumbering="Sequence" archiveAboveSize="1048576" archiveFileName="${LogDir}/{#######}.a" /&gt; &lt;/targets&gt; &lt;rules&gt; &lt;logger name="AppLog" writeTo="LogTarget1" /&gt; &lt;/rules&gt; &lt;/nlog&gt; </code></pre> <p>This config makes 1 MB log file for each day of month and keep at most 10 archived 1 MB log chunks in <code>My Documents\MyApp\Log</code> folder; like <code>29.log</code>, <code>30.log</code> and <code>31.log</code>.</p> <p><strong>Edit:</strong> It's for some time that I use this <code>NLog.config</code> file and it covers pretty much every cases that I need. I have different levels of logging from different classes in separate files and when they've got big, they will get archived based on size, in a hourly manner:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;nlog autoReload="true" throwExceptions="true" internalLogFile="nlog-internals.log" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;variable name="LogHome" value="${basedir}/Log"/&gt; &lt;variable name="DailyDir" value="${LogHome}/${date:format=yyyy}/${date:format=MM}/${date:format=dd}"/&gt; &lt;variable name="HourlyArchive" value="${DailyDir}/${date:format=HH}-Archive/${level}-${logger}-{#######}-archived.a"/&gt; &lt;variable name="AppLogPath" value="${DailyDir}/${level}-${logger}.log"/&gt; &lt;variable name="DataLogPath" value="${DailyDir}/_data/inouts-${shortdate}.log"/&gt; &lt;variable name="EventSource" value="Application" /&gt; &lt;targets&gt; &lt;target name="AppAsyncTarget" xsi:type="AsyncWrapper"&gt; &lt;target xsi:type="RetryingWrapper" retryDelayMilliseconds="3000" retryCount="10"&gt; &lt;target xsi:type="File" fileName="${AppLogPath}" encoding="utf-8" maxArchiveFiles="50" archiveNumbering="Sequence" archiveAboveSize="1048576" archiveFileName="${HourlyArchive}" layout="`${longdate}`${level}`${message}" /&gt; &lt;/target&gt; &lt;/target&gt; &lt;target name="DataAsyncTarget" xsi:type="AsyncWrapper"&gt; &lt;target xsi:type="RetryingWrapper" retryDelayMilliseconds="1500" retryCount="300"&gt; &lt;target xsi:type="File" fileName="${DataLogPath}" encoding="utf-8" layout="`${longdate}`${message}" /&gt; &lt;/target&gt; &lt;/target&gt; &lt;target name="EventLogAsyncTarget" xsi:type="AsyncWrapper"&gt; &lt;target xsi:type="RetryingWrapper"&gt; &lt;target xsi:type="EventLog" source="${EventSource}" machineName="." /&gt; &lt;/target&gt; &lt;/target&gt; &lt;/targets&gt; &lt;rules&gt; &lt;logger name="Data" writeTo="DataAsyncTarget" final="true" /&gt; &lt;logger name="Event" writeTo="EventLogAsyncTarget" final="true" /&gt; &lt;logger name="*" writeTo="AppAsyncTarget" /&gt; &lt;/rules&gt; &lt;/nlog&gt; </code></pre> <p>And in each class that I want a logging functionality, I put this:</p> <pre><code>static readonly Logger SlotClassLogger = LogManager.GetCurrentClassLogger(); static Logger ClassLogger { get { return SlotClassLogger; } } </code></pre> <p>Two additional loggers are for piling some data on a daily basis and writing to Windows Event Log; which are app-wide loggers:</p> <pre><code>public static Logger DataLog { get; private set; } public static Logger AppEventLog { get; private set; } </code></pre> <p>And they should be initialize at app start:</p> <pre><code>DataLog = LogManager.GetLogger("Data"); AppEventLog = LogManager.GetLogger("Event"); </code></pre> <p>Note: Sometimes on you app exit you get an exception produced by NLog. It's because something that is not initialized, can not get disposed! You have just write an empty entry into your logger at app start, say:</p> <pre><code>DataLog.Info(string.Empty); </code></pre> <p>I have added this size limitation so log file can be viewed in (say) Notepad on a low-end server, for quick reviews. You should modify them based on your needs.</p>
2,645,293
Automapper failing to map on IEnumerable
<p>I have two classes like so:</p> <pre><code>public class SentEmailAttachment : ISentEmailAttachment { public SentEmailAttachment(); public string FileName { get; set; } public string ID { get; set; } public string SentEmailID { get; set; } public string StorageService { get; set; } public string StorageServiceFileID { get; set; } } </code></pre> <p>And</p> <pre><code>public class SentEmailAttachmentItem : ISentEmailAttachment { [ItemName] public string ID { get; set; } public string SentEmailID { get; set; } public string FileName { get; set; } public string StorageService { get; set; } public string StorageServiceFileID { get; set; } } </code></pre> <p>Identical, as you can see (they both implement interface to ensure this)</p> <p>I then have the following mapping:</p> <pre><code>Mapper.CreateMap&lt;IEnumerable&lt;SentEmailAttachmentItem&gt;, IEnumerable&lt;SentEmailAttachment&gt;&gt;(); Mapper.CreateMap&lt;IEnumerable&lt;SentEmailAttachment&gt;, IEnumerable&lt;SentEmailAttachmentItem&gt;&gt;(); </code></pre> <p>I then have the following Unit test:</p> <pre><code>//create a load of sent email attachments var listOfSentEmailAttachments = new List&lt;SentEmailAttachment&gt;(); for (int i = 0; i &lt; 10; i++) listOfSentEmailAttachments.Add(new SentEmailAttachment { FileName = "testFileName", ID = Guid.NewGuid().ToString(), SentEmailID = Guid.NewGuid().ToString(), StorageService = "S3", StorageServiceFileID = "SomeFileID" }); var sentEmailAttachmentItems = Mapper.DynamicMap&lt;IEnumerable&lt;SentEmailAttachment&gt;, IEnumerable&lt;SentEmailAttachmentItem&gt;&gt;(listOfSentEmailAttachments); var itemToTest = sentEmailAttachmentItems.First(); Assert.IsInstanceOfType(itemToTest, typeof(SentEmailAttachmentItem)); </code></pre> <p>This fails - The IEnumerable sentEmailAttachmentItems is empty. It didn't map the list of SentEmailAttachments to it...</p> <p>Any idea what's going on??</p> <p>I have it working on single objects (mapping one of each to one of each) but not a collection...</p>
2,646,570
2
0
null
2010-04-15 12:47:21.94 UTC
7
2015-11-18 15:29:48.077 UTC
2011-11-09 23:38:17.547 UTC
null
221,708
null
131,809
null
1
55
c#|automapper
45,809
<p>You do not need to explicitly map collection types, only the item types. Just do:</p> <pre><code>Mapper.CreateMap&lt;SentEmailAttachment, SentEmailAttachmentItem&gt;(); var attachments = Mapper.Map&lt;IEnumerable&lt;SentEmailAttachment&gt;, List&lt;SentEmailAttachmentItem&gt;&gt;(someList); </code></pre> <p>That will work just fine.</p>
48,686,826
React js - What is the difference betwen HOC and decorator
<p>Can someone explain what is the difference between these two? I mean except the syntactic difference, do both of these techniques are used to achieve the same thing (which is to reuse component logic)?</p>
48,688,778
3
1
null
2018-02-08 13:38:05.257 UTC
5
2021-10-16 18:47:40.987 UTC
null
null
null
null
5,108,111
null
1
33
reactjs|python-decorators|higher-order-components
13,605
<p>For all practical reasons, decorators and HOC (Higher-Order-Component aka Wrapper) do the same thing.</p> <p>One major difference is that, once you add a decorator, the property/class can only be used in it's decorated form. HOC pattern leaves higher order as well as the lower order components available for use.</p> <p>For further reading on decorators -&gt; <a href="https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841" rel="nofollow noreferrer">https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841</a><br /> Decorators isn't a widely implemented JS feature. It is still in its proposal stage. Babel 7 by default allows decorators as a default plugin in their stage 0 configuration. <a href="https://babeljs.io/docs/plugins/transform-decorators/" rel="nofollow noreferrer">https://babeljs.io/docs/plugins/transform-decorators/</a></p>
1,360,579
Post Publish Events
<p>For normal (say Windows Forms) C# applications, to execute commands after a successful build I would use the Build Events->Post-build event command line in Project Properties.</p> <p>I have a Web Site project which I "Publish", using the "Publish..." command in the context menu in the solution explorer.</p> <p>Is there a way to run commands after the successful publish and if so how is it done? (eg a Post-Publish event command line field)</p> <p>Visual Studio 2008, ASP .Net Web site project, C#.</p>
1,360,604
1
0
null
2009-09-01 04:53:06.363 UTC
3
2009-10-29 03:22:17.85 UTC
null
null
null
null
154,186
null
1
35
c#|asp.net|visual-studio-2008|events|publish
21,405
<p><strong>Update:</strong> Since Publish Web does not apply to folder-based web site projects, this answer assumes you are asking about a Web Application project.</p> <p>You can't do this from inside the VS IDE. However, you can edit your project file in Notepad or your favorite XML editor and add a new target at the end of the file called <code>AfterPublish</code>.</p> <p>You might want to read a bit more on <a href="http://msdn.microsoft.com/en-us/library/ms171451.aspx" rel="noreferrer">MSBuild</a> if you are not sure what you can do in this target.</p> <p>You can find more details on extending the build process in VS at MSDN - <a href="http://msdn.microsoft.com/en-us/library/ms366724.aspx" rel="noreferrer">HowTo: Extend the Visual Studio Build Process</a>.</p>
2,157,554
How to handle command-line arguments in PowerShell
<p>What is the "best" way to handle command-line arguments?</p> <p>It seems like there are several answers on what the "best" way is and as a result I am stuck on how to handle something as simple as:</p> <pre><code>script.ps1 /n name /d domain </code></pre> <p>AND</p> <pre><code>script.ps1 /d domain /n name. </code></pre> <p>Is there a plugin that can handle this better? I know I am reinventing the wheel here.</p> <p>Obviously what I have already isn't pretty and surely isn't the "best", but it works.. and it is UGLY.</p> <pre><code>for ( $i = 0; $i -lt $args.count; $i++ ) { if ($args[ $i ] -eq "/n"){ $strName=$args[ $i+1 ]} if ($args[ $i ] -eq "-n"){ $strName=$args[ $i+1 ]} if ($args[ $i ] -eq "/d"){ $strDomain=$args[ $i+1 ]} if ($args[ $i ] -eq "-d"){ $strDomain=$args[ $i+1 ]} } Write-Host $strName Write-Host $strDomain </code></pre>
2,157,625
1
0
null
2010-01-28 20:01:10.357 UTC
147
2022-04-22 17:47:56.18 UTC
2015-06-29 19:15:30.243 UTC
null
299,327
null
261,317
null
1
571
powershell|command-line-arguments
832,861
<p>You are reinventing the wheel. Normal PowerShell scripts have parameters starting with <code>-</code>, like <code>script.ps1 -server http://devserver</code></p> <p>Then you handle them in a <code>param</code> section (note that this <strong>must</strong> begin at the first non-commented line in your script).</p> <p>You can also assign default values to your params, read them from console if not available or stop script execution:</p> <pre><code> param ( [string]$server = &quot;http://defaultserver&quot;, [Parameter(Mandatory=$true)][string]$username, [string]$password = $( Read-Host &quot;Input password, please&quot; ) ) </code></pre> <p>Inside the script you can simply</p> <pre><code>write-output $server </code></pre> <p>since all parameters become variables available in script scope.</p> <p>In this example, the <code>$server</code> gets a default value if the script is called without it, script stops if you omit the <code>-username</code> parameter and asks for terminal input if <code>-password</code> is omitted.</p> <p>Update: You might also want to pass a &quot;flag&quot; (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a &quot;force&quot; where the script runs in a more careful mode when force is not used.</p> <p>The keyword for that is <code>[switch]</code> parameter type:</p> <pre><code> param ( [string]$server = &quot;http://defaultserver&quot;, [string]$password = $( Read-Host &quot;Input password, please&quot; ), [switch]$force = $false ) </code></pre> <p>Inside the script then you would work with it like this:</p> <pre><code>if ($force) { //deletes a file or does something &quot;bad&quot; } </code></pre> <p>Now, when calling the script you'd set the switch/flag parameter like this:</p> <pre><code>.\yourscript.ps1 -server &quot;http://otherserver&quot; -force </code></pre> <p>If you explicitly want to state that the flag is not set, there is a special syntax for that</p> <pre><code>.\yourscript.ps1 -server &quot;http://otherserver&quot; -force:$false </code></pre> <p>Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):</p> <ul> <li><a href="https://technet.microsoft.com/en-us/library/hh847841.aspx" rel="noreferrer">about_Scripts</a></li> <li><a href="https://technet.microsoft.com/en-us/library/hh847829.aspx" rel="noreferrer">about_Functions</a></li> <li><a href="https://technet.microsoft.com/en-us/library/hh847743.aspx" rel="noreferrer">about_Functions_Advanced_Parameters</a></li> </ul>
31,302,232
Gradle task check if property is defined
<p>I have a Gradle task that executes a TestNG test suite. I want to be able to pass a flag to the task in order to use a special TestNG XML suite file (or just use the default suite if the flag isn't set).</p> <pre class="lang-bash prettyprint-override"><code>gradle test </code></pre> <p>... should run the default standard suite of tests</p> <pre class="lang-bash prettyprint-override"><code>gradle test -Pspecial </code></pre> <p>... should run the special suite of tests</p> <p>I've been trying something like this:</p> <pre><code>test { if (special) { test(testng_special.xml); } else { test(testng_default.xml); } } </code></pre> <p>But I get a undefined property error. What is the correct way to go about this?</p>
31,302,279
4
0
null
2015-07-08 19:42:34.25 UTC
null
2022-06-07 16:21:28.817 UTC
2022-06-07 16:21:28.817 UTC
null
8,583,692
null
2,506,293
null
1
55
gradle|properties|testng|build.gradle|task
49,252
<pre><code>if (project.hasProperty('special')) </code></pre> <p>should do it.</p> <p>Note that what you're doing to select a testng suite won't work, AFAIK: the test task doesn't have any <code>test()</code> method. Refer to <a href="https://discuss.gradle.org/t/how-to-run-acceptance-tests-with-testng-from-gradle/4107">https://discuss.gradle.org/t/how-to-run-acceptance-tests-with-testng-from-gradle/4107</a> for a working example:</p> <pre><code>test { useTestNG { suites 'src/main/resources/testng.xml' } } </code></pre>
40,557,606
How to URL encode in Python 3?
<p>I have tried to follow <a href="https://docs.python.org/3.0/library/urllib.parse.html" rel="noreferrer">the documentation</a> but was not able to use <code>urlparse.parse.quote_plus()</code> in <code>Python 3</code>:</p> <pre><code>from urllib.parse import urlparse params = urlparse.parse.quote_plus({'username': 'administrator', 'password': 'xyz'}) </code></pre> <p>I get</p> <blockquote> <p>AttributeError: 'function' object has no attribute 'parse'</p> </blockquote>
40,557,716
3
0
null
2016-11-11 23:09:21.333 UTC
14
2022-08-26 20:54:45.923 UTC
null
null
null
null
1,312,080
null
1
90
python|urlencode
197,922
<p>You misread the documentation. You need to do two things:</p> <ol> <li>Quote each key and value from your dictionary, and</li> <li>Encode those into a URL</li> </ol> <p>Luckily <code>urllib.parse.urlencode</code> does both those things in a single step, and that's the function you should be using.</p> <pre><code>from urllib.parse import urlencode, quote_plus payload = {'username':'administrator', 'password':'xyz'} result = urlencode(payload, quote_via=quote_plus) # 'password=xyz&amp;username=administrator' </code></pre>
40,710,811
Count items greater than a value in pandas groupby
<p>I have the Yelp dataset and I want to count all reviews which have greater than 3 stars. I get the count of reviews by doing this:</p> <pre><code>reviews.groupby('business_id')['stars'].count() </code></pre> <p>Now I want to get the count of reviews which had more than 3 stars, so I tried this by taking inspiration from <a href="https://stackoverflow.com/questions/22751498/pandas-groupby-apply-function-to-count-values-greater-than-zero">here</a>:</p> <pre><code>reviews.groupby('business_id')['stars'].agg({'greater':lambda val: (val &gt; 3).count()}) </code></pre> <p>But this just gives me the count of all stars like before. I am not sure if this is the right way to do it? What am I doing incorrectly here. Does the lambda expression not go through each value of the stars column?</p> <p>EDIT: Okay I feel stupid. I should have used the sum function instead of count to get the value of elements greater than 3, like this:</p> <pre><code>reviews.groupby('business_id')['stars'].agg({'greater':lambda val: (val &gt; 3).sum()}) </code></pre>
40,710,862
6
0
null
2016-11-20 23:47:25.59 UTC
2
2022-02-03 09:01:28.93 UTC
2017-05-23 11:59:55.387 UTC
null
-1
null
4,928,920
null
1
22
python|python-3.x|pandas
50,503
<p>You can try to do : </p> <pre><code>reviews[reviews['stars'] &gt; 3].groupby('business_id')['stars'].count() </code></pre>
55,679,401
Remove prefix (or suffix) substring from column headers in pandas
<p>I'm trying to remove the sub string _x that is located in the end of part of my df column names.</p> <p><strong>Sample df code:</strong></p> <pre><code>import pandas as pd d = {'W_x': ['abcde','abcde','abcde']} df = pd.DataFrame(data=d) df['First_x']=[0,0,0] df['Last_x']=[1,2,3] df['Slice']=['abFC=0.01#%sdadf','12fdak*4%FC=-0.035faf,dd43','FC=0.5fasff'] </code></pre> <p><strong>output:</strong></p> <pre><code> W_x First_x Last_x Slice 0 abcde 0 1 abFC=0.01 1 abcde 0 2 12fdak*4%FC=-0.035faf,dd43 2 abcde 0 3 FC=0.5fasff </code></pre> <p><strong>Desired output:</strong></p> <pre><code> W First Last Slice 0 abcde 0 1 abFC=0.01 1 abcde 0 2 12fdak*4%FC=-0.035faf,dd43 2 abcde 0 3 FC=0.5fasff </code></pre>
58,322,479
7
0
null
2019-04-14 19:49:19.657 UTC
9
2022-02-15 10:21:00.78 UTC
2019-04-14 19:55:21.907 UTC
null
4,909,087
null
9,185,511
null
1
35
python|pandas
58,118
<p>I usually use @cs95 way but wrapping it in a data frame method just for convenience:</p> <pre><code>import pandas as pd def drop_prefix(self, prefix): self.columns = self.columns.str.lstrip(prefix) return self pd.core.frame.DataFrame.drop_prefix = drop_prefix </code></pre> <p>Then you can use it as with inverse method already implemented in pandas <code>add_prefix</code>:</p> <pre><code>pd.drop_prefix('myprefix_') </code></pre>
63,592,900
Plotly-Dash: How to design the layout using dash bootstrap components?
<p>I'm very new to Dash Plotly and I'm trying to figure out how can I design a layout like this.</p> <p><a href="https://i.stack.imgur.com/WesWm.png" rel="noreferrer">Layout</a>:</p> <p><a href="https://i.stack.imgur.com/MNz5W.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MNz5W.png" alt="enter image description here" /></a></p> <p>As I understood, this can be done more easy using dash bootstrap components. <a href="https://dash-bootstrap-components.opensource.faculty.ai" rel="noreferrer">https://dash-bootstrap-components.opensource.faculty.ai</a> As a first step I should reproduce the layout (grey tiles) and as a second step, I should add some text and some graphs. Just basic.</p> <p>Thank you.</p>
63,602,391
2
0
null
2020-08-26 07:47:26.023 UTC
12
2021-06-14 07:33:32.073 UTC
2020-08-28 22:00:35.487 UTC
null
3,437,787
null
12,934,613
null
1
14
plotly|plotly-dash
24,583
<p>You should check out this <a href="https://dash-bootstrap-components.opensource.faculty.ai/docs/components/layout/" rel="noreferrer">link</a> to learn more about Dash Bootstrap Components, and how to structure your layout.</p> <p>I have made an example using <code>JupyterDash</code> that matches your desired layout.</p> <p><a href="https://i.stack.imgur.com/KEm4K.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KEm4K.png" alt="enter image description here" /></a></p> <pre class="lang-py prettyprint-override"><code>import plotly.express as px from jupyter_dash import JupyterDash import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc from dash.dependencies import Input, Output import plotly.express as px # Iris bar figure def drawFigure(): return html.Div([ dbc.Card( dbc.CardBody([ dcc.Graph( figure=px.bar( df, x=&quot;sepal_width&quot;, y=&quot;sepal_length&quot;, color=&quot;species&quot; ).update_layout( template='plotly_dark', plot_bgcolor= 'rgba(0, 0, 0, 0)', paper_bgcolor= 'rgba(0, 0, 0, 0)', ), config={ 'displayModeBar': False } ) ]) ), ]) # Text field def drawText(): return html.Div([ dbc.Card( dbc.CardBody([ html.Div([ html.H2(&quot;Text&quot;), ], style={'textAlign': 'center'}) ]) ), ]) # Data df = px.data.iris() # Build App app = JupyterDash(external_stylesheets=[dbc.themes.SLATE]) app.layout = html.Div([ dbc.Card( dbc.CardBody([ dbc.Row([ dbc.Col([ drawText() ], width=3), dbc.Col([ drawText() ], width=3), dbc.Col([ drawText() ], width=3), dbc.Col([ drawText() ], width=3), ], align='center'), html.Br(), dbc.Row([ dbc.Col([ drawFigure() ], width=3), dbc.Col([ drawFigure() ], width=3), dbc.Col([ drawFigure() ], width=6), ], align='center'), html.Br(), dbc.Row([ dbc.Col([ drawFigure() ], width=9), dbc.Col([ drawFigure() ], width=3), ], align='center'), ]), color = 'dark' ) ]) # Run app and display result inline in the notebook app.run_server(mode='external') </code></pre>
35,332,784
How to call a controller function inside a view in laravel 5
<p>In laravel 4 i just used a function </p> <pre><code>$varbl = App::make("ControllerName")-&gt;FunctionName($params); </code></pre> <p>to call a controller function from a my balde template(view page). Now i'm using Laravel 5 to do a new project and i tried this method to call a controller function from my blade template .But its not working and showing some errors. Is there any method to call a controller function from a view page in Laravel 5?</p>
35,335,014
10
0
null
2016-02-11 07:03:06.18 UTC
10
2021-04-27 02:35:05.597 UTC
null
null
null
null
2,854,591
null
1
21
php|laravel-5
111,911
<p>If you have a function which is being used at multiple places you should define it in helpers file, to do so create one (may be) in app/Http/Helpers folder and name it helpers.php, mention this file in the <code>autoload</code> block of your composer.json in following way : </p> <pre><code>"autoload": { "classmap": [ "database" ], "psr-4": { "App\\": "app/" }, "files": [ "app/Http/Helpers/helpers.php" ] }, </code></pre> <p>run composer dump-autoload, and then you may call this function from anywhere, let it be controller view or model.</p> <p>or if you don't need to put in the helpers. You can just simply call it from it's controller. Just make it a <code>static function</code>. Create.</p> <pre><code>public static function funtion_name($args) {} </code></pre> <p>Call.</p> <pre><code>\App\Http\Controllers\ControllerName::function_name($args) </code></pre> <p>If you don't like the very long code, you can just make it </p> <pre><code>ControllerName::function_name($args) </code></pre> <p>but don't forget to call it from the top of the view page.</p> <pre><code>use \App\Http\Controllers\ControllerName; </code></pre>
28,952,747
Calculate Total Traveled Distance iOS Swift
<p>How can I calculate the total distance traveled use CoreLocation in Swift</p> <p>I haven't been able to so far find any resources for how to do this in Swift for iOS 8,</p> <p>How would you calculate the total distance moved since you began tracking your location?</p> <p>From what I've read so far, I need to save location of a points, then calculate the distance between current point, and last point, then add that distance to a totalDistance variable</p> <p>Objective-C is extremely unfamiliar to me, so I haven't been able to work out the swift syntax </p> <p>Here is what I've worked out so far, not sure if I'm doing it right. Though the <code>distanceFromLocation</code>method is returning all 0.0 so obviously something is wrong</p> <pre><code>func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { var newLocation: CLLocation = locations[0] as CLLocation oldLocationArray.append(newLocation) var totalDistance = CLLocationDistance() var oldLocation = oldLocationArray.last var distanceTraveled = newLocation.distanceFromLocation(oldLocation) totalDistance += distanceTraveled println(distanceTraveled) } </code></pre>
28,953,613
3
0
null
2015-03-09 22:15:40.27 UTC
8
2017-11-30 00:32:30.26 UTC
2015-06-12 23:06:15.597 UTC
null
2,303,865
null
3,786,510
null
1
10
ios|xcode|swift|core-location|cllocation
15,713
<p>update: <strong>Xcode 8.3.2 • Swift 3.1</strong></p> <p>The problem there is because you are always getting the same location over and over again. Try like this:</p> <pre><code>import UIKit import MapKit class ViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var mapView: MKMapView! let locationManager = CLLocationManager() var startLocation: CLLocation! var lastLocation: CLLocation! var startDate: Date! var traveledDistance: Double = 0 override func viewDidLoad() { super.viewDidLoad() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() locationManager.startMonitoringSignificantLocationChanges() locationManager.distanceFilter = 10 mapView.showsUserLocation = true mapView.userTrackingMode = .follow } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if startDate == nil { startDate = Date() } else { print("elapsedTime:", String(format: "%.0fs", Date().timeIntervalSince(startDate))) } if startLocation == nil { startLocation = locations.first } else if let location = locations.last { traveledDistance += lastLocation.distance(from: location) print("Traveled Distance:", traveledDistance) print("Straight Distance:", startLocation.distance(from: locations.last!)) } lastLocation = locations.last } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { if (error as? CLError)?.code == .denied { manager.stopUpdatingLocation() manager.stopMonitoringSignificantLocationChanges() } } } </code></pre> <p><a href="https://www.dropbox.com/s/mv6rl113nosb2ta/DistanceTravelled.zip?dl=0" rel="noreferrer">Sample Project</a></p>
36,623,177
Property initialization using "by lazy" vs. "lateinit"
<p>In Kotlin, if you don't want to initialize a class property inside the constructor or in the top of the class body, you have basically these two options (from the language reference):</p> <ol> <li><a href="https://kotlinlang.org/docs/reference/delegated-properties.html#lazy" rel="noreferrer">Lazy Initialization</a></li> </ol> <blockquote> <p><code>lazy()</code> is a function that takes a lambda and returns an instance of <code>Lazy&lt;T&gt;</code> which can serve as a delegate for implementing a lazy property: the first call to <code>get()</code> executes the lambda passed to <code>lazy()</code> and remembers the result, subsequent calls to <code>get()</code> simply return the remembered result.</p> <p><strong>Example</strong></p> <pre><code>public class Hello { val myLazyString: String by lazy { &quot;Hello&quot; } } </code></pre> </blockquote> <p>So, the first call and the subsequential calls, wherever it is, to <code>myLazyString</code> will return <code>Hello</code></p> <ol start="2"> <li><a href="https://kotlinlang.org/docs/reference/properties.html#late-initialized-properties" rel="noreferrer">Late Initialization</a></li> </ol> <blockquote> <p>Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.</p> <p>To handle this case, you can mark the property with the lateinit modifier:</p> <pre><code>public class MyTest { lateinit var subject: TestSubject @SetUp fun setup() { subject = TestSubject() } @Test fun test() { subject.method() } } </code></pre> <p>The modifier can only be used on var properties declared inside the body of a class (not in the primary constructor), and only when the property does not have a custom getter or setter. The type of the property must be non-null, and it must not be a primitive type.</p> </blockquote> <p>So, how to choose correctly between these two options, since both of them can solve the same problem?</p>
36,623,703
9
0
null
2016-04-14 12:30:00.12 UTC
124
2022-07-20 14:19:54.347 UTC
2021-10-03 10:44:06.993 UTC
null
466,862
null
2,327,342
null
1
448
properties|kotlin
194,576
<p>Here are the significant differences between <code>lateinit var</code> and <code>by lazy { ... }</code> delegated property:</p> <ul> <li><p><code>lazy { ... }</code> delegate can only be used for <code>val</code> properties, whereas <code>lateinit</code> can only be applied to <code>var</code>s, because it can't be compiled to a <code>final</code> field, thus no immutability can be guaranteed;</p> </li> <li><p><code>lateinit var</code> has a backing field which stores the value, and <code>by lazy { ... }</code> creates a delegate object in which the value is stored once calculated, stores the reference to the delegate instance in the class object and generates the getter for the property that works with the delegate instance. So if you need the backing field present in the class, use <code>lateinit</code>;</p> </li> <li><p>In addition to <code>val</code>s, <code>lateinit</code> cannot be used for nullable properties or Java primitive types (this is because of <code>null</code> used for uninitialized value);</p> </li> <li><p><code>lateinit var</code> can be initialized from anywhere the object is seen from, e.g. from inside a framework code, and multiple initialization scenarios are possible for different objects of a single class. <code>by lazy { ... }</code>, in turn, defines the only initializer for the property, which can be altered only by overriding the property in a subclass. If you want your property to be initialized from outside in a way probably unknown beforehand, use <code>lateinit</code>.</p> </li> <li><p>Initialization <code>by lazy { ... }</code> is thread-safe by default and guarantees that the initializer is invoked at most once (but this can be altered by using <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/lazy.html" rel="noreferrer">another <code>lazy</code> overload</a>). In the case of <code>lateinit var</code>, it's up to the user's code to initialize the property correctly in multi-threaded environments.</p> </li> <li><p>A <code>Lazy</code> instance can be saved, passed around and even used for multiple properties. On contrary, <code>lateinit var</code>s do not store any additional runtime state (only <code>null</code> in the field for uninitialized value).</p> </li> <li><p>If you hold a reference to an instance of <code>Lazy</code>, <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-lazy/is-initialized.html" rel="noreferrer"><code>isInitialized()</code></a> allows you to check whether it has already been initialized (and you can <a href="https://stackoverflow.com/a/42012368/2196460">obtain such instance with reflection</a> from a delegated property). To check whether a lateinit property has been initialized, you can <a href="https://kotlinlang.org/docs/reference/properties.html#checking-whether-a-lateinit-var-is-initialized-since-12" rel="noreferrer">use <code>property::isInitialized</code> since Kotlin 1.2</a>.</p> </li> <li><p>A lambda passed to <code>by lazy { ... }</code> may capture references from the context where it is used into its <a href="https://kotlinlang.org/docs/reference/lambdas.html#closures" rel="noreferrer">closure</a>.. It will then store the references and release them only once the property has been initialized. This may lead to object hierarchies, such as Android activities, not being released for too long (or ever, if the property remains accessible and is never accessed), so you should be careful about what you use inside the initializer lambda.</p> </li> </ul> <p>Also, there's another way not mentioned in the question: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.properties/-delegates/not-null.html" rel="noreferrer"><code>Delegates.notNull()</code></a>, which is suitable for deferred initialization of non-null properties, including those of Java primitive types.</p>
26,128,815
UIWebView delegate method shouldStartLoadWithRequest: equivalent in WKWebView?
<p>I have a module inside my iOS 7+ app which is a UIWebView. The html page loads a javascript that creates custom-shaped buttons (using the Raphaeljs library). With UIWebView, I set delegate to self. The delegate method <code>webView: shouldStartLoadWithRequest: navigationType:</code> is called each time one of my custom button is pressed. The requests should not be handled by the html, but rather by the iOS code. So I used a request convention (read somewhere here on stackoverflow) using "inapp" as the scheme of my requests. I then check for the host and take the appropriate action.</p> <p>This code works fine on iOS 7. But the web views appear blank on iOS 8 (bug?), so I decided to use WKWebView for iOS 8 devices. The web views now render fine (and amazingly faster!), but my buttons have no effect.</p> <p>I tried using <code>- (WKNaviation *)loadRequest:(NSURLRequest *)request</code>, but it's not called.</p> <p>I can't find a direct equivalent of the UIWebView delegate method <code>webView: shouldStartLoadWithRequest: navigationType:</code>. What's the best way of handling those requests with WKWebView?</p>
26,227,729
8
0
null
2014-09-30 19:42:37.67 UTC
27
2022-07-20 08:19:18.62 UTC
null
null
null
null
873,436
null
1
60
ios|objective-c|uiwebview|wkwebview
58,733
<p>Re-reading your description it looks like what you actually need to know about is how to reimplement a Javascript/Objective-C bridge using WKWebView.</p> <p>I've just done this myself, following the tutorial at <a href="http://tetontech.wordpress.com/2014/07/17/objective-c-wkwebview-to-javascript-and-back/" rel="noreferrer">http://tetontech.wordpress.com/2014/07/17/objective-c-wkwebview-to-javascript-and-back/</a> and the info at <a href="http://nshipster.com/wkwebkit/" rel="noreferrer">http://nshipster.com/wkwebkit/</a></p> <p>WKWebView has a built-in way of communicating between Javascript and Objective-C/Swift: <code>WKScriptMessageHandler</code>.</p> <p>First, include the WebKit headers and <code>WKScriptMessageHandler</code> protocol in your view controller's header:</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; #import &lt;WebKit/WebKit.h&gt; @interface ViewController : UIViewController &lt;WKScriptMessageHandler&gt; @end </code></pre> <p>The when initialising your <code>WKWebView</code>, you need to configure it with a script message handler. Name it whatever you want, but to me it seems like naming it for your app makes sense.</p> <pre><code> WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init]; [theConfiguration.userContentController addScriptMessageHandler:self name:@"myApp"]; _theWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration]; [_theWebView loadRequest:request]; [self.view addSubview:_theWebView]; </code></pre> <p>Now, implement <code>userContentController:didReceiveScriptMessage:</code>. This fires when your webview receives a message, so it does the work you were previously doing with <code>webView:shouldStartLoadWithRequest:navigationType:</code>.</p> <pre><code>- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { NSDictionary *sentData = (NSDictionary *)message.body; NSString *messageString = sentData[@"message"]; NSLog(@"Message received: %@", messageString); } </code></pre> <p>You're now ready to receive messages from Javascript. The function call you need to add to your Javascript is this:</p> <pre><code>window.webkit.messageHandlers.myApp.postMessage({"message":"Hello there"}); </code></pre>
28,006,913
RSpec allow/expect vs just expect/and_return
<p>In RSpec, specifically version >= 3, is there any difference between:</p> <ul> <li>Using <code>allow</code> to set up message expectations with parameters that return test doubles, and then using <code>expect</code> to make an assertion on the returned test doubles</li> <li>Just using <code>expect</code> to set up the expectation with parameters and return the test double</li> </ul> <p>or is it all just semantics? I know that providing/specifying a return value with <code>expect</code> was <a href="https://www.relishapp.com/rspec/rspec-mocks/v/2-13/docs/message-expectations/expect-a-message#provide-a-return-value" rel="noreferrer">the syntax in RSpec mocks 2.13</a>, but as far as I can see, <a href="http://www.relishapp.com/rspec/rspec-mocks/v/3-1/docs/configuring-responses/returning-a-value#specify-a-return-value" rel="noreferrer">the syntax changed in RSpec mocks 3</a> to use <code>allow</code>. </p> <p>However, in the (passing) sample code below, using either <code>allow</code>/<code>expect</code> or just <code>expect</code>/<code>and_return</code> seems to generate the same result. If one syntax was favoured over another, perhaps I would have expected there to be some kind of deprecation notice, but since there isn't, it would seem that both syntaxes are considered valid:</p> <pre class="lang-rb prettyprint-override"><code>class Foo def self.bar(baz) # not important what happens to baz parameter # only important that it is passed in new end def qux # perform some action end end class SomethingThatCallsFoo def some_long_process(baz) # do some processing Foo.bar(baz).qux # do other processing end end describe SomethingThatCallsFoo do let(:foo_caller) { SomethingThatCallsFoo.new } describe '#some_long_process' do let(:foobar_result) { double('foobar_result') } let(:baz) { double('baz') } context 'using allow/expect' do before do allow(Foo).to receive(:bar).with(baz).and_return(foobar_result) end it 'calls qux method on result of Foo.bar(baz)' do expect(foobar_result).to receive(:qux) foo_caller.some_long_process(baz) end end context 'using expect/and_return' do it 'calls qux method on result of Foo.bar(baz)' do expect(Foo).to receive(:bar).with(baz).and_return(foobar_result) expect(foobar_result).to receive(:qux) foo_caller.some_long_process(baz) end end end end </code></pre> <p>If I deliberately make the tests fail by changing the passed-in <code>baz</code> parameter in the expectation to a different test double, the errors are pretty much the same:</p> <pre class="lang-rb prettyprint-override"><code> 1) SomethingThatCallsFoo#some_long_process using allow/expect calls quux method on result of Foo.bar(baz) Failure/Error: Foo.bar(baz).qux &lt;Foo (class)&gt; received :bar with unexpected arguments expected: (#&lt;RSpec::Mocks::Double:0x3fe97a0127fc @name="baz"&gt;) got: (#&lt;RSpec::Mocks::Double:0x3fe97998540c @name=nil&gt;) Please stub a default value first if message might be received with other args as well. # ./foo_test.rb:16:in `some_long_process' # ./foo_test.rb:35:in `block (4 levels) in &lt;top (required)&gt;' 2) SomethingThatCallsFoo#some_long_process using expect/and_return calls quux method on result of Foo.bar(baz) Failure/Error: Foo.bar(baz).qux &lt;Foo (class)&gt; received :bar with unexpected arguments expected: (#&lt;RSpec::Mocks::Double:0x3fe979935fd8 @name="baz"&gt;) got: (#&lt;RSpec::Mocks::Double:0x3fe979cc5c0c @name=nil&gt;) # ./foo_test.rb:16:in `some_long_process' # ./foo_test.rb:43:in `block (4 levels) in &lt;top (required)&gt;' </code></pre> <p>So, are there any real differences between these two tests, either in result or expressed intent, or is it just semantics and/or personal preference? Should <code>allow</code>/<code>expect</code> be used over <code>expect</code>/<code>and_return</code> in general as it seems like it's the replacement syntax, or are each of them meant to be used in specific test scenarios?</p> <p><strong>Update</strong></p> <p>After reading <a href="https://stackoverflow.com/a/28007007/567863">Mori's answer</a>'s, I commented out the <code>Foo.bar(baz).qux</code> line from the example code above, and got the following errors:</p> <pre class="lang-rb prettyprint-override"><code> 1) SomethingThatCallsFoo#some_long_process using allow/expect calls qux method on result of Foo.bar(baz) Failure/Error: expect(foobar_result).to receive(:qux) (Double "foobar_result").qux(any args) expected: 1 time with any arguments received: 0 times with any arguments # ./foo_test.rb:34:in `block (4 levels) in &lt;top (required)&gt;' 2) SomethingThatCallsFoo#some_long_process using expect/and_return calls qux method on result of Foo.bar(baz) Failure/Error: expect(Foo).to receive(:bar).with(baz).and_return(foobar_result) (&lt;Foo (class)&gt;).bar(#&lt;RSpec::Mocks::Double:0x3fc211944fa4 @name="baz"&gt;) expected: 1 time with arguments: (#&lt;RSpec::Mocks::Double:0x3fc211944fa4 @name="baz"&gt;) received: 0 times # ./foo_test.rb:41:in `block (4 levels) in &lt;top (required)&gt;' </code></pre> <ul> <li>The <code>allow</code> spec fails because the <code>foobar_result</code> double never gets to stand in for the result of <code>Foo.bar(baz)</code>, and hence never has <code>#qux</code> called on it</li> <li>The <code>expect</code> spec fails at the point of <code>Foo</code> never receiving <code>.bar(baz)</code> so we don't even get to the point of interrogating the <code>foobar_result</code> double</li> </ul> <p>Makes sense: it's not just a syntax change, and that <code>expect</code>/<code>and_return</code> does have a purpose different to <code>allow</code>/<code>expect</code>. I really should have checked the most obvious place: the <a href="https://github.com/rspec/rspec-mocks/blob/master/README.md" rel="noreferrer">RSpec Mocks README</a>, specifically the following sections:</p> <ul> <li><a href="https://github.com/rspec/rspec-mocks/blob/master/README.md#mock-objects-and-test-stubs" rel="noreferrer">Mock Objects and Test Stubs</a></li> <li><a href="https://github.com/rspec/rspec-mocks/blob/master/README.md#test-specific-extension" rel="noreferrer">Test-Specific Extension</a></li> <li><a href="https://github.com/rspec/rspec-mocks/blob/master/README.md#setting-responses" rel="noreferrer">Setting Responses</a></li> </ul>
28,007,007
1
0
null
2015-01-18 03:41:16.23 UTC
34
2021-09-23 10:54:49.41 UTC
2017-05-23 12:26:35.83 UTC
null
-1
null
567,863
null
1
58
ruby|testing|rspec|mocking|rspec3
43,868
<p>See the classic article <a href="http://martinfowler.com/articles/mocksArentStubs.html">Mocks Aren't Stubs</a>. <code>allow</code> makes a stub while <code>expect</code> makes a mock. That is <code>allow</code> allows an object to return X instead of whatever it would return unstubbed, and <code>expect</code> is an <code>allow</code> <em>plus</em> an expectation of some state or event. When you write</p> <pre><code>allow(Foo).to receive(:bar).with(baz).and_return(foobar_result) </code></pre> <p>... you're telling the spec environment to modify <code>Foo</code> to return <code>foobar_result</code> when it receives <code>:bar</code> with <code>baz</code>. But when you write</p> <pre><code>expect(Foo).to receive(:bar).with(baz).and_return(foobar_result) </code></pre> <p>... you're doing the same, plus telling the spec to fail <em>unless</em> <code>Foo</code> receives <code>:bar</code> with <code>baz</code>.</p> <p>To see the difference, try both in examples where <code>Foo</code> does <em>not</em> receive <code>:bar</code> with <code>baz</code>.</p>
22,859,953
TortoiseSVN - "revert changes from this revision" vs "revert to this revision"
<p>The link:</p> <p><a href="http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-howto-rollback.html">http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-howto-rollback.html</a> </p> <p>describes two ways of rolling back an SVN directory after a wrongful commit. What is the difference between the two options</p> <pre><code>Revert changes from this revision Revert to this revision </code></pre> <p>As a test, I added a file, rolling back using "Revert changes from this revision" and did the same process for the "Revert to this revision", and there is no difference with the state of the SVN log.</p> <p>Am I missing something?</p>
22,860,652
4
0
null
2014-04-04 10:16:35.513 UTC
14
2016-04-29 13:17:20.467 UTC
2016-04-29 13:17:20.467 UTC
null
5,395,773
null
288,393
null
1
50
svn|version-control|tortoisesvn|revert
42,001
<p>Let's say you have these N sucessive commits: 1, 2, 3 and 4.</p> <p>If you select the commit 2 and choose "Revert to this revision", your working copy will contain the changes brought by commits 1 and 2. Commits 3 and 4 will be "canceled".</p> <p>If you select the commit 2 and choose "Revert changes from this revision", your working copy will contain the changes brought by commits 1, 3 and 4. Commit 2 will be "canceled", or rather, played in reverse on the top of commit 4: if a line was added, it will be removed. If a line was removed, it will be readded. </p>
22,814,378
ng-Animate not working for a Hide and Show setting
<p>I'm using AngularJS version 1.2.11. I've set a toolbar to slide in and out with a transition using ng-Animate (show and hide).</p> <p>Here is the HTML:</p> <pre><code> &lt;div&gt; &lt;div class="full-height"&gt; &lt;menu-main class="full-height pull-left"&gt;&lt;/menu-main&gt; &lt;menu-sub class="full-height pull-left" ng-show="data.active" ng-animate="'animate'"&gt; &lt;/menu-sub&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>And here is the CSS for the same toolbar element </p> <pre><code>.animate.fade-hide, .animate..fade-show { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 3.5s; -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 3.5s; -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 3.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 3.5s; } .animate.fade-hide, { position: fixed; top: 500px; opacity: 0.3; } .animate.fade-hide, .animate.fade-hide-active { position: fixed; top: 500px; opacity: 0.3; } .animate.fade-show { position: fixed; top: 100px; opacity: 1; } .animate.fade-show, .animate.fade-show-active { position: fixed; top: 100px; opacity: 1; } </code></pre> <p>The animation does not work, and I'm not sure if I'm doing this correctly. </p>
22,934,732
1
0
null
2014-04-02 14:18:50.2 UTC
6
2016-06-30 10:04:35.89 UTC
2016-06-30 10:04:35.89 UTC
null
2,333,214
null
3,368,623
null
1
23
angularjs|ng-animate|ng-show|ng-hide
48,732
<p>The ng-animate attribute is deprecated in 1.2 and no longer used. Instead, animations are now class based.</p> <p>Also make sure you are referencing <code>angular-animate.js</code> and adding ngAnimate as a dependent module:</p> <pre><code>var app = angular.module('myApp', ['ngAnimate']); </code></pre> <p>You then name your animations, for example 'fadein' and 'fadeout', and decorate them with some additional classes following a special naming convention that can be found in the Angular <a href="http://code.angularjs.org/1.2.0-rc.3/docs/guide/animations" rel="noreferrer">documentation</a>.</p> <p>Another good source on the topic is <a href="http://www.yearofmoo.com/2013/08/remastered-animation-in-angularjs-1-2.html" rel="noreferrer">Year of moo</a>.</p> <p>Fadein example:</p> <pre><code>/* After the transition this will be the only class remaining */ .fadein { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; opacity: 1; /* Default value but added for clarity */ } /* Initial state when showing */ .fadein.ng-hide-remove { opacity: 0; display: block !important; } /* Will transition towards this state */ .fadein.ng-hide-remove.ng-hide-remove-active { opacity: 1; } </code></pre> <p><strong>Demo</strong>: <a href="http://plnkr.co/edit/V9w2EwUh0unszf62TZZB?p=preview" rel="noreferrer">http://plnkr.co/edit/V9w2EwUh0unszf62TZZB?p=preview</a></p>
34,264,710
What is the point of float('inf') in Python?
<p>Just wondering over here, what is the point of having a variable store an infinite value in a program? Is there any actual use and is there any case where it would be preferable to use <code>foo = float('inf')</code>, or is it just a little snippet they stuck in for the sake of putting it in?</p>
34,264,749
6
0
null
2015-12-14 10:28:56.297 UTC
22
2022-02-22 11:23:34.267 UTC
2020-03-07 14:00:35.86 UTC
null
10,436,547
null
3,262,301
null
1
111
python
178,285
<p>It acts as an unbounded upper value for comparison. This is useful for finding lowest values for something. for example, calculating path route costs when traversing trees.</p> <p>e.g. Finding the "cheapest" path in a list of options:</p> <pre><code>&gt;&gt;&gt; lowest_path_cost = float('inf') &gt;&gt;&gt; # pretend that these were calculated using some worthwhile algorithm &gt;&gt;&gt; path_costs = [1, 100, 2000000000000, 50] &gt;&gt;&gt; for path in path_costs: ... if path &lt; lowest_path_cost: ... lowest_path_cost = path ... &gt;&gt;&gt; lowest_path_cost 1 </code></pre> <p>if you didn't have <code>float('Inf')</code> available to you, what value would you use for <code>the initial lowest_path_cost</code>? Would <code>9999999</code> be enough -- <code>float('Inf')</code> removes this guesswork.</p>
37,225,035
Serialize in JSON a base64 encoded data
<p>I'm writing a script to automate data generation for a demo and I need to serialize in a JSON some data. Part of this data is an image, so I encoded it in base64, but when I try to run my script I get:</p> <pre><code>Traceback (most recent call last): File "lazyAutomationScript.py", line 113, in &lt;module&gt; json.dump(out_dict, outfile) File "/usr/lib/python3.4/json/__init__.py", line 178, in dump for chunk in iterable: File "/usr/lib/python3.4/json/encoder.py", line 422, in _iterencode yield from _iterencode_dict(o, _current_indent_level) File "/usr/lib/python3.4/json/encoder.py", line 396, in _iterencode_dict yield from chunks File "/usr/lib/python3.4/json/encoder.py", line 396, in _iterencode_dict yield from chunks File "/usr/lib/python3.4/json/encoder.py", line 429, in _iterencode o = _default(o) File "/usr/lib/python3.4/json/encoder.py", line 173, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: b'iVBORw0KGgoAAAANSUhEUgAADWcAABRACAYAAABf7ZytAAAABGdB... ... BF2jhLaJNmRwAAAAAElFTkSuQmCC' is not JSON serializable </code></pre> <p>As far as I know, a base64-encoded-whatever (a PNG image, in this case) is just a string, so it should pose to problem to serializating. What am I missing?</p>
37,239,382
3
0
null
2016-05-14 09:35:16.317 UTC
27
2019-12-13 16:39:52.613 UTC
null
null
null
null
3,110,448
null
1
59
json|python-3.x|serialization|base64
79,203
<p>You must be careful about the datatypes.</p> <p>If you read a binary image, you get bytes. If you encode these bytes in base64, you get ... bytes again! (see documentation on <a href="https://docs.python.org/3/library/base64.html#base64.b64encode">b64encode</a>)</p> <p>json can't handle raw bytes, that's why you get the error.</p> <p>I have just written some example, with comments, I hope it helps:</p> <pre><code>from base64 import b64encode from json import dumps ENCODING = 'utf-8' IMAGE_NAME = 'spam.jpg' JSON_NAME = 'output.json' # first: reading the binary stuff # note the 'rb' flag # result: bytes with open(IMAGE_NAME, 'rb') as open_file: byte_content = open_file.read() # second: base64 encode read data # result: bytes (again) base64_bytes = b64encode(byte_content) # third: decode these bytes to text # result: string (in utf-8) base64_string = base64_bytes.decode(ENCODING) # optional: doing stuff with the data # result here: some dict raw_data = {IMAGE_NAME: base64_string} # now: encoding the data to json # result: string json_data = dumps(raw_data, indent=2) # finally: writing the json string to disk # note the 'w' flag, no 'b' needed as we deal with text here with open(JSON_NAME, 'w') as another_open_file: another_open_file.write(json_data) </code></pre>
41,912,629
angular2 wait until observable finishes in if condition
<p>I have implemented a if statement like this</p> <pre class="lang-ts prettyprint-override"><code>if (this.service.check() ) { return true; } else { } </code></pre> <p>this if condition waits for a response from the backend. But before the observable gets executed it's going into the else statement and finishing the condition without checking the if condition at start.</p> <p>this is my observable method to get the data from backend</p> <pre class="lang-ts prettyprint-override"><code>public check(){ this.getActorRole().subscribe( (resp =&gt; { if (resp == true){ return true } }), (error =&gt; { console.log(error); }) ); } } </code></pre> <p>So how make the condition waits until it gets the response from the backend</p>
41,912,670
1
0
null
2017-01-28 17:23:13.65 UTC
6
2017-01-28 17:27:01.347 UTC
2017-01-28 17:27:01.347 UTC
null
217,408
null
3,843,856
null
1
29
angular|observable
91,445
<p>You can't wait for an <code>Observable</code> or <code>Promise</code> to complete. You can only subscribe to it to get notified when it completes or emits an event.</p> <pre class="lang-ts prettyprint-override"><code>public check(){ return this.getActorRole() // &lt;&lt;&lt;=== add return .map(resp =&gt; { if (resp == true){ return true } ); } } </code></pre> <p>then you can do</p> <pre class="lang-ts prettyprint-override"><code>this.service.check().subscribe(value =&gt; { if (value) { return true; } else { } } </code></pre> <p>but if the caller of this code also depends on the return value you again need to</p> <pre class="lang-ts prettyprint-override"><code>this.service.check() .map(value =&gt; { if (value) { return true; } else { } } </code></pre> <p>and then do the <code>subscribe()</code> where you call this code</p>
38,727,047
Duplicate line in Visual Studio Code
<p>I am trying to find the shortcut for duplicating a line in Visual Studio Code (I am using 1.3.1) I tried the obvious <kbd>CTRL</kbd> + <kbd>D</kbd> but that doesn't seem to work. </p>
38,727,104
16
5
null
2016-08-02 17:36:32.207 UTC
43
2022-08-22 09:58:01.67 UTC
2017-09-26 12:07:55.237 UTC
null
114,664
null
266,360
null
1
337
visual-studio-code
264,185
<p>Click <strong>File</strong> > <strong>Preferences</strong> > <strong>Keyboard Shortcuts</strong>:</p> <p><a href="https://i.stack.imgur.com/QtEgE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QtEgE.png" alt="enter image description here"></a></p> <p>Search for <code>copyLinesDownAction</code> or <code>copyLinesUpAction</code> in your keyboard shortcuts </p> <p>Usually it is <kbd>SHIFT</kbd>+<kbd>ALT</kbd> + <kbd>↓</kbd></p> <hr> <p>Update for Ubuntu: </p> <p>It seems that Ubuntu is hiding that shortcut from being seen by VSCode (i.e. it uses it probably by its own). There is an issue about that on <a href="https://github.com/Microsoft/vscode/issues/6197" rel="noreferrer">GitHub</a>. </p> <p>In order to work in Ubuntu you will have to define your own shortcut, e.g. to copy the line using <kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>alt</kbd>+<kbd>j</kbd> and <kbd>CTRL</kbd> +<kbd>SHIFT</kbd> + <kbd>ALT</kbd> + <kbd>k</kbd> you could use a <code>keybindings.json</code> like this: </p> <pre><code>[ { "key": "ctrl+shift+alt+j", "command": "editor.action.copyLinesDownAction", "when": "editorTextFocus &amp;&amp; !editorReadonly" }, { "key": "ctrl+shift+alt+k", "command": "editor.action.copyLinesUpAction", "when": "editorTextFocus &amp;&amp; !editorReadonly" } ] </code></pre>
45,008,016
Check if a string is not NULL or EMPTY
<p>In below code, I need to check if version string is not empty then append its value to the request variable.</p> <pre><code>if ([string]::IsNullOrEmpty($version)) { $request += "/" + $version } </code></pre> <p>How to check not in if condition?</p>
45,008,087
7
1
null
2017-07-10 09:11:07.3 UTC
9
2021-09-01 02:13:01.5 UTC
2017-07-10 09:27:09.033 UTC
null
1,630,171
null
8,171,406
null
1
65
powershell
256,343
<pre><code>if (-not ([string]::IsNullOrEmpty($version))) { $request += "/" + $version } </code></pre> <p>You can also use <code>!</code> as an alternative to <code>-not</code>.</p>
38,730,273
How to limit FPS in a loop with C++?
<p>I'm trying to limit the frames per second in a loop that is performing intersection checking, using C++ with chrono and thread.</p> <p>Here is my code:</p> <pre><code>std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::chrono::system_clock::time_point lastFrame = std::chrono::system_clock::now(); while (true) { // Maintain designated frequency of 5 Hz (200 ms per frame) now = std::chrono::system_clock::now(); std::chrono::duration&lt;double, std::milli&gt; delta = now - lastFrame; lastFrame = now; if (delta.count() &lt; 200.0) { std::chrono::duration&lt;double, std::milli&gt; delta_ms(200.0 - delta.count()); auto delta_ms_duration = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(delta_ms); std::this_thread::sleep_for(std::chrono::milliseconds(delta_ms_duration.count())); } printf("Time: %f \n", delta.count()); // Perform intersection test } </code></pre> <p>The problem I'm having is that every other output of delta is showing miniscule amounts, rather than the ~200 ms / frame I'm aiming for:</p> <pre><code>Time: 199.253200 Time: 2.067700 Time: 199.420400 Time: 2.408100 Time: 199.494200 Time: 2.306200 Time: 199.586800 Time: 2.253400 Time: 199.864000 Time: 2.156500 Time: 199.293800 Time: 2.075500 Time: 201.787500 Time: 4.426600 Time: 197.304100 Time: 4.530500 Time: 198.457200 Time: 3.482000 Time: 198.365300 Time: 3.415400 Time: 198.467400 Time: 3.595000 Time: 199.730100 Time: 3.373400 </code></pre> <p>Any thoughts as to why this is happening?</p>
38,730,516
4
9
null
2016-08-02 20:55:17.737 UTC
13
2017-05-30 18:01:47.44 UTC
2016-08-03 15:32:15.07 UTC
null
3,457,728
null
3,457,728
null
1
28
c++|chrono
14,664
<p>If you think about how your code works, you'll find out that it works exactly how you wrote it. Delta oscillates because of a logical mistake in the code.</p> <p>This is what happens:</p> <ul> <li>We start with <code>delta == 0</code>.</li> <li>Because the delta is smaller than <code>200</code>, you code sleeps <code>200 - delta(0) == 200</code> ms.</li> <li>Now, the delta itself becomes close to <code>200</code> (because you've measured that sleep time as well as an actual work) and you sleep <code>200 - delta(200) == 0</code> ms.</li> <li>After that the cycle repeats.</li> </ul> <p>To fix the problem you need to not measure the sleep time.</p> <p>This is how it can be done:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdio&gt; #include &lt;chrono&gt; #include &lt;thread&gt; std::chrono::system_clock::time_point a = std::chrono::system_clock::now(); std::chrono::system_clock::time_point b = std::chrono::system_clock::now(); int main() { while (true) { // Maintain designated frequency of 5 Hz (200 ms per frame) a = std::chrono::system_clock::now(); std::chrono::duration&lt;double, std::milli&gt; work_time = a - b; if (work_time.count() &lt; 200.0) { std::chrono::duration&lt;double, std::milli&gt; delta_ms(200.0 - work_time.count()); auto delta_ms_duration = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(delta_ms); std::this_thread::sleep_for(std::chrono::milliseconds(delta_ms_duration.count())); } b = std::chrono::system_clock::now(); std::chrono::duration&lt;double, std::milli&gt; sleep_time = b - a; // Your code here printf("Time: %f \n", (work_time + sleep_time).count()); } } </code></pre> <p>This code gives me a steady sequence of deltas:</p> <pre><code>Time: 199.057206 Time: 199.053581 Time: 199.064718 Time: 199.053515 Time: 199.053307 Time: 199.053415 Time: 199.053164 Time: 199.053511 Time: 199.053280 Time: 199.053283 </code></pre>
7,576,217
Assigning a domain name to localhost for development environment
<p>I am building a website and would not like to reconfigure the website from pointing to <code>http://127.0.0.1</code> to <code>http://www.example.com</code>. Furthermore, the certificate that I am using is of course made with the proper domain name of <code>www.example.com</code> but my test environment makes calls to <code>127.0.0.1</code> which makes the security not work properly.</p> <p>What I currently want to do is configure my development environment to assign the domain name <code>www.example.com</code> to <code>127.0.0.1</code> so that all <code>http://www.example.com/xyz</code> is routed to <code>http://127.0.0.1:8000/xyz</code> and <code>https://www.example.com/xyz</code> is routed to <code>https://127.0.0.1:8080/xyz</code>.</p> <p>I am <em>not</em> using Apache. I am currently using node.js as my web server and my development environment is in Mac OS X Lion.</p>
7,576,369
1
2
null
2011-09-27 22:04:35.44 UTC
24
2018-03-04 16:37:23.733 UTC
2018-03-04 16:37:23.733 UTC
null
608,639
null
967,974
null
1
67
node.js|macos|ssl|dns|ssl-certificate
71,194
<p>If you edit your etc/hosts file you can assign an arbitrary host name to be set to 127.0.0.1. Open up /etc/hosts in your favorite text editor and add this line:</p> <pre><code>127.0.0.1 www.example.com </code></pre> <p>Unsure of how to avoid specifying the port in the HTTP requests you make to example.com, but if you must avoid specifying that at the request level, you could run nodejs as root to make it listen on port 80. </p> <p>Edit: After editing /etc/hosts, you may already have the DNS request for that domain cached. You can clear the cached entry by running this on the command line.</p> <pre><code>dscacheutil -flushcache </code></pre>
22,588,518
Lambda Expression and generic defined only in method
<p>Suppose I've a generic interface:</p> <pre><code>interface MyComparable&lt;T extends Comparable&lt;T&gt;&gt; { public int compare(T obj1, T obj2); } </code></pre> <p>And a method <code>sort</code>:</p> <pre><code>public static &lt;T extends Comparable&lt;T&gt;&gt; void sort(List&lt;T&gt; list, MyComparable&lt;T&gt; comp) { // sort the list } </code></pre> <p>I can invoke this method and pass a lambda expression as argument:</p> <pre><code>List&lt;String&gt; list = Arrays.asList("a", "b", "c"); sort(list, (a, b) -&gt; a.compareTo(b)); </code></pre> <p>That will work fine. </p> <p>But now if I make the interface non-generic, and the method generic:</p> <pre><code>interface MyComparable { public &lt;T extends Comparable&lt;T&gt;&gt; int compare(T obj1, T obj2); } public static &lt;T extends Comparable&lt;T&gt;&gt; void sort(List&lt;T&gt; list, MyComparable comp) { } </code></pre> <p>And then invoke this like:</p> <pre><code>List&lt;String&gt; list = Arrays.asList("a", "b", "c"); sort(list, (a, b) -&gt; a.compareTo(b)); </code></pre> <p>It doesn't compile. It shows error at lambda expression saying: </p> <blockquote> <p>"Target method is generic"</p> </blockquote> <p>OK, when I compiled it using <code>javac</code>, it shows following error:</p> <pre><code>SO.java:20: error: incompatible types: cannot infer type-variable(s) T#1 sort(list, (a, b) -&gt; a.compareTo(b)); ^ (argument mismatch; invalid functional descriptor for lambda expression method &lt;T#2&gt;(T#2,T#2)int in interface MyComparable is generic) where T#1,T#2 are type-variables: T#1 extends Comparable&lt;T#1&gt; declared in method &lt;T#1&gt;sort(List&lt;T#1&gt;,MyComparable) T#2 extends Comparable&lt;T#2&gt; declared in method &lt;T#2&gt;compare(T#2,T#2) 1 error </code></pre> <p>From this error message, it seems like compiler is not able to infer the type arguments. Is that the case? If yes, then why is it happening like this?</p> <p>I tried various ways, searched through the internet. Then I found <a href="http://www.javacodegeeks.com/2012/02/whats-cooking-in-java-8-project-lambda.html">this JavaCodeGeeks article</a>, which shows a way, so I tried:</p> <pre><code>sort(list, &lt;T extends Comparable&lt;T&gt;&gt;(a, b) -&gt; a.compareTo(b)); </code></pre> <p>which again doesn't work, contrary to what that article claims that it works. Might be possible that it used to work in some initial builds.</p> <p>So my question is: Is there any way to create lambda expression for a generic method? I can do this using a method reference though, by creating a method:</p> <pre><code>public static &lt;T extends Comparable&lt;T&gt;&gt; int compare(T obj1, T obj2) { return obj1.compareTo(obj2); } </code></pre> <p>in some class say <code>SO</code>, and pass it as:</p> <pre><code>sort(list, SO::compare); </code></pre>
22,588,738
5
0
null
2014-03-23 08:18:00.177 UTC
27
2022-01-06 12:35:10.68 UTC
2021-11-17 18:58:09.17 UTC
null
32,453
null
1,679,863
null
1
119
java|generics|lambda|java-8
85,706
<p>You can't use a <em>lambda expression</em> for a <em>functional interface</em>, if the method in the <em>functional interface</em> has <em>type parameters</em>. See <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.3">section §15.27.3 in JLS8</a>:</p> <blockquote> <p>A lambda expression is compatible [..] with a target type <em>T</em> if <em>T</em> is a functional interface type (§9.8) and the expression is <strong>congruent</strong> with the function type of [..] T. [..] A lambda expression is <strong>congruent</strong> with a function type if all of the following are true:</p> <ul> <li>The function type has <em>no type parameters</em>.</li> <li>[..]</li> </ul> </blockquote>
3,042,304
How to determine what user and group a Python script is running as?
<p>I have a CGI script that is getting an <code>"IOError: [Errno 13] Permission denied"</code> error in the stack trace in the web server's error log.</p> <p>As part of debugging this problem, I'd like to add a little bit of code to the script to print the user and (especially) group that the script is running as, into the error log (presumably STDERR).</p> <p>I know I can just print the values to <code>sys.stderr</code>, but how do I figure out what user and group the script is running as?</p> <p>(I'm particularly interested in the group, so the <code>$USER</code> environment variable won't help; the CGI script has the setgid bit set so it should be running as group "list" instead of the web server's "www-data" - but I need code to see if that's actually happening.)</p>
3,042,321
3
0
null
2010-06-15 03:15:11.55 UTC
4
2020-02-28 17:53:22.833 UTC
2020-02-28 17:53:10.563 UTC
null
4,304,503
null
204,291
null
1
32
python|unix|permissions
30,725
<p>You can use the following piece of code:</p> <pre><code>import os print(os.getegid()) </code></pre>
2,365,701
Decorating class methods - how to pass the instance to the decorator?
<p>This is Python 2.5, and it's <a href="https://developers.google.com/appengine/docs/python/" rel="nofollow noreferrer">GAE</a> too, not that it matters.</p> <p>I have the following code. I'm decorating the foo() method in bar, using the <code>dec_check</code> class as a decorator.</p> <pre><code>class dec_check(object): def __init__(self, f): self.func = f def __call__(self): print 'In dec_check.__init__()' self.func() class bar(object): @dec_check def foo(self): print 'In bar.foo()' b = bar() b.foo() </code></pre> <p>When executing this I was hoping to see:</p> <pre><code>In dec_check.__init__() In bar.foo() </code></pre> <p>But I'm getting <code>TypeError: foo() takes exactly 1 argument (0 given)</code> as <code>.foo()</code>, being an object method, takes <code>self</code> as an argument. I'm guessing problem is that the instance of <code>bar</code> doesn't actually exist when I'm executing the decorator code.</p> <p><strong>So how do I pass an instance of <code>bar</code> to the decorator class?</strong></p>
2,365,771
3
0
null
2010-03-02 18:38:03.747 UTC
40
2021-12-03 00:40:16.353 UTC
2021-12-03 00:28:58.85 UTC
null
355,230
null
120,390
null
1
71
python|python-decorators
42,402
<p>You need to make the decorator into a <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow noreferrer">descriptor</a> -- either by ensuring its (meta)class has a <code>__get__</code> method, or, <strong>way</strong> simpler, by using a decorator <em>function</em> instead of a decorator <em>class</em> (since functions are already descriptors). E.g.:</p> <pre><code>def dec_check(f): def deco(self): print 'In deco' f(self) return deco class bar(object): @dec_check def foo(self): print 'in bar.foo' b = bar() b.foo() </code></pre> <p>this prints</p> <pre><code>In deco in bar.foo </code></pre> <p>as desired.</p>
3,166,951
writing some characters like '<' in an xml file
<p>since the beginning of my programmation, I used some special character like "&lt;-", ""&lt;&lt;" im my string.xml in Eclipse while developping for Android.</p> <p>All worked fine for one year, but today, i just wanted to make some minor changes and began to edit my xml files.</p> <p>I get now compilation error on these characters because eclipse believe it's part of the xml blocks.</p> <p>Any idea on how I could add this symbol "&lt;" in my xml files?</p> <p>Thank a lot.</p>
3,166,967
3
1
null
2010-07-02 15:11:15.213 UTC
23
2016-07-07 19:48:21.68 UTC
null
null
null
null
327,402
null
1
115
android|xml|special-characters
72,479
<p>Use</p> <p><code>&amp;lt;</code> for <code>&lt;</code></p> <p><code>&amp;gt;</code> for <code>&gt;</code></p> <p><code>&amp;amp;</code> for <code>&amp;</code></p>
3,126,201
Javascript && operator versus nested if statements: what is faster?
<p>Now, before you all jump on me and say "you're over concerned about performance," let it hereby stand that I ask this more out of curiosity than rather an overzealous nature. That said...</p> <p>I am curious if there is a performance difference between use of the &amp;&amp; ("and") operator and nested if statements. Also, is there an actual processing difference? I.e., does &amp;&amp; <em>always</em> process <em>both</em> statements, or will it stop @ the first one if the first one fails? How would that be different than nested if statements?</p> <p>Examples to be clear:</p> <p>A) &amp;&amp; ("and") operator</p> <pre><code>if(a == b &amp;&amp; c == d) { ...perform some code fashizzle... } </code></pre> <p>versus B) nested if statements</p> <pre><code>if(a == b) { if(c == d) { ...perform some code fashizzle... } } </code></pre>
3,126,211
4
1
null
2010-06-27 02:46:17.647 UTC
8
2015-05-11 12:57:01.183 UTC
null
null
null
null
209,803
null
1
38
javascript|performance|conditional-operator
55,292
<p>The performance difference is negligible. The <code>&amp;&amp;</code> operator won't check the right hand expression when the left hand expression evaluates <code>false</code>. However, the <code>&amp;</code> operator will check <em>both</em> regardless, maybe your confusion is caused by this fact.</p> <p>In this particular example, I'd just choose the one using <code>&amp;&amp;</code>, since that's better readable.</p>
29,231,013
How can I use a simple Dropdown list in the search box of GridView::widget, Yii2?
<p>I am trying to make a dropdown list in the search box of a <code>GridView::widget</code>, Yii2 for searching related data. So, how can I create a simple dropdown list in the search box of <code>GridView::widget</code>, Yii2 framework?<br></p> <p>Thanks.</p>
32,580,108
2
0
null
2015-03-24 11:08:39.86 UTC
19
2017-03-20 08:49:03.247 UTC
2015-10-13 12:50:59.443 UTC
null
4,097,436
null
4,473,768
null
1
50
php|search|gridview|drop-down-menu|yii2
57,041
<p>You can also use below code </p> <pre><code>[ 'attribute'=&gt;'attribute name', 'filter'=&gt;array("ID1"=&gt;"Name1","ID2"=&gt;"Name2"), ], </code></pre> <p>OR</p> <pre><code>[ 'attribute'=&gt;'attribute name', 'filter'=&gt;ArrayHelper::map(Model::find()-&gt;asArray()-&gt;all(), 'ID', 'Name'), ], </code></pre>
28,404,817
AnnotationConfigApplicationContext has not been refreshed yet - what's wrong?
<p>My very basic spring application stopped working and I can't understand what's happened. <strong>pom.xml:</strong></p> <pre><code>&lt;properties&gt; &lt;spring.version&gt;4.1.1.RELEASE&lt;/spring.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p><strong>Config class:</strong></p> <pre><code>@Configuration public class MyConfig { @Bean public HelloWorld helloWorld() { return new HelloWorld(); } } </code></pre> <p><strong>Bean class:</strong></p> <pre><code>public class HelloWorld { private String message; public void setMessage(String message) { this.message = message; } public String getMessage() { return message; } } </code></pre> <p><strong>Entry point of application:</strong></p> <pre><code>public class MainApp { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(MyConfig.class); HelloWorld bean = ctx.getBean(HelloWorld.class); bean.setMessage("ladjfaj"); System.out.println(bean.getMessage()); } } </code></pre> <p>And I'm getting an error </p> <blockquote> <p>Exception in thread "main" java.lang.IllegalStateException: org.springframework.context.annotation.AnnotationConfigApplicationContext@6ebf8cf5 has not been refreshed yet at org.springframework.context.support.AbstractApplicationContext.assertBeanFactoryActive(AbstractApplicationContext.java:943) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:967) at com.nikolas.config.MainApp.main(MainApp.java:12)</p> </blockquote>
28,404,863
3
0
null
2015-02-09 07:31:34.56 UTC
1
2022-08-15 20:05:10.807 UTC
null
null
null
null
2,659,898
null
1
27
java|spring|configuration
47,600
<p>You have to call <code>ctx.refresh()</code> before you can call <code>ctx.getBean(HelloWorld.class);</code></p>
40,678,930
Use switch with number case and char case
<p>I want to make a <code>switch</code> loop. </p> <p>If input is from <code>1</code> to <code>5</code>. It will print a number. Else it will print <code>"this is not a number"</code>. And if the input is <code>'e'</code>. The <code>switch</code> loop should be ended. </p> <p>I can make the number part, but I don't know how can I to make input with <code>'e'</code>. It just won't read. Here is my code:</p> <pre><code>int main() { int i,a = 0; printf("Write something:"); scanf("%d", &amp;i); do{ switch (i) { case 1: printf("1"); break; case 2: printf("2"); break; case 3: printf("3"); break; case 4: printf("4"); break; case 5: printf("5"); break; case 'e': a=1; break; default: printf("This is not a number”); break; } }while (a==0);} </code></pre> <p>My problem is I can't have input as <code>'e'</code> or any char. Because if I do that I will create a paradox loop or just don't work at all. Where am I wrong?</p>
40,679,033
5
4
null
2016-11-18 13:57:58.977 UTC
null
2021-05-03 20:05:15.827 UTC
2016-11-18 14:17:59.573 UTC
null
1,085,062
null
7,032,877
null
1
2
c|char|switch-statement|case
63,460
<p>Just treat the integers as characters like this;</p> <p>By the way, you probably want to read a new character each time through the while loop, otherwise you'll get stuck printing forever. The default case below allows us to break from the loop.</p> <pre><code>int main() { char i,a = 0; printf(&quot;Write something:&quot;); scanf(&quot;%c&quot;, &amp;i); do{ switch (i) { case '1': case '2': case '3': case '4': case '5': printf(&quot;%c&quot;,i); break; case 'e': a=1; break; default: printf(&quot;This is not a number&quot;); break; } }while (a==0); } </code></pre>
2,664,618
What does it mean that "Lisp can be written in itself?"
<p>Paul Graham wrote that <a href="http://www.paulgraham.com/rootsoflisp.html" rel="noreferrer">"The unusual thing about Lisp-- in fact, the defining quality of Lisp-- is that it can be written in itself."</a> But that doesn't seem the least bit unusual or definitive to me.</p> <p>ISTM that a programming language is defined by two things: Its compiler or interpreter, which defines the syntax and the semantics for the language by fiat, and its standard library, which defines to a large degree the idioms and techniques that skilled users will use when writing code in the language.</p> <p>With a few specific exceptions, (the non-C# members of the .NET family, for example,) most languages' standard libraries are written in that language for two very good reasons: because it will share the same set of syntactical definitions, function calling conventions, and the general "look and feel" of the language, and because the people who are likely to write a standard library for a programming language are its users, and particularly its designer(s). So there's nothing unique there; that's pretty standard.</p> <p>And again, there's nothing unique or unusual about a language's compiler being written in itself. C compilers are written in C. Pascal compilers are written in Pascal. Mono's C# compiler is written in C#. Heck, even <a href="http://en.wikipedia.org/wiki/PyPy" rel="noreferrer">some scripting languages</a> have implementations "written in itself".</p> <p>So what does it mean that Lisp is unusual in being written in itself?</p>
2,664,632
5
2
null
2010-04-19 00:46:03.873 UTC
13
2020-05-14 11:18:29.867 UTC
2012-04-29 15:20:30.177 UTC
null
50,776
null
32,914
null
1
25
programming-languages|lisp
7,198
<p>Probably what Paul means is that the representation of Lisp <em>syntax</em> as a Lisp <em>value</em> is standardized and pervasive. That is, a Lisp program is just a special kind of S-expression, and it's exceptionally easy to write Lisp code that manipulates Lisp code. Writing a Lisp interpreter in Lisp is a special case, and is not so exciting as the general ability to have a unified representation for both code and data.</p>
2,378,402
Jackson Vs. Gson
<p>After searching through some existing libraries for JSON, I have finally ended up with these two:</p> <ul> <li>Jackson</li> <li>Google GSon</li> </ul> <p>I am a bit partial towards GSON, but word on the net is that GSon suffers from a certain celestial performance <a href="http://www.cowtowncoder.com/blog/archives/2009/09/entry_326.html" rel="noreferrer">issue</a> (as of Sept 2009).</p> <p>I am continuing my comparison; in the meantime, I'm looking for help to make up my mind.</p>
2,378,615
5
10
null
2010-03-04 10:20:30.693 UTC
115
2014-12-30 17:58:41.26 UTC
2013-08-22 21:23:52.923 UTC
null
13,295
null
119,772
null
1
396
java|json|comparison|gson|jackson
193,288
<p>I did this research the last week and I ended up with the same 2 libraries. As I'm using Spring 3 (that adopts Jackson in its default Json view '<a href="http://static.springsource.org/spring/docs/3.0.0.RC2/javadoc-api/org/springframework/web/servlet/view/json/MappingJacksonJsonView.html" rel="noreferrer">JacksonJsonView</a>') it was more natural for me to do the same. The 2 lib are pretty much the same... at the end they simply map to a json file! :) </p> <p>Anyway as you said <strong>Jackson</strong> has a + in performance and that's very important for me. The project is also quite active as you can see from <a href="https://github.com/FasterXML/jackson" rel="noreferrer">their web page</a> and that's a very good sign as well.<br></p>
3,089,151
Specifying an order to junit 4 tests at the Method level (not class level)
<p>I know this is bad practice, but it needs to be done, or I'll need to switch to <code>testng</code>. Is there a way, similar to JUnit 3's testSuite, to specify the order of the tests to be run in a class?</p>
3,623,660
6
0
null
2010-06-21 23:18:27.147 UTC
18
2020-12-08 18:24:12.023 UTC
2015-02-19 00:39:55.903 UTC
null
445,131
null
357,848
null
1
39
java|unit-testing|junit4|junit3
25,356
<p>If you're sure you <em>really</em> want to do this: There may be a better way, but this is all I could come up with...</p> <p>JUnit4 has an annotation: <code>@RunWith</code> which lets you override the default Runner for your tests.</p> <p>In your case you would want to create a special subclass of <code>BlockJunit4ClassRunner</code>, and override <code>computeTestMethods()</code> to return tests in the order you want them executed. For example, let's say I want to execute my tests in reverse alphabetical order:</p> <pre><code>public class OrderedRunner extends BlockJUnit4ClassRunner { public OrderedRunner(Class klass) throws InitializationError { super(klass); } @Override protected List computeTestMethods() { List list = super.computeTestMethods(); List copy = new ArrayList(list); Collections.sort(copy, new Comparator() { public int compare(FrameworkMethod o1, FrameworkMethod o2) { return o2.getName().compareTo(o1.getName()); } }); return copy; } }</code></pre> <pre><code>@RunWith(OrderedRunner.class) public class OrderOfTest { @Test public void testA() { System.out.println("A"); } @Test public void testC() { System.out.println("C"); } @Test public void testB() { System.out.println("B"); } }</code></pre> <p>Running this test produces:</p> <pre>C B A</pre> <p>For your specific case, you would want a comparator that would sort the tests by name in the order you want them executed. (I would suggest defining the comparator using something like Google Guava's class <code>Ordering.explicit("methodName1","methodName2").onResultOf(...);</code> where onResultOf is provided a function that converts FrameworkMethod to its name... though obviously you are free to implement that any way you want.</p>
2,503,705
How to get a child element to show behind (lower z-index) than its parent?
<p>I need a certain dynamic element to always appear on top of another element, no matter what order in the DOM tree they are. Is this possible? I've tried <code>z-index</code> (with <code>position: relative</code>), and it doesn't seem to work.</p> <p>I need:</p> <pre><code>&lt;div class="a"&gt; &lt;div class="b"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="b"&gt; &lt;div class="a"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>To display exactly the same when rendered. And for flexibility purposes (I'm planning on distributing a plugin that needs this functionality), I'd really like to not have to resort to absolute or fixed positioning.</p> <p>For what it's worth, to perform the function I was wanting, I made a conditional statement where the overlapping child element would become transparent in the case it was blocking the view of its parent. It's not perfect, but it's something.</p>
2,503,782
7
1
null
2010-03-23 21:19:39.21 UTC
9
2022-05-17 03:39:21.99 UTC
2018-10-16 20:43:08.663 UTC
user166390
2,756,409
null
257,878
null
1
45
html|css|dom
29,066
<p>If the elements make a hierarchy, it cannot be done that way, because every positioned element creates new <a href="http://css-discuss.incutio.com/wiki/Overlapping_And_ZIndex" rel="noreferrer">stacking context</a>, and z-index is relative to the elements of the same stacking context.</p>
3,066,703
Blocks and yields in Ruby
<p>I am trying to understand blocks and <code>yield</code> and how they work in Ruby.</p> <p>How is <code>yield</code> used? Many of the Rails applications I've looked at use <code>yield</code> in a weird way.</p> <p>Can someone explain to me or show me where to go to understand them?</p>
3,066,939
10
1
null
2010-06-18 01:34:40.26 UTC
126
2022-05-19 13:29:29.653 UTC
2022-05-19 13:29:29.653 UTC
null
4,294,399
null
223,367
null
1
307
ruby|ruby-block
154,543
<p>Yes, it is a bit puzzling at first.</p> <p>In Ruby, methods can receive a code block in order to perform arbitrary segments of code.</p> <p>When a method expects a block, you can invoke it by calling the <code>yield</code> function.</p> <p>Example:</p> <p>Take <code>Person</code>, a class with a <code>name</code> attribute and a <code>do_with_name</code> method. When the method is invoked it will pass the <code>name</code> attribute to the block.</p> <pre><code>class Person def initialize( name ) @name = name end def do_with_name # expects a block yield( @name ) # invoke the block and pass the `@name` attribute end end </code></pre> <p>Now you can invoke this method and pass an arbitrary code block.</p> <pre><code>person = Person.new(&quot;Oscar&quot;) # Invoking the method passing a block to print the value person.do_with_name do |value| puts &quot;Got: #{value}&quot; end </code></pre> <p>Would print:</p> <pre><code>Got: Oscar </code></pre> <p>Notice the block receives as a parameter a variable called <code>value</code>. When the code invokes <code>yield</code> it passes as argument the value of <code>@name</code>.</p> <pre><code>yield( @name ) </code></pre> <p>The same method can be invoked with a different block.</p> <p>For instance to reverse the name:</p> <pre><code>reversed_name = &quot;&quot; # Invoke the method passing a different block person.do_with_name do |value| reversed_name = value.reverse end puts reversed_name =&gt; &quot;racsO&quot; </code></pre> <p>Other more interesting real life examples:</p> <p>Filter elements in an array:</p> <pre><code> days = [&quot;Monday&quot;, &quot;Tuesday&quot;, &quot;Wednesday&quot;, &quot;Thursday&quot;, &quot;Friday&quot;] # Select those which start with 'T' days.select do | item | item.match /^T/ end =&gt; [&quot;Tuesday&quot;, &quot;Thursday&quot;] </code></pre> <p>Or sort by name length:</p> <pre><code> days.sort do |x,y| x.size &lt;=&gt; y.size end =&gt; [&quot;Monday&quot;, &quot;Friday&quot;, &quot;Tuesday&quot;, &quot;Thursday&quot;, &quot;Wednesday&quot;] </code></pre> <p>If the block is optional you can use:</p> <pre><code>yield(value) if block_given? </code></pre> <p>If is not optional, just invoke it.</p> <p>You can try these examples on your computer with <code>irb</code> (<a href="https://en.wikipedia.org/wiki/Interactive_Ruby_Shell" rel="noreferrer">Interactive Ruby Shell</a>)</p> <p>Here are all the examples in a copy/paste ready form:</p> <pre><code>class Person def initialize( name ) @name = name end def do_with_name # expects a block yield( @name ) # invoke the block and pass the `@name` attribute end end person = Person.new(&quot;Oscar&quot;) # Invoking the method passing a block to print the value person.do_with_name do |value| puts &quot;Got: #{value}&quot; end reversed_name = &quot;&quot; # Invoke the method passing a different block person.do_with_name do |value| reversed_name = value.reverse end puts reversed_name # Filter elements in an array: days = [&quot;Monday&quot;, &quot;Tuesday&quot;, &quot;Wednesday&quot;, &quot;Thursday&quot;, &quot;Friday&quot;] # Select those which start with 'T' days.select do | item | item.match /^T/ end # Sort by name length: days.sort do |x,y| x.size &lt;=&gt; y.size end </code></pre>
2,588,149
What is the "->" PHP operator called?
<p>What do you call this arrow looking <code>-&gt;</code> operator found in PHP? </p> <p>It's either a minus sign, dash or hyphen followed by a greater than sign (or right chevron). </p> <p>How do you pronounce it when reading code out loud?</p>
2,588,183
15
1
null
2010-04-06 20:41:44.43 UTC
36
2020-11-12 13:52:36.833 UTC
2020-11-12 13:34:50.773 UTC
null
2,370,483
null
192,227
null
1
128
php|operators|terminology
78,289
<p>The official name is &quot;object operator&quot; - <a href="http://php.net/manual/en/tokens.php" rel="nofollow noreferrer">T_OBJECT_OPERATOR</a>.</p>
25,075,706
Automatic failing/non-execution of interdependent tests in Robot Framework
<p>I have a large number of test cases, in which several test cases are interdependent. Is it possible that while a later test case is getting executed you can find out the status of a previously executed test case? In my case, the 99th test case depends on the status of some prior test cases and thus, if either the 24th or the 38th fails I would like the 99th test case NOT to get executed at all and thus save me a lot of time. Kindly, explain with some example if possible. Thanks in advance!</p>
25,079,032
2
0
null
2014-08-01 08:11:29.323 UTC
10
2022-07-15 17:01:48.403 UTC
2020-01-21 21:05:27.35 UTC
null
699,665
null
3,802,759
null
1
11
python|testing|automated-tests|robotframework
9,845
<p>Robot is very extensible, and a feature that was introduced in version 2.8.5 makes it easy to write a keyword that will fail if another test has failed. This feature is the ability for a <a href="https://github.com/robotframework/robotframework/issues/811" rel="nofollow noreferrer">library to act as a listener</a>. With this, a library can keep track of the pass/fail status of each test. With that knowledge, you can create a keyword that fails immediately if some other test fails.</p> <p>The basic idea is, cache the pass/fail status as each test finishes (via the special <code>_end_test</code> method). Then, use this value to determine whether to fail immediately or not.</p> <p>Here's an example of how to use such a keyword:</p> <pre><code>*** Settings *** Library /path/to/DependencyLibrary.py *** Test Cases *** Example of a failing test fail this test has failed Example of a dependent test [Setup] | Require test case | Example of a failing test log | hello, world </code></pre> <p>Here is the library definition:</p> <pre><code>from robot.libraries.BuiltIn import BuiltIn class DependencyLibrary(object): ROBOT_LISTENER_API_VERSION = 2 ROBOT_LIBRARY_SCOPE = &quot;GLOBAL&quot; def __init__(self): self.ROBOT_LIBRARY_LISTENER = self self.test_status = {} def require_test_case(self, name): key = name.lower() if (key not in self.test_status): BuiltIn().fail(&quot;required test case can't be found: '%s'&quot; % name) if (self.test_status[key] != &quot;PASS&quot;): BuiltIn().fail(&quot;required test case failed: '%s'&quot; % name) return True def _end_test(self, name, attrs): self.test_status[name.lower()] = attrs[&quot;status&quot;] </code></pre>
23,805,915
Run parallel test task using gradle
<p>We use JUnit as a test framework. We have many projects. We use gradle (version 1.12) as a build tool. To run the unit tests in parallel using gradle we use the below script in every project under test task.</p> <pre><code>maxParallelForks = Runtime.runtime.availableProcessors() </code></pre> <p>Ex:</p> <pre><code>test { maxParallelForks = Runtime.runtime.availableProcessors() } </code></pre> <p>We also maintain the single gradle.properties file.</p> <p>Is it possible to define <strong>test.maxParallelForks = Runtime.runtime.availableProcessors()</strong> in gradle.properties file rather than defining it in each build.gradle file under test task?</p>
23,807,352
4
0
null
2014-05-22 11:45:24.23 UTC
17
2022-09-17 16:41:22.017 UTC
2020-12-15 11:13:15.073 UTC
null
1,080,523
null
2,122,885
null
1
54
junit|gradle|build.gradle
57,823
<p><code>$rootDir/build.gradle</code>:</p> <pre><code>subprojects { tasks.withType(Test) { maxParallelForks = Runtime.runtime.availableProcessors() } } </code></pre>
51,049,663
Python3.6 error: ModuleNotFoundError: No module named 'src'
<p>I know similar questions have been asked before... But I had a quick doubt... I have been following this link: <a href="https://www.python-course.eu/python3_packages.php" rel="nofollow noreferrer">https://www.python-course.eu/python3_packages.php</a></p> <p>my code structure:</p> <pre><code>my-project -- __init__.py -- src -- __init__.py -- file1.py -- test -- __init__.py -- test_file1.py </code></pre> <p>test_file1.py:</p> <pre><code>import unittest from src.file1 import * class TestWriteDataBRToOS(unittest.TestCase): def test_getData(self): sampleData = classInFile1() sampleData.getData() self.assertNotEqual(sampleData.usrname, &quot;&quot;) if __name__ == '__main__': unittest.main() </code></pre> <p>Here I get the error:</p> <pre><code>ModuleNotFoundError: No module named 'src' </code></pre> <p>If I change to :</p> <pre><code>import sys sys.path.insert(0, '../src') import unittest from file1 import * </code></pre> <p>then it works!</p> <p>Can someone help me understand why it won't work like how it has been described in the link pasted above or any alternative way instead of writing the <code>sys.path.insert(0, '../src')</code> statement.</p> <p>Thanks!</p> <p>Edit:</p> <p>after executing from my-project dir: <code>python -m unittest test/test_file1/TestWriteDataBRToOS</code> I am getting the error as updated below.</p> <pre><code>Traceback (most recent call last): File &quot;/usr/lib/python2.7/runpy.py&quot;, line 174, in _run_module_as_main &quot;__main__&quot;, fname, loader, pkg_name) File &quot;/usr/lib/python2.7/runpy.py&quot;, line 72, in _run_code exec code in run_globals File &quot;/usr/lib/python2.7/unittest/__main__.py&quot;, line 12, in &lt;module&gt; main(module=None) File &quot;/usr/lib/python2.7/unittest/main.py&quot;, line 94, in __init__ self.parseArgs(argv) File &quot;/usr/lib/python2.7/unittest/main.py&quot;, line 149, in parseArgs self.createTests() File &quot;/usr/lib/python2.7/unittest/main.py&quot;, line 158, in createTests self.module) File &quot;/usr/lib/python2.7/unittest/loader.py&quot;, line 130, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File &quot;/usr/lib/python2.7/unittest/loader.py&quot;, line 91, in loadTestsFromName module = __import__('.'.join(parts_copy)) ImportError: Import by filename is not supported. </code></pre>
51,050,147
4
0
null
2018-06-26 18:50:52.933 UTC
5
2022-08-01 20:47:29.847 UTC
2022-04-08 12:53:25.817 UTC
null
11,103,856
null
3,868,051
null
1
32
python-3.6|python-unittest
94,403
<p>You have to run the test from the <code>my-project</code> folder, rather than from the <code>test</code> folder.</p> <pre><code>python -m unittest test.test_file1.TestWriteDataBRToOS </code></pre>
40,059,929
Cannot find the UseMysql method on DbContextOptions
<p>I am playing around with the dotnet core on linux, and i am trying to configure my DbContext with a connection string to a mysql Server.</p> <p>my DbContext looks like so:</p> <pre><code>using Microsoft.EntityFrameworkCore; using Models.Entities; namespace Models { public class SomeContext : DbContext { //alot of dbSets... public DbSet&lt;SomeEntity&gt; SomeDbSet { get; set; } public SomeContext(DbContextOptions&lt;SomeContext&gt; options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMysql //Cannot find this method } protected override void OnModelCreating(ModelBuilder modelBuilder) { //using modelBuilder to map some relationships } } } </code></pre> <p>My dependencies looks like so:</p> <pre><code>&quot;dependencies&quot;: { &quot;Microsoft.NETCore.App&quot;: { &quot;version&quot;: &quot;1.0.0&quot;, &quot;type&quot;: &quot;platform&quot; }, &quot;Microsoft.AspNetCore.Diagnostics&quot;: &quot;1.0.0&quot;, &quot;Microsoft.AspNetCore.Server.IISIntegration&quot;: &quot;1.0.0&quot;, &quot;Microsoft.AspNetCore.Server.Kestrel&quot;: &quot;1.0.1&quot;, &quot;Microsoft.Extensions.Logging.Console&quot;: &quot;1.0.0&quot;, &quot;Microsoft.Extensions.Configuration.EnvironmentVariables&quot;: &quot;1.0.0&quot;, &quot;Microsoft.Extensions.Configuration.FileExtensions&quot;: &quot;1.0.0&quot;, &quot;Microsoft.Extensions.Configuration.Json&quot;: &quot;1.0.0&quot;, &quot;Microsoft.Extensions.Configuration.CommandLine&quot;: &quot;1.0.0&quot;, &quot;Microsoft.AspNetCore.Mvc&quot;:&quot;1.0.0&quot;, &quot;Microsoft.EntityFrameworkCore&quot;: &quot;1.0.1&quot;, &quot;MySql.Data.Core&quot;: &quot;7.0.4-ir-191&quot;, &quot;MySql.Data.EntityFrameworkCore&quot;: &quot;7.0.4-ir-191&quot; }, </code></pre> <p>I also tried to use the mysql server in my Startup.cs in the following code</p> <pre><code>public class Startup { public void ConfigureServices(IServiceCollection services) { var connection = @&quot;Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;&quot;; services.AddDbContext&lt;SomeContext&gt;(options =&gt; options.UseMysql); //Cannot find UseMysql* } </code></pre> <p>I tried to change my directive from</p> <pre><code>using Microsoft.EntityFrameworkCore; </code></pre> <p>to</p> <pre><code>using MySQL.Data.EntityFrameworkCore; </code></pre> <p>Which makes sense? maybe? but then all of the references to DbContext and DbSet is gone, so i suppose the solution is a mix of sorts??</p>
40,060,297
4
0
null
2016-10-15 13:58:54.53 UTC
4
2021-04-30 20:26:29.613 UTC
2021-04-30 20:26:29.613 UTC
null
2,992,311
null
2,992,311
null
1
17
c#|mysql|entity-framework|asp.net-core
40,861
<p>You need</p> <pre><code>using Microsoft.EntityFrameworkCore; using MySQL.Data.EntityFrameworkCore.Extensions; </code></pre> <p>Oracle is not complying to the standard practices when using Dependency Injection, so its all a bit different. The standard practice is to put the extension methods for Depedency Injection into <code>Microsoft.Extensions.DependencyInjection</code> namespace, which is included in most ASP.NET Core app projects so the method becomes automatically available when a package is imported. </p>
10,687,035
Stop build execution in Jenkins
<p>I am using Jenkins to run a Maven project having Junit tests in Sauce Connect. I created a job and to stop/abort the build in between I clicked the Cross button (X) shown near progress bar for build execution. But the build execution does not get stopped. When I moved to console output for the build, it was showing message as "Closing Sauce Connect" and it takesd too much time and Jenkins does not stop build process.</p> <p>Could anyone please advice as to how can we manually stop/abort build execution.</p> <p>Additionally, is there any site where we can find proper documentation regarding Jenkins for Beginners as i have few more problems regarding its start and stop process.</p>
10,689,249
2
0
null
2012-05-21 14:19:15.387 UTC
3
2015-10-20 08:24:22.477 UTC
2015-10-20 08:24:22.477 UTC
null
322,020
null
968,813
null
1
16
jenkins
45,599
<p>Jenkins will terminate the build nicely, i.e. wait for the running processes to end after sending the termination signal. If the processes take a long time to terminate, it will wait. The easiest way is to change your build/code such that it terminates immediately, or has a timeout for closing connections etc.</p> <p>Regarding more documentation, have a look at the <a href="https://wiki.jenkins-ci.org/display/JENKINS/Meet+Jenkins" rel="nofollow">Jenkins wiki</a> or get the <a href="http://www.wakaleo.com/books/jenkins-the-definitive-guide" rel="nofollow">Jenkins book</a>.</p>
10,392,987
visibility:visible/hidden div
<p>What is the best way to show a div when clicked on a button and then hide it with a close button??</p> <p>My Jquery code is as follows:</p> <pre><code>$(".imageIcon").click(function(){ $('.imageShowWrapper').css("visibility", 'visible'); }); $(".imageShowWrapper").click(function(){ $('.imageShowWrapper').css("visibility", 'hidden'); }); </code></pre> <p>except the problem I'm having is it closes automatically without any clicks. It loads everything ok, displays for about 1/2 sec and then closes. Any ideas?</p>
10,393,008
6
0
null
2012-05-01 02:50:02.34 UTC
2
2019-01-16 01:46:07.7 UTC
null
null
null
null
1,347,112
null
1
18
jquery|css|html|visibility
95,353
<p>You can use the <code>show</code> and <code>hide</code> methods:</p> <pre><code>$(".imageIcon").click(function() { $('.imageShowWrapper').show(); }); $(".imageShowWrapper").click(function() { $(this).hide(); }); </code></pre>
10,586,838
Illegal characters in path when loading a string with XDocument
<p>I have very simple XML in a string that I'm trying to load via <code>XDocument</code> so that I can use LINQ to XML:</p> <pre><code> var xmlString = @"&lt;?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?&gt; &lt;person&gt;Test Person&lt;/person&gt;"; var doc = XDocument.Load(xmlString); //'Illegal characters in path' error thrown here </code></pre> <p>I get an <code>Illegal characters in path.</code> error thrown when I try to load the XML; could someone please explain why this is happening? Thanks.</p>
10,586,880
3
0
null
2012-05-14 15:56:46.643 UTC
5
2017-09-05 06:32:41.217 UTC
2015-12-03 19:50:11.46 UTC
null
98,713
null
1,202,717
null
1
45
c#|xml|.net-4.0
29,685
<p>You are looking for <code>XDocument.Parse</code> - <code>XDocument.Load</code> is for <em>files</em> not xml strings:</p> <pre><code>var doc = XDocument.Parse(xmlString); </code></pre>
10,697,161
Why FloatBuffer instead of float[]?
<p>I've been using FloatBuffers in my Android code for a while (copied it from some opengles tutorial), but I cannot understand exactly what this construct is and why it is needed.</p> <p>For example this code (or similar) I see in many many peoples' code and android tutorials:</p> <pre><code>float[] vertices = ...some array... ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4); vbb.order(ByteOrder.nativeOrder()); // use the device hardware's native byte order FloatBuffer fb = vbb.asFloatBuffer(); // create a floating point buffer from the ByteBuffer fb.put(vertices); // add the coordinates to the FloatBuffer fb.position(0); // set the buffer to read the first coordinate </code></pre> <p>This seems awfully verbose and messy for something which as far as I can tell is just a fancy wrapper around of an array of floats.</p> <p>Questions: </p> <ul> <li><p>What is the justification for this type of class (ByteBuffer, FloatBuffer), as opposed to any other kind of collection or simple array of floats?</p></li> <li><p>What's the idea behind creating a ByteBuffer before converting it into a FloatBuffer? </p></li> </ul>
10,697,239
2
0
null
2012-05-22 06:53:25.937 UTC
24
2012-08-24 09:38:29.45 UTC
null
null
null
null
1,236,185
null
1
50
java|android|opengl-es
21,024
<p>The main reason is performance: ByteBuffers and the other NIO classes enable accelerated operations when interfacing with native code (typically by avoiding the need to copy data into a temporary buffer).</p> <p>This is pretty important if you are doing a lot of OpenGL rendering calls for example.</p> <p>The reason for creating a ByteBuffer first is that you want to use the allocateDirect call to create a <em>direct</em> byte buffer, which benefits from the accelerated operations. You then create a FloatBuffer from this that shares the same memory. The FloatBuffer doesn't itself have an allocateDirect method for some reason, which is why you have to go via ByteBuffer.</p>
30,806,119
NestedScrollView and CoordinatorLayout. Issue on Scrolling
<p>I have a strange issue with the <code>CoordinatorLayout</code> and the <code>NestedScrollView</code> (with the design support library 22.2.0)</p> <p>Using a content smaller than <code>NestedScrollView</code> I should have a fixed content. However trying to scroll up and down the content I can obtain that the content is displaced and never again in their own place.</p> <p>Here a little sample:<img src="https://i.stack.imgur.com/yzpfk.gif" alt="enter image description here"></p> <p>Here the code:</p> <pre><code>&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"&gt; &lt;android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:layout_scrollFlags="scroll|enterAlways" /&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"&gt; &lt;FrameLayout android:paddingTop="24dp" android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="@dimen/padding"&gt; &lt;/FrameLayout&gt; &lt;/android.support.v4.widget.NestedScrollView&gt; &lt;android.support.design.widget.FloatingActionButton android:id="@+id/fab_action" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="16dp" android:visibility="gone" android:src="@drawable/ic_done" /&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre>
30,807,149
5
1
null
2015-06-12 14:54:21.72 UTC
14
2018-12-21 13:06:57.827 UTC
2015-12-13 09:59:40.043 UTC
null
2,016,562
null
2,016,562
null
1
35
android|material-design|android-support-library|android-design-library|android-coordinatorlayout
64,284
<p>This can also be observed in the <a href="https://github.com/chrisbanes/cheesesquare">cheesesquare</a> demo when removing all but one card in the details fragment.</p> <p>I was able to solve this (for now) using this class: <a href="https://gist.github.com/EmmanuelVinas/c598292f43713c75d18e">https://gist.github.com/EmmanuelVinas/c598292f43713c75d18e</a></p> <pre><code>&lt;android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="com.evs.demo.layout.FixedScrollingViewBehavior"&gt; ..... &lt;/android.support.v4.widget.NestedScrollView&gt; </code></pre>
31,245,959
How to add JBoss Server in Eclipse?
<p>I am new to JBoss and have just installed Eclipse. I have added a project to the workspace and now I want to deploy it to a Jboss server. However, in the <em>New Server Runtime Environment</em> list, JBoss is not available:</p> <p><img src="https://i.stack.imgur.com/UZbC0.png" alt="New Server Runtime Environment without JBoss"></p> <p>I am using the below Eclipse version:</p> <blockquote> <p>Java EE IDE for Web Developers.</p> <p>Version: Mars Release (4.5.0)</p> </blockquote> <p>Why is JBoss not listed as a runtime environment? What do I have to do to add JBoss to the list of available runtime environments?</p>
31,248,157
7
1
null
2015-07-06 12:33:26.01 UTC
6
2019-12-15 18:05:25.113 UTC
2015-07-06 15:04:05.693 UTC
null
1,421,925
null
476,828
null
1
22
java|eclipse|jboss|server
115,366
<p>Here is the solution follow below steps</p> <ol> <li>In Eclipse Mars go to Help-> Install New Software </li> <li>Click on add button and paste the URL of the update site which is in our case: <a href="http://download.jboss.org/jbosstools/updates/development/mars/" rel="noreferrer">Eclipse Mars tools for Jboss</a></li> <li>Now select the <strong>JBossAS</strong> Tools plugin and Click "Next"</li> </ol>
19,355,818
How to make scrollviewer work with Height set to Auto in WPF?
<p>I have learned that if the height of a grid row, where the <code>ScrollViewer</code> resides, is set as <code>Auto</code>, the vertical scroll bar will not take effect since the actual size of the <code>ScrollViewer</code> can be larger than the height in sight. So in order to make the scroll bar work, I should set the height to either a fixed number or star height</p> <p>However, I now have this requirement, that I have two different views reside in two grid rows, and I have a toggle button to switch between these two views: when one view is shown, the other one is hidden/disappeared. So I have defined two rows, both heights are set as <code>Auto</code>. And I bind the visibility of the view in each row to a boolean property from my ViewModel (one is converted from <code>True</code> to <code>Visible</code> and the other from <code>True</code> to <code>Collapsed</code>. The idea is when one view's visibility is <code>Collapsed</code>, the height of the grid row/view will be changed to 0 automatically.</p> <p>The view show/hidden is working fine. However, in one view I have a <code>ScrollViewer</code>, which as I mentioned doesn't work when the row height is set as <code>Auto</code>. Can anybody tell me how I can fulfill such requirement while still having the <code>ScrollViewer</code> working automatically`? I guess I can set the height in code-behind. But since I am using MVVM, it would require extra communication/notification. Is there a more straightforward way to do that? </p>
19,356,424
5
0
null
2013-10-14 08:02:57.367 UTC
8
2020-06-15 13:15:56.893 UTC
2019-02-05 02:49:09.693 UTC
null
196,919
null
944,213
null
1
17
wpf|xaml|uwp-xaml|scrollviewer|autosize
46,008
<p>Change Height from <code>Auto</code> to <code>*</code>, if you can.</p> <p>Example:</p> <pre><code> &lt;Window x:Class="WpfApplication3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="200" Width="525"&gt; &lt;StackPanel Orientation="Horizontal" Background="LightGray"&gt; &lt;Grid Width="100"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;ScrollViewer VerticalScrollBarVisibility="Auto" x:Name="_scroll1"&gt; &lt;Border Height="300" Background="Red" /&gt; &lt;/ScrollViewer&gt; &lt;TextBlock Text="{Binding ElementName=_scroll1, Path=ActualHeight}" Grid.Row="1"/&gt; &lt;/Grid&gt; &lt;Grid Width="100"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="*" /&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;ScrollViewer VerticalScrollBarVisibility="Auto" x:Name="_scroll2"&gt; &lt;Border Height="300" Background="Green" /&gt; &lt;/ScrollViewer&gt; &lt;TextBlock Text="{Binding ElementName=_scroll2, Path=ActualHeight}" Grid.Row="1"/&gt; &lt;/Grid&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre>
19,537,116
Can we delete duplicate records from a table in teradata without using intermediate table
<p>Can we delete duplicate records from a multiset table in teradata without using intermediate table.</p> <p>Suppose we have 2 rows with values 1, 2, 3 and 1, 2, 3 in my multiset table then after delete i should have only one row i.e. 1, 2, 3.</p>
19,549,032
4
0
null
2013-10-23 08:51:52.077 UTC
1
2021-03-30 19:23:00.753 UTC
null
null
null
null
1,948,361
null
1
1
teradata
41,420
<p>You can't unless the ROWID usage has been enabled on your system (and probablity is quite low). You can easily test it by trying to explain a SELECT ROWID FROM table;</p> <p>Otherwise there are two possible ways.</p> <p>Low number of duplicates:</p> <ul> <li>create a new table as result of <code>SELECT all columns FROM table GROUP BY all columns HAVING COUNT(*) &gt; 1;</code></li> <li><code>DELETE FROM tab WHERE EXISTS (SELECT * FROM newtab WHERE...)</code></li> <li><code>INSERT INTO tab SELECT * FROM newtab</code></li> </ul> <p>High number of duplicates:</p> <ul> <li>copy to a new table using <code>SELECT DISTINCT *</code> or copy to a SET TABLE to get rid of the duplicates and then re-INSERT back </li> </ul>
20,960,405
Bootstrap 3 Dropdown on iPad not working
<p>I have a simple Bootstrap 3 dropdown that is working in all browsers that I've tested (Chrome, FF, IE, Chrome on Android) but it is not working in Safari or Chrome on the iPad (ios 7.04).</p> <p>I thought this was an issue with the ontouchstart as suggested in some other posts dealing with Bootstrap 2 but I've tried that with a local file and have had no success: <a href="https://stackoverflow.com/questions/17435359/bootstrap-collapsed-menu-links-not-working-on-mobile-devices/17440942#17440942">Bootstrap Collapsed Menu Links Not Working on Mobile Devices</a></p> <p>I also don't want a solution where I have to modify the original javascript file since we're currently pulling that from a CDN.</p> <p>I created a simple snippet here to test: <a href="https://www.bootply.com/Bdzlt3G36C" rel="noreferrer">https://www.bootply.com/Bdzlt3G36C</a></p> <p>Here's the original code that's in the bootply in case that link dies in the future:</p> <pre><code>&lt;div class="col-sm-5 col-offset-2 top-buffer"&gt; &lt;div class="dropdown"&gt; &lt;a class="dropdown-toggle" id="ddAction" data-toggle="dropdown"&gt; Action &lt;/a&gt; &lt;ul class=" dropdown-menu" =""="" role="menu" aria-labelledby="ddaction"&gt; &lt;li role="presentation"&gt;&lt;a class="dropdown-toggle" id="ddAction" data-toggle="dropdown&gt; Action &lt;/a&gt; &lt;ul class=" dropdown-menu"="" role="menu" aria-labelledby="ddaction"&gt; &lt;/a&gt;&lt;a role="menuitem" tabindex="-1" href="http://www.google.com"&gt;Open Google&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
20,963,048
6
1
null
2014-01-06 22:21:25.327 UTC
7
2019-02-21 09:59:52.883 UTC
2018-08-23 12:15:46.373 UTC
null
1,342,185
null
1,342,185
null
1
30
javascript|ios|css|twitter-bootstrap-3
34,362
<p>I figured it out. I was missing the href="#" in my anchor tag. It was working fine in other browsers but not chrome or safari on IOS. Works fine now. Here's the final code for anyone that's interested:</p> <pre><code> &lt;div class="dropdown"&gt; &lt;a class="dropdown-toggle" id="ddAction" data-toggle="dropdown" href="#"&gt; Action &lt;/a&gt; &lt;ul class="dropdown-menu" role="menu" aria-labelledby="ddaction"&gt; &lt;li role="presentation"&gt; &lt;a role="menuitem" tabindex="-1" href="http://www.google.com"&gt;Open Google&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>And a working sample here: <a href="http://www.bootply.com/104147" rel="noreferrer">http://www.bootply.com/104147</a></p>
21,096,819
JNI and Gradle in Android Studio
<p>I'm trying to add native code to my app. I have everything in <code>../main/jni</code> as it was in my Eclipse project. I have added <code>ndk.dir=...</code> to my <code>local.properties</code>. I haven't done anything else yet (I'm not sure what else is actually required, so if I've missed something let me know). When I try and build I get this error:</p> <pre><code>Execution failed for task ':app:compileDebugNdk'. &gt; com.android.ide.common.internal.LoggedErrorException: Failed to run command: /Users/me/android-ndk-r8e/ndk-build NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=/Users/me/Project/app/build/ndk/debug/Android.mk APP_PLATFORM=android-19 NDK_OUT=/Users/me/Project/app/build/ndk/debug/obj NDK_LIBS_OUT=/Users/me/Project/app/build/ndk/debug/lib APP_ABI=all Error Code: 2 Output: make: *** No rule to make target `/Users/me/Project/webapp/build/ndk/debug//Users/me/Project/app/src/main/jni/jni_part.cpp', needed by `/Users/me/Project/app/build/ndk/debug/obj/local/armeabi-v7a/objs/webapp//Users/me/Project/app/src/main/jni/jni_part.o'. Stop. </code></pre> <p>What do I need to do?</p> <p><strong>Android.mk:</strong></p> <pre><code>LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) # OpenCV OPENCV_CAMERA_MODULES:=on OPENCV_INSTALL_MODULES:=on include .../OpenCV-2.4.5-android-sdk/sdk/native/jni/OpenCV.mk LOCAL_MODULE := native_part LOCAL_SRC_FILES := jni_part.cpp LOCAL_LDLIBS += -llog -ldl include $(BUILD_SHARED_LIBRARY) </code></pre> <p><strong>Application.mk:</strong></p> <pre><code>APP_STL := gnustl_static APP_CPPFLAGS := -frtti -fexceptions APP_ABI := armeabi armeabi-v7a APP_PLATFORM := android-8 </code></pre>
26,693,354
6
1
null
2014-01-13 16:51:04.907 UTC
43
2017-10-13 11:28:13.19 UTC
2014-07-14 12:30:43.867 UTC
null
1,368,342
null
319,618
null
1
76
android|java-native-interface|gradle|android-studio|android-ndk-r7
126,267
<h2>Gradle Build Tools 2.2.0+ - The closest the NDK has ever come to being called 'magic'</h2> <p>In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the <code>externalNativeBuild</code> and pointing <code>ndkBuild</code> path argument at an <code>Android.mk</code> or change <code>ndkBuild</code> to <code>cmake</code> and point the path argument at a <code>CMakeLists.txt</code> build script.</p> <pre><code>android { compileSdkVersion 19 buildToolsVersion "25.0.2" defaultConfig { minSdkVersion 19 targetSdkVersion 19 ndk { abiFilters 'armeabi', 'armeabi-v7a', 'x86' } externalNativeBuild { cmake { cppFlags '-std=c++11' arguments '-DANDROID_TOOLCHAIN=clang', '-DANDROID_PLATFORM=android-19', '-DANDROID_STL=gnustl_static', '-DANDROID_ARM_NEON=TRUE', '-DANDROID_CPP_FEATURES=exceptions rtti' } } } externalNativeBuild { cmake { path 'src/main/jni/CMakeLists.txt' } //ndkBuild { // path 'src/main/jni/Android.mk' //} } } </code></pre> <p>For much more detail check <a href="https://developer.android.com/studio/projects/add-native-code.html" rel="noreferrer">Google's page on adding native code</a>.</p> <p>After this is setup correctly you can <code>./gradlew installDebug</code> and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.</p> <h2>Android Studio Clean and Build Integration - DEPRECATED</h2> <p>The other answers do point out the correct way to prevent the automatic creation of <code>Android.mk</code> files, but they fail to go the extra step of integrating better with Android Studio. I have added the ability to actually clean and build from source without needing to go to the command-line. Your <code>local.properties</code> file will need to have <code>ndk.dir=/path/to/ndk</code></p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 14 buildToolsVersion "20.0.0" defaultConfig { applicationId "com.example.application" minSdkVersion 14 targetSdkVersion 14 ndk { moduleName "YourModuleName" } } sourceSets.main { jni.srcDirs = [] // This prevents the auto generation of Android.mk jniLibs.srcDir 'src/main/libs' // This is not necessary unless you have precompiled libraries in your project. } task buildNative(type: Exec, description: 'Compile JNI source via NDK') { def ndkDir = android.ndkDirectory commandLine "$ndkDir/ndk-build", '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source '-j', Runtime.runtime.availableProcessors(), 'all', 'NDK_DEBUG=1' } task cleanNative(type: Exec, description: 'Clean JNI object files') { def ndkDir = android.ndkDirectory commandLine "$ndkDir/ndk-build", '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source 'clean' } clean.dependsOn 'cleanNative' tasks.withType(JavaCompile) { compileTask -&gt; compileTask.dependsOn buildNative } } dependencies { compile 'com.android.support:support-v4:20.0.0' } </code></pre> <p>The <code>src/main/jni</code> directory assumes a standard layout of the project. It should be the relative from this <code>build.gradle</code> file location to the <code>jni</code> directory.</p> <h2>Gradle - for those having issues</h2> <p>Also check this <a href="https://stackoverflow.com/questions/25769536/how-when-to-generate-gradle-wrapper-files/27982996#27982996">Stack Overflow answer</a>.</p> <p>It is really important that your gradle version and general setup are correct. If you have an older project I highly recommend creating a new one with the latest Android Studio and see what Google considers the standard project. Also, use <code>gradlew</code>. This protects the developer from a gradle version mismatch. Finally, the gradle plugin must be configured correctly.</p> <p>And you ask what is the latest version of the gradle plugin? <a href="http://tools.android.com/tech-docs/new-build-system" rel="noreferrer">Check the tools page</a> and edit the version accordingly.</p> <h3>Final product - /build.gradle</h3> <pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules. // Running 'gradle wrapper' will generate gradlew - Getting gradle wrapper working and using it will save you a lot of pain. task wrapper(type: Wrapper) { gradleVersion = '2.2' } // Look Google doesn't use Maven Central, they use jcenter now. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.2.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() } } </code></pre> <p>Make sure <code>gradle wrapper</code> generates the <code>gradlew</code> file and <code>gradle/wrapper</code> subdirectory. This is a big gotcha.</p> <h2>ndkDirectory</h2> <p>This has come up a number of times, but <code>android.ndkDirectory</code> is the correct way to get the folder after 1.1. <a href="http://tools.android.com/tech-docs/new-build-system/migrating-to-1-0-0" rel="noreferrer">Migrating Gradle Projects to version 1.0.0</a>. If you're using an experimental or ancient version of the plugin your mileage may vary.</p>
21,495,616
Difference between modelAttribute and commandName attributes in form tag in spring?
<p>In Spring 3, I have seen two different attribute in form tag in jsp</p> <pre><code>&lt;form:form method="post" modelAttribute="login"&gt; </code></pre> <p>in this the attribute modelAttribute is the name of the form object whose properties are used to populate the form. And I used it in posting a form and in controller I have used <code>@ModelAttribute</code> to capture value, calling validator, applying business logic. Everything is fine here. Now</p> <pre><code>&lt;form:form method="post" commandName="login"&gt; </code></pre> <p>What is expected by this attribute, is it also a form object whose properties we are going to populate?</p>
21,500,148
5
0
null
2014-02-01 07:57:00.377 UTC
27
2018-05-24 01:43:30.493 UTC
2018-05-24 01:43:30.493 UTC
null
1,033,581
null
2,219,920
null
1
97
forms|spring-mvc|modelattribute
85,630
<p>If you look at the <a href="https://github.com/spring-projects/spring-framework/blob/4.3.x/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java#L53" rel="noreferrer">source code of <code>FormTag</code> (4.3.x)</a> which backs your <code>&lt;form&gt;</code> element, you'll notice this</p> <pre><code>/** * Set the name of the form attribute in the model. * &lt;p&gt;May be a runtime expression. */ public void setModelAttribute(String modelAttribute) { this.modelAttribute = modelAttribute; } /** * Get the name of the form attribute in the model. */ protected String getModelAttribute() { return this.modelAttribute; } /** * Set the name of the form attribute in the model. * &lt;p&gt;May be a runtime expression. * @see #setModelAttribute */ public void setCommandName(String commandName) { this.modelAttribute = commandName; } /** * Get the name of the form attribute in the model. * @see #getModelAttribute */ protected String getCommandName() { return this.modelAttribute; } </code></pre> <p>They are both referring to the same field, thus having same effect.</p> <p>But, as the field name indicates, <code>modelAttribute</code> should be preferred, as others have also pointed out.</p>
18,902,072
What standard do language codes of the form "zh-Hans" belong to?
<p>Through the REST API of an application, I receive language codes of the following form: <code>ll-Xxxx</code>. </p> <ul> <li>two lowercase letters languages (looks like <a href="http://en.wikipedia.org/wiki/ISO_639-1" rel="noreferrer">ISO 639-1</a>), </li> <li>a dash, </li> <li>a code going up to four letters, starting with an uppercase letter (looks like an ISO 639-3 <a href="http://en.wikipedia.org/wiki/Macrolanguage" rel="noreferrer">macrolanguage code</a>). </li> </ul> <p>Some examples: </p> <pre><code>az-Arab Azerbaijani in the Arabic script az-Cyrl Azerbaijani in the Cyrillic script az-Latn Azerbaijani in the Latin script sr-Cyrl Serbian in the Cyrillic script sr-Latn Serbian in the Latin script uz-Cyrl Uzbek in the Cyrillic script uz-Latn Uzbek in the Latin script zh-Hans Chinese in the simplified script zh-Hant Chinese in the traditional script </code></pre> <p>From what I found online:</p> <blockquote> <p>[<strong>ISO 639-1</strong>] is the first part of the ISO 639 series of international standards for language codes. Part 1 covers the registration of <strong>two-letter codes</strong>. </p> </blockquote> <p>and</p> <blockquote> <p><strong>ISO 639-3</strong> is an international standard for language codes. In defining some of its language codes, <strong>some are defined as macrolanguages</strong> [...]</p> </blockquote> <p>Now I need to write a piece of code to verify that I receive a valid language code.<br> But since what I receive is a mix of 639-1 (2 letters language) and 639-3 (macrolanguage), what standard am I supposed to stick with ? Are these code belonging to some sort of mixed up (perhaps common) standard ?</p>
38,959,322
2
0
null
2013-09-19 18:14:04.99 UTC
7
2016-12-09 17:40:36.51 UTC
2016-08-15 19:23:37.39 UTC
null
6,002,174
null
1,030,960
null
1
30
internationalization|iso
39,302
<p>The current reference for identifying languages is <a href="https://tools.ietf.org/html/bcp47" rel="noreferrer"><strong>IETF BCP 47</strong></a>, which combines IETF RFC 5646 and RFC 4647. </p> <p>Codes of the form <code>ll-Xxxx</code> combine an ISO 639-1 <em>language code</em> (two letters) and an <a href="https://en.wikipedia.org/wiki/ISO_15924" rel="noreferrer">ISO 15924</a> <em>script code</em> (four letters). BCP 47 recommends that language codes be written in lower case and that script codes be written "lowercase with the initial letter capitalized", but this is basically for readability. </p> <p>BCP 47 also recommends that the <em>language code</em> should be the shortest available ISO 639 tag. So if a language is represented in both <a href="https://en.wikipedia.org/wiki/ISO_639-1" rel="noreferrer">ISO 639-1</a> (two letters) and <a href="https://en.wikipedia.org/wiki/ISO_639-3" rel="noreferrer">ISO 639-3</a> (three letters), than you should use the ISO 639-1. </p>
8,573,603
Redirect to page with add page tab dialog
<p>Facebook recently notified they are <a href="http://developers.facebook.com/blog/post/611/" rel="noreferrer">deprecating support for app profile pages</a>. </p> <p>Apps created after Dec 10th no longer have the app page option, together with the "add to my page" functionality, and must use the new <a href="http://developers.facebook.com/docs/reference/dialogs/add_to_page/" rel="noreferrer">Add page tab dialog</a>. </p> <p>After the user selects which page to add the application to, is there any way to redirect the user to the selected page? </p> <p>Similar functionality existed in the "old" add to page dialog, e.g. <br> <code><a href="https://www.facebook.com/add.php?api_key=MY_ADD_ID&amp;pages=1" rel="noreferrer">https://www.facebook.com/add.php?api_key=MY_ADD_ID&amp;pages=1</a></code></p> <p>Activating the dialog with a response function seems to bring no result.</p> <p>`<pre><code> // Add app to page function addToPage() {</p> <pre><code>// calling the API ... FB.ui({ method: 'pagetab', redirect_uri: 'MY_URL', },function(response) { alert(response); }); </code></pre> <p>}<br> </code></pre> ` So, two questions: <br> a) Is there any possibility for the app using the dialog to "know" which page was selected? <br> b) Is there any way to redirect the user to the selected page.</p> <p>Thx! </p>
8,768,363
3
0
null
2011-12-20 09:53:41.027 UTC
12
2012-11-10 12:19:57.76 UTC
2011-12-20 12:30:17.973 UTC
null
1,005,886
null
1,005,886
null
1
9
facebook|dialog|tabs
9,209
<pre><code>&lt;script type="text/javascript"&gt; function addToPage() { // calling the API ... FB.ui( { method: 'pagetab' }, function(response) { if (response != null &amp;&amp; response.tabs_added != null) { $.each(response.tabs_added, function(pageid) { alert(pageid); }); } } ); } &lt;/script&gt; </code></pre> <p>Use above code...you will get page id of pages selected by the user</p>
8,697,706
Exclude one folder in htaccess protected directory
<p>I have a directory protected by htaccess. Here is the code I use now:</p> <pre><code>AuthName "Test Area" Require valid-user AuthUserFile "/***/.htpasswd" AuthType basic </code></pre> <p>This is working fine. However, I now have a directory inside of this folder that I would like to allow anyone to access, but am not sure how to do it.</p> <p>I know that it is possible to just move the files outside of the protected directory, but to make a long story short the folder needs to stay inside the protected folder, but be accessible to all.</p> <p>How can I restrict access to the folder, but allow access to the subfolder?</p>
8,697,894
5
0
null
2012-01-02 05:31:03.67 UTC
7
2019-10-27 00:34:45.05 UTC
2012-01-02 06:01:15.06 UTC
null
350,858
null
979,573
null
1
28
apache|.htaccess|authentication
43,144
<p>According to <a href="http://perishablepress.com/press/2007/11/26/enable-file-or-directory-access-to-your-htaccess-password-protected-site/" rel="noreferrer">this article</a> you can accomplish this by using <code>SetEnvIf</code>. You match each of the folders and files you want to grand access to and define an environment variable 'allow' for them. Then you add a condition that allows access if this environment variable is present.</p> <p>You need to add the following directives to your .htaccess.</p> <pre><code>SetEnvIf Request_URI "(path/to/directory/)$" allow SetEnvIf Request_URI "(path/to/file\.php)$" allow Order allow,deny Allow from env=allow Satisfy any </code></pre>
26,863,242
SignalR MVC 5 Websocket no valid Credentials
<p>i try to use SignalR in MVC Application. It works well but i get the following Error in the Chrome console</p> <pre><code> WebSocket connection to 'ws://localhost:18245/signalr/connect?transport=webSockets&amp;clientProtocol=1.4&amp;connectionToken=bNDGLnbSQThqY%2FSjo1bt 8%2FL45Xs22BDs2VcY8O7HIkJdDaUJ4ftIc54av%2BELjr27ekHUiTYWgFMfG6o7RaZwhf fpXavzWQ1jvkaxGm5rI%2BWtK7j0g1eQC2aOYP366WmRQLXCiYJfsm4EbwX6T8n2Aw %3D%3D&amp;connectionData=%5B%7B%22name%22%3A%22importerhub% 22%7D%5D&amp;tid=9' failed: HTTP Authentication failed; no valid credentials available </code></pre> <p>The funny thing is that the jquery method i call from the Controller over the Hub works fine.</p> <p>jQuery:</p> <pre><code> $(function () { // Initialize the connection to the server var importerHub = $.connection.importerHub; // Preparing a client side function // called sendMessage that will be called from the server side importerHub.client.sendMessage = function (message) { showOrUpdateSuccessMessage(message); }; $.connection.hub.start(); }); </code></pre> <p>Controller:</p> <pre><code>var hubContext = GlobalHost.ConnectionManager.GetHubContext&lt;ImporterHub&gt;(); hubContext.Clients.All.sendMessage("All operations complete"); </code></pre> <p>I use .Net v4.5.1, SignalR v2.1.2.0 and IIS 8.5 with Windows Authentication.</p> <p>How can I fix this error?</p>
26,896,208
4
0
null
2014-11-11 10:57:14.283 UTC
8
2019-07-08 02:53:18.03 UTC
null
null
null
null
1,088,603
null
1
30
jquery|asp.net-mvc|controller|signalr|owin
20,186
<p>It looks like you are running into a Chrome issue. The problem is that Chrome doesn't properly handle Windows Authentication for WebSockets.</p> <p>Below is the initial issue submitted a couple years ago reporting that Chrome did not support any form of HTTP authentication:</p> <p><a href="https://code.google.com/p/chromium/issues/detail?id=123862" rel="noreferrer">https://code.google.com/p/chromium/issues/detail?id=123862</a></p> <p>That issue has been resolved for Basic and Digest authentication, but not for Windows (NTLM/Negotiate) authentication. There was an issue created less than a month ago to track progress on Chrome support for Windows authentication with WebSockets:</p> <p><a href="https://code.google.com/p/chromium/issues/detail?id=423609" rel="noreferrer">https://code.google.com/p/chromium/issues/detail?id=423609</a></p> <p>Apparently, the issue with Windows authentication is partially fixed in the Chrome dev channel, but only if the client has already authenticated with the server prior to establishing a WebSocket.</p> <p>The reason you can still call <code>sendMessage</code> from your Controller is because SignalR automatically falls back to using a transport other than WebSockets (i.e. server-sent events or long-polling), when the WebSocket connection fails. Chrome will properly handle Windows authentication with SignalR's other transports.</p> <p>I suggest not changing anything. It looks like Chrome will eventually support Windows authentication for WebSockets.</p> <p>The only real problem, other than the error in your chrome console, is that it might take slightly longer to establish a SignalR connection in Chrome. If that's a big issue, you can always <a href="http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#transport" rel="noreferrer">specify what transports the client should attempt using</a>. So on Chrome, you could only try <code>serverSentEvents</code> and <code>longPolling</code>, but then when Chrome <em>does</em> fix the issue, you won't be using the best possible transport until you change your code.</p>
26,652,611
Laravel Recursive Relationships
<p>I'm working on a project in <em>Laravel</em>. I have an Account model that can have a parent or can have children, so I have my model set up like so:</p> <pre><code>public function immediateChildAccounts() { return $this-&gt;hasMany('Account', 'act_parent', 'act_id'); } public function parentAccount() { return $this-&gt;belongsTo('Account', 'act_parent', 'act_id'); } </code></pre> <p>This works fine. What I want to do is get all children under a certain account. Currently, I'm doing this:</p> <pre><code>public function allChildAccounts() { $childAccounts = $this-&gt;immediateChildAccounts; if (empty($childAccounts)) return $childAccounts; foreach ($childAccounts as $child) { $child-&gt;load('immediateChildAccounts'); $childAccounts = $childAccounts-&gt;merge($child-&gt;allChildAccounts()); } return $childAccounts; } </code></pre> <p>This also works, but I have to worry if it's slow. This project is the re-write of an old project we use at work. We will have several thousand accounts that we migrate over to this new project. For the few test accounts I have, this method poses no performance issues.</p> <p>Is there a better solution? Should I just run a raw query? Does <em>Laravel</em> have something to handle this? </p> <p><strong>In summary</strong> What I want to do, for any given account, is get every single child account and every child of it's children and so on in a single list/collection. A diagram:</p> <pre><code>A -&gt; B -&gt; D |--&gt; C -&gt; E |--&gt; F G -&gt; H </code></pre> <p>If I run A->immediateChildAccounts(), I should get {B, C}<br> If I run A->allChildAccounts(), I should get {B, D, C, E, F} (order doesn't matter)</p> <p>Again, my method works, but it seems like I'm doing way too many queries.</p> <p>Also, I'm not sure if it's okay to ask this here, but it is related. How can I get a list of all accounts that <strong>don't</strong> include the child accounts? So basically the inverse of that method above. This is so a user doesn't try to give an account a parent that's already it's child. Using the diagram from above, I want (in pseudocode):</p> <p>Account::where(account_id not in (A->allChildAccounts())). So I would get {G, H}</p> <p>Thanks for any insight.</p>
26,654,139
9
0
null
2014-10-30 12:08:07.873 UTC
32
2021-04-12 00:42:16.093 UTC
2014-10-31 01:36:44.713 UTC
null
1,378,470
null
1,378,470
null
1
57
php|laravel|eloquent
50,906
<p>This is how you can use recursive relations:</p> <pre><code>public function childrenAccounts() { return $this-&gt;hasMany('Account', 'act_parent', 'act_id'); } public function allChildrenAccounts() { return $this-&gt;childrenAccounts()-&gt;with('allChildrenAccounts'); } </code></pre> <p>Then:</p> <pre><code>$account = Account::with('allChildrenAccounts')-&gt;first(); $account-&gt;allChildrenAccounts; // collection of recursively loaded children // each of them having the same collection of children: $account-&gt;allChildrenAccounts-&gt;first()-&gt;allChildrenAccounts; // .. and so on </code></pre> <p>This way you save a lot of queries. This will execute 1 query per each nesting level + 1 additional query.</p> <p>I can't guarantee it will be efficient for your data, you need to test it definitely.</p> <hr> <p>This is for childless accounts:</p> <pre><code>public function scopeChildless($q) { $q-&gt;has('childrenAccounts', '=', 0); } </code></pre> <p>then:</p> <pre><code>$childlessAccounts = Account::childless()-&gt;get(); </code></pre>
264,175
Entity Framework & LINQ To SQL - Conflict of interest?
<p>I've been reading on the blogosphere for the past week that Linq to SQL is dead [and long live EF and Linq to Entities]. But when I read the overview on MSDN, it appeared to me Linq to Entities generates eSQL just the way Linq to SQL generates SQL queries.</p> <p>Now, since the underlying implementation (and since SQL Server is not yet an ODBMS) is still a Relational store, at some point the Entity framework has to make the translation into SQL queries. Why not fix the Linq to SQL issues (m:m relationships, only SQL server support etc.) and use Linq to SQL in as the layer that generates these queries?</p> <p>Is this because of performance or EF uses a different way of transforming the eSQL statement into SQL?</p> <p>It seemed to me - at least for my unlearned mind - a natural fit to dogfood Linq to SQL in EF.</p> <p>Comments?</p>
265,109
3
0
null
2008-11-05 02:10:28.79 UTC
9
2017-05-26 18:49:11.947 UTC
2017-05-26 18:49:11.947 UTC
Kevin Fairchild
15,168
Vyas Bharghava
28,413
null
1
13
entity-framework|linq|linq-to-sql|linq-to-entities|entity-sql
2,544
<p>It is worth noting that Entity Framework has (at least) three ways of being consumed:</p> <ul> <li>LINQ to Entities over Object Services over Entity Client</li> <li>Entity SQL over Object Services over Entity Client</li> <li>Entity SQL using Entity Client command objects (most similar to classic ADO.NET)</li> </ul> <p>Entity Client ultimately spits out a representation of the ESQL command (in a canonical, database agnostic form) which the ADO.NET Provider for the specific RDBMS is responsible for converting into store specific SQL. This is the right model IMHO as over the years a lot of time has been invested (and will continue to be invested) in producing great ADO.NET Providers for each store. </p> <p>As Entity Framework needs to work with many stores and therefore many ADO.NET Providers there is less scope for them to easily optimise what the Entity Client generates on a per store basis (at least - thats where we are with v1). The LINQ to SQL team had a much smaller problem to solve - "works only with SQL Server" and hence could do store specific stuff more easily. I know the EF team are aware that there are cases where EF to SQL Server is producing TSQL less efficiently than L2S and are working on improving this for V2.</p> <p>Interestingly this model allows new capabilities to be added between the Entity Client and the ADO.NET Provider for a store. These "wrapping providers" can add services such as logging, auditing, security, caching. This is discussed as a V2 feature over at <a href="http://blogs.msdn.com/efdesign/archive/2008/07/09/transparent-caching-support-in-the-entity-framework.aspx" rel="noreferrer">http://blogs.msdn.com/efdesign/archive/2008/07/09/transparent-caching-support-in-the-entity-framework.aspx</a> </p> <p>If you look therefor at the bigger picture you can see that it would be horribly difficult and indeed restrictive to try and somehow retrofit L2S TSQL generation into the archiecture of the Entity Framework.</p>
228,775
.NET Web Service & BackgroundWorker threads
<p>I'm trying to do some async stuff in a webservice method. Let say I have the following API call: <a href="http://www.example.com/api.asmx" rel="nofollow noreferrer">http://www.example.com/api.asmx</a></p> <p>and the method is called <em>GetProducts()</em>.</p> <p>I this GetProducts methods, I do some stuff (eg. get data from database) then just before i return the result, I want to do some async stuff (eg. send me an email).</p> <p>So this is what I did.</p> <pre><code>[WebMethod(Description = "Bal blah blah.")] public IList&lt;Product&gt; GetProducts() { // Blah blah blah .. // Get data from DB .. hi DB! // var myData = ....... // Moar clbuttic blahs :) (yes, google for clbuttic if you don't know what that is) // Ok .. now send me an email for no particular reason, but to prove that async stuff works. var myObject = new MyObject(); myObject.SendDataAsync(); // Ok, now return the result. return myData; } } public class TrackingCode { public void SendDataAsync() { var backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += BackgroundWorker_DoWork; backgroundWorker.RunWorkerAsync(); //System.Threading.Thread.Sleep(1000 * 20); } private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { SendEmail(); } } </code></pre> <p>Now, when I run this code the email is never sent. If I uncomment out the Thread.Sleep .. then the email is sent.</p> <p>So ... why is it that the background worker thread is torn down? is it dependant on the parent thread? Is this the wrong way I should be doing background or forked threading, in asp.net web apps?</p>
228,798
3
0
null
2008-10-23 06:54:59.247 UTC
9
2016-12-31 08:17:59.66 UTC
2016-12-31 08:17:59.66 UTC
null
1,033,581
PK
30,674
null
1
14
c#|asp.net|multithreading|backgroundworker
17,990
<p><code>BackgroundWorker</code> is useful when you need to synchronize back to (for example) a UI* thread, eg for affinity reasons. In this case, it would seem that simply using <code>ThreadPool</code> would be more than adequate (and much simpler). If you have high volumes, then a producer/consumer queue may allow better throttling (so you don't drown in threads) - but I suspect <code>ThreadPool</code> will be fine here...</p> <pre><code>public void SendDataAsync() { ThreadPool.QueueUserWorkItem(delegate { SendEmail(); }); } </code></pre> <p>Also - I'm not quite sure what you want to achieve by sleeping? This will just tie up a thread (not using CPU, but doing no good either). Care to elaborate? It <em>looks</em> like you are pausing your actual web page (i.e. the Sleep happens on the web-page thread, not the e-mail thread). What are you trying to do here?</p> <p>*=actually, it will use whatever sync-context is in place</p>
509,978
Something faster than HttpHandlers?
<p>What is the fastest way to execute a method on an ASP.NET website?</p> <p>The scenario is pretty simple: I have a method which should be executed when a web page is hit. Nothing else is happening on the page, the only rendered output is a "done" message. I want the processing to be as fast as possible.</p> <p>Every single hit is unique, so caching is not an option.</p> <p>My plan is to use an HttpHandler and configure it in web.config (mypage.ashx) rather than a regular .aspx page. This should reduce the overhead significantly.</p> <p>So my question is really: Is there a faster way to accomplish this than using HttpHandlers?</p>
510,001
3
0
null
2009-02-04 03:40:39.213 UTC
12
2010-02-25 21:13:44.837 UTC
null
null
null
Jakob Gade
10,932
null
1
19
asp.net|performance|httphandler
3,926
<p>Depending on what you're doing, I wouldn't expect to see a lot of improvement over just using an HttpHandler. I'd start by just writing the HttpHandler and seeing how it performs. If you need it to be faster, try looking more closely at the things you're actually doing while processing the request and seeing what can be optimized. For example, if you're doing any logging to a database, try writing to a local database instead of across a network. If it's still not fast enough, then maybe look into writing something lower level. Until that point though, I'd stick with whatever's easiest for you to write.</p> <p>For reference, I've written an ad server in ASP.NET (using HttpHandlers) that can serve an ad (including targeting and logging the impression to a local database) in 0-15ms under load. I thought I was doing quite a bit of processing - but that's a pretty good response time IMHO.</p> <hr> <p><strong>Update after several months</strong>:</p> <p>If you clear all the HttpModules that are included by default, this will remove a fair amount of overhead. By default, the following HttpModules are included in every site via the machine-level web.config file:</p> <ul> <li>OutputCache</li> <li>Session (for session state)</li> <li>WindowsAuthentication</li> <li>FormsAuthentication</li> <li>PassportAuthentication</li> <li>RoleManager</li> <li>UrlAuthorization</li> <li>FileAuthorization</li> <li>AnonymousIdentification</li> <li>Profile</li> <li>ErrorHandler</li> <li>ServiceModel</li> </ul> <p>Like I said above, my ad server doesn't use any of these, so I've just done this in that app's web.config:</p> <pre><code>&lt;httpModules&gt; &lt;clear /&gt; &lt;/httpModules&gt; </code></pre> <p>If you need some of those, but not all, you can remove the ones you don't need:</p> <pre><code>&lt;httpModules&gt; &lt;remove name="PassportAuthentication" /&gt; &lt;remove name="Session" /&gt; &lt;/httpModules&gt; </code></pre> <p><strong>ASP.NET MVC Note:</strong> ASP.NET MVC requires the session state module unless you do something specific to workaround it. See this question for more information: <a href="https://stackoverflow.com/questions/884852/how-can-i-disable-session-state-in-asp-net-mvc">How can I disable session state in ASP.NET MVC?</a></p> <p><strong>Update for IIS7:</strong> Unfortunately, things aren't quite as simple in IIS7. Here is <a href="https://serverfault.com/questions/72338/iis7-lock-violation-error-http-handlers-modules-and-the-clear-element">how to clear HTTP Modules in IIS7</a></p>
17,960
PowerShell App.Config
<p>Has anyone worked out how to get PowerShell to use <code>app.config</code> files? I have a couple of .NET DLL's I'd like to use in one of my scripts but they expect their own config sections to be present in <code>app.config</code>/<code>web.config</code>.</p>
5,625,350
3
0
null
2008-08-20 13:33:58.057 UTC
12
2018-08-10 05:04:56.33 UTC
2011-04-11 18:25:49.03 UTC
Chris
419
Kev
419
null
1
27
powershell|configuration-files
20,113
<p>Cross-referencing with this thread, which helped me with the same question: <a href="https://stackoverflow.com/questions/2789920/subsonic-access-to-app-config-connection-strings-from-referenced-dll-in-powershel">Subsonic Access To App.Config Connection Strings From Referenced DLL in Powershell Script</a></p> <p>I added the following to my script, before invoking the DLL that needs config settings, where $configpath is the location of the file I want to load:</p> <pre><code>[appdomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $configpath) Add-Type -AssemblyName System.Configuration </code></pre> <p>See <a href="https://stackoverflow.com/questions/6150644/change-default-app-config-at-runtime/6151688#6151688">this</a> post to ensure the configuration file specified is applied to the running context. </p>
64,727,165
Is it OK for a class constructor to block forever?
<p>Let's say I have an object that provides some sort of functionality in an infinite loop.</p> <p>Is is acceptable to just put the infinite loop in the constructor?</p> <p>Example:</p> <pre><code>class Server { public: Server() { for(;;) { //... } } }; </code></pre> <p>Or is there an inherent initialization problem in C++ if the constructor never completes?</p> <p>(The idea is that to run a server you just say <code>Server server;</code>, possibly in a thread somewhere...)</p>
64,728,578
6
11
null
2020-11-07 11:27:20.627 UTC
1
2020-11-12 05:55:49.32 UTC
2020-11-08 17:50:10.87 UTC
null
224,132
null
1,219,247
null
1
41
c++|multithreading|constructor|infinite-loop
4,399
<p>It's not wrong per standard, it's just a bad design.</p> <p>Constructors don't usually block. Their purpose is to take a raw chunk of memory, and transform it into a valid C++ object. Destructors do the opposite: they take valid C++ objects and turn them back into raw chunks of memory.</p> <p>If your constructor blocks forever (emphasis on forever), it does something different than just turn a chunk of memory into an object. It's ok to block for a short time (a mutex is a perfect example of it), if this serves the construction of the object. In your case, it looks like your constructor is accepting and serving clients. This is not turning memory into objects.</p> <p>I suggest you split the constructor into a &quot;real&quot; constructor that builds a server object and another <code>start</code> method that serves clients (by starting an event loop).</p> <p>ps: In some cases you <em>have</em> to execute the functionality/logic of the object separately from the constructor, for example if your class inherit from <code>std::enable_shared_from_this</code>.</p>
22,414,524
How can I make Laravel return a custom error for a JSON REST API
<p>I'm developing some kind of RESTful API. When some error occurs, I throw an <code>App::abort($code, $message)</code> error. </p> <p>The problem is: I want him to throw a json formed array with keys "code" and "message", each one containing the above mentioned data. </p> <pre><code>Array ( [code] =&gt; 401 [message] =&gt; "Invalid User" ) </code></pre> <p>Does any one knows if it's possible, and if it is, how I do it?</p>
22,417,496
10
0
null
2014-03-14 19:53:37.313 UTC
15
2022-04-20 08:28:41.56 UTC
2014-03-14 23:32:11.44 UTC
null
3,134,069
null
1,243,382
null
1
42
php|json|rest|laravel-4|restful-architecture
126,626
<p>go to your <code>app/start/global.php</code>.</p> <p>This will convert all errors for <code>401</code> and <code>404</code> to a custom json error instead of the Whoops stacktrace. Add this:</p> <pre><code>App::error(function(Exception $exception, $code) { Log::error($exception); $message = $exception-&gt;getMessage(); // switch statements provided in case you need to add // additional logic for specific error code. switch ($code) { case 401: return Response::json(array( 'code' =&gt; 401, 'message' =&gt; $message ), 401); case 404: $message = (!$message ? $message = 'the requested resource was not found' : $message); return Response::json(array( 'code' =&gt; 404, 'message' =&gt; $message ), 404); } }); </code></pre> <p>This is one of many options to handle this errors. </p> <hr> <p>Making an API it is best to create your own helper like <code>Responser::error(400, 'damn')</code> that extends the <code>Response</code> class.</p> <p>Somewhat like:</p> <pre><code>public static function error($code = 400, $message = null) { // check if $message is object and transforms it into an array if (is_object($message)) { $message = $message-&gt;toArray(); } switch ($code) { default: $code_message = 'error_occured'; break; } $data = array( 'code' =&gt; $code, 'message' =&gt; $code_message, 'data' =&gt; $message ); // return an error return Response::json($data, $code); } </code></pre>
6,503,562
Which algorithm is used for noise canceling in earphones?
<p>I want to program software for noise canceling in real time, the same way it happens in earphones with active noise canceling. Are there any open algorithms or, at least, science papers about it? A Google search found info about non-realtime noise reduction only.</p>
6,504,135
1
1
null
2011-06-28 08:19:44.137 UTC
13
2017-09-24 21:50:07.05 UTC
2015-06-20 21:38:28.677 UTC
null
7,920
null
818,748
null
1
19
algorithm|audio|noise-reduction
15,980
<p>from <a href="http://www.best-headphone-review.com/bestnoisecancellingheadphones.html" rel="nofollow noreferrer">This site</a></p> <p><em>Active noise cancelling headphones in addition to all the normal headphone circuitry, have a microphone and additional special circuitry. At a basic level the microphone on the headphone picks up the ambient noise around you and relays it to the special circuitry. The special circuitry interprets the sounds and mimics it in an inverse (opposite) manner. The inverse sound it produces is sent through the headphone speakers and cancels out the ambient noise around you.</em> </p> <p>All this is based on sound waves interference. When 2 waves of opposite phases interfere the result is no sound. (it works with light too.)</p> <p>You should have a look at the wikipedia page on <a href="http://en.wikipedia.org/wiki/Interference_%28wave_propagation%29" rel="nofollow noreferrer">waves interference</a> to find the right phase you need to produce to cancel the outside noise</p> <p><strong>For a sinusoidal system:</strong></p> <p>Let's take 2 waves :</p> <p><img src="https://i.stack.imgur.com/nWbfy.png" alt="enter image description here"></p> <p>and </p> <p><img src="https://i.stack.imgur.com/u7bKp.png" alt="enter image description here"></p> <p>We want to express the resulting wave as :</p> <p><img src="https://i.stack.imgur.com/LnkBm.png" alt="enter image description here"></p> <p>Given A1 you want to find A2 such that <strong>A0 = 0</strong></p> <p>It means given Phi1 you need to find Phi2 such that A0=0</p> <p>You can prove that: </p> <p><img src="https://i.stack.imgur.com/uFHLc.png" alt="enter image description here"></p> <p>And solving A0 = 0 you will get the frequency of the wave you need to create to cancel the noise. It's called destructive interferences.</p> <p><img src="https://i.stack.imgur.com/Mr9hf.jpg" alt="enter image description here"></p> <p>Sound waves are not in 1 dimension... so you will just get the destructive interference in one direction:</p> <p><img src="https://i.stack.imgur.com/vK4rd.png" alt="enter image description here"></p> <p>Now you just need to find some stuff of sound signals...</p> <hr> <p>I will try to answer your comment.</p> <p><strong>First:</strong></p> <p>A 2D problem is not much more difficult that the 1D.</p> <p>The outside noise can be approximate as a source situated at the infinity. You will create a destructive noise with a source in your headphones, and you can assume that the amplitude is the same at equal distance of the source . </p> <p>You need to write that down on a x,y axis (it can be good to use polar coordinates) </p> <p><img src="https://i.stack.imgur.com/PyjWF.jpg" alt="enter image description here"></p> <p>and you will be able to get the amplitude on each point on the plan using simple <a href="http://en.wikipedia.org/wiki/Trigonometry" rel="nofollow noreferrer">trigonometry formula</a>s like :</p> <p>:\sin (A + B) = \sin A \cdot \cos B + \cos A \cdot \sin B</p> <p>:\cos (A + B) = \cos A \cdot \cos B - \sin A \cdot \sin B</p> <p>:\sin (A - B) = \sin A \cdot \cos B - \cos A \cdot \sin B</p> <p>:\cos (A - B) = \cos A \cdot \cos B + \sin A \cdot \sin B</p> <p><strong>Second:</strong></p> <p>All the delays are modeled in the "Phi" of your destructive source. Can just Adapt the Calculated Phi so it takes the delay into account.</p> <p>You may need more specific information on sound since my information is very theoretic on any types of waves.</p>
41,755,276
'runtimes' Folder after Publishing a .Net Core App to Azure Publish Via VS Online
<p>What is the purpose of the 'runtimes' folder that gets published along with all my project files? I have a VS Online account, and have the build/deploy process configured through there. The 'runtimes' folder is certainly not a folder that exists in source control or my project folder.</p> <p>'runtimes' folder contents: </p> <p><img src="https://i.stack.imgur.com/D814U.png" alt="&#39;runtimes&#39; folder contents"></p> <p>example contents:</p> <p><img src="https://i.stack.imgur.com/VXWXa.png" alt="example contents"></p> <p>Thanks,<br> Drew</p>
42,162,767
5
1
null
2017-01-20 02:50:21.753 UTC
1
2022-01-20 09:09:45.27 UTC
2017-01-20 04:11:52.51 UTC
null
4,758,255
null
3,444,821
null
1
29
asp.net-core|.net-core|azure-web-app-service
13,665
<p>These exist because you are building your application as a self contained application as opposed to one that is dependent upon the framework being installed on the machine executing it. Documentation can be found at <a href="https://docs.microsoft.com/en-us/dotnet/articles/core/deploying/" rel="noreferrer">https://docs.microsoft.com/en-us/dotnet/articles/core/deploying/</a> describing the various options that can be used to control this output.</p>
41,740,632
How to change activity on bottom navigation button click?
<p>I want to use bottom navigation bar in my existing android app but the problem is all screen are activity ,is it possible to load activity without hiding the bottom navigation bar.</p> <p><strong>example:</strong> <strong>activity_main.xml</strong></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:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;android.support.v4.widget.NestedScrollView android:id="@+id/myScrollingContent" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;!-- Your loooooong scrolling content here. --&gt; &lt;/android.support.v4.widget.NestedScrollView&gt; &lt;com.roughike.bottombar.BottomBar android:id="@+id/bottomBar" android:layout_width="match_parent" android:layout_height="60dp" android:layout_gravity="bottom" app:bb_tabXmlResource="@xml/bottom_bar" app:bb_behavior="shy"/&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre> <p>this is my base activity,</p> <p><strong>MainActivity.java</strong></p> <pre><code>public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BottomBar bottomBar; bottomBar = (BottomBar) findViewById(R.id.bottomBar); bottomBar.setOnTabSelectListener(new OnTabSelectListener() { @Override public void onTabSelected(@IdRes int tabId) { if (tabId == R.id.matching) { Log.i("matching","matching inside "+tabId); Intent in=new Intent(getBaseContext(),Main2Activity.class); startActivity(in); }else if (tabId == R.id.watchlist) { Log.i("matching","watchlist inside "+tabId); Intent in=new Intent(getBaseContext(),Main3Activity.class); startActivity(in); } } }); } } </code></pre> <p><strong>Main2Activity</strong></p> <pre><code>public class Main2Activity extends MainActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main2); NestedScrollView dynamicContent = (NestedScrollView) findViewById(R.id.myScrollingContent); View wizard = getLayoutInflater().inflate(R.layout.activity_main2, null); dynamicContent.addView(wizard); </code></pre> <p><strong>Main3Activity</strong></p> <pre><code>public class Main3Activity extends MainActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main3); NestedScrollView dynamicContent = (NestedScrollView) findViewById(R.id.myScrollingContent); View wizard = getLayoutInflater().inflate(R.layout.activity_main3, null); dynamicContent.addView(wizard); } } </code></pre> <p><strong>manifest</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.bottom.bottomnavigation"&gt; &lt;application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"&gt; &lt;activity android:name=".Main2Activity"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".MainActivity" /&gt; &lt;activity android:name=".Main3Activity"&gt;&lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre>
43,256,816
2
2
null
2017-01-19 11:25:42.697 UTC
8
2018-06-18 20:37:28.283 UTC
2017-01-19 12:42:39.047 UTC
null
2,308,683
null
5,421,844
null
1
20
android|android-layout|android-fragments|android-bottomnav
44,966
<p>I have solved this problem in following way:</p> <p>1.Create one <strong>BaseActivity</strong> with bottom nav bar.</p> <pre><code> package com.example.apple.bottomnavbarwithactivity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.RadioButton; import android.widget.RadioGroup; public class BaseActivity extends AppCompatActivity { RadioGroup radioGroup1; RadioButton deals; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_base); radioGroup1=(RadioGroup)findViewById(R.id.radioGroup1); deals = (RadioButton)findViewById(R.id.deals); radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { Intent in; Log.i("matching", "matching inside1 bro" + checkedId); switch (checkedId) { case R.id.matching: Log.i("matching", "matching inside1 matching" + checkedId); in=new Intent(getBaseContext(),MatchingActivity.class); startActivity(in); overridePendingTransition(0, 0); break; case R.id.watchList: Log.i("matching", "matching inside1 watchlistAdapter" + checkedId); in = new Intent(getBaseContext(), WatchlistActivity.class); startActivity(in); overridePendingTransition(0, 0); break; case R.id.rates: Log.i("matching", "matching inside1 rate" + checkedId); in = new Intent(getBaseContext(),RatesActivity.class); startActivity(in); overridePendingTransition(0, 0); break; case R.id.listing: Log.i("matching", "matching inside1 listing" + checkedId); in = new Intent(getBaseContext(), ListingActivity.class); startActivity(in); overridePendingTransition(0, 0); break; case R.id.deals: Log.i("matching", "matching inside1 deals" + checkedId); in = new Intent(getBaseContext(), DealsActivity.class); startActivity(in); overridePendingTransition(0, 0); break; default: break; } } }); } } </code></pre> <p>BaseActivity layout named <strong>base_activity.xml</strong></p> <p> </p> <pre><code> &lt;LinearLayout android:layout_width="match_parent" android:layout_height="56dp" android:elevation="10dp" android:background="@color/white" android:id="@+id/bottonNavBar" android:paddingTop="5dp" android:orientation="horizontal" android:layout_alignParentBottom="true" android:foregroundGravity="bottom"&gt; &lt;RadioGroup android:id="@+id/radioGroup1" android:gravity="center" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="horizontal" android:baselineAligned="false"&gt; &lt;RadioButton android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" android:text="Matching" android:layout_weight="1" android:button="@null" android:padding="2dp" android:checked="false" android:textSize="12sp" android:drawableTop="@drawable/selector_matching" android:textColor="@drawable/selector_nav_text" android:id="@+id/matching"/&gt; &lt;RadioButton android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" android:button="@null" android:layout_weight="1" android:padding="2dp" android:checked="false" android:textSize="12sp" android:drawableTop="@drawable/selector_watchlist" android:textColor="@drawable/selector_nav_text" android:id="@+id/watchList" android:text="Watchlist"/&gt; &lt;RadioButton android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" android:id="@+id/rates" android:button="@null" android:paddingTop="5dp" android:paddingBottom="2dp" android:paddingLeft="2dp" android:paddingRight="2dp" android:layout_weight="1" android:checked="false" android:textSize="12sp" android:drawableTop="@drawable/selector_rates" android:textColor="@drawable/selector_nav_text" android:text="Rates"/&gt; &lt;RadioButton android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" android:button="@null" android:padding="2dp" android:checked="false" android:layout_weight="1" android:textSize="12sp" android:drawableTop="@drawable/selector_deals" android:textColor="@drawable/selector_nav_text" android:id="@+id/deals" android:text="Deals"/&gt; &lt;RadioButton android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" android:button="@null" android:padding="2dp" android:checked="false" android:layout_weight="1" android:textSize="12sp" android:drawableTop="@drawable/selector_listing" android:textColor="@drawable/selector_nav_text" android:id="@+id/listing" android:text="Listing"/&gt; &lt;/RadioGroup&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/dynamicContent" android:orientation="vertical" android:layout_marginBottom="56dp" android:background="@color/white" android:layout_gravity="bottom"&gt; &lt;/LinearLayout&gt; </code></pre> <p></p> <p>2.extend BaseActivity in all the activity that you want to open on bottom nav click and also need to inflate the activity layouts For example, I have created five sample activity.</p> <p><strong>i] MatchingActivity.</strong></p> <pre><code> package com.example.apple.bottomnavbarwithactivity; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; //extends our custom BaseActivity public class MatchingActivity extends BaseActivity { LinearLayout dynamicContent,bottonNavBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_matching); //dynamically include the current activity layout into baseActivity layout.now all the view of baseactivity is accessible in current activity. dynamicContent = (LinearLayout) findViewById(R.id.dynamicContent); bottonNavBar= (LinearLayout) findViewById(R.id.bottonNavBar); View wizard = getLayoutInflater().inflate(R.layout.activity_matching, null); dynamicContent.addView(wizard); //get the reference of RadioGroup. RadioGroup rg=(RadioGroup)findViewById(R.id.radioGroup1); RadioButton rb=(RadioButton)findViewById(R.id.matching); // Change the corresponding icon and text color on nav button click. rb.setCompoundDrawablesWithIntrinsicBounds( 0,R.drawable.ic_matching_clicked, 0,0); rb.setTextColor(Color.parseColor("#3F51B5")); } } </code></pre> <p><strong>ii]WatchlistActivity</strong></p> <pre><code> package com.example.apple.bottomnavbarwithactivity; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; public class WatchlistActivity extends AppCompatActivity { LinearLayout dynamicContent,bottonNavBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_watchlist1); dynamicContent = (LinearLayout) findViewById(R.id.dynamicContent); bottonNavBar= (LinearLayout) findViewById(R.id.bottonNavBar); View wizard = getLayoutInflater().inflate(R.layout.activity_watchlist1, null); dynamicContent.addView(wizard); RadioGroup rg=(RadioGroup)findViewById(R.id.radioGroup1); RadioButton rb=(RadioButton)findViewById(R.id.watchList); rb.setCompoundDrawablesWithIntrinsicBounds( 0,R.drawable.favourite_heart_selected, 0,0); rb.setTextColor(Color.parseColor("#3F51B5")); } } </code></pre> <p><strong>iii]RatesActivity</strong></p> <pre><code> package com.example.apple.bottomnavbarwithactivity; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; public class RatesActivity extends BaseActivity { LinearLayout dynamicContent,bottonNavBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_rates); dynamicContent = (LinearLayout) findViewById(R.id.dynamicContent); bottonNavBar= (LinearLayout) findViewById(R.id.bottonNavBar); View wizard = getLayoutInflater().inflate(R.layout.activity_rates, null); dynamicContent.addView(wizard); RadioGroup rg=(RadioGroup)findViewById(R.id.radioGroup1); RadioButton rb=(RadioButton)findViewById(R.id.rates); rb.setCompoundDrawablesWithIntrinsicBounds( 0,R.drawable.ic_rate_clicked, 0,0); rb.setTextColor(Color.parseColor("#3F51B5")); } } </code></pre> <p><strong>iv] ListingActivity</strong></p> <pre><code> package com.example.apple.bottomnavbarwithactivity; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; public class ListingActivity extends BaseActivity { LinearLayout dynamicContent,bottonNavBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_listing); dynamicContent = (LinearLayout) findViewById(R.id.dynamicContent); bottonNavBar= (LinearLayout) findViewById(R.id.bottonNavBar); View wizard = getLayoutInflater().inflate(R.layout.activity_listing, null); dynamicContent.addView(wizard); RadioGroup rg=(RadioGroup)findViewById(R.id.radioGroup1); RadioButton rb=(RadioButton)findViewById(R.id.listing); rb.setCompoundDrawablesWithIntrinsicBounds( 0,R.drawable.ic_listing_clicked, 0,0); rb.setTextColor(Color.parseColor("#3F51B5")); } } </code></pre> <p><strong>v] DealsActivity</strong></p> <pre><code> package com.example.apple.bottomnavbarwithactivity; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; public class DealsActivity extends BaseActivity { LinearLayout dynamicContent,bottonNavBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_deals); dynamicContent = (LinearLayout) findViewById(R.id.dynamicContent); bottonNavBar= (LinearLayout) findViewById(R.id.bottonNavBar); View wizard = getLayoutInflater().inflate(R.layout.activity_deals, null); dynamicContent.addView(wizard); RadioGroup rg=(RadioGroup)findViewById(R.id.radioGroup1); RadioButton rb=(RadioButton)findViewById(R.id.deals); rb.setCompoundDrawablesWithIntrinsicBounds( 0,R.drawable.ic_deals_clicked, 0,0); rb.setTextColor(Color.parseColor("#3F51B5")); } } </code></pre> <p><strong>Note:</strong> make sure that you handle <strong>back press</strong> properly.I have not written any code for <strong>back press</strong>.</p> <p><a href="https://i.stack.imgur.com/eqAa4.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/eqAa4.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/pngET.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/pngET.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/8rlKB.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/8rlKB.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/TkJ80.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/TkJ80.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/Q3m51.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Q3m51.jpg" alt="enter image description here"></a></p>
34,881,775
Automatic cookie handling with OkHttp 3
<p>I am using okhttp 3.0.1. </p> <p>Every where I am getting example for cookie handling that is with okhttp2 </p> <pre><code>OkHttpClient client = new OkHttpClient(); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); client.setCookieHandler(cookieManager); </code></pre> <p>Can please some one guide me how to use in version 3. setCookieHandler method is not present in the version 3.</p>
34,886,860
12
1
null
2016-01-19 16:19:45.387 UTC
25
2022-08-03 20:34:14.343 UTC
2022-08-03 20:34:14.343 UTC
null
1,457,596
null
2,672,763
null
1
54
java|cookies|okhttp
75,758
<p>right now I'm playing with it. try <a href="https://gist.github.com/franmontiel/ed12a2295566b7076161">PersistentCookieStore</a>, add gradle dependencies for <em>JavaNetCookieJar</em>:</p> <p><code>compile "com.squareup.okhttp3:okhttp-urlconnection:3.0.0-RC1"</code></p> <p>and init</p> <pre class="lang-js prettyprint-override"><code> // init cookie manager CookieHandler cookieHandler = new CookieManager( new PersistentCookieStore(ctx), CookiePolicy.ACCEPT_ALL); // init okhttp 3 logger HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); // init OkHttpClient OkHttpClient httpClient = new OkHttpClient.Builder() .cookieJar(new JavaNetCookieJar(cookieHandler)) .addInterceptor(logging) .build(); </code></pre> <p>`</p>
24,356,993
Removing special characters VBA Excel
<p>I'm using VBA to read some TITLES and then copy that information to a powerpoint presentation.</p> <p>My Problem is, that the TITLES have special characters, but Image files that I am also coping over do not.</p> <p>The TITLE forms part of a path to load a JPEG into a picture container. E.g. "P k.jpg", but the title is called "p.k".</p> <p>I want to be able to ignore the special characters in the TITLE and just get it to see a space instead so it picks up the right JPG file.</p> <p>Is that possible?</p> <p>Thank you!</p>
24,357,636
4
0
null
2014-06-23 00:23:15.073 UTC
8
2018-03-29 14:21:11.123 UTC
null
null
null
null
2,063,535
null
1
20
vba|excel|excel-2010
189,894
<p>What do you consider "special" characters, just simple punctuation? You should be able to use the <code>Replace</code> function: <code>Replace("p.k","."," ")</code>. </p> <pre><code>Sub Test() Dim myString as String Dim newString as String myString = "p.k" newString = replace(myString, ".", " ") MsgBox newString End Sub </code></pre> <p>If you have several characters, you can do this in a custom function or a simple chained series of <code>Replace</code> functions, etc.</p> <pre><code> Sub Test() Dim myString as String Dim newString as String myString = "!p.k" newString = Replace(Replace(myString, ".", " "), "!", " ") '## OR, if it is easier for you to interpret, you can do two sequential statements: 'newString = replace(myString, ".", " ") 'newString = replace(newString, "!", " ") MsgBox newString End Sub </code></pre> <p>If you have a lot of potential special characters (non-English accented ascii for example?) you can do a custom function or iteration over an array.</p> <pre><code>Const SpecialCharacters As String = "!,@,#,$,%,^,&amp;,*,(,),{,[,],},?" 'modify as needed Sub test() Dim myString as String Dim newString as String Dim char as Variant myString = "!p#*@)k{kdfhouef3829J" newString = myString For each char in Split(SpecialCharacters, ",") newString = Replace(newString, char, " ") Next End Sub </code></pre>
42,648,610
Error when executing `jupyter notebook` (No such file or directory)
<p>When I execute <code>jupyter notebook</code> in my virtual environment in Arch Linux, the following error occurred.</p> <p><code>Error executing Jupyter command 'notebook': [Errno 2] No such file or directory</code></p> <p>My Python version is 3.6, and my Jupyter version is 4.3.0</p> <p>How can I resolve this issue?</p>
42,667,069
12
2
null
2017-03-07 12:41:09.983 UTC
19
2020-11-19 09:12:18.273 UTC
2020-07-14 02:08:55.74 UTC
null
6,355,435
null
6,355,435
null
1
126
python-3.x|jupyter-notebook
134,938
<p>It seems to me as though the installation has messed up somehow. Try running:</p> <pre><code># For Python 2 pip install --upgrade --force-reinstall --no-cache-dir jupyter # For Python 3 pip3 install --upgrade --force-reinstall --no-cache-dir jupyter </code></pre> <p>This should reinstall everything from PyPi. This <strong><em>should</em></strong> solve the problem as I think running <code>pip install "ipython[notebook]"</code> messed things up. </p>
41,497,871
Importing self-signed cert into Docker's JRE cacert is not recognized by the service
<ul> <li>A Java Service is running inside the Docker container, which access the external HTTPS url and its self-sign certificate is unavailable to the service/ JRE cacert keystore and therefore connection fails.</li> <li>Hence imported the self-signed certificate of HTTPS external URL into Docker container's JRE cacert keystore. (after checking the <code>$JAVA_HOME</code> env. variable)</li> <li>Restarted the Docker container (using <code>docker restart</code> command), hoping that the service is also get restarted and pick the changes from JRE cacert. But this didn't happen, the Java service still fails to access external HTTPS URL.</li> </ul> <p>Any idea how a Java service running inside the Docker container pick the JRE cacert changes with new certificate import? </p>
41,499,582
3
0
null
2017-01-06 02:12:46.063 UTC
16
2021-10-25 14:11:53.817 UTC
2018-11-19 11:19:25.167 UTC
null
476,828
null
2,649,698
null
1
36
java|docker|https|docker-compose|docker-machine
65,023
<blockquote> <p>Hence imported the self-signed certificate of HTTPS external URL into Docker container's JRE cacert keystore.</p> </blockquote> <p>No: you need to import it into the Docker <em>image</em> from which you run your container.</p> <p>Importing it into the container would only create a <a href="https://docs.docker.com/engine/userguide/storagedriver/imagesandcontainers/#/container-and-layers" rel="noreferrer">temporary writable data layer</a>, which will be discarded when you restart your container.</p> <p>Something like <a href="https://stackoverflow.com/a/35304873/6309">this answer</a>:</p> <pre><code>USER root COPY ldap.cer $JAVA_HOME/jre/lib/security RUN \ cd $JAVA_HOME/jre/lib/security \ &amp;&amp; keytool -keystore cacerts -storepass changeit -noprompt -trustcacerts -importcert -alias ldapcert -file ldap.cer </code></pre>
5,626,327
How to shift elements of an array to the left without using loops in matlab?
<p>I have a fixed sized array in Matlab. When I want to insert a new element I do the following: </p> <ol> <li>To make room first array element will be overwritten</li> <li>Every other element will be shifted at new location <code>index-1</code> ---left shift.</li> <li>The new element will be inserted at the place of last element which becomes empty by shifting the elements. </li> </ol> <p>I would like to do it without using any loops.</p>
5,626,350
3
1
null
2011-04-11 19:17:27.88 UTC
null
2016-02-25 14:04:39.363 UTC
2011-04-11 19:23:18.083 UTC
null
505,088
null
623,300
null
1
7
matlab
60,945
<p>I'm not sure I understand your question, but I think you mean this:</p> <pre><code>A = [ A(1:pos) newElem A((pos+1):end) ] </code></pre> <p>That will insert the variable (or array) <code>newElem</code> after position <code>pos</code> in array <code>A</code>.</p> <p>Let me know if that works for you!</p> <p><strong>[Edit]</strong> Ok, looks like you actually just want to use the array as a shift register. You can do it like this:</p> <pre><code>A = [ A(2:end) newElem ] </code></pre> <p>This will take all elements from the 2nd to the last of <code>A</code> and added your <code>newElem</code> variable (or array) to the end.</p>
5,967,426
Select day of week from date
<p>I have the following table in MySQL that records event counts of stuff happening each day</p> <pre><code>event_date event_count 2011-05-03 21 2011-05-04 12 2011-05-05 12 </code></pre> <p>I want to be able to query this efficiently by date range AND by day of week. For example - "What is the event_count on Tuesdays in May?"</p> <p>Currently the event_date field is a date type. Are there any functions in MySQL that let me query this column by day of week, or should I add another column to the table to store the day of week?</p> <p>The table will hold hundreds of thousands of rows, so given a choice I'll choose the most efficient solution (as opposed to most simple).</p>
5,967,514
3
1
null
2011-05-11 16:16:30.147 UTC
6
2017-10-30 10:20:47.367 UTC
2011-05-11 16:27:08.13 UTC
null
560,648
null
156,477
null
1
27
mysql
52,697
<p>Use <a href="http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek" rel="noreferrer">DAYOFWEEK</a> in your query, something like:</p> <pre><code>SELECT * FROM mytable WHERE MONTH(event_date) = 5 AND DAYOFWEEK(event_date) = 7; </code></pre> <p>This will find all info for Saturdays in May.</p> <p>To get the <em>fastest reads</em> store a denormalized field that is the day of the week (and whatever else you need). That way you can index columns and avoid full table scans.</p> <p>Just try the above first to see if it suits your needs and if it doesn't, add some extra columns and store the data on write. Just watch out for update anomalies (make sure you update the day_of_week column if you change event_date).</p> <p>Note that the denormalized fields will increase the time taken to do writes, increase calculations on write, and take up more space. Make sure you really need the benefit and can measure that it helps you.</p>
5,987,242
How to search over huge non-text based data sets?
<p>In a project I am working, the client has a an old and massive(terabyte range) RDBMS. Queries of all kinds are slow and there is no time to fix/refactor the schema. I've identified the sets of common queries that need to be optimized. This set is divided in two: full-text and metadata queries.</p> <p>My plan is to extract the data from their database and partition it across two different storage systems each optimized for a particular query set.</p> <p>For full-text search, Solr is the engine that makes most sense. It's sharding and replication features make it a great fit for half of the problem.</p> <p>For metadata queries, I am not sure what route to take. Currently, I'm thinking of using an RDBMS with an extremely de-normalized schema that represents a particular subset of the data from the "Authoritative" RDBMS. However, my client is concerned about the lack of sharding and replication of such subsystem and difficulty/complications of setting such features as compared with Solr that already includes them. Metadata in this case takes the form of integers, dates, bools, bits, and strings(with max size of 10chars).</p> <p>Is there a database storage system that features built-in sharding and replication that may be particular useful to query said metadata? Maybe a no-sql solution out there that provides a good query engine? </p> <p>Illuminate please.</p> <p>Additions/Responses:</p> <p><em>Solr can be used for metadata, however, the metadata is volatile. Therefore, I would have to commit often to the indexes. This would cause search to degrade pretty fast.</em></p>
6,101,323
4
5
null
2011-05-13 04:31:07.2 UTC
11
2011-05-23 18:30:35.387 UTC
2011-05-16 20:27:43.78 UTC
null
49,881
null
49,881
null
1
36
c#|search|solr|nosql|ravendb
1,332
<p>Use <strong>MongoDB</strong> for your metadata store:</p> <ul> <li>Built-in <a href="http://www.mongodb.org/display/DOCS/Sharding" rel="nofollow">sharding</a></li> <li>Built-in replication</li> <li>Failover &amp; high availability</li> <li><a href="http://www.mongodb.org/display/DOCS/Querying" rel="nofollow">Simple query engine</a> that should work for most common cases</li> </ul> <p><strong>However</strong>, the downside is that you can not perform joins. Be smart about denormalizing your data so that you can avoid this.</p>
1,526,912
Impossibly Fast C++ Delegates and different translation units
<p>According to Sergey Ryazanov, his <a href="https://www.codeproject.com/Articles/11015/The-Impossibly-Fast-C-Delegates" rel="nofollow noreferrer">Impossibly Fast C++ Delegates</a> are not comparable:</p> <blockquote> <p>My delegates cannot be compared. Comparison operators are not defined because a delegate doesn't contain a pointer to method. Pointer to a stub function can be different in various compilation units.</p> </blockquote> <p>To which one the readers have replied:</p> <blockquote> <p>"Pointer to a stub function can be different in various compilation units." AFAIK, this is not true. Compilers are required to re-use template functions generated in different compilation units (this I am sure of - but I think Borland once violated this rule). I think it is because classes (ones not in 'nameless' namespaces) use external linkage and the way you use the stub functions will always prevent them from being inlined (although this shouldn't be an issue either as taking the address of the function will force a non-inline version to be generated and 'external linkage' performed by the linker will eliminate all but one similarly named function (they are assumed and required to be identical by the standard))... </p> <p>If you define a template function one translation unit (cpp file) and then define the same function differently in another translation unit, only one of the two versions will make it into the final executable. (This actually violates the "One Definition Rule", but works on GCC, at least... not sure about MSVC.) The point is: the address [of the stub] will be the same in different units.</p> <p>I would urge you to update the article (including comparison capability) if you find this to be true for MSVC - if MSVC is standards conferment, in this regard.</p> </blockquote> <p>Now the article is four years old and the author hasn't replied to any of the comments during the past three years or so, so I'm wondering if there's any merit to the above comment and whether this specific implementation can indeed be changed to support comparisons.</p> <p>Does the C++ standard specifically prohibit such usage and if so, are any of the recent compilers actually standard-compliant in that regard?</p>
1,526,972
2
1
null
2009-10-06 17:14:13.533 UTC
11
2019-04-01 07:53:39.747 UTC
2019-03-31 14:06:34.4 UTC
null
2,430,597
null
50,251
null
1
19
c++|delegates|language-lawyer|one-definition-rule
8,172
<p>The code is both standard compliant, and fine. I don't see any place where he violates ODR, and it is true that all instantiations of a function template with the same template parameters should have "the same address" (in a sense that pointers to functions should all be equal) - how this is achieved is not important. ISO C++03 14.5.5.1[temp.over.link] describes the rules in more detail.</p> <p>So, a comparison could well be defined there in a conformant and portable way. </p>
2,024,062
Is it possible to wildcard logger names in log4net configuration?
<p>In my application, I use log4net, with all types creating their own logger based on their type - e.g. :</p> <pre><code>private static readonly ILog Log = LogManager.GetLogger(typeof(Program)); </code></pre> <p>As I am developing, I leave the root logger on DEBUG so as to catch all log output from my code. </p> <p>However, a third party component also uses this same approach, but is generating 100s of log messages a second, none of which I am interested in.</p> <p>Is it possible to use some sort of wildcarding in the logger configuration, to force all their loggers to only log at WARN, e.g. :</p> <pre><code> &lt;logger name="com.thirdparty.*"&gt; &lt;level value="WARN"/&gt; &lt;/logger&gt; </code></pre> <p>[The exact example above, using a * doesn't work]</p>
2,024,103
2
0
null
2010-01-07 22:11:33.997 UTC
3
2013-11-25 12:01:08.803 UTC
null
null
null
null
134,754
null
1
30
c#|.net|log4net
10,554
<p>You can just specify part of a namespace so it will apply to all messages within that namespace (including nested). </p> <p>Here is the example I often use:</p> <pre class="lang-xml prettyprint-override"><code> &lt;root&gt; &lt;level value="FATAL" /&gt; &lt;appender-ref ref="RollingFile" /&gt; &lt;/root&gt; &lt;logger name="MyCompany.Web" &gt; &lt;level value="WARN" /&gt; &lt;appender-ref ref="WebErrors" /&gt; &lt;/logger&gt; &lt;!-- Will log all FATALs from NHibernate, including NHibernate.SQL and all the nested --&gt; &lt;logger name="NHibernate" &gt; &lt;level value="FATAL" /&gt; &lt;/logger&gt; </code></pre> <hr> <p>Additionally I would recommend to read the manual. It provides a lot of explanation. For example you can read about <a href="http://logging.apache.org/log4net/release/manual/introduction.html#hierarchy" rel="noreferrer">Logger Hierarchy</a>. Here is the quote from there:</p> <blockquote> <p>A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger. The hierarchy works very much in the same way as the namespace and class hierarchy in .NET.</p> </blockquote> <p>and also:</p> <blockquote> <p><strong>Level Inheritance:</strong> The inherited level for a given logger X, is equal to the first non-null level in the logger hierarchy, starting at X and proceeding upwards in the hierarchy towards the root logger.</p> </blockquote>
2,013,758
How to start doing TDD in a django project?
<p>I have read a lot of essays talking about benifits TDD can bring to a project, but I have never practiced TDD in my own project before.</p> <p>Now I'm starting an experimental project with Django, and I think maybe I can have a try of TDD.</p> <p>But what I find now is that I don't even know how to answer the question "what should I put in my test cases?".</p> <p>Please tell me how should I plan TDD in a project, in this case, a web project based on Django.</p> <p>Thanks.</p>
2,016,334
2
0
null
2010-01-06 14:59:05.903 UTC
16
2013-12-05 13:23:57.987 UTC
null
null
null
null
225,262
null
1
39
django|tdd
8,829
<p>Your first step should be to read over the django test documentation...</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/testing/#topics-testing" rel="noreferrer">http://docs.djangoproject.com/en/dev/topics/testing/#topics-testing</a></p> <p>After that your first test should be as simple as</p> <ul> <li>Create a test client</li> <li>Issue a request for your <em>intended</em> main page</li> <li>check the return status code is 200</li> </ul> <p>now run your test, and watch it fail because you don't have a main page yet.</p> <p>Now, work on getting that test to pass and repeat the process.</p>
46,009,471
Xcode 9 "no iTunes Connect account" error when uploading
<p>With a certain project in Xcode 9 beta 6 when I try to Upload to the App Store I get:</p> <p><a href="https://i.stack.imgur.com/Et9wt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Et9wt.png" alt="enter image description here"></a></p> <p>I am the "Admin" role for this account.</p> <ul> <li>All contracts are up-to-date</li> <li>I tried removing/re-adding my account from Xcode prefs several times</li> <li>Submitting for the same project from Xcode 8 works (however I need to upload from Xcode 9 for this project because it links against iOS 11 beta)</li> </ul> <p>Another developer on the team is seeing the same thing so this seems like it might be common. Anyone find a workaround?</p>
46,279,679
24
2
null
2017-09-02 00:38:39.653 UTC
12
2020-05-20 06:32:22.303 UTC
2017-09-02 18:56:24.26 UTC
null
2,904,769
null
2,904,769
null
1
50
xcode|app-store-connect
20,095
<p>I encountered the same issue with xCode 9 GM build and others reported it as well in xCode 10 and xCode 11. Deleting the derived data actually solved it for me. Hopefully it will help others as well.</p> <ol> <li>Close xCode</li> <li><code>rm -fr ~/Library/Developer/Xcode/DerivedData/ </code></li> <li>Reopen xCode and try to upload again</li> </ol>
29,256,519
I implemented a trait for another trait but cannot call methods from both traits
<p>I have a trait called <code>Sleep</code>:</p> <pre><code>pub trait Sleep { fn sleep(&amp;self); } </code></pre> <p>I could provide a different implementation of sleep for every struct, but it turns out that most people sleep in a very small number of ways. You can sleep in a bed:</p> <pre><code>pub trait HasBed { fn sleep_in_bed(&amp;self); fn jump_on_bed(&amp;self); } impl Sleep for HasBed { fn sleep(&amp;self) { self.sleep_in_bed() } } </code></pre> <p>If you're camping, you can sleep in a tent:</p> <pre><code>pub trait HasTent { fn sleep_in_tent(&amp;self); fn hide_in_tent(&amp;self); } impl Sleep for HasTent { fn sleep(&amp;self) { self.sleep_in_tent() } } </code></pre> <p>There are some oddball cases. I have a friend that can sleep standing against a wall, but most people, most of the time, fall into some simple case.</p> <p>We define some structs and let them sleep:</p> <pre><code>struct Jim; impl HasBed for Jim { fn sleep_in_bed(&amp;self) {} fn jump_on_bed(&amp;self) {} } struct Jane; impl HasTent for Jane { fn sleep_in_tent(&amp;self) {} fn hide_in_tent(&amp;self) {} } fn main() { use Sleep; let jim = Jim; jim.sleep(); let jane = Jane; jane.sleep(); } </code></pre> <p>Uh-oh! Compile error:</p> <pre class="lang-none prettyprint-override"><code>error[E0599]: no method named `sleep` found for type `Jim` in the current scope --&gt; src/main.rs:44:9 | 27 | struct Jim; | ----------- method `sleep` not found for this ... 44 | jim.sleep(); | ^^^^^ | = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item `sleep`, perhaps you need to implement it: candidate #1: `Sleep` error[E0599]: no method named `sleep` found for type `Jane` in the current scope --&gt; src/main.rs:47:10 | 34 | struct Jane; | ------------ method `sleep` not found for this ... 47 | jane.sleep(); | ^^^^^ | = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item `sleep`, perhaps you need to implement it: candidate #1: `Sleep` </code></pre> <p>This compiler error is strange because if there was something wrong with a trait implementing another trait, I expected to hear about it way back when I did that, not at the very bottom of the program when I try to use the result.</p> <p>In this example, there are only 2 structs and 2 ways to sleep, but in the general case there are many structs and several ways to sleep (but not as many ways as there are structs). </p> <p>A <code>Bed</code> is mostly an implementation for <code>Sleep</code>, but in the general case a <code>Bed</code> has many uses and could implement many things.</p> <p>The only immediately obvious approach is to convert <code>impl Sleep for...</code> into a macro that structs themselves use, but that seems hacky and terrible.</p>
29,256,897
3
1
null
2015-03-25 13:05:10.043 UTC
9
2022-09-24 04:25:10.697 UTC
2019-06-11 14:01:40.037 UTC
null
155,423
null
116,834
null
1
57
rust|traits
21,119
<p>You need to implement the second trait <em>for objects that implement the first trait</em>:</p> <pre><code>impl&lt;T&gt; Sleep for T where T: HasBed, { fn sleep(&amp;self) { self.sleep_in_bed() } } </code></pre> <p>Previously, you were implementing <code>Sleep</code> for the trait's type, better expressed as <code>dyn HasBed</code>. See <a href="https://stackoverflow.com/q/50650070/155423">What does &quot;dyn&quot; mean in a type?</a> for more details.</p> <p>However, this is going to break as soon as you add a second blanket implementation:</p> <pre><code>impl&lt;T&gt; Sleep for T where T: HasTent, { fn sleep(&amp;self) { self.sleep_in_tent() } } </code></pre> <p>With</p> <pre class="lang-none prettyprint-override"><code>error[E0119]: conflicting implementations of trait `Sleep`: --&gt; src/main.rs:24:1 | 10 | / impl&lt;T&gt; Sleep for T 11 | | where 12 | | T: HasBed, 13 | | { ... | 16 | | } 17 | | } | |_- first implementation here ... 24 | / impl&lt;T&gt; Sleep for T 25 | | where 26 | | T: HasTent, 27 | | { ... | 30 | | } 31 | | } | |_^ conflicting implementation </code></pre> <p>It's possible for something to implement <strong>both</strong> <code>HasBed</code> and <code>HasTent</code>. If something were to appear that implemented both, then the code would now be ambiguous. The workaround for this would be <em>specialization</em>, but there's no stable implementation of that yet.</p> <p>How do you accomplish your goal? I think you have already suggested the current best solution - write a macro. You could also <a href="https://stackoverflow.com/q/29233324/155423">write your own derive macro</a>. Macros really aren't that bad, but they can be unwieldy to write.</p> <p>Another thing, which may be entirely based on the names you chose for your example, would be to simply embed structs into other structs, optionally making them public. Since your implementation of <code>Sleep</code> basically only depends on the bed / tent, no <em>functionality</em> would be lost by doing this. Of course, some people might feel that breaks encapsulation. You could again create macros to implement a delegation of sorts.</p> <pre><code>trait Sleep { fn sleep(&amp;self); } struct Bed; impl Bed { fn jump(&amp;self) {} } impl Sleep for Bed { fn sleep(&amp;self) {} } struct Tent; impl Tent { fn hide(&amp;self) {} } impl Sleep for Tent { fn sleep(&amp;self) {} } struct Jim { bed: Bed, } struct Jane { tent: Tent, } fn main() { let jim = Jim { bed: Bed }; jim.bed.sleep(); } </code></pre>
29,282,457
equivalent to Files.readAllLines() for InputStream or Reader?
<p>I have a file that I've been reading into a List via the following method:</p> <pre><code>List&lt;String&gt; doc = java.nio.file.Files.readAllLines(new File("/path/to/src/resources/citylist.csv").toPath(), StandardCharsets.UTF_8); </code></pre> <p>Is there any nice (single-line) Java 7/8/nio2 way to pull off the same feat with a file that's inside an executable Jar (and presumably, has to be read with an InputStream)? Perhaps a way to open an InputStream via the classloader, then somehow coerce/transform/wrap it into a Path object? Or some new subclass of InputStream or Reader that contains an equivalent to File.readAllLines(...)?</p> <p>I know I <em>could</em> do it the traditional way in a half page of code, or via some external library... but before I do, I want to make sure that recent releases of Java can't already do it "out of the box".</p>
29,282,588
2
2
null
2015-03-26 15:25:59.633 UTC
8
2021-04-01 16:29:36.487 UTC
null
null
null
null
388,603
null
1
57
java|jar|nio2
35,646
<p>An <code>InputStream</code> represents a stream of bytes. Those bytes don't necessarily form (text) content that can be read line by line.</p> <p>If you know that the <code>InputStream</code> can be interpreted as text, you can wrap it in a <code>InputStreamReader</code> and use <a href="http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#lines--" rel="noreferrer"><code>BufferedReader#lines()</code></a> to consume it line by line.</p> <pre><code>try (InputStream resource = Example.class.getResourceAsStream(&quot;resource&quot;)) { List&lt;String&gt; doc = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)).lines().collect(Collectors.toList()); } </code></pre>
6,295,148
What is the opposite of OOP?
<p>I started in High School learning java and python and I guess I just always learned OOP and nothing else my question is <strong>What are the other programming paradigms or types of programming languages beside OOP?</strong></p>
6,295,260
5
6
null
2011-06-09 15:15:51.863 UTC
14
2020-04-11 20:14:41.953 UTC
2017-01-18 08:17:20.053 UTC
null
-1
null
783,280
null
1
19
oop|paradigms
18,772
<p>"Opposite" isn't really a good way of putting it. What's the "opposite" of Democracy? OOP is a a paradigm -- a way of viewing the problem of programming.</p> <p>The four main coding paradigms are:</p> <ol> <li><strong>functional</strong> (viewing programs as mathematical formulas)</li> <li><strong>imperative</strong> (programs are series of instructions for the computer)</li> <li><strong>logical</strong> (model information and the relationship between that information), and </li> <li><strong>OOP</strong> (Model objects and how it interacts with other data)</li> </ol> <p><a href="http://www.cs.aau.dk/~normark/prog3-03/html/notes/paradigms_themes-paradigm-overview-section.html#paradigms_logic-paradigm-overview_title_1" rel="noreferrer">http://www.cs.aau.dk/~normark/prog3-03/html/notes/paradigms_themes-paradigm-overview-section.html#paradigms_logic-paradigm-overview_title_1</a></p> <p>Logical is the most different by far and you have to jump through a lot of hoops to solve some problems in logical programming. The other three all solve the same problems, but the approaches are different.</p>
6,152,979
How can I create a new folder in asp.net using c#?
<p>How can I create a new folder in asp.net using c#? </p>
6,152,988
7
0
null
2011-05-27 13:34:00.787 UTC
4
2015-11-18 11:27:30.447 UTC
2011-09-05 11:46:59.577 UTC
null
508,702
null
773,175
null
1
24
c#|asp.net|directory
55,782
<p><code>path</code> is the variable holding the directory name</p> <pre><code>Directory.CreateDirectory(path); </code></pre> <p>You can read more about it <a href="http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory(v=VS.100).aspx" rel="noreferrer">here</a></p>
5,744,233
How to empty the content of a div
<p>Does someone know how to empty the content of a div (without destroying it) in JavaScript?</p> <p>Thanks,</p> <p>Bruno</p>
5,744,262
8
3
null
2011-04-21 12:40:18.25 UTC
8
2021-06-24 06:45:04.72 UTC
2011-04-21 12:42:33.967 UTC
null
20,578
null
422,667
null
1
38
javascript|html
118,375
<p>If your div looks like this: </p> <p><code>&lt;div id="MyDiv"&gt;content in here&lt;/div&gt;</code></p> <p>Then this Javascript: </p> <p><code>document.getElementById("MyDiv").innerHTML = "";</code> </p> <p>will make it look like this: </p> <p><code>&lt;div id="MyDiv"&gt;&lt;/div&gt;</code></p>
5,785,724
How to insert a row between two rows in an existing excel with HSSF (Apache POI)
<p>Somehow I manage to create new rows between two rows in an existing excel file. The problem is, some of the formatting were not include along the shifting of the rows. </p> <p>One of this, is the row that are hide are not relatively go along during the shift. What I mean is(ex.), rows from 20 to 30 is hidden, but when a create new rows the formating still there. The hidden rows must also move during the insertion/creation of new rows, it should be 21 to 31. </p> <p>Another thing is, the other object in the sheet that are not in the cell. Like the text box are not move along after the new row is created. Its like the position of these object are fixed. But I want it to move, the same thing as I insert a new row or paste row in excel. If there is a function of inserting a new row, please let me know.</p> <p>This what I have right now, just a snippet from my code.</p> <pre><code>HSSFWorkbook wb = new HSSFWorkbook(template); //template is the source of file HSSFSheet sheet = wb.getSheet("SAMPLE"); HSSFRow newRow; HSSFCell cellData; int createNewRowAt = 9; //Add the new row between row 9 and 10 sheet.shiftRows(createNewRowAt, sheet.getLastRowNum(), 1, true, false); newRow = sheet.createRow(createNewRowAt); newRow = sheet.getRow(createNewRowAt); </code></pre> <p>If copy and paste of rows is possible that would be big help. But I already ask it here and can't find a solution. So I decided to create a row as an interim solution. I'm done with it but having a problem like this. </p> <p>Any help will be much appreciated. Thanks!</p>
5,786,426
8
2
null
2011-04-26 03:53:31.26 UTC
21
2019-11-20 05:17:42.2 UTC
2011-05-31 15:08:03.04 UTC
null
761,828
null
527,577
null
1
58
java|excel|apache-poi|poi-hssf
116,892
<p>Helper function to copy rows shamelessly adapted from <a href="http://www.zachhunter.com/2010/05/npoi-copy-row-helper/" rel="noreferrer">here</a></p> <pre><code>import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.util.CellRangeAddress; import java.io.FileInputStream; import java.io.FileOutputStream; public class RowCopy { public static void main(String[] args) throws Exception{ HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream("c:/input.xls")); HSSFSheet sheet = workbook.getSheet("Sheet1"); copyRow(workbook, sheet, 0, 1); FileOutputStream out = new FileOutputStream("c:/output.xls"); workbook.write(out); out.close(); } private static void copyRow(HSSFWorkbook workbook, HSSFSheet worksheet, int sourceRowNum, int destinationRowNum) { // Get the source / new row HSSFRow newRow = worksheet.getRow(destinationRowNum); HSSFRow sourceRow = worksheet.getRow(sourceRowNum); // If the row exist in destination, push down all rows by 1 else create a new row if (newRow != null) { worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1); } else { newRow = worksheet.createRow(destinationRowNum); } // Loop through source columns to add to new row for (int i = 0; i &lt; sourceRow.getLastCellNum(); i++) { // Grab a copy of the old/new cell HSSFCell oldCell = sourceRow.getCell(i); HSSFCell newCell = newRow.createCell(i); // If the old cell is null jump to next cell if (oldCell == null) { newCell = null; continue; } // Copy style from old cell and apply to new cell HSSFCellStyle newCellStyle = workbook.createCellStyle(); newCellStyle.cloneStyleFrom(oldCell.getCellStyle()); ; newCell.setCellStyle(newCellStyle); // If there is a cell comment, copy if (oldCell.getCellComment() != null) { newCell.setCellComment(oldCell.getCellComment()); } // If there is a cell hyperlink, copy if (oldCell.getHyperlink() != null) { newCell.setHyperlink(oldCell.getHyperlink()); } // Set the cell data type newCell.setCellType(oldCell.getCellType()); // Set the cell data value switch (oldCell.getCellType()) { case Cell.CELL_TYPE_BLANK: newCell.setCellValue(oldCell.getStringCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: newCell.setCellValue(oldCell.getBooleanCellValue()); break; case Cell.CELL_TYPE_ERROR: newCell.setCellErrorValue(oldCell.getErrorCellValue()); break; case Cell.CELL_TYPE_FORMULA: newCell.setCellFormula(oldCell.getCellFormula()); break; case Cell.CELL_TYPE_NUMERIC: newCell.setCellValue(oldCell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: newCell.setCellValue(oldCell.getRichStringCellValue()); break; } } // If there are are any merged regions in the source row, copy to new row for (int i = 0; i &lt; worksheet.getNumMergedRegions(); i++) { CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i); if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) { CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(), (newRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow() )), cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn()); worksheet.addMergedRegion(newCellRangeAddress); } } } } </code></pre>
6,016,405
How to get a Facebook access token on iOS
<p>iOS beginner here. I have the following code:</p> <pre><code>[facebook authorize:nil delegate:self]; NSString *string1=[facebook accessToken]; NSLog(string1); </code></pre> <p>The log shows: <code>miFOG1WS_7DL88g6d95Uxmzz7GCShsWx_FHuvZkmW0E.eyJpdiI6IjNZZkFBY1c5ZnBaMGEzOWM2RzNKbEEifQ.LNjl06lsOQCO9ArVARqff3Ur2XQHku3CMHDBKkpGg351EB33LGxVv96Hh5R860KDJL0cLq8QezSW0GovYxnhUucOwxlITV364sVKDXIzC3bAn9P_74r2Axl1SgOaTyMMkQ_aSQ2OWh-8d3Zn9BDt3pXVWzBLJ9I4XAosnw0GjuE</code></p> <p>This seems too long to be an access token. I read it's supposed to be only 40 characters long. What am I doing wrong?</p>
6,016,470
10
0
null
2011-05-16 11:01:07.377 UTC
11
2019-09-20 08:01:50.123 UTC
null
null
null
null
584,432
null
1
36
iphone|facebook|access-token
49,308
<p>You can use delegate method:</p> <pre><code>- (void)fbDialogLogin:(NSString *)token expirationDate:(NSDate *)expirationDate </code></pre> <p>for more information you can refer to the following question :<a href="https://stackoverflow.com/questions/5151122/any-way-to-pull-out-session-key-from-access-token-returned-by-facebook-ios-sdk">Facebook Access Token</a></p>
6,028,750
How to assert an actual value against 2 or more expected values?
<p>I'm testing a method to see if it returns the correct string. This string is made up of a lot of lines whose order might change, thus usually giving 2 possible combinations. That order is not important for my application.</p> <p>However, because the order of the lines might change, writing just an Assert statement will not work, since sometimes it will pass the test, and sometimes it will fail the test.</p> <p>So, is it possible to write a test that will assert an actual string value against 2 or more expected string values and see if it is equal to any of them?</p>
6,028,873
15
0
null
2011-05-17 09:20:32.59 UTC
8
2022-04-21 17:01:22.13 UTC
2011-05-17 09:28:31.247 UTC
null
40,342
null
279,362
null
1
42
java|unit-testing|junit|assert
87,614
<p>Using the Hamcrest <a href="https://code.google.com/p/hamcrest/wiki/Tutorial" rel="noreferrer"><code>CoreMatcher</code></a> (included in JUnit 4.4 and later) and <code>assertThat()</code>:</p> <pre><code>assertThat(myString, anyOf(is(&quot;value1&quot;), is(&quot;value2&quot;))); </code></pre>
4,960,513
Using mod_rewrite to convert paths with hash characters into query strings
<p>I have a PHP project where I need to send a hash character (#) within the path of a URL. (<a href="http://www.example.com/parameter#23/parameter#67/index.php" rel="nofollow noreferrer">http://www.example.com/parameter#23/parameter#67/index.php</a>) I thought that urlencode would allow that, converting the hash to %23</p> <p>But now I see that even the urlencoded hash forces the browser to treat everything to the right as the URL fragment (or query).</p> <p>Is there a way to pass a hash through, or do I need to do a character substitution prior to urlencode?</p> <p><strong>Edit to add (Sep 19 2017):</strong></p> <p>It turns out that I was asking the wrong question. My issue wasn't with using the hash character within the path (encoding it does work), but in using mod_rewrite to convert it over to a query string. I had failed to re-encode it within the RewriteRule. I'll edit the title to match.</p> <p>Here is the rewrite rule I was using:</p> <pre><code>RewriteEngine On # convert path strings into query strings RewriteRule "^(.*)/(.*)/hashtags.php" /hashtags.php?parameter_1=$1&amp;amp;parameter_2=$2 [QSA,L] </code></pre> <p>As soon as I added the B tag, it worked correctly:</p> <pre><code>RewriteEngine On # convert path strings into query strings RewriteRule "^(.*)/(.*)/hashtags.php" /hashtags.php?parameter_1=$1&amp;amp;parameter_2=$2 [QSA,L,B] </code></pre>
19,616,196
1
5
null
2011-02-10 17:27:18.08 UTC
4
2017-09-19 16:47:09.187 UTC
2017-09-19 16:47:09.187 UTC
null
318,831
null
318,831
null
1
35
php|apache|mod-rewrite|hash|urlencode
36,861
<p>Encode the Hash in the URL with %23</p> <pre><code>http://twitter.com/home?status=I+believe+in+%23love </code></pre> <p>"I believe in #love"</p> <p>URL Encoding Reference: <a href="http://www.w3schools.com/tags/ref_urlencode.asp">http://www.w3schools.com/tags/ref_urlencode.asp</a></p>
5,119,994
get current user in Django Form
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1202839/get-request-data-in-django-form">get request data in Django form</a> </p> </blockquote> <p>There's part of my Guest Model:</p> <pre><code>class Guest(models.Model): event = models.ForeignKey(Event, related_name='guests') user = models.ForeignKey(User, unique=True, related_name='guests') ... </code></pre> <p>Form to get the response from the Guest:</p> <pre><code>class RSVPForm(forms.Form): attending_d= forms.ChoiceField(choices=VISIBLE_ATTENDING_CHOICES, initial='yes', widget=forms.RadioSelect) attending_b = forms.ChoiceField(choices=VISIBLE_ATTENDING_CHOICES, initial='yes', widget=forms.RadioSelect) number_of_guests = forms.IntegerField(initial=0) comment = forms.CharField(max_length=255, required=False, widget=forms.Textarea) .... def save(self): guest = self.guest_class.objects.get(user=1) guest.attending_status_d = self.cleaned_data['attending_d'] guest.attending_status_b = self.cleaned_data['attending_b'] guest.number_of_guests = self.cleaned_data['number_of_guests'] guest.comment = self.cleaned_data['comment'] guest.save() return guest </code></pre> <p>The problem is in save method. How can I associate guest with the currently logged in user?</p> <pre><code>guest = self.Guest.objects.get(user=1) </code></pre> <p>Instead of <code>user=1</code> I need to have id of the currently logged in user.</p> <p>Thank you!</p>
5,122,029
1
0
null
2011-02-25 16:45:21.047 UTC
12
2017-10-24 09:58:03.03 UTC
2017-05-23 12:03:05.203 UTC
null
-1
null
616,173
null
1
36
django-forms|django-users
43,103
<p>I found the way :)</p> <ol> <li><p>Write a <code>__init__</code> method on the form :</p> <pre><code>def __init__(self, user, *args, **kwargs): self.user = user super(RSVPForm, self).__init__(*args, **kwargs) </code></pre></li> <li><p>Change view function, and pass request.user to the form</p> <pre><code>def event_view(request, slug, model_class=Event, form_class=RSVPForm, template_name='rsvp/event_view.html'): event = get_object_or_404(model_class, slug=slug) if request.POST: form = form_class(request.user, request.POST) if form.is_valid(): guest = form.save() return HttpResponseRedirect(reverse('rsvp_event_thanks', kwargs={'slug': slug, 'guest_id': guest.id})) else: form = form_class(request.user) return render_to_response(template_name, { 'event': event, 'form': form, }, context_instance=RequestContext(request)) </code></pre></li> <li><p>the line of the save() method would look like this now:</p> <pre><code>guest = self.guest_class.objects.get(user=self.user) </code></pre></li> </ol>