pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
24,724,434
0
Sort array by delegate <p>I want to sort an array alphabetically using a delegate. The input is</p> <pre><code>"m", "a", "d", "f", "h" </code></pre> <p>but the output is</p> <pre><code> a a d f h </code></pre> <p>i.e. it is ordered alphabetically but the "m" is missing and with "a" doubled. What is the reason?</p> <p>Source code:</p> <pre><code>class ArrayMethods { public void sort(String[] array, t xcompare) { xcompare = compare; for (int i = 0; i &lt; array.Length - 1 ; i++) { array[i] = xcompare(array[i], array[i + 1]); } foreach (var a in array) { Console.WriteLine(a); } } public String compare(string p, string x) { string result = ""; if (String.Compare(p, x) &lt; 0) { result = p; } else { result = x; } return result; } } public delegate string t(string firstString, string secondString); class Program { public static string[] names = { "m", "a", "d", "f", "h" }; static void Main(string[] args) { ArrayMethods arrayMethods = new ArrayMethods(); t delHandler = null; arrayMethods.sort(names, delHandler); Console.ReadKey(); } } </code></pre>
38,087,254
0
<p>I'm using BroadcastReceivers to solve these kind of problems to avoid problems related to the Android lifecicle.</p> <p>The basic idea of broadcast receiver is a publisher-subscriber, the interested fragmets should register with an appropriate intent filter to the events they're interested in and the activity should be spamming events.</p> <p>More about broadcast receivers at <a href="https://developer.android.com/reference/android/content/BroadcastReceiver.html" rel="nofollow">https://developer.android.com/reference/android/content/BroadcastReceiver.html</a></p>
23,072,844
0
<p>You could check if the <code>#localVideo</code> element exists. Also, if they are the only elements in the <code>#A</code> element, you can remove them by calling <code>$('#A').empty();</code>.</p> <pre><code>$(document).ready(function() { $('#BtnOn').click(function() { if ($('#localVideo').length == 0) { $('#A').append('&lt;video id="localVideo" style="background-color:black"&gt;&lt;/video&gt;&lt;div id="remoteVideos"&gt;&lt;/div&gt;'); } }); $('#BtnOff').click(function() { if ($('#localVideo').length &gt; 0) { $("#localVideo").remove(); $("#remoteVideos").remove(); } }); }); </code></pre> <p>You could also consider hiding and showing the video elements, rather than adding and removing them.</p>
5,264,764
0
JSF/Richfaces/A4j ==> component/field conversion and reRendering problem <p>I have an input field in a JSF Page like the following (maps to BigDecimal on backing bean)</p> <pre><code> &lt;h:inputText disabled="#{volumeBean.grossVolumeDisabled}" id="grossVolume" size="10" validateOnExit="true" value="#{volumeBean.enteredGrossVolume}" &gt; &lt;a4j:support ajaxSingle="true" event="onblur" ignoreDupResponses="true" oncomplete="checkFieldValidation(this)" onsubmit="updateDirty()"/&gt; &lt;/h:inputText&gt; </code></pre> <p>And an a4j:commandButton to "refresh" all the data from the database on the page: </p> <pre><code> &lt;a4j:commandButton accesskey="T" action="#{volumeBean.revert}" button-type="ajax" disabled="#{volumeBean.revertDisabled}" id="volumeBean_reset" immediate="true" reRender="volumesTable" value="#{msg.button_RESET}"/&gt; </code></pre> <p>Here are the steps to reproduce my problem: And please note that the error occurs regardless of whether there is a reRender attribute set on the a4j:support</p> <p>Here are the steps to reproduce - just to clarify further:</p> <ol> <li>navigate to the screen where the BigDecimal input field exists</li> <li>type aa into the field (should be a number but put non-numeric characters purposely)</li> <li>tab off the field</li> <li>notice that an error is reported 'aa' is not a valid netVolume</li> <li>click on the RESET button</li> <li>all of the changed fields have their original values EXCEPT those that have non-numeric data entered</li> <li>unless the user manually deletes the non-numeric data in the fields or refreshes the entire screen, the "bad data" sticks</li> </ol>
12,367,606
0
Powershell variable interrogation of date & time difference <p>Morning All,</p> <p>I have a variable as follows: <code>$machines = $user2,$name,$serial,$purchased</code> sample data stored in $machines is:</p> <pre><code>User1, Laptop1, xyz1234, 01/01/2010 </code></pre> <p>I am wanting to create a new variable called $tobereplaced containing all of the records in $machines with a date greater than 4 years old from todays date.</p> <p>the fuzzy logic code for this im expecting to be someting like <code>$tobereplaced = $machines.$purchased | where {$_$purchased = -getdate &gt; 4 years}</code> etc etc but i cant quite figure it out.</p> <p>Assistance would be greatly appreciated.</p> <p>Thanks</p>
14,272,251
0
<p>Firefox has a <strong>"text-only"</strong> zoom feature, unlike Chrome that lacks this feature.</p> <p>To make <strong>everything</strong> zoom in Firefox, <strong>remove</strong> the checkmark and Reset the zoom level.</p> <p><img src="https://i.stack.imgur.com/VSHLA.png" alt="enter image description here"></p> <p>For Chrome browser, look into Zoom plugins that have this feature.</p>
4,747,750
0
<p>Is there a larger context in which you are operating? In ASP.NET I've created a PerRequestLifetimeManager that returns the same object when it is requested multiple times during a single HTTP request.</p> <p><strong>EDIT:</strong> Here's an implementation if you're interested.</p> <pre><code>public class PerRequestLifetimeManager : LifetimeManager { private readonly object key = new object(); public override object GetValue() { if (HttpContext.Current != null &amp;&amp; HttpContext.Current.Items.Contains(key)) return HttpContext.Current.Items[key]; else return null; } public override void RemoveValue() { if (HttpContext.Current != null) HttpContext.Current.Items.Remove(key); } public override void SetValue(object newValue) { if (HttpContext.Current != null) HttpContext.Current.Items[key] = newValue; } </code></pre>
11,359,111
0
How can I delete old translations? <p>I have noticed that when I change a word on a new action before submitting it to Facebook, it generates new translations. How can I delete old translations so that I don't need to translate them ?</p> <p>Thank you, Zoé</p>
15,140,966
0
<p>(I've tried to edit @false's <a href="http://stackoverflow.com/a/15140312/1545971">response</a>, but it was rejected)</p> <p><code>my_len_tail/2</code> is faster (in terms of both the number of inferences and actual time) than buldin <code>length/2</code> when generating a list, but has problem with <code>N in 1..2</code> constraint.</p> <pre><code>?- time(( my_len_tail(L,N),N=10000000 )). % 20,000,002 inferences, 2.839 CPU in 3.093 seconds (92% CPU, 7044193 Lips) L = [_G67, _G70, _G73, _G76, _G79, _G82, _G85, _G88, _G91|...], N = 10000000 . ?- time(( length(L,N),N=10000000 )). % 30,000,004 inferences, 3.557 CPU in 3.809 seconds (93% CPU, 8434495 Lips) L = [_G67, _G70, _G73, _G76, _G79, _G82, _G85, _G88, _G91|...], N = 10000000 . </code></pre>
15,385,693
0
Fetch details of a ListItem in ListView from MySQL Database <p>I have successfully fetched a list from a database and binded it in a ListView. If I select an item from the listView if fetches the correct details of that item. If I select another list item from the listview, it brings the same same data of the previous item selected. </p> <p>How do I go about solving that? perfectly..</p> <p>My code is running</p>
23,498,695
0
<p>You can't have multiple instances of the same <code>MockUp</code> subclass at the same time (each such mock-up would simply override the previous one when it got instantiated). Instead, add an <code>Invocation</code> parameter to your <code>@Mock</code> method, and then use the information it provides to distinguish between multiple data sets. For example:</p> <pre><code>@Test public void testClientWithVariedDataFromFastScanners() { new MockUp&lt;FastScanner&gt;() { // some data structure for test data @Mock int nextInt(Invocation inv) { int idx = inv.getInvocationIndex(); FastScanner fs = inv.getInvokedInstance(); // Find the next value by using idx or fs as a lookup index // into the data structures: int i = ... return i; } }; client.doSomethingUsingFastScanners(); } </code></pre> <p>Also, if you want to call whatever methods (including <code>static</code> methods) on a mock-up subclass, just make it a <em>named</em> class rather than an anonymous one.</p>
1,820,856
0
<p>Well, you deserve a medal for putting that much time into this issue.</p> <p>I'd suggest these things:</p> <ol> <li>Make him read <em>Code Complete</em>. <ul> <li>Treat him like a senior programmer, but check every step he makes until you see good results.</li> <li>Don't take over or he won't learn. Let him make mistakes, but then make him fix it.</li> <li>He should always make estimates. Then have him acknowledge when his estimation is wrong.</li> <li>Always encourage him to <em>think</em>. Fresh CS students hardly think; they code like robots.</li> </ul></li> </ol> <p>Give him some ground rules, like: never write the same code twice, and if you do so, check your design, etc.</p> <p>Also remember that he is afraid from you as much as he wants to learn from you. You may have forgotten things that he is learning, so you need to push him to ask questions and make sure he doesn't feel stupid in doing so.</p> <p>In six months he will be good and ready! (to leave and look for a better paid job :-) )</p>
30,765,246
0
<p><code>natualHeight</code></p> <p>Look veeeeeeery closely at that word... =)</p> <p>It's probably just finding that <code>NaN</code> is neither less than nor greater than nor equal to <code>NaN</code>. (You have the same typo on naturalWidth too)</p>
39,334,620
0
Create Android Widget inside App <p>I'd like to link to my app widget configuration activity from inside my app. I know it's possible to launch the Android widget picker but can I bypass that step and let my users create a widget on their home screen from inside my app?</p>
38,584,976
0
How can i reload the URL automatically if session is expired? <p>I am using maven spring boot and spring security with java configuration. I have also created Security Configuration which extends <code>WebSecurityConfigurerAdapter</code>. </p> <p>Here what i need is once my session is expired then automatically reload all the pages based on antMatchers. </p> <p><strong><em>Note</strong>: I am using <code>jquery</code> rest client with <code>@RestController</code> instead of jsp and servlet.</em></p>
15,016,371
0
SQL adding two columns (datetime) <p>I have two columns that contains datetimes and i need two add them together somehow. I've tried using sum but that didnt work. Im using sqlserver 2008.</p> <p><strong>Columns</strong></p> <p><strong>loanPeriod</strong> = the loanperiod of the item </p> <p><strong>checkOutDate</strong>= when the item was borrowed</p> <p>And Im trying to achieve this lastreturndate = (checkoutDate + loanperiod)</p>
29,615,773
0
<p>There are a few key points when doing this sort of thing (and these apply to languages other than Tcl too). Firstly, you should <strong>compute the delta</strong> from the span you want and the number of steps you want. Secondly, you should <strong>keep your incrementing and loop control using integers</strong> if you can, so as to avoid fencepost errors caused by rounding; instead <strong>compute the value for the loop iteration</strong> by multiplying the delta by the loop counter and adding to the originating value. Thirdly, you should consider what the right <strong>precision</strong> is when printing your results; in Tcl, this tends to mean using <code>format</code> with the <code>%f</code> conversion and appropriate width specifier.</p> <pre><code>set from -0.3925 set to 0.3925 set points 19 set delta [expr {($to-$from) / double($points-1)}] for {set i 0} {$i&lt;$points} {incr i} { set x [expr {$from + $i*$delta}] puts [format "%.5f" $x] } </code></pre> <p>This produces this output:</p> <pre> -0.39250 -0.34889 -0.30528 -0.26167 -0.21806 -0.17444 -0.13083 -0.08722 -0.04361 0.00000 0.04361 0.08722 0.13083 0.17444 0.21806 0.26167 0.30528 0.34889 0.39250 </pre>
37,385,489
0
<ol> <li><p>No, nested collections as properties can not be used.</p></li> <li><p>The philosophy is simple: maximum decomposition of objects and relationships to effectively use graph algorithms as a tool of analysis. Using your example with food:</p> <ul> <li>Who eats the same foods for breakfast?</li> <li>Who was the lunch at the same time?</li> <li>What if you need to count calorie meal?</li> <li>How different cooking methods of the same person on different days?</li> <li>Who supplies these products?</li> <li>In some recipes include these products?</li> <li>What are the vegetables and fruit juices that people were in the day for breakfast?</li> </ul></li> </ol> <p>And as an illustration of an exemplary model:</p> <p><a href="https://i.stack.imgur.com/pmRI8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pmRI8.png" alt="enter image description here"></a></p>
23,652,918
0
<p>It may be that the space in the title is not being url encoded correctly. Try using <code>encodeURIComponent()</code> to solve this.</p> <pre><code>var link = '@Url.Action("accountPartial", "BillingProfile")?ln=' + ln + '&amp;profileID=' + profileID + '&amp;title=' + encodeURIComponent(title) + '&amp;active=' + active; </code></pre> <p>Just an idea. Can't be sure.</p>
40,531,886
0
Rectangle is not moving if i set the x y from another class. <p>Alright, so I got two classes here, the main and the keylistener class which i use to pass keyboard inputs to the main class.</p> <pre><code> import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.image.BufferStrategy; import java.util.ArrayList; import java.util.Random; import javax.swing.JFrame; public class Game extends Canvas implements Runnable{ private static final long serialVersionUID = 1L; private final static int WIDTH = 240; private final static int HEIGHT = WIDTH / 12 * 9; private final static int SCALE = 2; private String TITLE = "Game"; private boolean running = false; private Thread thread; Random r = new Random(); ArrayList&lt;Point&gt; snakePart = new ArrayList&lt;Point&gt;(); Point head; KeyHandle keyhandle; public static void main(String[] args) { new Game(); } public Game() { init(); JFrame frame = new JFrame(TITLE); Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE); setMinimumSize(size); setMaximumSize(size); setPreferredSize(size); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(this); frame.pack(); frame.setVisible(true); start(); } public void init() { head = new Point(0,0); addKeyListener(new KeyHandle()); } @Override public void run() { final double ticks = 60.0; long initTime = System.nanoTime(); double ns = 1000000000 / ticks; double delta = 0; long timer = System.currentTimeMillis(); double updates = 0; int frames = 0; while (running) { long nowTime = System.nanoTime(); delta += (nowTime - initTime) / ns; initTime = nowTime; if (delta &gt;= 1) { tick(); updates++; delta--; } render(); frames++; if (System.currentTimeMillis() - timer &gt; 1000) { timer += 1000; System.out.println("Ticks: " + updates + " Frames: " + frames); updates = 0; frames = 0; } } stop(); } public void tick() { } public void render() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); return; } Graphics g = bs.getDrawGraphics(); g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.white); g.drawRect(head.x, head.y, 10, 10); bs.show(); g.dispose(); } private synchronized void start() { if (running) return; running = true; thread = new Thread(this); thread.start(); } private synchronized void stop() { if (!running) return; running = false; try { thread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.exit(1); } } </code></pre> <p>and then i've got the keylistener class which looks like this</p> <pre><code>import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class KeyHandle implements KeyListener { Game game; @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_UP){ } else if(e.getKeyCode() == KeyEvent.VK_DOWN){ game.head.y += 10; } else if(e.getKeyCode() == KeyEvent.VK_LEFT){ } else if(e.getKeyCode() == KeyEvent.VK_RIGHT){ } else if(e.getKeyCode() == KeyEvent.VK_ESCAPE){ } } @Override public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_UP){ } else if(e.getKeyCode() == KeyEvent.VK_DOWN){ } else if(e.getKeyCode() == KeyEvent.VK_LEFT){ } else if(e.getKeyCode() == KeyEvent.VK_RIGHT){ } else if(e.getKeyCode() == KeyEvent.VK_ESCAPE){ } } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } } </code></pre> <p>Now the problem appears when I try to edit the "head" y and x values as seen in the second class.</p> <pre><code>if(e.getKeyCode() == KeyEvent.VK_DOWN){ game.head.y += 10; </code></pre> <p>What am I doing wrong here and is there a better way to pass and set x and y values more efficiently.</p>
38,854,818
0
How twitter ios app is doing to push the profile page with a new UINavigationController <p>I wondering how Twiter is doing, in the ios app, to push a profile viewController with a new navbar or a new navigationController above the current viewController ?</p> <p><a href="https://i.stack.imgur.com/zKp9i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zKp9i.png" alt="enter image description here"></a></p>
25,683,894
0
<p>try with below code :-</p> <pre><code>if (Request.Cookies["AdminPrintModule"] != null) { HttpCookie cookie = Request.Cookies["AdminPrintModule"]; test = cookie["PrinterSetting2"].ToString(); } </code></pre> <p>Have a look at this document <a href="http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/" rel="nofollow">http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/</a> :-</p> <p>Below are few types to write and read cookies :-</p> <blockquote> <p>Non-Persist Cookie - A cookie has expired time Which is called as Non-Persist Cookie </p> <p>How to create a cookie? Its really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie </p> <blockquote> <p>Example 1: </p> <pre><code> HttpCookie userInfo = new HttpCookie("userInfo"); userInfo["UserName"] = "Annathurai"; userInfo["UserColor"] = "Black"; userInfo.Expires.Add(new TimeSpan(0, 1, 0)); Response.Cookies.Add(userInfo); </code></pre> <p>Example 2: </p> <pre><code> Response.Cookies["userName"].Value = "Annathurai"; Response.Cookies["userColor"].Value = "Black"; </code></pre> <p><strong>How to retrieve from cookie?</strong> </p> <p>Its easy way to retrieve cookie value form cookes by help of Request object. Example 1: </p> <pre><code> string User_Name = string.Empty; string User_Color = string.Empty; User_Name = Request.Cookies["userName"].Value; User_Color = Request.Cookies["userColor"].Value; </code></pre> <p>Example 2: </p> <pre><code> string User_name = string.Empty; string User_color = string.Empty; HttpCookie reqCookies = Request.Cookies["userInfo"]; if (reqCookies != null) { User_name = reqCookies["UserName"].ToString(); User_color = reqCookies["UserColor"].ToString(); } </code></pre> </blockquote> </blockquote>
25,409,953
0
Are there specific rules for defining a function in C? <p>I am writing a script that can process .c and .h files. Using regular expressions I am finding all functions within a given file. During my experiences with C I always defined functions in the following manner:</p> <pre><code>void foo(int a){ //random code } </code></pre> <p>Is it possible to declare a function in the following manner: </p> <pre><code>void foo(int a){ //random code } </code></pre> <p>I always assumed that the function type, name, and parameters needed to be in the same line, but I've been told otherwise so I'm not exactly sure. </p>
33,274,822
0
<p>First check the Gemfile is present in server or not.</p> <p>If present, then specify the location in your configuration file by adding below code.</p> <blockquote> <p><code>set :bundle_gemfile, "rails_code/Gemfile"</code></p> </blockquote>
24,177,890
0
Group by STRING and sum another field as you group <p>I just recently got a job maintaining an app that stores some products in a table. In the table there is the quantity of the product. There are a random number of records in the table so one product could have 1 to n records inside. Because I wasn't designing the app someone made the table this way, (If it was me, I'd create a new table just for products then group by id, would work great I presume, but I cant change it now.). Now I have a problem since I never did this before (Not on MSSQL and not on SQLite for that matter). How would you group by product name and sum the quantity of grouped items? </p> <p>This doesn't work but probabbly I can be more clear what i want:</p> <pre><code>SELECT Name, Quantity FROM products GROUP BY Name </code></pre> <p>(there is SUM somewhere here, but if I put sum on quantity this will probabbly just return the sum of all quantities not just the ones grouped.</p> <p>Another example (these are records in the table):</p> <pre><code>NAME Quantity ItemA 1 ItemA 7 ItemB 8 ItemC 1 ItemB 2 </code></pre> <p>The desired result of the query to fetch all elements but grouped would be:</p> <pre><code>ItemA 8 ItemB 10 ItemC 1 </code></pre>
12,734,612
0
<p>While your particular case concerns Windows Azure specific (the 4 minute timeout of LBs), the question is pure IIS / ASP.NET workwise. Anyway, I don't think it is possible to send "ping-backs" to the client while in AsyncController/AsyncPage. This is the whole idea of the AsyncPages/Controllers. The IIS leaves the socket aside having the thread serving other requests. And gets back only when you got the OutstandingOperations to zero with AsyncManager.OutstandingOperations.Decrement(); Only then the control is given back to send final response to the client. And once you are the point of sending response, there is no turning back. </p> <p>I would rather argue for the architectural approach of why you thing someone would wait 4 minutes to get a response (even with a good animated "please wait")? A lot of things may happen during this time. From browser crash, through internet disruption to total power loss/disruption at client. If you are doing real Azure, why not just send tasks for a Worker Role via a Queue (Azure Storage Queues or Service Bus Queues). The other option that stays in front of you for so long running tasks is to use SingalR and fully AJAXed solution. Where you communicate via SignalR the status of the long running operation.</p> <p><strong>UPDATE 1 due to comments</strong></p> <p>In addition to the approach suggested by @knightpfhor this can be also achieved with a Queues. Requestor creates a task with some Unique ID and sends it to "Task submission queue". Then "listens" (or polls at regular/irregular intervals) a "Task completion" queue for a message with given Task ID. </p> <p>In any way I don't see a reason for keeping client connected for the whole duration of the long running task. There are number of ways to decouple such communication.</p>
1,014,515
0
<p>An IronPython or IronRuby project can be compiled to a dll or executable just fine and will be 'real' executables in every way with the proviso that the person running them must have the relevant .Net framework and dependencies installed (dependencies may be present in the same directory by default instead but the framework must be installed). The integration with Visual Studio is still not there but projects like <a href="http://www.codeplex.com/IronPythonStudio" rel="nofollow noreferrer">IronPythonStudio</a> use the free VS Shell to good effect. The existence of the DLR as a dependency for c# dynamic in VS 2010 should mean that integration with VS from the Iron* groups becomes an easier goal and a higher priority.</p> <p>The result is in no way interpreted (the CIL is jitted into machine code at runtime or via ngen if desired) and certain aspects of the DLR mean some actions are deferred in a similar fashion to latebinding but more powerfully and crucially with some sophisticated caching mechanisms to allow this to be relatively fast compared with naive interpreters.</p> <p>Many traditionally interpreted scripting languages are creating their own VM based compilation strategies or leverage existing ones (like the JVM, the .Net CLR or open ones like the <a href="http://llvm.org/" rel="nofollow noreferrer">LLVM</a>) since this leads to significant performance increases in many common cases. </p> <p>In the case of the Iron* languages the benefit of the MS CLR as a basis is that the resulting executables 'Just Work' on the vast majority of installations of the most common OS family. Contrast to Java where a jar file is not 'runnable' by directly clicking / or 'executing' via the shell in many operating systems. The flipside from this is that this reduces interoperability compared to say a JVM or LLVM based solution where the platform support is broader but, inevitably, more diverse in OS integration.</p>
39,345,374
0
Open two tcp connection using TcpListener class on both side <p>I want to open tcp connection between two machine. I want to use the class TcpListener on the client side and on the server side and by this to have the option to make the two side 'talk' with the other by sending and receiving byte[]. </p> <p>That mean that each side is a server and a client. </p> <p>I using the code from msdn to do it. But on this code the server start and wait till the client will connect to him. </p> <p>If i doing so on the both sides i will fail. Is there any other way ? </p> <p>The code:</p> <pre><code>public static void Main() { TcpListener server=null; try { // Set the TcpListener on port 13000. Int32 port = 13000; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); // TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); // Buffer for reading data Byte[] bytes = new Byte[256]; String data = null; // Enter the listening loop. while(true) { Console.Write("Waiting for a connection... "); // Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. TcpClient client = server.AcceptTcpClient(); Console.WriteLine("Connected!"); data = null; // Get a stream object for reading and writing NetworkStream stream = client.GetStream(); int i; // Loop to receive all the data sent by the client. while((i = stream.Read(bytes, 0, bytes.Length))!=0) { // Translate data bytes to a ASCII string. data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); Console.WriteLine("Received: {0}", data); // Process the data sent by the client. data = data.ToUpper(); byte[] msg = System.Text.Encoding.ASCII.GetBytes(data); // Send back a response. stream.Write(msg, 0, msg.Length); Console.WriteLine("Sent: {0}", data); } // Shutdown and end connection client.Close(); } } catch(SocketException e) { Console.WriteLine("SocketException: {0}", e); } finally { // Stop listening for new clients. server.Stop(); } Console.WriteLine("\nHit enter to continue..."); Console.Read(); } </code></pre>
14,186,873
0
What's the best practice to code shared enums between classes <pre><code>namespace Foo { public enum MyEnum { High, Low } public class Class1 { public MyEnum MyProperty { get; set; } } } </code></pre> <p><code>MyEnum</code> is declared outside <code>Class1</code> cause I need it here and in other classes</p> <p>Seems good, but what if I decide later to delete the file containing<code>Class1</code>?</p> <p><code>MyEnum</code> declaration will be lost!!</p> <p>What's the best practice to code shared enums between classes?</p>
8,376,715
0
colorbox new attribute for class ids <p>in colorbox there are two vars ;</p> <pre><code> // Abstracting the HTML and event identifiers for easy rebranding colorbox = 'colorbox', prefix = 'cbox', </code></pre> <p>Can I change these via a jquery function when i call colorbox.</p> <p>Thanks in advance.</p>
17,177,976
0
<p>I had the same issue.</p> <p>But I found another solution. I used the artisan worker as is, but I modified the 'watch' time. By default(from laravel) this time is hardcoded to zero, I've changed this value to 600 (seconds). See the file: 'vendor/laravel/framework/src/Illuminate/Queue/BeanstalkdQueue.php' and in function 'public function pop($queue = null)'</p> <p>So now the work is also listening to the queue for 10 minutes. When it does not have a job, it exits, and supervisor is restarting it. When it receives a job, it executes it after that it exists, and supervisor is restarting it.</p> <p>==> No polling anymore!</p> <p>notes: </p> <ul> <li>it does not work for iron.io queue's or others. </li> <li>it might not work when you want that 1 worker accept jobs from more than 1 queue.</li> </ul>
4,045,883
0
<p>You might want to get a command line to modify metadata. Some tools modify both native and XMP metadata.</p> <p>I wrote a blog on metadata editing a while ago: <a href="http://www.barcodeschool.com/2010/09/publishers-fix-the-metadata-in-the-pdf-file/" rel="nofollow">http://www.barcodeschool.com/2010/09/publishers-fix-the-metadata-in-the-pdf-file/</a></p>
37,307,920
0
<p>You should implement this in your SQL using a case statement.</p> <p><a href="https://dev.mysql.com/doc/refman/5.7/en/case.html" rel="nofollow">https://dev.mysql.com/doc/refman/5.7/en/case.html</a></p> <p>The above answers using the IF() function are correct, but in my opinion it is better to use the CASE-WHEN so as to match other database engines like Microsoft SQL Server and Oracle.</p>
29,623,571
0
<pre><code>// Global Declaration Intent intent; String imageFileName,videoFileName; Uri uri; private void clickPhotoFromCamera() { intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); imageFileName = "JPEG_" + timeStamp + ".jpg"; File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), imageFileName); uri = Uri.fromFile(imageStorageDir); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent, 1); } private void captureVideoFromCamera() { intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); videoFileName = "VID_" + timeStamp + ".mp4"; File videoStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), videoFileName); uri = Uri.fromFile(videoStorageDir); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent, 2); } private void uploadMediaFromGallery() { intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); intent.setType("image/* video/*"); startActivityForResult(intent, 3); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == 1) { imagePath = uri.getPath(); // Do whatever you want with image path... } else if (requestCode == 2) { videoPath = uri.getPath(); // Do whatever you want with Video path... } else { uri = data.getData(); mediaPath = getPath(getApplicationContext(), uri); } } } </code></pre> <p><Br> // For get Image or video from path...</p> <pre><code>File mediaFile = new File(mediaPath); Bitmap bitmap; if (mediaFile.exists()) { if (isImage(mediaPath)) { Bitmap myBitmap = BitmapFactory.decodeFile(mediaFile.getAbsolutePath()); int height = (myBitmap.getHeight() * 512 / myBitmap.getWidth()); Bitmap scale = Bitmap.createScaledBitmap(myBitmap, 512, height, true); int rotate = 0; try { exif = new ExifInterface(mediaFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); switch (orientation) { case ExifInterface.ORIENTATION_NORMAL: rotate = 0; break; case ExifInterface.ORIENTATION_ROTATE_270: rotate = 270; break; case ExifInterface.ORIENTATION_ROTATE_180: rotate = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: rotate = 90; break; } Matrix matrix = new Matrix(); matrix.postRotate(rotate); Bitmap rotateBitmap = Bitmap.createBitmap(scale, 0, 0, scale.getWidth(), scale.getHeight(), matrix, true); displayImage.setImageBitmap(rotateBitmap); } else { bitmap = ThumbnailUtils.createVideoThumbnail(mediaPath, Thumbnails.MICRO_KIND); displayImage.setImageBitmap(bitmap); } } public static boolean isImage(String str) { boolean temp = false; String[] arr = { ".jpeg", ".jpg", ".png", ".bmp", ".gif" }; for (int i = 0; i &lt; arr.length; i++) { temp = str.endsWith(arr[i]); if (temp) { break; } } return temp; } </code></pre>
35,520,933
0
<p>It can be checked with this.</p> <pre><code>bool isLettersOnly = !word.Any(c =&gt; !char.IsLetter(c)); </code></pre>
33,919,527
0
smbclient: command not found <p>I would like to connect to a remote server with the <code>smbclient</code> command and pass some arguments to the script.</p> <p>Here is my command:</p> <pre><code>smbclient //$SERVER -c 'cd $PATH;get $FILE /tmp/$FILE' $PASS -U$PSEUDO -W domain </code></pre> <p>When I launch this command without variables on the command line it works. But when I use it in the script it says:</p> <pre><code>./test1.sh: line 14: smbclient: command not found </code></pre> <p>Why is that?</p> <pre><code>Here is my complete script with for exemple arguments testSRV, testPATH and testFile : \#! /bin/bash SERVEUR=$1 PATH=$2 FILE=$3 echo $PATH #Return testPATH echo $FILE #Return testFILE \#COMPLETEPATH="cd $testPATH;get $testFILE /tmp/$testFILE" \#echo $COMPLETEPATH //return /usr/bin/smbclient //$SERVER -c 'cd $PATH;get $FILE' testpassword -U testuser -W testdomain </code></pre>
14,211,086
0
Enable animation with blend using property binding condition <p>I am working with blend 4, I am trying to play some StoryBoard using ControlStoryBoardAction with the contidion: if a specific Border Element in my UC has greater width then 250.</p> <p>I set the next configuration: <img src="https://i.stack.imgur.com/KGs2g.png" alt="Set data binding"></p> <p><img src="https://i.stack.imgur.com/Zm5Cb.png" alt="Config ControlStoryBoardAction "></p> <p>And when I run my application I am getting the following error:</p> <p>LeftOperand of type "OpeningViewModel" cannot be used with operator "GreaterThan". Source=Microsoft.Expression.Interactions</p> <p>What I am doing wrong? How can I launch StoryBoard with element property condition?</p>
15,329,227
0
<p>public class twoTimes </p> <p>{</p> <pre><code> public static void main(String[] args) { for ( int i=1; i&lt;11; i++)//; &lt;----- Due to this it is not working { System.out.println("count is" + i); } } </code></pre> <p>}</p>
5,226,456
0
<p>Here's your problem:</p> <pre><code>.Where(s =&gt; s.ID == 1).FirstOrDefault(); </code></pre> <p>this will obviously return the same object on each iteration. And I'm guessing that theStat has an ID of 1, which is why it is updated.</p>
39,179,867
0
Laravel : Error messaging not working <p>Hello friends I have a form when i enter correct value and pressing submit button i am getting success message </p> <p>if i am entering wrong value then <strong>i am not getting error message please suugest something</strong></p> <p><strong>Controller</strong></p> <pre><code> if($getHours &lt;= 16) { DB::table('labors')-&gt;insert($labors_data); session::flash('status', 'Labor Timesheet Added Successfully'); return Redirect:: to('ViewLaborD2S'); } else { session::flash('status', 'You have entered More than 16 Hours'); return Redirect:: to('ViewLaborD2S'); } </code></pre> <p><strong>View</strong></p> <pre><code> @if (session('status')) &lt;div class="alert alert-success"&gt; &lt;p style="text-align:center;"&gt;{{ session('status') }}&lt;/p&gt; &lt;/div&gt; @else(session('message')) &lt;div class="alert alert-danger"&gt; &lt;p style="text-align:center;"&gt;{{ session('message') }}&lt;/p&gt; &lt;/div&gt; @endif </code></pre> <p>I want to show Success message if i entered correct value and if i enter wrong value show error message</p>
28,697,204
0
<pre><code>x = {"job" =&gt; 1, "big job" =&gt; 2, "super job" =&gt; 1, "work" =&gt; 2, "super big job" =&gt; 1} p x.sort_by{|x,|-x.split.size}.to_h #=&gt; {"super big job"=&gt;1, "big job"=&gt;2, "super job"=&gt;1, "work"=&gt;2, "job"=&gt;1} </code></pre>
17,935,283
0
How to get all the parent classes of a derived class in C# Reflection <p>It is weird that I was not able to find a similar question but this is what actually I want, finding all the parent classes of a derived class. </p> <p>I tested a code with a hope that it works for me :</p> <pre><code>void WriteInterfaces() { var derivedClass = new DerivedClass(); var type = derivedClass.GetType(); var interfaces = type.FindInterfaces((objectType, criteria) =&gt; objectType.Name == criteria.ToString(),"BaseClass"); foreach(var face in interfaces) { face.Name.Dump(); } } interface BaseInterface {} class BaseClass : BaseInterface {} class BaseClass2 : BaseClass {} class DerivedClass : BaseClass2{} </code></pre> <p>Basically, here my main intention is to check if a derived class somehow inherits a base class somewhere in its base hierarchy.</p> <p>However, this code returns null and works only with interfaces.</p>
2,854,088
0
Serialize struct with pointers to NSData <p>I need to add some kind of archiving functionality to a Objective-C Trie implementation (<a href="http://github.com/nathanday/ndtrie" rel="nofollow noreferrer">NDTrie</a> on github), but I have very little experience with C and it's data structures.</p> <pre><code>struct trieNode { NSUInteger key; NSUInteger count, size; id object; __strong struct trieNode ** children; __strong struct trieNode * parent; }; @interface NDTrie (Private) - (struct trieNode*)root; @end </code></pre> <p>What I need is to create an <code>NSData</code> with the tree structure from that root - or serialize/deserialize the whole tree some other way (conforming to <code>NSCoding</code>?), but I have no clue how to work with <code>NSData</code> and a C struct containing pointers.</p> <p>Performance on deserializing the resulting object would be crucial, as this is an iPhone project and I will need to load it in the background every time the app starts.</p> <p>What would be the best way to achieve this?</p> <p>Thanks!</p>
34,662,032
0
<p>When working with HTTP content (which is the case of Safari and Mail app), you must not forget to handle its content type. The <a href="https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html" rel="nofollow">Uniform Type Identifier</a> (UTI) for handle content type is <code>public.mime-type</code> and let's say that the content type header of a server response is set to <em>application/gpx</em>, so in your <em>plist</em> you must add to the <code>UTTypeTagSpecification</code> section:</p> <pre><code>&lt;dict&gt; &lt;key&gt;public.filename-extension&lt;/key&gt; &lt;array&gt; &lt;string&gt;GPX&lt;/string&gt; &lt;string&gt;gpx&lt;/string&gt; &lt;/array&gt; &lt;key&gt;public.mime-type&lt;/key&gt; &lt;string&gt;application/gpx&lt;/string&gt; &lt;/dict&gt; </code></pre> <p><strong>Note</strong>: I've seen <em>application/gpx</em> and <em>application/gpx+xml</em> as content type for GPX data around web and I don't know if there's a standard mime type so it's better to use both.</p>
20,662,268
0
<p>try to write <code>Range("c" &amp; row).FormulaR1C1=temp</code></p>
36,312,102
0
<p>In your INSTALLED_APPS </p> <pre><code>INSTALLED_APPS = [ ..., 'HdfsstatsConfig', ] </code></pre> <p>in your views.py</p> <pre><code>from .viewcreator import Builder </code></pre> <p><strong>UPDATE, DJANGO IMPORTS</strong></p> <p>There are 3 ways to imports module in django </p> <p><strong>1. Absolute import:</strong> Import a module from outside your current application Example from myapp.views import HomeView <a href="https://i.stack.imgur.com/9YJky.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9YJky.png" alt="enter image description here"></a></p> <p><strong>2. Explicit import:</strong> Import a module from inside you current application <a href="https://i.stack.imgur.com/QqIer.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QqIer.png" alt="enter image description here"></a></p> <p><strong>3. Relative import:</strong> Same as explicit import but <strong>not recommended</strong></p> <pre><code>from models import MyModel </code></pre> <p><a href="https://i.stack.imgur.com/ngCKg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ngCKg.png" alt="enter image description here"></a></p>
27,548,347
0
<p>First, remove stuff that shouldn't be there:</p> <pre><code>$str = preg_replace('/[^PDL\d-]/i', '', $str); </code></pre> <p>That gives you the following normalised results:</p> <pre class="lang-none prettyprint-override"><code>D456789-1 D456789-1 D456789-1ldlddld </code></pre> <p>Then, attempt to match the data you want:</p> <pre><code>if (preg_match('/^([PDL])(\d+-\d)/i', $str, $match)) { $code = $match[1]; $load = $match[2]; } else { // uh oh, something wrong with the format! } </code></pre>
15,755,847
0
<p>I presume you want the strings instead of the numerical values, correct?</p> <pre><code>s = '' for j in range(30, 0, -1): s += "{}/{} + ".format(31-j, j) print s[:-2] </code></pre> <p>Read <a href="http://docs.python.org/3/library/string.html#format-string-syntax" rel="nofollow">this documentation</a> to get a grasp of it. Essentially, it's formatting the string, using the two pairs of curly braces as placeholders, and passing in the value 31-j in the first slot, and j in the second.</p> <p>Surely there is a more elegant way to do it, but this is the quick and dirty method.</p>
29,487,821
0
<p>You are using django 1.6.5, in this version migrations were not introduced so its may give you error on running migrations because django rest framework auth token migration tries to import migrations from django.db</p> <p>Upgrade your south package from 0.8.4 to 1.0.1 version that will solve your problem Please check the following link related to south version 1.0.1 <a href="http://south.readthedocs.org/en/latest/releasenotes/1.0.html" rel="nofollow">http://south.readthedocs.org/en/latest/releasenotes/1.0.html</a></p>
7,613,322
0
<p>I am trying to build a huge central for 9-patch images.</p> <p>Feel free to visit and grab whatever you need from there.</p> <p>As long as it is for building your android applications :)</p> <p><a href="http://android9patch.blogspot.com/">http://android9patch.blogspot.com/</a></p>
23,475,818
0
SpannableStringBuilder cannot be cast to android.text.SpannableString <p>I need to save data from <code>TextView</code> to and SQLite database in HTML format.</p> <p>I'm using this code to convert text from <code>TextView</code> to HTML-formatted string:</p> <pre><code>public static String htmlToString(TextView textview) { SpannableString contentText = (SpannableString) textview.getText(); return Html.toHtml(contentText).toString(); } </code></pre> <p>However, I get this error:</p> <blockquote> <p>05-05 17:01:37.033: E/AndroidRuntime(14295): java.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to android.text.SpannableString</p> </blockquote> <p>How can I fix this?</p>
39,739,495
0
<p>I think you need:</p> <pre><code>print (data[0].min(axis=1)) 0 3662.1 1 3660.0 2 3659.5 3 3660.0 4 3661.5 5 3662.6 6 3661.5 7 3660.0 8 3661.5 9 3662.1 10 3660.0 11 3661.0 12 3664.1 13 3664.1 14 3661.5 15 3661.0 ... ... </code></pre> <p>Maybe beter is omit <code>flow = pd.DataFrame(data)</code> and use:</p> <pre><code>data = [pd.read_csv(f, index_col=None, header=None) for f in temp] mins = [df.min(axis=1) for df in data[0]] print (mins[0]) print (mins[1]) </code></pre>
8,308,369
0
<p>You can store anything you like in localStorage provided the item stored is turned into a string, no problem in your case, and the total storage doesn't exceed 5Mb per site.</p> <p>You approach could something like this.</p> <ol> <li>When the page loads (use jQuery) check if the base HTML template is there</li> <li>If not use jQuery to load it and store it in localStorage</li> <li>use a jQuery selector to select the appropriate element in the current page. This could be the element. And use $(...).html(stored html template); to display the base html.</li> <li>If you need to insert dynamic values use something like John Resig <a href="http://ejohn.org/blog/javascript-micro-templating/" rel="nofollow">MicroTemplating</a> to insert variables.</li> </ol>
20,248,466
0
<p><code>Nancy.Testing</code> does not use any network communication at all. If you can think of a nice abstract then please let us know and we can talk and see if it's something we'd like to get into the package!</p>
12,448,760
0
<p>There are better ways to solve your problem. The typical protocol I use is:</p> <ul> <li>Register a window message using <a href="http://www.google.de/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;ved=0CCAQFjAA&amp;url=http://msdn.microsoft.com/en-us/library/windows/desktop/ms644947%28v=vs.85%29.aspx&amp;ei=AP9VUOGwEM7asgbEwoGQDw&amp;usg=AFQjCNHLyesu0zvZPqoRPseqiIB_aU4yAA&amp;sig2=D5DF_rScIHllWpasvxGK5g" rel="nofollow"><code>RegisterWindowMessage</code></a> in both applications. The message name should contain a GUID to make it unique</li> <li>In Application A, use<br> <code>PostMessage(HWND_BROADCAST, registeredMsg, idIWantToFindYou, HWNDofA)</code><br> to publish <em>your</em> window handle to all top level windows. since there's more than one use for registered messages, and you should limit the number of messages you register, use <code>idIWantTofindYou</code> to distinguish between different commands for your message. </li> <li>The receiving application(s) B now have the window handle of the sender, and can establish a connection (e.g. by<br> <code>PostMessage(HWNDofA, registeredMessage, idHereIsMyHWnd, HWNDofB)</code></li> </ul> <p>The upside of this mechanism is not running into problems with unresponsive programs. However, the "connection" isn't immediate, so you have to change your program flow. Alternatively, you can use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms633497%28v=vs.85%29.aspx" rel="nofollow"><code>EnumWindows</code></a> and <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms644952%28v=vs.85%29.aspx" rel="nofollow"><code>SendMessageTimeout</code></a> to probe all top-level windows.</p> <hr> <p>If you need to use the window class: </p> <p>The class name assigned by MFC is only so window classes with the same attributes get reused. I am not aware of any problems with using your own window classes. </p> <p>So the following <em>should</em> work:</p> <ul> <li>Fill a <code>WNDCLASS</code> or <code>WNDCLASSEX</code> with the required attributes</li> <li>Use <code>DefWindowProc</code> as <code>WNDPROC</code> (that's what MFC does, MFC's <code>WNDPROC</code> is set when creating the window)</li> <li>Use <a href="http://msdn.microsoft.com/en-us/library/kcb1w44w%28VS.80%29.aspx" rel="nofollow"><code>AfxRegisterClass</code></a> or <code>RegisterClass</code> to register the window class. <code>AfxRegisterClass</code> checks if the class is already registered and if the class is registered from a DLL, it will unregister the class when the DLL is unloaded. Otherwise they are roughly equivalent. </li> </ul>
4,353,080
0
Testing on a single-core PC with hyperthreading <p>If a multithreaded program runs safe on a single-core CPU with hyperthreading, will it also run safe on a dual-core CPU with hyperthreading? Concerning thread-safety etc.</p> <p>EDIT</p> <p>Ok, I try to be more specific. I mean the bad source code lines, where I will have forgotten or failed to make sure, that they won't be an (concurrency) issue.</p> <p>So, maybe the 1-core htt "lies" by preventing dead-locks, crashes, cpu spikes or anything that my code causes on a 2-core machine. I'm unsure, how exactly 2 (logical) processors of a htt PC are different from 2 processors of a dual-core PC, how transparent htt is. If there's any issue, I'll probably buy a second PC just for that, that's why I asked.</p>
27,412,177
0
custom pager for knockout arrayBinding <p>i need to make a custom pager like [&lt;] 1 2 3 4 ... > for a knockout binding array with 5 items. The items are in an article cuote .</p> <p>I already tried with some examples aviables on internet, but i'm new in this matters so i didn't solve the issue.</p> <p>Can someone tell me how i can do this? greetings comunity!</p>
7,034,090
0
<p>The class is being applied by the date picker plug-in, probably using the <code>addClass</code> function. The plug-in, when it's initialized, probably creates a <code>DIV</code> (<code>id=;dp-popup'</code>) that has the necessary values for the current month. That <code>DIV</code> is hidden (<code>display:none</code>) but still has the class of dp-popup when first initialized. When you click in the textbox or click the button, there's an event handler assigned to those events (<code>focus</code> for the textbox, <code>click</code> for the button) that sets the display style of the <code>DIV</code> to not be hidden and it also positions it right below the text box.</p> <p>I didn't dig into the code a whole lot, but looking at the markup a little, that's how I suspect it's working.</p>
36,002,165
0
How do you reduce Vertex cover to Hamiltonian Cycle? <p><a href="http://i.stack.imgur.com/HH8Bp.jpg" rel="nofollow">This is the example the book uses</a></p> <p>The book I'm using is Introduction to Algorithms 3rd edition. Anyway they explain how to reduce Vertex Cover to Hamiltonian Cycle to prove Hamiltonian Cycle is NP complete. I understand that for every edge in the vertex cover you need to create a widget, and I understand that for every member of the vertex cover you have a selector. However what's giving me problems is the method of moving through the widgets. There is a formula but it seems very arbitrary to me. Could anyone explain it in simpler terms? I'd much appreciate it.</p> <p>Edit: I also understand there exist three different ways in which you have traverse a widget.</p>
11,258,645
0
<p>Judging on your "desired output" image, your usage of kmeans is wrong. The pixel coordinates should play no role in the clustering. You should only hand the color triplets to kmeans.</p> <pre><code>sample = cvCreateMat( image-&gt;height*image-&gt;width, 3, CV_32FC1 ); </code></pre> <p>…</p> <pre><code> for(j=0;j&lt;image-&gt;width;j++) { b = data[i*image-&gt;widthStep + j*image-&gt;nChannels +0]; g = data[i*image-&gt;widthStep + j*image-&gt;nChannels +1]; r = data[i*image-&gt;widthStep + j*image-&gt;nChannels +2]; cvSetReal2D( sample, k, 0, b); cvSetReal2D( sample, k, 1, g); cvSetReal2D( sample, k, 2, r); k++; } </code></pre> <p>Then you also have an indexing bug further down the road when setting data.</p>
5,489,502
0
How to get previous month and year relative to today, using strtotime and date? <p>I need to get previous month and year, relative to current date.</p> <p>However, see following example.</p> <pre><code>// Today is 2011-03-30 echo date('Y-m-d', strtotime('last month')); // Output: 2011-03-02 </code></pre> <p>This behavior is understandable (to a certain point), due to different number of days in february and march, and code in example above is what I need, but works only 100% correctly for between 1st and 28th of each month.</p> <p>So, how to get last month AND year (think of <code>date("Y-m")</code>) in the most elegant manner as possible, which works for every day of the year? Optimal solution will be based on <code>strtotime</code> argument parsing.</p> <p>Update. To clarify requirements a bit.</p> <p>I have a piece of code that gets some statistics of last couple of months, but I first show stats from last month, and then load other months when needed. That's intended purpose. So, during THIS month, I want to find out which month-year should I pull in order to load PREVIOUS month stats.</p> <p>I also have a code that is timezone-aware (not really important right now), and that accepts <code>strtotime</code>-compatible string as input (to initialize internal date), and then allows date/time to be adjusted, also using <code>strtotime</code>-compatible strings.</p> <p>I know it can be done with few conditionals and basic math, but that's really messy, compared to this, for example (if it worked correctly, of course):</p> <pre><code>echo tz::date('last month')-&gt;format('Y-d') </code></pre> <p>So, I ONLY need previous month and year, in a <code>strtotime</code>-compatible fashion.</p> <p>Answer (thanks, @dnagirl):</p> <pre><code>// Today is 2011-03-30 echo date('Y-m-d', strtotime('first day of last month')); // Output: 2011-02-01 </code></pre>
28,790,503
0
Are there security measures against udp hole punching? <p>I want to establish an UDP communication between two peers, say Alice and Bob. Alice is behind a port restricted cone NAT (so that the same internal port gets mapped to the same external port even if the destination is changed), while Bob is behind a symmetric NAT (which means that the external port will change every time a new destination is chosen regardless of the internal port, thus making the external port unpredictable). I have a server in between and I want to make an UDP hole punch.</p> <p>I implemented the following strategy:</p> <ul> <li>Bob opens a large number of ports and from all of them sends a packet to Alice's external port (he gets to know if through the server).</li> <li>Alice sends packets to Bob's NAT at random ports until the connection is established.</li> </ul> <p>Having two NATs of those types at hand, I did some experiments. Bob opens 32 ports, and Alice sends 64 packets every 0.1 seconds. The connection is usually established within 1 or 2 seconds, which is more than suitable for my needs.</p> <p>However, I was wondering if I could get in trouble with some strict NAT routers or firewalls. On example, could it happen that a router won't allow an internal peer to open 32 ports? Or (and this sounds somehow more likely) could it happen that a router that sees a lot of packets incoming on random ports that get dropped will blacklist the ip and drop all its packets for some time? I read that sometimes this could happen in case of a DoS attack but my packet rate is something like 4 to 6 orders of magnitude lighter than a DoS attack.</p> <p>I am asking about reasonable network configuration: I am pretty sure that in principle it is possible to setup a firewall to behave in that way. I will be targeting mainly users that lie behind standard home connections, so my main target is common internet providers that use NATs.</p>
39,697,387
1
Real-time Synchronize data between two python application <p>Im going to have two python scripts. one is server and another one is client. the server is used to get information from Network Devices like Router or Switch via SNMP. The client needs to get the data from server and output to users.</p> <p>My algorithm is to let server store all data from snmp into MySQL every minute. Then client reads data from Mysql and show out to user interface every minute also. </p> <p>I would like to know if there is any other better way to synchronize data between server and client?</p> <p>Thank in advance. </p>
10,645,240
0
<p>Your first example you have no period before <code>'ui-state-highlight'</code> so you are trying to select elements with a TYPE of ui-state-highlight (as opposed to a type of DIV, INPUT, SELECT, etc)</p> <pre><code> $('ui-state-highlight') </code></pre> <p>Your second example you actually select elements with a class of 'ui-state-default'</p> <pre><code> $('.ui-state-default') </code></pre> <p><strong>Edit:</strong> Based on your corrections I am guessing that the problem here is that you may be trying to get the background color for any elements with the ui-state-highlight class but there aren't any actually displayed on your page.</p> <p>Try the following code, based on answer to <a href="http://stackoverflow.com/questions/2707790/get-a-css-value-from-external-style-sheet-with-javascript-jquery">Get a CSS value from external style sheet with Javascript/jQuery</a></p> <pre><code>var $p = $("&lt;p class='ui-state-highlight'&gt;&lt;/p&gt;").hide().appendTo("body"); input = $p.css("background"); $p.remove(); </code></pre> <p>You create a new <code>&lt;p&gt;&lt;/p&gt;</code> temporarily and then grab the background color off it before removing it.</p>
39,975,924
0
<p>try this</p> <pre><code>Option Explicit Sub test() Dim j As Long Dim rng As Range, cell As Range Dim i As Long j = Application.InputBox("No. of rows to be inserted?", Type:=1) With Worksheets("REFS") '&lt;-_| change "REFS" to your actual worksheet name i = 1 With .Range("D2", .Cells(.Rows.Count, "D").End(xlUp)) Do While i &lt;= .Rows.Count With .Cells(i).EntireRow .Copy .Offset(1).Resize(j).Insert Shift:=xlDown Application.CutCopyMode = False End With i = i + j + 1 Loop End With End With End Sub </code></pre> <p>I'm using <a href="https://msdn.microsoft.com/en-us/library/office/ff839468(v=office.15).aspx" rel="nofollow">Application.InputBox()</a> method instead of <a href="https://msdn.microsoft.com/en-us/library/office/aa195768(v=office.11).aspx" rel="nofollow">VBA InputBox()</a> one because the former lets you force the user input data type (in the example Type:=1 forces <em>numeric</em> input)</p>
25,040,579
0
Variables initialized as long ints in for loop cause crash <p>Using MinGW C compiler, this code crashes my program. NN has value 439470944 and NN and j are initialized as long-integers.</p> <pre><code>float *F=NULL; F = (float *)malloc(NN*sizeof(float)); for(j=0; j&lt;NN;j++) F[j] = 0; // ensure F[] starts empty. </code></pre>
37,314,219
0
<p>First, of course, your application must declare that it is doing serial communication in the application manifest: </p> <pre><code>&lt;DeviceCapability Name="serialcommunication"&gt; &lt;Device Id="vidpid:xxxx xxxx"&gt; &lt;Function Type="name:serialPort"/&gt; &lt;/Device&gt; &lt;/DeviceCapability&gt; </code></pre> <p>Could this be the missing bit?</p>
12,825,367
0
<p>You should have no problem. Just add your own event handler using jQuery's API and you'll be set. From the jQuery Docs on <code>.on()</code>:</p> <blockquote> <p>As of jQuery 1.4, the same event handler can be bound to an element multiple times.</p> </blockquote> <pre><code>$('#myButton').on('click', myHandler) </code></pre>
12,061,689
0
<p>Found it! <a href="http://dylanmarkow.com/blog/2012/05/06/load-order-with-rubymotion/" rel="nofollow">http://dylanmarkow.com/blog/2012/05/06/load-order-with-rubymotion/</a></p>
33,201,579
0
<p>Your additional field is inside an element with</p> <pre><code>ng-if="register" </code></pre> <p>ng-if is a directive that creates its own scope. So, when something is entered into the field <code>&lt;input ng-model="email" ...&gt;</code>, an email attribute is created and populated <strong>in the ng-if scope</strong>, instead of being created in the controller scope.</p> <p>Rule of thumb: always have a dot in your ng-model, and always initialize the form model in the controller:</p> <pre><code>$scope.formModel = {}; &lt;input ng-model="formModel.email" ...&gt; </code></pre> <p>This will also make things simpler, since to post the form, all you'll have to do is something like</p> <pre><code>$http.post(url, $scope.formModel).then(...); </code></pre>
28,637,862
0
<p>Have a look at DateDiff function: <a href="http://www.w3schools.com/vbscript/func_datediff.asp" rel="nofollow">http://www.w3schools.com/vbscript/func_datediff.asp</a>. Example:</p> <pre><code>diff = DateDiff("d", "02/19/2015", "02/20/2015") ' difference in days diff = DateDiff("h", "02/19/2015", "02/20/2015") ' difference in hours diff = DateDiff("n", "02/19/2015", "02/20/2015") ' difference in mins diff = DateDiff("s", "02/19/2015", "02/20/2015") ' difference in seconds </code></pre> <p>To calculate the difference, you would need to parse out the date from the string and use DateDiff. </p> <p>The order of dates determines the output. In the example above, all values will be positive. If you revert them, output would result in negative. Providing the same date/time will result in 0.</p> <pre><code>diff = DateDiff("d", "02/20/2015", "02/19/2015") ' output = -1 diff = DateDiff("d", "02/20/2015", "02/20/2015") ' output = 0 </code></pre>
36,123,828
0
Double from CoreData returns very small number <p>I am working on a diving application, and one of the feature is to store diving's rating as double into CoreData. The interface should be able to retrieve the double value from the coredata object and then display on screen. However, the problem I got from my code is that the double returned from the object is very small (e with the power of -315). I have no idea why this is happening.</p> <pre><code>if let dives = self.diveSite?.logged_dives { for dive in dives { print("######### dive site info ########") rating = Double(dive.rating) + rating print(dive) print("raw dive site rating is \(dive.rating)") print("dive rating is \(rating)") } } else { print("no logged_dives") } </code></pre> <p>Here is what's been printed out on the console...</p> <pre><code>######### dive site info ######## &lt;ScubaDoo.DiveLog: 0x7fe9ea02cbc0&gt; (entity: DiveLog; id: 0xd000000000180002 &lt;x-coredata://2B6F1E6F-1EDA-4910-91FA-0593E05F9EB2/DiveLog/p6&gt; ; data: { current = nil; depth = 0; "dive_at" = "0xd000000000140000 &lt;x-coredata://2B6F1E6F-1EDA-4910-91FA-0593E05F9EB2/DiveSite/p5&gt;"; id = nil; latitude = 0; longitude = 0; rating = 5; "sea_condition" = nil; temperature = 0; time = nil; weather = nil; }) raw dive site rating is 5.35679601527854e-315 dive rating is 1.06203402623994e-314 dive site rating is 1.06203402623994e-314 </code></pre> <p>The DiveLog object in swift is as below. I really do not have a clue about this. It seems that something is out of bound while getting the rating properties?</p> <pre><code>import Foundation import CoreData extension DiveLog { @NSManaged var time: NSDate? @NSManaged var latitude: NSNumber? @NSManaged var id: String? @NSManaged var rating: NSNumber? @NSManaged var depth: NSNumber? @NSManaged var temperature: NSNumber? @NSManaged var weather: String? @NSManaged var current: String? @NSManaged var sea_condition: String? @NSManaged var longitude: NSNumber? @NSManaged var dive_at: DiveSite? } </code></pre>
4,758,750
0
JQuery restart setInterval <p>Sorry to be a bore but having trouble restarting a setInterval with a toggle function. I get to stop it - when needed, but I cannot get it to restart when the toggle "closes"</p> <p>Here is my code </p> <p>Set the setInterval</p> <pre><code>var auto_refresh = setInterval( function() { $('.holder').load('board.php'); }, 5000 ); </code></pre> <p>Stop on toggle - BUT want it to start on the "reverse toggle"</p> <pre><code>$('.readmore').live('click',function() { $(this).next().slideToggle('slow'); clearInterval(auto_refresh); }, function() { var auto_refresh = setInterval( function() { $('.holder').load('board.php'); }, 5000 ); }); </code></pre> <p>Help much appreciated, as is prob. very simple just I've never beed good at putting functions "within functions"</p>
13,330,043
0
Git remote branches not listed <p>So I'm trying to create a remote branch so I can push updates to a project I'm doing to my Github account, but for whatever reason, my remote branches aren't being created.</p> <p>These are the commands I am running:</p> <pre><code>git remote add origin [email protected]:&lt;username&gt;/first_app.git git push origin master </code></pre> <p>After running the first line, everything seems to work fine and I don't get any error messages. BUT, when I check what remote branches I have, nothing will show. The command I ran for that was:</p> <pre><code>git branch -r </code></pre> <p>Ignoring that I figured I would at least try the second command from above. When I did, naturally, it says:</p> <pre><code>ERROR: Repository not found </code></pre> <p>If someone could help me figure this out it would be greatly appreciated. I've been trying to find information on this online but haven't run into anything yet.</p>
27,875,459
0
<p>No, there isn't. By the time the timeout function runs, the browser will have already submitted the form and be loading the new page. </p> <p>If you want to cancel the submission <em>conditionally</em> than the closest you could come would be to <em>always</em> prevent the default form behaviour and then conditionally restart it (by calling <code>submit()</code>) in the timeout.</p>
21,829,617
0
Reducing multi-column xts to single column xts based on provided column indexes <p>I have an xts object with multiple columns of the same type. I have another xts object with integers that correspond to column positions in the first object. I would like to generate an third xts object that contains one column representing the value of the column indicated by the corresponding index. For example:</p> <pre><code># xts.1: 2003-07-30 17:00:00 0.2015173 0.10159303 0.19244332 0.08138396 2003-08-28 17:00:00 0.1890154 0.06889412 0.12700216 0.04631253 2003-09-29 17:00:00 0.1336947 0.08023267 0.09167604 0.02376319 2003-10-30 16:00:00 0.1713496 0.13324238 0.11427968 0.05946272 # xts.2: 2003-07-30 17:00:00 1 2003-08-28 17:00:00 4 2003-09-29 17:00:00 2 2003-10-30 16:00:00 3 # Desired result: 2003-07-30 17:00:00 0.2015173 2003-08-28 17:00:00 0.04631253 2003-09-29 17:00:00 0.08023267 2003-10-30 16:00:00 0.11427968 </code></pre> <p>I feel like I'm missing something very elementary about how to do this but, if so, it's escaping me at the moment.</p>
13,031,499
0
<p>Ok - here is a very basic working example of list indexing. The main change is to move the creation of the model from getModel() to prepare(). This is because getModel() is called for every value you need to set the list - so you end up re-creating your model each time overwriting the previous change.</p> <pre><code>package com.blackbox.x.actions; import java.util.ArrayList; import java.util.List; import com.blackbox.x.actions.ListDemo.ValuePair; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.Preparable; public class ListDemo extends ActionSupport implements ModelDriven&lt;List&lt;ValuePair&gt;&gt;, Preparable { private List&lt;ValuePair&gt; values; @Override public List&lt;ValuePair&gt; getModel() { return values; } public String execute() { for (ValuePair value: values) { System.out.println(value.getValue1() + ":" + value.getValue2()); } return SUCCESS; } public void prepare() { values = new ArrayList&lt;ValuePair&gt;(); values.add(new ValuePair("chalk","cheese")); values.add(new ValuePair("orange","apple")); } public class ValuePair { private String value1; private String value2; public ValuePair(String value1, String value2) { this.value1 = value1; this.value2 = value2; } public String getValue1() { return value1; } public void setValue1(String value1) { this.value1 = value1; } public String getValue2() { return value2; } public void setValue2(String value2) { this.value2 = value2; } } } </code></pre> <p>and the corresponding jsp </p> <pre><code>&lt;%@ taglib prefix="s" uri="/struts-tags" %&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;s:form action="list-demo" theme="simple"&gt; &lt;table&gt; &lt;s:iterator value="model" status="rowStatus"&gt; &lt;tr&gt; &lt;td&gt;&lt;s:textfield name="model[%{#rowStatus.index}].value1" value="%{model[#rowStatus.index].value1}"/&gt;&lt;/td&gt; &lt;td&gt;&lt;s:textfield name="model[%{#rowStatus.index}].value2" value="%{model[#rowStatus.index].value2}"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/s:iterator&gt; &lt;/table&gt; &lt;s:submit/&gt; &lt;/s:form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
35,135,273
0
<p>Using <a href="http://docs.aws.amazon.com/ssm/latest/APIReference/Welcome.html" rel="nofollow">Amazon EC2 Simple Systems Manager</a>, you can configure an SSM document to run a script on an instance, and pass that script a parameter. The Lambda instance would need to run the SSM send-command, targeting the instance by its instance id.</p> <p>Sample SSM document: run_my_example.json:</p> <pre><code>{ "schemaVersion": "1.2", "description": "Run shell script to launch.", "parameters": { "taskId":{ "type":"String", "default":"", "description":"(Required) the Id of the task to run", "maxChars":16 } }, "runtimeConfig": { "aws:runShellScript": { "properties": [ { "id": "0.aws:runShellScript", "runCommand": ["run_my_example.sh"] } ] } } } </code></pre> <p>The above SSM document accepts taskId as a parameter.</p> <p>Save this document as a JSON file, and call create-document using the AWS CLI:</p> <pre><code>aws ssm create-document --content file:///tmp/run_my_example.json --name "run_my_example" </code></pre> <p>You can review the description of the SSM document by calling <code>describe-document</code>:</p> <pre><code>aws ssm describe-document --name "run_my_example" </code></pre> <p>You can specify the taskId parameter and run the command by using the document name with the <code>send-command</code></p> <pre><code>aws ssm send-command --instance-ids i-12345678 --document-name "run_my_example" --parameters --taskid=123456 </code></pre> <p><strong>NOTES</strong></p> <ul> <li><p>Instances must be running the <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/remote-commands-prereq.html" rel="nofollow">latest version of the SSM agent</a>.</p></li> <li><p>You will need to have some logic in the Lambda script to identify the instance ids of the server EG look up the instance id of a specifically tagged instance.</p></li> </ul>
15,416,778
0
<p>Like TGMCians says, a <code>Toast</code> will do the trick.</p> <p>If you want to write it to the LogCat instead, then you can use</p> <pre><code>Log.i(tag, message) </code></pre> <p>You can then view this in the LogCat in Eclipse by going to Window > Show View > Other > Android > LogCat</p>
22,620,997
0
<p><code>XML Tools</code> from the <code>Plugin Manager</code> can do the trick as well. Then once download the plugin, tick <code>Tag auto-close</code> in <code>Plugins &gt; XML Tools</code></p>
28,913,483
0
<pre><code>$numdays = cal_days_in_month (CAL_GREGORIAN, $mon,$yr); for($i=1;$i&lt;=$numdays;$i++) { if(date('N',strtotime($y.'-'.$m.'-'.$i))==7) $sun++; } </code></pre> <p>Sunday calculation after u calculate employee working days </p> <pre><code>$tot=$numdays-$sun-$emp_working_days;echo $tot; </code></pre>
4,228,434
0
<p>The reason your initial attempt is not working is that you're attempting to capitalize a symbol or a string that represents the field name and not the actual variable.</p> <p>You could do something like this and then the data would be capitalized before it's sent to the view.</p> <pre><code>@sexes = Sex.all @sexes = @sexes.each{|sex| sex.name.capitalize} </code></pre> <p>or</p> <pre><code>@sexes = Sex.all.each{|sex| sex.name.capitalize} </code></pre>
30,777,456
0
Trouble rebalancing the root node of an AVL tree <p>Hello guys i seem to be having trouble rebalancing the AVL tree. It balances everything else except the root node. I don't know why it doesn't balance the root node. When i pass values such as 50, 40, 30, 20, and 10. I get 50,30, 20, 10 and 40. 50 should not be the root, the correct root value should be 40. Below is my code:</p> <pre><code>public void insert(T data){ AVLNode&lt;T&gt; newNode = new AVLNode&lt;T&gt;(data); if(isEmpty()){ root = newNode; } else{ insert(root, newNode); } } private void insert(AVLNode&lt;T&gt; root, AVLNode&lt;T&gt; newNode){ if(newNode.getData().compareTo(root.getData())&lt;0){ if(root.getLeftChild()!=null){ AVLNode&lt;T&gt; leftNodes = root.getLeftChild(); insert(leftNodes, newNode); root.setLeftChild(rebalance(leftNodes)); } else{ root.setLeftChild(newNode); } } else if(newNode.getData().compareTo(root.getData())&gt;0){ if(root.getRightChild()!=null){ AVLNode&lt;T&gt; rightNodes = root.getRightChild(); insert(rightNodes, newNode); root.setRightChild(rebalance(rightNodes)); } else{ root.setRightChild(newNode); } } else{ root.setData(newNode.getData()); } updateHeight(root); } //re-balances the tree. private AVLNode&lt;T&gt; rebalance(AVLNode&lt;T&gt; root){ int difference = balance(root); if (difference &gt; 1){ if(balance(root.getLeftChild())&gt;0){ root = rotateRight(root); } else{ root = rotateLeftRight(root); } } else if(difference &lt; -1){ if(balance(root.getRightChild())&lt;0){ root = rotateLeft(root); } else{ root = rotateRightLeft(root); } } return root; } //updates the height of the tree. public void updateHeight(AVLNode&lt;T&gt; root){ if((root.getLeftChild()==null) &amp;&amp; (root.getRightChild()!=null)){ root.setHeight(root.getRightChild().getHeight()+1); } else if((root.getLeftChild() !=null)&amp;&amp;(root.getRightChild()==null)){ root.setHeight(root.getLeftChild().getHeight()+1); } else root.setHeight(Math.max(getHeight(root.getLeftChild()), getHeight(root.getRightChild()))+1); } private int balance(AVLNode&lt;T&gt; root) { return getHeight(root.getLeftChild())-getHeight(root.getRightChild()); } //single left left rotation of the tree private AVLNode&lt;T&gt; rotateLeft(AVLNode&lt;T&gt; root){ AVLNode&lt;T&gt; NodeA = root.getRightChild(); root.setRightChild(NodeA.getLeftChild()); NodeA.setLeftChild(root); root.setHeight(Math.max(getHeight(root.getLeftChild()), getHeight(root.getRightChild()))+1); //updates the height NodeA.setHeight(Math.max(getHeight(NodeA.getLeftChild()), getHeight(NodeA.getRightChild()))+1); return NodeA; } //single right right rotation of the tree private AVLNode&lt;T&gt; rotateRight(AVLNode&lt;T&gt; root){ AVLNode&lt;T&gt; NodeA = root.getLeftChild(); root.setLeftChild(NodeA.getRightChild()); NodeA.setRightChild(root); root.setHeight(Math.max(getHeight(root.getLeftChild()), getHeight(root.getRightChild()))+1); //updates the height of the AVL tree NodeA.setHeight(Math.max(getHeight(NodeA.getLeftChild()), getHeight(NodeA.getRightChild()))+1); return NodeA; } //a double rotation. Left right rotation private AVLNode&lt;T&gt; rotateLeftRight(AVLNode&lt;T&gt; root){ AVLNode&lt;T&gt; nodeA = root.getLeftChild(); root.setLeftChild(rotateLeft(nodeA)); return rotateRight(root); } //a right left rotation private AVLNode&lt;T&gt; rotateRightLeft(AVLNode&lt;T&gt; root){ AVLNode&lt;T&gt; nodeA = root.getRightChild(); root.setRightChild(rotateRight(nodeA)); return rotateLeft(root); } </code></pre>
21,810,681
0
Android calls onNavigationItemSelected too late to guard against it <p>Even though I am a frequent reader, this is my first question on Stackoverflow, so be gentle. ;)</p> <p>I have an activity that can be navigated laterally using a view pager or an action bar drop down list. To achieve this, I have attached an OnPageChangeListener and an OnNavigationListener to update the view pager when navigating by the action bar and vice versa. </p> <p>In order to avoid an infinite loop (pager listener setting action bar, navigation listener gets notified and sets pager, pager gets notified and sets action bar, etc.), I acquire a lock and check for this in the beginning of my event handler (the boolean field <code>inhibited</code>). </p> <p>Since I know that the consequent updates will happen asynchronously, by means of Android posting layout requests on the message queue, I release the lock asynchronously as well by wrapping it in a <code>Runnable</code> and posting it to the queue.</p> <p>My expectation would be that this my runnable gets placed on the queue <em>after</em> all the messages posted by the framework to update the action bar spinner, view pager and whatever else it is that it thinks it needs to be doing, since these should all be posted during the calls to <code>pager.setCurrentItem</code>, <code>navigationAdapter.notifyDataSetChanged</code> and <code>setSelectedNavigationItem</code>. (An expectation that is also reflected in the // comment.) However, when running this code, I find my callback is invoked from the OnNavigationListener after the lock is already released. </p> <p>My question is, where does this delayed call come from and how can I <em>elegantly</em> prevent it (that is without ugly hacks like <code>postDelayed</code> or the like)?</p> <p>Here is the code for my Listener:</p> <pre><code>private class NavigationListener implements OnPageChangeListener, OnNavigationListener { private boolean inhibited = false; protected void inhibit() { inhibited = true; } protected void release() { inhibited = false; } private void moveToPosition(int monthId) { if (!inhibited) { try { inhibit(); pager.setCurrentItem(pagerAdapter.getIndex(monthId), true); navigationAdapter.notifyDataSetChanged(); getActionBar().setSelectedNavigationItem(navigationAdapter.getPositionForMonth(monthId)); } finally { // Need to release asynchronously because calling setCurrentItem and notifyDataSetChanged will // (asynchronously) refresh the UI and cause calls to their respective listeners. Therefore, simply // releasing the lock would result in an infinite loop. // When posting this runnable, any posts from setting the pager page and refreshing the spinner data // will already have been posted, so the release call is guaranteed to be behind them in the message queue. // Likewise, it is sure to be executed before the user can produce more input events, that is, any additional // swipe gestures or selections will be added to the message queue after the release call. pager.post(new Runnable() { @Override public void run() { release(); } }); } } } public boolean onNavigationItemSelected(int itemPosition, long itemId) { int month = (int) itemId; moveToPosition(month); /* more irrelevant code here */ return true; } public void onPageScrollStateChanged(int arg0) {} public void onPageScrolled(int arg0, float arg1, int arg2) {} public void onPageSelected(int position) { moveToPosition(pagerAdapter.getMonthId(position)); } } </code></pre> <p>Can post more code if required but didn't want to spam the question....</p>
39,430,328
0
How to set mongodb settings, like mongodb.debug in php.ini file? <p>How to set mongodb settings, like mongodb.debug in php.ini file?</p> <p>For example, here [ <a href="http://php.net/manual/en/mongodb.configuration.php#ini.mongodb.debug" rel="nofollow">http://php.net/manual/en/mongodb.configuration.php#ini.mongodb.debug</a> ] is described setting mongodb.debug with values "" / PHP_INI_ALL .</p> <p>How to set it in php.ini?</p>
256,052
0
<p>std::map's comparator isn't std::equal_to it's std::less, I'm not sure what the best way to short circuit a &lt; compare so that it would be faster than the built in one.</p> <p>If there are always &lt; 15 elems, perhaps you could use a key besides std::string?</p>
9,871,134
0
<p>Expose Action Classes as URLs if you want to save time and effort overheads.</p> <p>But, REST APIs would be your best bet in long term as they are scalable and if later on if you want users to update/create data through APIs.</p>
15,606,677
0
<p>This is another approach, using more iterables and more relying on defaults:</p> <pre><code>from itertools import imap, islice, izip def find_min_diff(iterable, sort_func=sorted): sorted_iterable = sort_func(iterable) return min(imap( lambda a, b: b - a, izip(sorted_iterable, islice(sorted_iterable, 1)), )) </code></pre>
29,146,259
0
<p>When you say:-</p> <pre><code>var _db = new PortOfTroyCustomers.Models.PortOfTroyContext(); </code></pre> <p>The compiler infers the type of the expression to the right of the assignment, this is known as implicit type in C#.</p> <p>Now, you are trying to assign, your query like this, we have <code>System.Data.Entity.DbSet</code> on right &amp; <code>System.Linq.IQueryable</code> on left which are different types:- </p> <pre><code>IQueryable&lt;Accommodation&gt; query = _db.Accommodations; </code></pre> <p>Thus, you need an explicit typecast like this:-</p> <pre><code>IQueryable&lt;Accommodation&gt; query = (IQueryable&lt;Accommodation&gt;)_db.Accommodations; </code></pre>
4,372,354
0
<p>The class of the <code>Like</code> button is <code>like_link stat_elem as_link</code>, but I'm not seeing any <code>#808080</code> deceleration. I'll post some working code once I find it.</p>
3,841,348
0
<p>Declare it right in your code there:</p> <pre><code>class Datastructure { private: struct Ship { // Constructor!!! Ship(); std::string s_class; std::string name; unsigned int length; } minShip, maxShip; std::vector&lt;Ship&gt; shipVector; public: Datastructure(); ~Datastructure(); }; </code></pre> <p>Then to define, use the proper scope:</p> <pre><code>Datastructure::Ship::Ship() { // stuff } </code></pre>
11,767,557
0
Scroll an NSTableView so that a row is centered <p>I want to programmatically scroll an NSTableView so that a particular row is centered. It's simple to scroll the NSTableView so that a particular row is visible:</p> <pre><code>[theTableView scrollRowToVisible:pos]; </code></pre> <p>However, usually the row in question is at the bottom of the visible area, whereas I'd like it to be roughly in the center.</p> <p>Another stupid approach is to scroll a few rows beyond the one I want to be visible, e.g., something like:</p> <pre><code> // pos = index of desired row // numRows = number of rows in the table NSRect visibleRect = [resultsTableView visibleRect]; NSRange visibleRange = [resultsTableView rowsInRect:visibleRect]; NSUInteger offset = visibleRange.length/2; NSUInteger i; if (pos + offset &gt;= numRows) i = numRows - 1; else if (pos &lt; visibleRange.length) i = pos; else i = pos + offset; [resultsTableView scrollRowToVisible:i]; </code></pre> <p>This works if all rows are exactly the same height, but I am interested in making rows with different heights.</p> <p>Is there a better, perhaps more direct, way to do this? For example, I have noticed that the NSTableView is wrapped in an NSScrollView.... (The table was made using Interface Builder.)</p> <p>Thanks!</p>
3,483,077
0
Applying the Y-Combinator to a recursive function with two arguments in Clojure? <p>Doing the Y-Combinator for a single argument function such as factorial or fibonacci in Clojure is well documented: <a href="http://rosettacode.org/wiki/Y_combinator#Clojure" rel="nofollow noreferrer">http://rosettacode.org/wiki/Y_combinator#Clojure</a> </p> <p>My question is - how do you do it for a two argument function such as this getter for example?</p> <p>(Assumption here is that I want to solve this problem recursively and this non-idiomatic clojure code is there deliberately for another reason)</p> <p>[non y-combinator version]</p> <pre><code>(defn get_ [n lat] (cond (empty? lat) () (= 0 (- n 1)) (first lat) true (get_ (- n 1) (rest lat)))) (get_ 3 '(a b c d e f g h i j)) </code></pre>
26,130,776
0
<p>From the API doc for <code>HTable</code>'s <code>flushCommits()</code> method: "Executes all the buffered Put operations". You should call this at the end of your <code>blah()</code> method -- it looks like they're currently being buffered but never executed or executed at some random time. </p>
29,163,424
0
<p>I think that this link could give you some hints about the design of RESTful services / Web API: <a href="https://templth.wordpress.com/2014/12/15/designing-a-web-api/" rel="nofollow">https://templth.wordpress.com/2014/12/15/designing-a-web-api/</a>.</p> <p>It's clear that not all Web services that claim to be RESTful are really RESTful ;-)</p> <p>To be short, RESTful services should leverage HTTP methods for what they are designed for:</p> <ul> <li>method <code>GET</code>: return the state of a resource</li> <li>method <code>POST</code>: execute an action (creation of an element in a resource list, ...)</li> <li>method <code>PUT</code>: update the complete state of a resource</li> <li>method <code>PATCH</code>: update partially the state of a resource</li> <li>method <code>DELETE</code>: delete a resource</li> </ul> <p>You need to be also to be aware that they can apply at different levels, so methods won't do the same things:</p> <ul> <li>a list resource (for example, path <code>/elements</code>)</li> <li>an element resource (for example, path <code>/elements/{elementid}</code>)</li> <li>a field of an element resource (for example, path <code>elements/{elementid}/fieldname</code>). This is convenient to manage field values with multiple cardinality. You don't have to send the complete value of the fields (whole list) but add / remove elements from it.</li> </ul> <p>Another important thing is to leverage HTTP headers. For example, the header <code>Accept</code> for content negotiation...</p> <p>I find the Web API of Github well designed and its documentation is also great. You could browse it to make you an idea. See its documentation here: <a href="https://developer.github.com/v3/" rel="nofollow">https://developer.github.com/v3/</a>.</p> <p>Hope it helps you, Thierry</p>
9,476,189
0
<p>If you don't do any query then there is nothing to boost.</p> <p>A dismax query is nothing more than a query which matches in any one of several fields. You can boost a dismax query in the way that you specified, but you need to do the query to boost it.</p> <p>q.alt is only used when no query is specified.</p>
20,559,990
0
<p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/package-summary.html" rel="nofollow">Servlet API</a> provides a way to read the Request Parameters. For example,</p> <p><a href="http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterNames%28%29" rel="nofollow"><code>ServletRequest.getParameterNames()</code></a> returns you a map of key-value pairs of the request parameters.</p> <p>However, for Path variables and values, I don't know if Spring MVC offers a simplified way of doing it, but using Servlet API again, you can read the URI using <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRequestURI%28%29" rel="nofollow"><code>HttpServletRequest.getRequestURI()</code></a>. You'll have to have your own logic to split it up into appropriate Path parameters.</p>
36,265,049
1
Can't escape a while loop, Python 2.7 <p>For some reason i can't escape while loop , i tried debugging it, and looks like for loop is untouched and i don't understand why. (it's fraction of mine tictactoe game code)</p> <pre><code>users_main = [] computers_main = [] while True: computers_storage = [] users_storage = [] if 0==0: condition = True while condition: guess_y = int(raw_input('Enter coordinate y:')) -1 guess_x = int(raw_input('Enter coordinate x:')) -1 users_storage.append(guess_y) users_storage.append(guess_x) users_main.append(users_storage) for a in computers_main: if a == users_storage: del users_storage[-2] del users_main[-1] condition = True break else: condition = False break break </code></pre>
26,625,601
0
<p>@user2009755, you need to create a master and slave file only in the master. And in configuration files in $HADOOP_HOME/etc/hadoop, make necessary changes to the URI pointing to the master node.<br><br>NOTE: Try to format the namenode and delete the tmp files (usually /tmp/*) but if you changed it in <code>core-site.xml</code>, format that directory in all nodes and start all the daemons, it worked for me.</p>
14,870,369
0
tranpose only the two outer words of three <p>How to transpose "foo" and "bar" in "foo and bar" in emacs with the least number of key strokes?</p> <p>input:</p> <pre><code>foo and bar </code></pre> <p>output:</p> <pre><code>bar and foo </code></pre>