Id
int64
34.6M
60.5M
Title
stringlengths
15
150
Body
stringlengths
33
36.7k
Tags
stringlengths
3
112
CreationDate
stringdate
2016-01-01 00:21:59
2020-02-29 17:55:56
Y
stringclasses
3 values
35,701,397
Generate a 2-D array in Javascript
<p>I would like to generate a 2-D array in javascript representing the grid below.Tried different things but in vain. <a href="https://i.stack.imgur.com/k2DSG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k2DSG.png" alt="enter image description here"></a></p>
<javascript><arrays>
2016-02-29 13:55:26
LQ_CLOSE
35,701,628
Can't print a long long double output
<p>My question is simple, How to print a long long double output?. I know how to print a long double i.e</p> <pre><code>printf("%Lf",output); </code></pre>
<c><printf><double>
2016-02-29 14:05:55
LQ_CLOSE
35,702,705
Is there a way to change the CSS resize corner's position?
<p>So this is a bit of a strange question. Programming a web application with a resizable div. I'm using the CSS resize property at the moment as it seemed like it was the easiest way to do it. The problem is my box has a locked bottom and left position (which I want to maintain), but the resize corner chosen by default is the lower right one, which produces weird results for resizing the top. Looked around online but couldn't find a way to move that corner to the upper right instead of the bottom right. Any advice on how to produce this result? Also not opposed to using a different method of resizing. Here's the current style being applied to the box:</p> <pre><code>display: block; font-size: 9pt; position: absolute; bottom: 50px; left: 20px; padding: 10px; min-height: 0; min-width: 0; border: solid 1px black; width:400px; height:400px; resize: both; overflow-x: auto; overflow-y: hidden; </code></pre> <p>And here's a picture of the div in question with the corner that currently has the resize tool on it boxed. Any advice would be greatly appreciated. I'm more than happy to elaborate on things I might've missed as well. Thanks! </p> <p><a href="http://i.stack.imgur.com/rxa8R.png" rel="noreferrer">Box I want to resize in question</a></p>
<javascript><html><css><resize>
2016-02-29 14:57:45
HQ
35,702,742
Javascript - Variables from html div
I have this simple div <!-- begin snippet: js hide: false --> <!-- language: lang-html --> <div id='names'> name1[John] name2[Blake] name3[Sven] name4[Ellis] </div> <!-- end snippet --> And I want to return this variabels using javascript <!-- begin snippet: js hide: false --> <!-- language: lang-js --> var name1 = "John"; var name2 = "Blake"; var name3 = "Sven"; var name4 = "Ellis"; <!-- end snippet --> Any help please .. <br>Thanks!
<javascript><jquery>
2016-02-29 15:00:03
LQ_EDIT
35,702,887
Decision tree learning: Basic idea
<p>As given in the textbook <strong>Machine Learning</strong> by <em>Tom M. Mitchell</em>, the first statement about decision tree states that, "Decision tree leaning is a method for approximating discrete valued functions". Could someone kindly elaborate this statement, probably even justify it with an example. Thanks in advance :) :) </p>
<machine-learning>
2016-02-29 15:07:52
LQ_CLOSE
35,703,177
JQuery set input box value to this.value onclick?
<pre><code>$("#something1").click(function(){ $("#something2").val(this.val); }); </code></pre> <p>I'm trying to set the value of something2 to the value of something1 onclick ...</p>
<javascript><jquery>
2016-02-29 15:23:01
LQ_CLOSE
35,703,258
Invert Angular 2 *ngFor
<pre><code>&lt;li *ngFor="#user of users "&gt; {{ user.name }} is {{ user.age }} years old. &lt;/li&gt; </code></pre> <p>Is it possible to invert the ngFor that the items are added bottom up? </p>
<angular>
2016-02-29 15:26:35
HQ
35,703,335
Is it possible to use an IF statement in PHP along with differnet sql queries?
Basically I want to update a value in the table if the date field is equal to todays date, otherwise I'd like to insert a new row into the table if the date is not equal to today. Say for example something like (I know syntax is wrong here) - if($date == $today){ $sql = $con->query("UPDATE table SET field= 'field+$value', field2='field2 + $value2' WHERE id=2") }else{ $sql = $con->query("INSERT INTO table (field1, field,2,field3)VALUES('{$value1}', '{$value2}', '{$value3}')"); } How would I go about doing something like this? is using an if statement like this in php/SQL queries possible? or is there a different way that it has to be done? Cheers.
<php><mysql><sql><database><if-statement>
2016-02-29 15:30:08
LQ_EDIT
35,704,412
Postgresql query current year
<p>I need to see only the current year rows from a table.</p> <p>Would it be possible filter a timestamp column only by current year parameter, is there some function that can return this value?</p> <pre><code>SELECT * FROM mytable WHERE "MYDATE" LIKE CURRENT_YEAR </code></pre>
<sql><postgresql>
2016-02-29 16:21:20
HQ
35,704,442
When i install the android studio in window 10 there is error is occurred .
like you can see in image also.the error is regarding android studio not able to find the jdk, but jdk is aleady install in PC.i used JAVA_HOME and give path name all that, but still error is occurred . Please help me>>>>>>>> [enter image description here][1] [1]: http://i.stack.imgur.com/3wwzC.png
<android>
2016-02-29 16:22:47
LQ_EDIT
35,704,535
Can you solve my below Scenario?
I had a little different scenario while I'm work with Excel Work sheet, that is Column A1 contains value like "2 * 3" or "2 x 4", here what is my problem is i have to calculate A value by applying following formula in Column B i.e =(A1), so similarly looks like "=(2 * 3)" or "=(2 x 4)" right. But my case it does not works well. If I'm directly put something like "=(2 * 3)" in column A1, then its works fine i.e my resultant value would be 6. But my scenario it can't be done why, What am wrong with that ? Can anybody understand my scenario, help me pleassseeeee.!!!
<excel><excel-formula>
2016-02-29 16:27:15
LQ_EDIT
35,704,632
MQTT Socket error on client <unknown>
<p>I have setup MQTT on a Raspberry Pi and configured an Arduino Uno to the broker, but I am seeing the following entry in the /var/log/mosquitto/mosquitto.log file:</p> <pre><code>New connection from 192.168.10.114 on port 1883. Socket error on client &lt;unknown&gt;, disconnecting. </code></pre> <p>The Pi is setup with ETH0 wired to my local LAN and has an IP address of 192.168.1.50</p> <p>There is also a WiFi AP setup on the Pi. The Arduino Uno connects via WiFi to send/receive MQTT messages. The WiFi AP has an IP address of 192.168.10.1 and provides DHCP leases via <code>dnsmasq</code>.</p> <p>I have tried publishing and subscribing test on the local MQTT broker server (the Pi) and get the same error:</p> <pre><code>Command: mosquitto_sub -h 192.168.10.1 -t topic mosquitto.log: New connection from 192.168.10.1 on port 1883. New client connected from 192.168.10.1 as mosqsub/1837-raspberryp (cl, k60). Socket error on client &lt;unknown&gt;, disconnecting. </code></pre> <p>Here is /etc/mosquitto/mosquitto.conf:</p> <pre><code>pid_file /var/run/mosquitto.pid persistence true log_dest file /var/log/mosquitto/mosquitto.log allow_anonymous true include_dir /etc/mosquitto/conf.d </code></pre> <p>sudo service mosquitto stop sudo service mosquitto start:</p> <pre><code>mosquitto version 1.4.8 terminating mosquitto version 1.4.8 (build date Sun, 14 Feb 2016 15:06:55 +0000) starting Config loaded from /etc/mosquitto/mosquitto.conf. Opening ipv4 listen socket on port 1883. Opening ipv6 listen socket on port 1883. </code></pre> <p>There might be an issue in my interfaces configuration. Here is /etc/network/interfaces:</p> <pre><code>source-directory /etc/network/interfaces.d auto lo iface lo inet loopback iface eth0 inet manual auto wlan0 allow-hotplug wlan0 iface wlan0 inet static address 192.168.10.1 netmask 255.255.255.0 </code></pre> <p>Can anyone point me on where the socket error is coming from on MQTT?</p>
<linux><raspberry-pi><mqtt>
2016-02-29 16:32:08
HQ
35,704,957
How do I see the ENV vars in a Rails app?
<p>I am taking over an old Rails app. No one has touched it in a year. The last developer left in April of 2015 and I have no way to contact him. I do have ssh access to the server, and I have access to the Github repo. </p> <p>I don't know any of the usernames/passwords. </p> <p>If I ssh to the server and I cat the database.yml file, I see stuff like: </p> <pre><code> staging: adapter: mysql2 encoding: utf8 pool: 5 socket: /var/lib/mysql/mysql.sock database: o_wawa_stage username: wawa_stage password: &lt;%= ENV['STAGE_DATABASE_PASSWORD'] %&gt; host: access.dmedia.com </code></pre> <p>If I run the "printenv" command then I don't see any of these vars. I assume they are only loaded by the Rails environment. </p> <p>I guess I can edit the templates to spit out the values with a bunch of "put" statements, but I'm thinking there must be a more obvious way to do this, other than printing the data where the public could see it? </p> <p>If I try to run "rails console" I get: </p> <pre><code> Rails Error: Unable to access log file. Please ensure that /var/www/haha/production/releases/20150118213616/log/development.log exists and is writable (ie, make it writable for user and group: chmod 0664 /var/www/haha/production/releases/20150118213616/log/development.log). The log level has been raised to WARN and the output directed to STDERR until the problem is fixed. </code></pre> <p>I don't have sudo on this box, so I can not address the error. </p>
<ruby-on-rails><environment-variables><env>
2016-02-29 16:48:55
HQ
35,705,165
I want to learn the inbuilt classes and methods in java libraries? please guide
<p>Please give some to-do task and techniques to learn inbuilt classes and methods in packages! I want to became a successful java developer!</p>
<java><javadoc>
2016-02-29 16:58:55
LQ_CLOSE
35,705,456
C# how to catch Exeption
I am new in `C#` programming and I don't understand this problem. using (WebClient wc = new WebClient()) { try{ wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; HtmlResult = wc.UploadString(URI, myParameters); }catch(AuthenticateExeption a){ throw new AuthenticateExeption("I can not connect to the server..."); } } I am trying `catch` exeption using my `AuthenticateExeption`, but code never go to `throw new AuthenticateExeption("I can not connect to the server...");` and program always down on `HtmlResult = wc.UploadString(URI, myParameters);` line. Why?
<c#>
2016-02-29 17:14:49
LQ_EDIT
35,705,619
Why Chrome on Linux shows "External protocol request" dialog for unknown protocol?
<p>I am creating a custom protocol handler for Google Chrome on Linux. My link looks like this:</p> <pre><code>&lt;a href="myprotocol:someargument"&gt;Trigger my app with param&lt;/a&gt; </code></pre> <p>I have noticed that if 'myprotocol:' is not registered (my app not installed), Google Chrome on Linux displays "External Protocol Request" dialog and tries to use xdg-open:</p> <p><a href="https://i.stack.imgur.com/difTw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/difTw.png" alt="enter image description here"></a></p> <p>While on other OS, such as Windows 10 and OS X El Capitan nothing is displayed if protocol is not registered. </p> <p>I have also verified that Firefox works consistently for unknown protocols on Windows, OS X and Linux - nothing is displayed.</p> <p>Chrome behavior on Linux is quite confusing for users. </p> <p>Any idea why Chrome on Linux (I was testing on Ubuntu 14.04) acts differently from any other OS and web browsers?</p>
<linux><google-chrome><ubuntu><protocols>
2016-02-29 17:24:27
HQ
35,705,698
Error loading project in Android Studio: cannot load modules
<p>When I Checkout a project form Google Cloud, Android Studio sais: "2 modules cannot be loaded. You can remove them from the project" and I cannot see the project. The error is in the iml files app.iml and ProjectName.iml.</p> <p>Thanks!</p>
<android><android-studio>
2016-02-29 17:29:22
HQ
35,705,877
Extracting entry positions in R
<p>I have a vector, A, with lots of entries, for example</p> <pre><code>1 4 2 5 6 7 8 3 5 </code></pre> <p>I want to get a list of all the positions of entries in that vector that are in [2,6], so id like the output to be </p> <pre><code>2 3 4 5 8 9 </code></pre> <p>please help</p>
<r>
2016-02-29 17:37:44
LQ_CLOSE
35,705,888
Email form validation to accept only one domain
<p>I know this is a relatively asked question but here goes. I have registration form where a user can sign up but I want it to be for a closed group of people so only people from my company can register. So only people with @company.com domain addresses can register. What I have so far is just a email validation code using patterns. How would I alter the below code to only allow @company.com emails? Cheers.</p> <pre><code>$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if(!preg_match($email_exp,$email_from)) { $error_message .= 'The Email Address you entered does not appear to be valid.&lt;br /&gt;'; } </code></pre>
<php>
2016-02-29 17:38:22
LQ_CLOSE
35,706,019
HTML input on firefox is not displaying text that set as black
<p><a href="http://secure.gethope.net" rel="nofollow">On Firefox text color in inout is not visible </a></p> <p>while text is visible on other browsers. </p>
<html><css><forms><validation><input>
2016-02-29 17:45:49
LQ_CLOSE
35,706,274
Is there a way how to import keyboard shortcuts from IntelliJ to Visual Studio 2015
<p>I would like to know if it´s possible to import keymap from IntelliJ or PHPStorm to Visual Studio. I´m used to work with IntelliJ IDE´s. Now I´m starting develop some apps in .NET and it´s kinda hard to get used to the new key schemes.</p>
<visual-studio><intellij-idea><keyboard-shortcuts>
2016-02-29 17:58:16
HQ
35,706,453
PHP While Loop Not Liking Two Variables
<p>I have the follow while loop in my code. I can't understand why it causes a loading error but when I remove the = from the statement, it suddenly works? Thanks in advance!</p> <p>Here is my code (Yes, I do have a form opening and closing tags!):</p> <pre><code> echo "&lt;select name='cquantity'&gt;"; $x = 0; $limit = 1; while ($x &lt;= $limit) { echo "&lt;option value='$x'&gt;$x&lt;/option&gt;"; } echo "&lt;/select&gt;"; </code></pre>
<php>
2016-02-29 18:07:50
LQ_CLOSE
35,706,835
React router redirect after action redux
<p>I'm using react-redux and standard react-routing. I need redirect after definite action.</p> <p>For example: I have registration a few steps. And after action:</p> <pre><code>function registerStep1Success(object) { return { type: REGISTER_STEP1_SUCCESS, status: object.status }; } </code></pre> <p>I want him redirect to page with registrationStep2. How to do it?</p> <p>p.s. In history browser '/registrationStep2' has never been. This page appears only after successful result registrationStep1 page.</p>
<reactjs><react-router><redux><redux-framework>
2016-02-29 18:28:09
HQ
35,707,222
Swap two numbers golang
<p>I am trying to understand the internals of go. Consider the following code</p> <pre><code>a,b := 10,5 b,a = a,b </code></pre> <p>The above code swaps 2 number perfectly and a becomes 5 and b becomes 10. I am not able to understand how this works. Considering in the second line of code, if a is assigned to b first, then b would be 10. Now if we assign b to a then shouldn't a be 10 too.</p> <p>Please help me understand how this works</p> <p>Thanks</p>
<go>
2016-02-29 18:49:16
HQ
35,707,244
Does anyone know how to change from AutoIT code to Java?
<p>I have the following AutoIT code and I'd like to know how to migrate/translate to Java</p> <p>AutoIT:</p> <pre><code> AutoItSetOption("WinTitleMatchMode","20") WinWait("Authentication Required") While WinExists("Authentication Required") Opt("SendKeyDelay", 50) $title = WinGetTitle("Authentication Required") ; retrieves whole window title $UN=WinGetText($title,"User Name:") ControlSend($title,"",$UN,"myemail@gmail.com{TAB}");Sets Username and {TAB} $PWD=WinGetText($title,"Password:") ControlSend($title,"",$PWD,"mypassword");Sets PWD and {ENTER} ControlSend($title,"",$PWD,"{ENTER}"); Sleep(2000) WEnd Exit </code></pre> <p>This is what I tried to convert to Java:</p> <pre><code>public void shouldEnterCredentials() throws Throwable { try { File file = new File("lib", "jacob-1.18-x64.dll"); //path to the jacob dll System.setProperty(LibraryLoader.JACOB_DLL_PATH, file.getAbsolutePath()); AutoItX x = new AutoItX(); String title = x.winGetTitle("Authentication Required"); String un = x.winGetText(title,"User Name:"); String pwd = x.winGetText(title,"Password:"); x.autoItSetOption("WinTitleMatchMode","20"); x.winWait("Authentication Required"); while (x.winExists("Authentication Required")){ x.autoItSetOption("OPT_SEND_KEY_DELAY", "50"); x.controlSend(title,"", un, "myemail@gmail.com{TAB}"); //Sets Username and {TAB} x.controlSend(title,"",pwd,"mypassword"); //Sets PWD and {ENTER} x.controlSend(title, "", pwd,"{ENTER}"); x.sleep(2000); } } catch (Exception e) { System.out.println("Error: " + e.getStackTrace()); } } </code></pre> <p>Can anyone help me, please?</p>
<java><autoit>
2016-02-29 18:50:28
LQ_CLOSE
35,707,534
How to scrape a table with rvest and xpath?
<p>using the following <a href="http://www.r-bloggers.com/using-rvest-to-scrape-an-html-table/" rel="noreferrer">documentation</a> i have been trying to scrape a series of tables from marketwatch.com </p> <p>here is the one represented by the code bellow: </p> <p><a href="https://i.stack.imgur.com/ak9iH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ak9iH.png" alt="enter image description here"></a></p> <p>The link and xpath are already included in the code:</p> <pre><code>url &lt;- "http://www.marketwatch.com/investing/stock/IRS/profile" valuation &lt;- url %&gt;% html() %&gt;% html_nodes(xpath='//*[@id="maincontent"]/div[2]/div[1]') %&gt;% html_table() valuation &lt;- valuation[[1]] </code></pre> <p>I get the following error: </p> <pre><code>Warning message: 'html' is deprecated. Use 'read_html' instead. See help("Deprecated") </code></pre> <p>Thanks in advance. </p>
<r><xpath><web-scraping><rvest>
2016-02-29 19:06:55
HQ
35,707,867
StackExchange redis client very slow compared to benchmark tests
<p>I'm implementing a Redis caching layer using the Stackexchange Redis client and the performance right now is bordering on unusable.</p> <p>I have a local environment where the web application and the redis server are running on the same machine. I ran the Redis benchmark test against my Redis server and the results were actually really good (I'm just including set and get operations in my write up):</p> <pre><code>C:\Program Files\Redis&gt;redis-benchmark -n 100000 ====== PING_INLINE ====== 100000 requests completed in 0.88 seconds 50 parallel clients 3 bytes payload keep alive: 1 ====== SET ====== 100000 requests completed in 0.89 seconds 50 parallel clients 3 bytes payload keep alive: 1 99.70% &lt;= 1 milliseconds 99.90% &lt;= 2 milliseconds 100.00% &lt;= 3 milliseconds 111982.08 requests per second ====== GET ====== 100000 requests completed in 0.81 seconds 50 parallel clients 3 bytes payload keep alive: 1 99.87% &lt;= 1 milliseconds 99.98% &lt;= 2 milliseconds 100.00% &lt;= 2 milliseconds 124069.48 requests per second </code></pre> <p>So according to the benchmarks I am looking at over 100,000 sets and 100,000 gets, per second. I wrote a unit test to do 300,000 set/gets:</p> <pre><code>private string redisCacheConn = "localhost:6379,allowAdmin=true,abortConnect=false,ssl=false"; [Fact] public void PerfTestWriteShortString() { CacheManager cm = new CacheManager(redisCacheConn); string svalue = "t"; string skey = "testtesttest"; for (int i = 0; i &lt; 300000; i++) { cm.SaveCache(skey + i, svalue); string valRead = cm.ObtainItemFromCacheString(skey + i); } } </code></pre> <p>This uses the following class to perform the Redis operations via the Stackexchange client:</p> <pre><code>using StackExchange.Redis; namespace Caching { public class CacheManager:ICacheManager, ICacheManagerReports { private static string cs; private static ConfigurationOptions options; private int pageSize = 5000; public ICacheSerializer serializer { get; set; } public CacheManager(string connectionString) { serializer = new SerializeJSON(); cs = connectionString; options = ConfigurationOptions.Parse(connectionString); options.SyncTimeout = 60000; } private static readonly Lazy&lt;ConnectionMultiplexer&gt; lazyConnection = new Lazy&lt;ConnectionMultiplexer&gt;(() =&gt; ConnectionMultiplexer.Connect(options)); private static ConnectionMultiplexer Connection =&gt; lazyConnection.Value; private static IDatabase cache =&gt; Connection.GetDatabase(); public string ObtainItemFromCacheString(string cacheId) { return cache.StringGet(cacheId); } public void SaveCache&lt;T&gt;(string cacheId, T cacheEntry, TimeSpan? expiry = null) { if (IsValueType&lt;T&gt;()) { cache.StringSet(cacheId, cacheEntry.ToString(), expiry); } else { cache.StringSet(cacheId, serializer.SerializeObject(cacheEntry), expiry); } } public bool IsValueType&lt;T&gt;() { return typeof(T).IsValueType || typeof(T) == typeof(string); } } } </code></pre> <p>My JSON serializer is just using Newtonsoft.JSON:</p> <pre><code>using System.Collections.Generic; using Newtonsoft.Json; namespace Caching { public class SerializeJSON:ICacheSerializer { public string SerializeObject&lt;T&gt;(T cacheEntry) { return JsonConvert.SerializeObject(cacheEntry, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); } public T DeserializeObject&lt;T&gt;(string data) { return JsonConvert.DeserializeObject&lt;T&gt;(data, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); } } } </code></pre> <p>My test times are around 21 seconds (for 300,000 sets and 300,000 gets). This gives me around 28,500 operations per second (at least 3 times slower than I would expect using the benchmarks). The application I am converting to use Redis is pretty chatty and certain heavy requests can approximate 200,000 total operations against Redis. Obviously I wasn't expecting anything like the same times I was getting when using the system runtime cache, but the delays after this change are significant. Am I doing something wrong with my implementation and does anyone know why my benchmarked figures are so much faster than my Stackechange test figures?</p> <p>Thanks, Paul</p>
<c#><redis><stackexchange.redis>
2016-02-29 19:24:30
HQ
35,708,506
linux wildcard usage in cp and mv
<p>I am composing a script to process 20 files. All of them located in different directories. I have partial file name. </p> <ol> <li>In log directory, File1_Date_time.err change to File1__Date_time_orig.err</li> <li>cd ../scripts/ </li> <li>sh File.sh </li> </ol> <p>File1 directory is /data/data1directory/Sample_File1/logs/File1_Data_time.err<Br> File2 directory is /data/data2directory/Sample_File2/logs/File2_Data_time.err<Br> .....</p> <p>My script looks like this. (runrunrun.sh)</p> <pre><code>#!/bin/bash INPUT=$1 mv /data/*/Sample_*/logs/*_Data_time.err /data/*/Sample_*/logs/*_Data_time_orig.err cp /data/*/Sample_*/scripts/*.sh /data/*/Sample_*/scripts/*_orig.sh sh /data/*/Sample_*/scripts/*_orig.sh </code></pre> <p>When running it, I tried.<Br> ./runrunrun.sh File1 <Br> . runrunrun.sh File1 <Br> sh runrunrun.sh File1 <Br></p> <p>mv: cannot move <code>/data/data1directory/Sample_File1/logs/File1_Data_time.err /data/*/Sample_*/logs/*_Data_time_orig.err</code>: No such file or directory cp also got similar feedback</p> <p>Am I doing it correct?</p> <p>Thanks!</p>
<linux><shell><cp><mv>
2016-02-29 20:00:05
HQ
35,708,577
C++ Programming, having trouble programming finding velocity and distance
<p>Hey I'm a beginner taking an intro to C++ class, and this is my first assignment. I posted this a couple of days ago but I still am somewhat lost. I have to use the formulas: d=v0*t + 1/2*g<em>t^2, and v= v0 + g</em>t. where v0 stays constant at 0 and g also stays constant at 9.807 m/s^2. I keep getting one error which is "expected unqualified-id before "{" token" on the first { and cannot seem to fix them, and im sure this code is incorrect, so can you help me figure this out?</p> <pre><code>#include &lt;cstdlib&gt; #include &lt;iostream&gt; #include &lt;math.h&gt; using namespace std; const float GRAVITY = 9.807, INITIALVELOCITY = 0; int seconds; { cout &lt;&lt; "Please enter the time in seconds." &lt;&lt; endl; cin &gt;&gt; seconds; } //end function Time int main(int argc, char *argv[]) { float distance, velocity, seconds; void getSeconds (void); cout.setf (ios::fixed,ios::floatfield); cin &gt;&gt; seconds; while (seconds &gt; 0) { distance = INITIALVELOCITY * seconds + (0.5 * GRAVITY * pow(seconds, 2)); velocity = INITIALVELOCITY + (GRAVITY * seconds); cout.precision (0); cout &lt;&lt; endl &lt;&lt; "WHEN THE TIME IS" &lt;&lt; seconds &lt;&lt; "SECONDS THE DISTANCE" "TRAVELED IS" &lt;&lt; distance &lt;&lt; "METERS THE VELOCITY IS" &lt;&lt; velocity &lt;&lt; "METERS PER SECOND."; cout. precision(1); cout&lt;&lt; seconds &lt;&lt; distance &lt;&lt; velocity &lt;&lt; endl &lt;&lt; endl; } system ("PAUSE"); return EXIT_SUCCESS; } //end main </code></pre>
<c++><physics>
2016-02-29 20:03:59
LQ_CLOSE
35,708,581
Do i have to install DNX on my server to serve asp.net 5 site?
<p>Thats really frustrating how hard is publish a website with asp.net 5. Very bad documentation, and all things said in internet does not work for me. Someone here already made it work? My server has iis 7.5. Do i have to install asp.net 5 on my server? I heard i do not need to install. Please help.</p>
<c#><asp.net><asp.net-core>
2016-02-29 20:04:19
LQ_CLOSE
35,709,018
Doest display php echo values from mysql
Tables: Users & UserGroup Users contains: ID, Name, Image, UserGroupID UserGroup contains: ID, Name, Menu UserGroupID(column) is linked with UserGroup table's ID. column Menu contains something like this: ` <header id="header-navbar" class="content-mini content-mini-full"> <ul class="nav-header pull-right"> <li> <div class="btn-group"> <button class="btn btn-default btn-image dropdown-toggle" data-toggle="dropdown" type="button"> <img src="../images/employees/'.$row_UserDetails['Image'].'" alt=""> <span class="caret"></span> </button> <ul class="dropdown-menu dropdown-menu-right"> <li> <a tabindex="-1" href="my-profile.php"> <i class="si si-user pull-right"></i> My Profile </a> </li> <li> <a tabindex="-1" href="../logout.php"> <i class="si si-logout pull-right"></i>Log out </a> </li> </ul> </div> </li> </ul> </header> ` Now at img src its creating a problem. '.$row_UserDetails['Image'].' Doesnt display the value. Why is that & how do we fix this? Anyways i am trying to display the above results from php mysql in php page using this: `<?php echo $row_UserGroup['Menu'];?>` but doesnt work. All displays fine except img src which value is coming from existing recordset.
<php><html><database>
2016-02-29 20:30:01
LQ_EDIT
35,709,153
Disabling AWS RDS backups when creating/updating instances?
<p>I am creating new RDS MySQL instances from snapshots and updating their configurations both via the API and through the UI. Regardless of how I create or update instances, these actions automatically trigger new snapshots to be created through some kind of automatic backup process. Is there a way to disable snapshot creation when performing these actions since I do not need the additional snapshots and their creation is causing an unnecessary delay?</p>
<amazon-web-services><database-backups><mysql-backup><aws-rds>
2016-02-29 20:38:25
HQ
35,709,434
C - Inconsistent Data from Socket
<p>I've got a simple proxy server program written in C for a course. I'm having some issues with inconsistent data. When I request the website, I save the resulting data in a file on the server side, then send it over to the client and save it on the client side as well. The results on both the client and server will be of different sizes and it appears that some of the HTML is being duplicated. Typically, the file saved on the server will be smaller than the one saved on the client, although both files are still larger than the actual web page (i.e., if I were to right click the page and 'save as', the resulting page is smaller than those returned by my code). I've tried various things to resolve this issue and nothing seems to work. The results even seem to differ between attempts at the same website. For instance, I can request the same website twice, yet the file sizes differ from both attempts. In very rare occasions, especially on small websites, both the client and server program return the correct web page and both files are of the appropriate size.</p> <p>Note: I'm aware that the code is still rather messy. I'm more worried about addressing this issue before I move any further. I will address issues (such as checking if the socket failed to open) once this issue is corrected, so please only address the issue I have outlined.</p> <p>Server.c</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netdb.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;regex.h&gt; #include &lt;time.h&gt; /*Code used to resolve URL into IP address adapted from following URL: http://www.binarytides.com/hostname-to-ip-address-c-sockets-linux/ */ //This code has been adapted from the server code provided in class int main(int argc, char** argv) { char str[655360]; char recvline[655360]; char parsedRecv[655360]; char domain[1025]; char directory[1025]; char absoluteURL[1025]; char temp[1025]; int listen_fd, conn_fd, n, tempCount; struct sockaddr_in servaddr; int bytesRead; int stringCounter; int port; FILE *fp; //Variables used for second socket and resolving of host char ip[100]; int sockfd, secondSocketCount; int len = sizeof(struct sockaddr); struct sockaddr_in secondServaddr; struct addrinfo *servinfo, *p; struct sockaddr_in *h; int rv; char simpleMatch[10]; int flag = 0; //End //Used for HTTP GET request char request[2049]; listen_fd = socket(AF_INET, SOCK_STREAM, 0); bzero(&amp;servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htons(INADDR_ANY); if(argc &lt; 2) { printf("Error! Enter a port number to run this server on.\n\tEx: ./server 22000\n\r\0"); return 0; } else { port = atoi(argv[1]); } servaddr.sin_port = htons(port); printf("\n"); printf("Awaiting connections...\n"); bind(listen_fd, (struct sockaddr*)&amp;servaddr, sizeof(servaddr)); listen(listen_fd, 10); //Once the server is listening, enter an infinite loop to keep listening while(1) { conn_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL); bytesRead = read(conn_fd, recvline, sizeof(recvline)); if(bytesRead &gt; 0) //data read { recvline[bytesRead] = '\0'; bzero(absoluteURL, 1025); strcpy(absoluteURL, recvline); //Extract host and page from recvline //For loop used to check if URL begins with HTTP or HTTPS for(stringCounter = 0; stringCounter &lt; 5; stringCounter++) { simpleMatch[stringCounter] = tolower(recvline[stringCounter]); } simpleMatch[strlen(simpleMatch)] = '\0'; if(strcmp("http:", simpleMatch) == 0) { for(stringCounter = 7, tempCount = 0; stringCounter &lt; strlen(recvline); stringCounter++, tempCount++) { temp[tempCount] = recvline[stringCounter]; } temp[strlen(temp)] = '\0'; strcpy(recvline, temp); } else if(strcmp("https", simpleMatch) == 0) { for(stringCounter = 8, tempCount = 0; stringCounter &lt; strlen(recvline); stringCounter++, tempCount++) { temp[tempCount] = recvline[stringCounter]; } temp[strlen(temp)] = '\0'; strcpy(recvline, temp); } //printf("\n\nAfter stripping HTTP, we are left with: %s\n\n", recvline); //Now that HTTP:// or HTTPS:// has been stripped, can parse for domain for(stringCounter = 0, tempCount = 0; stringCounter &lt; strlen(recvline); stringCounter++) { //moving domain into the domain string if(flag == 0) { if(recvline[stringCounter] != '/') { domain[stringCounter] = recvline[stringCounter]; } else { domain[stringCounter + 1] = '\0'; //directory[tempCount] = recvline[stringCounter]; flag = 1; tempCount++; } } else { directory[tempCount] = recvline[stringCounter]; tempCount++; } } //printf("\n\nDirectory is: %s\n\n", directory); //reset flag and append '\0' to directory and domain flag = 0; if(tempCount &lt; 1025) { directory[tempCount] = '\0'; } //directory[strlen(directory)] = '\0'; //domain[strlen(domain)] = '\0'; //Done extracting //Resolve hostname to IP if((rv = getaddrinfo(domain, NULL, NULL, &amp;servinfo)) != 0) { printf("Error: an IP address cannot be resolved for %s\n", domain); return 0; //fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); } else { for(p = servinfo; p != NULL; p = p-&gt;ai_next) { h = (struct sockaddr_in *) p-&gt;ai_addr; strcpy(ip, inet_ntoa(h-&gt;sin_addr)); } freeaddrinfo (servinfo); printf("%s resolved to: %s\n", domain, ip); } //End Resolve //Now that the IP is resolved, open a socket and connect to the IP //Open socket sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&amp;secondServaddr, sizeof(secondServaddr)); secondServaddr.sin_family = AF_INET; secondServaddr.sin_port = htons(80); inet_pton(AF_INET, ip, &amp;(secondServaddr.sin_addr)); //IP taken from earlier resolution connect(sockfd, (struct sockaddr*) &amp;secondServaddr, sizeof(secondServaddr)); //socket is open, can create and send request, finally bzero(request, 2049); //sprintf(request, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", directory, domain); //sprintf(request, "GET %s HTTP/1.1\r\n\r\n", absoluteURL); //sprintf(request, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", absoluteURL, domain); sprintf(request, "GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n", directory, domain); write(sockfd, request, strlen(request)); printf("\tAttempting to retrieve data: this may be slow.\n"); bzero(recvline, 655360); bzero(parsedRecv, 655360); //Old method used to retrieve data //This was changed when I began to run into issues /*while(1) { secondSocketCount = read(sockfd, parsedRecv, sizeof(parsedRecv)); if(secondSocketCount == -1) { printf("Error receiving data: server terminating.\n"); return 0; } else if(secondSocketCount == 0) { //no more data break; } strcat(recvline, parsedRecv); }*/ //This while loop is used to read in data (the response from the server) bzero(str, 655360); while(secondSocketCount = read(sockfd, recvline, sizeof(recvline)) &gt; 0) { strcat(str, recvline); } //bzero(parsedRecv, 655360); //recvline[strlen(recvline)] = '\0'; printf("\tData retrieved from main server.\n"); //This for loop finds the end of the HTTP header and copies everything after into parsedRecv for(stringCounter = 0, tempCount = 0; stringCounter &lt; strlen(str); stringCounter++) { //lazy if statement to find two \r\n in a row to mark the end of the header if(str[stringCounter] == '\r' &amp;&amp; str[stringCounter + 1] == '\n' &amp;&amp; str[stringCounter + 2] == '\r' &amp;&amp; str[stringCounter + 3] == '\n' &amp;&amp; flag == 0) { flag = 1; stringCounter += 3; } if(flag == 1) { parsedRecv[tempCount] = str[stringCounter]; tempCount++; } } flag = 0; parsedRecv[strlen(parsedRecv)] = '\0'; fp = fopen("ReturnedPageServer.html", "w"); if(fp != NULL) { fprintf(fp, "%s", parsedRecv); //fprintf(fp, "%s", recvline); } fclose(fp); printf("\tData saved to ReturnedPageServer.html\n"); } //strcpy(str, "This is a test of the Hello World Broadcast System.\n"); bzero(str, 655360); strcpy(str, parsedRecv); write(conn_fd, str, strlen(str)); close(conn_fd); printf("\tData sent to client.\n"); printf("Awaiting further connections...\n"); //strcpy(directory, ""); //strcpy(domain, ""); //strcpy(recvline, ""); bzero(directory, 1025); bzero(domain, 1025); bzero(temp, 1025); bzero(recvline, 655360); } return 0; } </code></pre> <p>Client.c</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netdb.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; //Code adapted from client code provided in class int main(int argc, char** argv) { int sockfd, n, port; int len = sizeof(struct sockaddr); char sendline[10000]; char recvline[655360]; struct sockaddr_in servaddr; FILE *fp; sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&amp;servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; if(argc &lt; 2) { printf("Error! Enter the port number for the server.\n\tEx: ./client 22000\n\r\0"); return 0; } else { port = atoi(argv[1]); } servaddr.sin_port = htons(port); inet_pton(AF_INET, "129.120.151.94", &amp;(servaddr.sin_addr)); //CSE01 IP connect(sockfd, (struct sockaddr*) &amp;servaddr, sizeof(servaddr)); printf("url: "); scanf("%s", sendline); //strcpy(sendline, "The server should display this text.\n\0"); //printf("\nLength of string: %d\n", strlen(sendline)); //printf("\t%s\n", sendline); write(sockfd, sendline, strlen(sendline)); fp = fopen("ReturnedPageClient.html", "w"); bzero(recvline, 655360); while(n = read(sockfd, recvline, sizeof(recvline)) &gt; 0) { //printf("%s", recvline); if(fp != NULL) { fprintf(fp, "%s", recvline); } else { printf("\tError saving file: client terminating.\n"); fclose(fp); return 0; } } fclose(fp); printf("\tResponse received from proxy server.\n\tFile saved as \"ReturnedPageClient.html\"\n"); close(sockfd); return 0; } </code></pre>
<c><linux><sockets><posix>
2016-02-29 20:54:03
LQ_CLOSE
35,709,996
trying to fix a code ms access
here is my code I keep getting the same error compile error: block if without end if here is my code that I am working with Private Sub Command1_Click() If IsNull(Me.txtusername) Then 'MsgBox "Please enter Username", vbInformation, "Username Required" If IsNull(Me.txtpassword) Then 'MsgBox "Please enter Password", vbInformation, "Password Required" Else 'processs the job If (IsNull(DLookup("[username]", "tbllogin info", "[username] ='" & Me.txtusername.Value & "' And password = '" & Me.txtpassword.Value & "'"))) Then MsgBox "login unsucessful" End If 'MsgBox "Login Succeddful" DoCmd.OpenForm "s-1 page" End Sub
<vba><ms-access>
2016-02-29 21:27:31
LQ_EDIT
35,710,263
"The visual Studio component cache is out of date, please restart Visual Studio."
<p>I'm on windows 7, using Atmel studio 7.0. When I opened up my project in Atmel Studio, it failed to load and gave this error:</p> <pre><code>The Visual Studio component cache is out of date please restart visual studio. </code></pre> <p>When I closed and reopened Atmel Studio, the same error continued. I also tried right clicking on my project, and selecting "Reload project" but then I got this error:</p> <pre><code>Value cannot be null. Parameter name: url </code></pre> <p>How can I open up my project?</p>
<visual-studio><atmel><atmelstudio>
2016-02-29 21:43:38
HQ
35,710,361
Python Flask send_file StringIO blank files
<p>I'm using python 3.5 and flask 0.10.1 and liking it, but having a bit of trouble with send_file. I ultimately want to process a pandas dataframe (from Form data, which is unused in this example but necessary in the future) and send it to download as a csv (without a temp file). The best way to accomplish this I've seen is to us StringIO.</p> <p>Here is the code I'm attempting to use:</p> <pre><code>@app.route('/test_download', methods = ['POST']) def test_download(): buffer = StringIO() buffer.write('Just some letters.') buffer.seek(0) return send_file(buffer, as_attachment = True,\ attachment_filename = 'a_file.txt', mimetype = 'text/csv') </code></pre> <p>A file downloads with the proper name, however the file is completely blank.</p> <p>Any ideas? Issues with encoding? Has this been answered elsewhere? Thanks!</p>
<python><flask><stringio>
2016-02-29 21:48:13
HQ
35,710,422
what's wrong in SELECT STATEMENT?
im using this code to get the last number in a fields where date of fields is today date: cn.Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Application.StartupPath & "\bysys.mdb") rs.Open("Select max(snum) From tblbill where idate = #" & Format(Today.Date, "dd/MM/yyyy") & "# ", cn, 1, 2) If IsDBNull(Rs.Fields(0).Value) Then TextBox6.Text = 1 Else TextBox6.Text = Rs.Fields(0).Value + 1 End If sometimes it works correctly but sometimes, always return 1.. please help!
<sql><vb.net><ms-access><select>
2016-02-29 21:52:11
LQ_EDIT
35,710,456
My HTML and CSS files won't link pleas
<p>html is like so:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;In Loving Memory of Jill Erin Hayes&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="/additional_pages/fp_frye.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="maincontent"&gt; &lt;div id="left"&gt; &lt;h1&gt;Jill E. Hayes&lt;/h1&gt; &lt;ul&gt;&lt;li&gt;mother&lt;/li&gt; &lt;li&gt;&lt;a href="https://www.utm.edu/departments/finearts/vanguard/index.php"&gt;actress&lt;/a&gt;&lt;/li&gt; &lt;li&gt;election commissioner&lt;/li&gt; &lt;li&gt;and so very much more&lt;/li&gt; &lt;/div&gt; &lt;div id="right"&gt; &lt;h2&gt;Her Story&lt;/h2&gt; &lt;p&gt;Born to Jerry and Debbie Hayes in Henry, TN in 1980, Jill was always very creative and fun. She flew through school, active in 4-H and theatre, all while maintaining good grades and a positive outlook on life. She attended the University of Tennessee at Martin after graduating Henry County High School, and in college, she majored in theatre and was a very active member of UTM's Vanguard theatre program. She met Joseph Frye in college, and the married and had two children, Shelby, named after her favorite play, &lt;i&gt;Steel Magnolias&lt;/i&gt;, and Hayes, named for her maiden name.&lt;/p&gt; &lt;p&gt;Jill gave up her dreams of Broadway to be a mother, and she got a job as the Henry County Administrator of Elections, where she not only helped her police officer husband raise their family, but also was able to be active in the democratic system, which she had always been passionate about. She worked elections for fifteen years before illness struck, and she was forced to resign to focus on regaining her health.&lt;/p&gt; &lt;p&gt;Lupus is, unfortunately, into a disease that garners much attention, despite being a fatal one. Jill went to countless doctors attempting to find out what was wrong with her before she was finally diagnosed with lupus, an aggressive autoimmune disease. This on top of being forced to quit her job as well as the divorce that ended a regrettably failing marriage was hard on her, but she still persevered to be the mother that both of her children needed. She managed to live with lupus for six years, before passing away at her parents' home on October 18, 2015, just weeks before her 25th birthday.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And then my Css file is like this:</p> <pre><code>body { background-color:light-green; } #maincontent { background-color:white; width:680px; height:400px; padding-top:20px; padding-left:20px; padding-right:20px; } #left { background-color:light-pink; width:200px; float:left; height:200px; } #right { background-color:light-green; width:400px; float:left; margin-left:40px; height:200px; } </code></pre> <p>I don't understand why it won't link, and I've visited several other forum topics on this subject. I'm very new to coding - this is for a class required to graduate - and I need help.</p>
<html><css>
2016-02-29 21:54:30
LQ_CLOSE
35,711,004
Could someone help me with create an application into kivy?
I just found out recently about kivy. Python i'm also studing recently. I would like application, made into kivy, which has 2 windows for input text and returning a label with result after clicking a button. This code must be in him: `def word_detect(a,b): y = [] e = [] s = [] for i in range(len(b)): z = [] for k in a: ml = 0 index = -1 for j in k: index += 1 if j == (b[i])[index]: ml += 1 if ml == int((b[i])[-1]): z.append(k) y.append(z) e.extend(z) for i in e: if (y[0]).count(i)==(y[1]).count(i)==(y[2]).count(i)==1 and s.count(i)==0: s.append(i) return s print word_detect(raw_input('list: '). upper(). split(','),raw_input('words: '). upper(). split(',')) ''' e.g: list : total,relax,mixer,remix,scope,candy,water words: helix 3, botex 1, below 2 result: ['relax'] RELAX hELiX - 3 matched letters boteX - 1 matched letter bELow - 2 matched letters '''`
<android><python><kivy><buildozer>
2016-02-29 22:28:34
LQ_EDIT
35,711,423
How to fix "Unable to acquire lock after 15 seconds" errors in Wildfly
<p>I have a web application that is <code>&lt;distributable/&gt;</code>, but also deployed to stand alone instances of Wildfly for local development work. Sometimes we have calls to the backend that can stall for a few seconds, which often leads to exceptions like the one shown below.</p> <p>How can I fix this given that I have no control over long running backend requests?</p> <pre><code>14:55:04,808 ERROR [org.infinispan.interceptors.InvocationContextInterceptor] (default task-6) ISPN000136: Error executing command LockControlCommand, writing keys []: org.infinispan.util.concurrent.TimeoutException: ISPN000299: Unable to acquire lock after 15 seconds for key LA6Q5r9L1q-VF2tyKE9Pc_bO9yYtzXu8dYt8l-BQ and requestor GlobalTransaction:&lt;null&gt;:37:local. Lock is held by GlobalTransaction:&lt;null&gt;:36:local at org.infinispan.util.concurrent.locks.impl.DefaultLockManager$KeyAwareExtendedLockPromise.lock(DefaultLockManager.java:236) at org.infinispan.interceptors.locking.AbstractLockingInterceptor.lockAllAndRecord(AbstractLockingInterceptor.java:199) at org.infinispan.interceptors.locking.AbstractTxLockingInterceptor.checkPendingAndLockAllKeys(AbstractTxLockingInterceptor.java:199) at org.infinispan.interceptors.locking.AbstractTxLockingInterceptor.lockAllOrRegisterBackupLock(AbstractTxLockingInterceptor.java:165) at org.infinispan.interceptors.locking.PessimisticLockingInterceptor.visitLockControlCommand(PessimisticLockingInterceptor.java:184) at org.infinispan.commands.control.LockControlCommand.acceptVisitor(LockControlCommand.java:110) at org.infinispan.interceptors.base.CommandInterceptor.invokeNextInterceptor(CommandInterceptor.java:99) at org.infinispan.interceptors.TxInterceptor.invokeNextInterceptorAndVerifyTransaction(TxInterceptor.java:157) at org.infinispan.interceptors.TxInterceptor.visitLockControlCommand(TxInterceptor.java:215) at org.infinispan.commands.control.LockControlCommand.acceptVisitor(LockControlCommand.java:110) at org.infinispan.interceptors.base.CommandInterceptor.invokeNextInterceptor(CommandInterceptor.java:99) at org.infinispan.interceptors.InvocationContextInterceptor.handleAll(InvocationContextInterceptor.java:107) at org.infinispan.interceptors.InvocationContextInterceptor.visitLockControlCommand(InvocationContextInterceptor.java:81) at org.infinispan.commands.control.LockControlCommand.acceptVisitor(LockControlCommand.java:110) at org.infinispan.interceptors.InterceptorChain.invoke(InterceptorChain.java:336) at org.infinispan.cache.impl.CacheImpl.lock(CacheImpl.java:828) at org.infinispan.cache.impl.CacheImpl.lock(CacheImpl.java:810) at org.infinispan.cache.impl.AbstractDelegatingAdvancedCache.lock(AbstractDelegatingAdvancedCache.java:177) at org.wildfly.clustering.web.infinispan.session.InfinispanSessionMetaDataFactory.getValue(InfinispanSessionMetaDataFactory.java:84) at org.wildfly.clustering.web.infinispan.session.InfinispanSessionMetaDataFactory.findValue(InfinispanSessionMetaDataFactory.java:69) at org.wildfly.clustering.web.infinispan.session.InfinispanSessionMetaDataFactory.findValue(InfinispanSessionMetaDataFactory.java:39) at org.wildfly.clustering.web.infinispan.session.InfinispanSessionFactory.findValue(InfinispanSessionFactory.java:61) at org.wildfly.clustering.web.infinispan.session.InfinispanSessionFactory.findValue(InfinispanSessionFactory.java:40) at org.wildfly.clustering.web.infinispan.session.InfinispanSessionManager.findSession(InfinispanSessionManager.java:234) at org.wildfly.clustering.web.undertow.session.DistributableSessionManager.getSession(DistributableSessionManager.java:140) at io.undertow.servlet.spec.ServletContextImpl.getSession(ServletContextImpl.java:726) at io.undertow.servlet.spec.HttpServletRequestImpl.getSession(HttpServletRequestImpl.java:370) at au.com.agic.settings.listener.SessionInvalidatorListener.clearSession(SessionInvalidatorListener.java:57) at au.com.agic.settings.listener.SessionInvalidatorListener.requestInitialized(SessionInvalidatorListener.java:52) at io.undertow.servlet.core.ApplicationListeners.requestInitialized(ApplicationListeners.java:245) at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:283) at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263) at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81) at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174) at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202) at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) </code></pre>
<wildfly><infinispan>
2016-02-29 22:56:44
HQ
35,712,050
Sort by value and key Python
I was searching for something to sort a list of pairs by values and keys in Python. I found this list.sort(key = lambda (k,v):(-v,k)), i tried to find some explanation about this but couldn't find anything which clarify my doubts. Can someone explain how this lambda function works?
<python><sorting><dictionary>
2016-02-29 23:46:13
LQ_EDIT
35,712,487
Keep Getting A SQL Syntax Error
<p>I've tried many things but for some reason I can not figure out why the following code keeps giving me an error.</p> <pre><code>$conn = new mysqli($servername, $username, $password, $dbname); if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } $sql = "INSERT INTO app_users (signupDate, userToken, ipAddress, countryCode, countryName, regionName, cityName, zipCode, latitude, longitude, timeZone, referer, userAgent, hostName) VALUES ('$ls_signupDate', '$ls_userToken', '$ls_ipAddress', '$ls_countryCode', '$ls_countryName', '$ls_regionName', '$ls_cityName', '$ls_zipCode', '$ls_latitude', '$ls_longitude', '$ls_timeZone', '$ls_referer', '$ls_userAgent', '$ls_hostName)'"; if ($conn-&gt;query($sql) === TRUE) { echo "Content Inserted successfully"; } else { echo "Error inserting content: " . $conn-&gt;error; } </code></pre> <p>The error it keeps giving me is...</p> <blockquote> <p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 2</p> </blockquote> <p><strong>What am I doing wrong here?</strong></p>
<php><mysql><database><mysqli><syntax-error>
2016-03-01 00:28:11
LQ_CLOSE
35,713,118
How does `ggplotGrob` work?
<p><a href="http://docs.ggplot2.org/0.9.3/ggplotGrob.html">docs.ggplot2.org</a> currently offers very little documentation for the function <code>ggplotGrob</code>. The <a href="http://svitsrv25.epfl.ch/R-doc/library/ggplot2/html/ggplotGrob-1l.html">EPFL website</a> is a little bit more informative but it is still not very helpful.</p> <p>Can you please provide a short tutorial on what one can do with the function <code>ggplotGrob</code>?</p>
<r><ggplot2>
2016-03-01 01:33:14
HQ
35,713,682
Socket.io gives CORS error even if I allowed cors it on server
<p>My node server and client are running on different ports(3001,5347 respectively). On client I had used,</p> <pre><code>var socket = io('http://127.0.0.1:3001'); </code></pre> <p>On server I tried all of following one by one</p> <pre><code> 1) io.set('origins', '*:*'); 2) io.set('origins', 'http://127.0.0.1:5347'); 3) io.set('origins', '*'); 4) io.set('origins', '127.0.0.1:5347'); </code></pre> <p>But I'm getting following error:</p> <blockquote> <p>XMLHttpRequest cannot load <a href="http://127.0.0.1:3001/socket.io/?EIO=3&amp;transport=polling&amp;t=1456799439856-4590" rel="noreferrer">http://127.0.0.1:3001/socket.io/?EIO=3&amp;transport=polling&amp;t=1456799439856-4590</a>. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'null' is therefore not allowed access.</p> </blockquote> <p>Note: I'm using express on server and I'm already using cors middleware in following way:</p> <pre><code>app.use(cors()); </code></pre> <p>Where app and cors are instances of express and cors respectively.</p>
<node.js><socket.io><cors>
2016-03-01 02:36:40
HQ
35,714,453
Python decorators in classes Eoor
class A(object): def wrapped(self, func): func.string = self.get_something() return func def get_something(self): return "something" @wrapped def main(self): print self.main.string a = A() a.main()
<python><python-decorators>
2016-03-01 04:06:15
LQ_EDIT
35,714,595
How are ReSharper C++ and Visual Assist different
<p>What's different between the two? JetBrains lists some differences <a href="https://www.jetbrains.com/resharper-cpp/documentation/resharper_cpp_vs_visual_assist.html" rel="noreferrer">here</a>, but I heard there might be some inaccuracies in the list.</p>
<c++><resharper><visual-studio-addins><visual-assist><resharper-c++>
2016-03-01 04:20:47
HQ
35,714,799
Need help writing to a file in Python
I am making a French Translator and purely for experience I want to make a 'Save' button they will save what is currently entered into the entry fields. e1 = Entry(master) e2 = Entry(master) e1.grid(row=0, column=1) e2.grid(row=1, column=1) def write(): name = 'SavedFile.txt' hello = int(3) file = open(name,'w+') file.write(e1.get()) file.close() menubar = Menu(master) master.config(menu=menubar) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Save", command=write()) Changing file.write(e1.get()) to file.write('hello'), works and writes 'Hello' to SavedFile. But I want it so when I click 'Save' under 'File', it rewrites to the file (preferably without overwriting what is there) P.s., s = e1.get() will actually make s = to whatever is currently in the field
<python>
2016-03-01 04:39:20
LQ_EDIT
35,715,256
Running the Haskell compiled to JavaScript on the JVM
<p>Java 8 has an inbuilt JavaScript engine called Nashorn so it is actually possible to run Haskell compiled to JavaScript on the JVM.</p> <p>The following program works:</p> <pre><code>{-# LANGUAGE JavaScriptFFI #-} module Main where foreign import javascript unsafe "console={log: function(s) { java.lang.System.out.print(s); }}" setupConsole :: IO () foreign import javascript unsafe "java.lang.System.exit($1)" sysexit :: Int -&gt; IO () main = do setupConsole putStrLn "Hello from Haskell!" sysexit 0 </code></pre> <p>We can run it with: (<em>Side note:</em> It is possible to run this as a normal Java program.<code>jjs</code> is just a convenient way to run pure JavaScript code on the JVM)</p> <pre><code>$ ghcjs -o Main Main.hs [1 of 1] Compiling Main ( Main.hs, Main.js_o ) Linking Main.jsexe (Main) $ which jjs ~/bin/jdk/bin/jjs $ jjs Main.jsexe/all.js Hello from Haskell! </code></pre> <p>In the above code, <code>console.log</code> needs to be defined using <code>java.lang.System.print</code> as Nashorn doesn't provide the default global <code>console</code> object and Haskell's <code>putStrLn</code> otherwise doesn't seem to be printing anything.</p> <p>The other thing is that the JVM needs to be exited with <code>sysexit</code> FFI function implemented with <code>java.lang.System.exit</code>. </p> <p>I have 2 questions:</p> <ol> <li>Similar to <code>console.log</code>, what other host dependencies are assumed in ghcjs that have to be defined?</li> <li>Is the JVM not shutting down normally because of ghcjs creating an event loop in the background or some other reason? Is there any way to avoid that and make the program exit normally?</li> </ol>
<haskell><ghcjs>
2016-03-01 05:23:20
HQ
35,715,296
PDO Connection established but not inserted in Cakephp.. Plz Help this
I am trying to insert the values into the table through controller in Cakephp. I've tested first.. It says db connected succesfully. but i've inserted something into the table using PDO by prepared statement it show the error like "Error: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound". Here is my table structure: CREATE TABLE IF NOT EXISTS `test` ( `id` int(10) unsigned NOT NULL, `name` varchar(255) NOT NULL, `job` varchar(255) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; The function i mentioned in my controller is, public function insdb() { $sqlInsert = $this->User->query("INSERT INTO `test` (`name`, `job`) VALUES (:name1,:job1)"); $preparedStatement = $conn->prepare($sqlInsert); $preparedStatement->User->execute(array(':name1' => 'Tony', ':job1' => 'gardner')); }
<mysql><pdo><insert>
2016-03-01 05:26:14
LQ_EDIT
35,715,590
How can i get the data from Swift based IBOutlet UITextFiled?
@IBOutlet var firstName:UITextField? @IBOutlet var lastName:UITextField? let string = firstName!.text print(string) The output is like as bellow, Optional("fhh") How can i get the data without optional text and double quotes.
<ios><swift><iboutlet>
2016-03-01 05:48:25
LQ_EDIT
35,715,968
In java, is there a way to generate a valid dictionary word of certain length randomly?
<p>I need to generate a valid dictionary word of certain length but in a random fashion. Is there an api or code snippet that does this? I tried googling it but couldn't find anything for this.</p> <p>Thanks</p>
<java>
2016-03-01 06:19:06
LQ_CLOSE
35,715,992
how work this insert and update with if statement query in mysql
SELECT IFNULL(post.id ,INSERT INTO post(pdate,body) VALUES (1,'a') ,UPDATE post set body='update',pdate=2 ) from post where body='a' and pdate=1
<mysql>
2016-03-01 06:20:38
LQ_EDIT
35,716,121
How to extract phrases from corpus using gensim
<p>For preprocessing the corpus I was planing to extarct common phrases from the corpus, for this I tried using <strong>Phrases</strong> model in gensim, I tried below code but it's not giving me desired output.</p> <p><strong>My code</strong></p> <pre><code>from gensim.models import Phrases documents = ["the mayor of new york was there", "machine learning can be useful sometimes"] sentence_stream = [doc.split(" ") for doc in documents] bigram = Phrases(sentence_stream) sent = [u'the', u'mayor', u'of', u'new', u'york', u'was', u'there'] print(bigram[sent]) </code></pre> <p><strong>Output</strong></p> <pre><code>[u'the', u'mayor', u'of', u'new', u'york', u'was', u'there'] </code></pre> <p><strong>But it should come as</strong> </p> <pre><code>[u'the', u'mayor', u'of', u'new_york', u'was', u'there'] </code></pre> <p>But when I tried to print vocab of train data, I can see bigram, but its not working with test data, where I am going wrong?</p> <pre><code>print bigram.vocab defaultdict(&lt;type 'int'&gt;, {'useful': 1, 'was_there': 1, 'learning_can': 1, 'learning': 1, 'of_new': 1, 'can_be': 1, 'mayor': 1, 'there': 1, 'machine': 1, 'new': 1, 'was': 1, 'useful_sometimes': 1, 'be': 1, 'mayor_of': 1, 'york_was': 1, 'york': 1, 'machine_learning': 1, 'the_mayor': 1, 'new_york': 1, 'of': 1, 'sometimes': 1, 'can': 1, 'be_useful': 1, 'the': 1}) </code></pre>
<python><nlp><gensim>
2016-03-01 06:30:21
HQ
35,716,830
Basemap with Python 3.5 Anaconda on Windows
<p>I use Python 3.5 with latest version of Anaconda on Windows (64 bit). I wanted to install Basemap using <code>conda install basemap</code>. Apparently there is a conflict between Python 3 and basemap. After some googling indeed I found that basemap is not supported on Python 3 for Windows users (ex: <a href="https://groups.google.com/a/continuum.io/forum/#!topic/anaconda/TjAwi3ilQaU" rel="noreferrer">https://groups.google.com/a/continuum.io/forum/#!topic/anaconda/TjAwi3ilQaU</a>).</p> <p>For obvious reasons I do not want to downgrade to Python 2. What would then be the simplest alternative solution?</p> <ul> <li>Is there an alternative package similar to basemap for ploting maps, etc.?</li> <li>Should I use a second environment which uses Python 2 and basemap? I have never done that but it seems possible (<a href="http://conda.pydata.org/docs/py2or3.html" rel="noreferrer">http://conda.pydata.org/docs/py2or3.html</a>). Is it "safe"? Should I install again all the other packages (matplotlib, numpy, etc.) on the second environment? </li> </ul> <p>Thanks in advance for the help and advice. </p>
<python><matplotlib><anaconda><matplotlib-basemap>
2016-03-01 07:16:35
HQ
35,717,029
How to call conditionally B::f only if derived from B in C++11?
<p>In case when static polymorphism is used, especially in templates (e.g. with policy/strategy pattern), it may be required to call base function member, but you don't know was instantiated class actually derived from this base or not.</p> <p>This easily can be solved with old good C++ ellipsis overload trick:</p> <pre><code>#include &lt;iostream&gt; template &lt;class I&gt; struct if_derived_from { template &lt;void (I::*f)()&gt; static void call(I&amp; x) { (x.*f)(); } static void call(...) { } }; struct A { void reset() { std::cout &lt;&lt; "reset A" &lt;&lt; std::endl; } }; struct B { void reset() { std::cout &lt;&lt; "reset B" &lt;&lt; std::endl; } }; struct C { void reset() { std::cout &lt;&lt; "reset C" &lt;&lt; std::endl; } }; struct E: C { void reset() { std::cout &lt;&lt; "reset E" &lt;&lt; std::endl; } }; struct D: E {}; struct X: A, D {}; int main() { X x; if_derived_from&lt;A&gt;::call&lt;&amp;A::reset&gt;(x); if_derived_from&lt;B&gt;::call&lt;&amp;B::reset&gt;(x); if_derived_from&lt;C&gt;::call&lt;&amp;C::reset&gt;(x); if_derived_from&lt;E&gt;::call&lt;&amp;E::reset&gt;(x); return 0; } </code></pre> <p>The question is:</p> <ul> <li>Is there any better <em>simple</em> way (e.g. SFINAE doesn't look so) to achieve same result in C++11/C++14?</li> <li>Would empty call of ellipsis parameter function be elided by optimizing compiler? Hope such case is not special against any "normal" function.</li> </ul>
<c++><templates><c++11><c++14>
2016-03-01 07:29:08
HQ
35,717,534
What is the real alternative of read_stream to read facebook news feeds?
<p>What is the real alternative of read_stream to read the news feeds from Facebook ? The answer is usually users_posts , but can the latter fetch the news feeds ? - for instance like the suggested posts on the timeline -</p> <p>In other words I am trying to know if there is a way through the new Graph API to pull ads like what we used to do with FQL and read_stream.</p>
<c#><php><facebook><facebook-graph-api><facebook-graph-api-v2.0>
2016-03-01 08:00:48
LQ_CLOSE
35,717,666
I am very new to GNUplot. please help me
I have a file with three columns. All three have different values. To plot it in a smooth surface with a color gradient for third column what should I do? the data file is look like follows: 1431.564087 -556.7048268 -14.09538931 1445.544205 -562.1413974 0 1445.544205 -562.1413974 -6.577848346 1452.06826 -564.6784636 6.577848346 1445.544205 -562.1413974 -6.577848346 1452.06826 -564.6784636 9.396926208 1442.748182 -561.0540833 -1.879385242 1444.612197 -561.7789593 11.27631145 1433.428103 -557.4297029 -4.698463104 1438.088142 -559.2418931 4.698463104 1433.428103 -557.4297029 0 1433.428103 -557.4297029 0.939692621 1432.496095 -557.0672648 -0.939692621 1433.428103 -557.4297029 0 1433.428103 -557.4297029 -2.819077862 1436.224127 -558.517017 -1.879385242 1438.088142 -559.2418931 0 1438.088142 -559.2418931 0 1438.088142 -559.2418931 0 1438.088142 -559.2418931 6.577848346
<gnuplot>
2016-03-01 08:10:01
LQ_EDIT
35,718,103
How to specify the size of the icon on the Marker in Google Maps V2 Android
<p>In may app i use Map from Google Maps V2 and in this map i am trying to add markers each Marker with an icon, but the marker is taking the size of the icon which is making the icon looks flue. How can i specify the size of the marker in <strong>dp</strong> so that i can control how it looks like on the map</p>
<android><google-maps><size><marker>
2016-03-01 08:38:43
HQ
35,718,504
StringUtils.isNumeric is undefined method
<p>I have imported that library:</p> <pre><code>import org.apache.commons.codec.binary.StringUtils; </code></pre> <p>And tried to use some of methods, but failed:</p> <pre><code>StringUtils.isNumeric("2398sdf"); </code></pre> <p>IDE keep saying me that, method is undefined. What is wrong here?</p>
<java><import><compiler-errors><apache-stringutils>
2016-03-01 09:02:15
LQ_CLOSE
35,718,652
Operator '==' cannot be applied to operands of type 'bool' and 'string' in mvc c#
<p>I am new in MVC C#. I am getting this error, I have checked and found similar which is not going to my error.</p> <p>The error is - <i>"Operator '==' cannot be applied to operands of type 'bool' and 'string'"</i></p> <p>The Code is -</p> <pre><code>List&lt;RptItem&gt; _r2 = _r1.Where(xx =&gt; xx.Value == ("rcat")) .Select(xx=&gt;(KeyValuePair&lt;string, string&gt;?)xx) .FirstOrDefault(); </code></pre> <p>Could someone help me, what I need to do.</p> <p>Thanks</p>
<c#><model-view-controller><razor>
2016-03-01 09:09:56
LQ_CLOSE
35,718,949
Is it good to use two tables seperately, or one table with both data within?
Is it good to do: **Phone Table:** id name 1 blabla 2 blabla 3 blabla . .. **Laptop Table:** id name 1 blabla 2 blabla 3 blabla . .. **OR** **Products Table:** id name type 1 blabla laptop 2 blabla phone 3 blabla laptop . .. Thanks All :)
<mysql><sql>
2016-03-01 09:24:09
LQ_EDIT
35,718,975
iOS & Android App Download
We have publish app in iOS & Android store last year. When I go to the google play store I can see 50,000 to 100,000 App downloads. But how can I know how much exact number of apps are downloaded. Kindly can somebody help me. How to check. Please note I have username & password for both iOS & Android developer account.
<ios><google-play>
2016-03-01 09:25:25
LQ_EDIT
35,718,993
Adding more then one client to the Spring OAuth2 Auth Server
<p>I have Spring OAuth Authorization server and I want to add support for more then one client(id). I configured clients like this:</p> <pre><code>clients .inMemory().withClient(client).secret(clientSecret) .resourceIds(resourceId) .authorizedGrantTypes("client_credentials", "password", "refresh_token", "implicit", "authorization_code") .authorities("ROLE_USER") .scopes("read", "write") .autoApprove(true) .and() .inMemory().withClient("acme").secret("acmesecret") .resourceIds(resourceId) .authorizedGrantTypes("client_credentials", "password", "refresh_token", "implicit", "authorization_code") .authorities("ROLE_USER_ACME") .scopes("read", "write") .autoApprove(true); </code></pre> <p>I can get access token with first client, but i get this error when trying to get access token with second client:</p> <pre><code>{ "timestamp": 1456822249638, "status": 401, "error": "Unauthorized", "message": "Bad credentials", "path": "/oauth/token" } </code></pre> <p>Is it possible to add more then one client and how to do it? Allso, how to read clients from a database?</p>
<java><spring><spring-security><oauth-2.0><spring-security-oauth2>
2016-03-01 09:26:24
HQ
35,719,704
deviding single column into two columns
how can i devide the payment column into refund and trasnfer fee on the bases of comments column <!-- begin snippet: js hide: false --> <!-- language: lang-html --> <table> <thead> <th>Payment</th> <th>comments</th> </thead> <tbody> <tr> <td>3000</td> <td>refund</td> </tr> <tr> <td>3000</td> <td>refund</td> </tr> <tr> <td>3000</td> <td>transfer fee</td> </tr> </tbody> </table> <!-- end snippet -->
<html><css>
2016-03-01 09:55:24
LQ_EDIT
35,719,797
Is using magic (me/self) resource identifiers going against REST principles?
<p>I've seen URIs that support magic ids for the authenticated user like below:</p> <pre><code>GET /user/me - list my profile GET /user/me/photos - list my photos </code></pre> <p>where the ones below use the actual user id</p> <pre><code>GET /user/742924 GET /user/742924/photos </code></pre> <p>The problem I see is that the same resource id points to a different resource depending on the authenticated user. </p> <p>Is this going against any REST principles?</p>
<web-services><rest><restful-url>
2016-03-01 09:59:27
HQ
35,720,166
error in cast variable
i get an error when i want to cast a query:this is the code of the query. var query = ( from article in db.V_CLIENT_PRIX where article.CLIENT == Current_Client_Id select new { ID = article.ID, ARTICLE = article.Article, REFERENCE = article.Reference, REMISE = article.Remise, PRIXVHT = article.PrixVHT, CLIENT = article.CLIENT, }); and i cast it like that: ConventionList articlelistconvention = new ConventionList(); articlelistconvention = (ConventionList)query; and this is the code of my model:ConventionList public class Commandelist { public string ARTICLE { get; set; } public string CIN { get; set; } public decimal STOCK { get; set; } public string REFERENCE { get; set; } public decimal PRIXVHT { get; set; } public string IMAGE { get; set; } public double QUANTITE { get; set; } } Can someone help me how to fix it and thank you
<c#>
2016-03-01 10:16:18
LQ_EDIT
35,720,399
Yii2 Rest API Bearer Authentication
<p>I've made a Yii2 REST API. With the API you can get a list of cars. Now I want to use the Bearer Authentication to protect the API. But I don't know how it works.</p> <p>First of all. I set up the authenticator in the behaviors method of my controller.</p> <pre><code>public function behaviors(){ return [ 'contentNegotiator' =&gt; [ 'class' =&gt; ContentNegotiator::className(), 'formats' =&gt; [ 'application/json' =&gt; Response::FORMAT_JSON, ], ], 'authenticator' =&gt; [ 'class' =&gt; CompositeAuth::className(), 'authMethods' =&gt; [ HttpBearerAuth::className(), ], ] ]; } </code></pre> <p>This works just fine. If I go to the URL I will get an 'Unauthorized' message. </p> <p>In my wordpress plugin I've made an function to use the API and set the header with the authentication key. </p> <pre><code>function getJSON($template_url) { $authorization = "Authorization: Bearer " . get_option("auth_key"); // Create curl resource $ch = curl_init(); // Set URL curl_setopt($ch, CURLOPT_URL, $template_url); // Return transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Set headers curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization)); // $output contains output as a string $output = curl_exec($ch); // Close curl resource curl_close($ch); return json_decode($output, true); } </code></pre> <p>But now my question is. How can I check in the API if this key is valid and give me the response. I want to search for the key in de database and if it exists it should also give me the id or email thats in the same row.</p> <p>I have no idea how to do this.</p>
<api><rest><authentication><yii2><bearer-token>
2016-03-01 10:26:39
HQ
35,720,851
Correct way to change a list of strings to list of ints
<pre><code>dict = {0: ['2', '6'], 1: ['2'], 2: ['3']} print("Original: ") print(dict) for key,vals in dict.items(): vals = [int(s) for s in vals] print("New: ") print(dict) </code></pre> <p>Output:</p> <pre><code>Original: {0: ['2', '6'], 1: ['2'], 2: ['3']} New: {0: ['2', '6'], 1: ['2'], 2: ['3']} </code></pre> <p>I can't figure why the list of values is not changing, I have tried the map() function and it also does not work, any reason why?</p>
<python><list><dictionary>
2016-03-01 10:47:01
LQ_CLOSE
35,721,256
c++ inter thread communication
here is my simple code, i want to get in the console_task, the value of the variable i in the dialer_task... without using global variable Thanks for help #include <stdio.h> #include <sys/types.h> #include <signal.h> #include <strings.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <thread> #include "console.hpp" using namespace std; void console_task(){ console(); } void dialer_task(){ int i=0; while (1) { printf("LOOP %d\n",i); i++; sleep(5); } } int main() { thread t1(console_task); thread t2(dialer_task); t1.join(); t2.join(); return 0; }
<c++><multithreading><c++11>
2016-03-01 11:07:03
LQ_EDIT
35,721,557
boto3: Spot Instance Creation
<p>I'm trying to create a spot instance using boto3. Although I follow the <a href="http://boto3.readthedocs.org/en/latest/reference/services/ec2.html#EC2.Client.request_spot_instances" rel="noreferrer">API documentation</a>, I receive an exception I couldn't be able to figure out. The code I'm using is: </p> <pre><code>import boto3 import datetime client = boto3.client('ec2') response = client.request_spot_instances( DryRun=False, SpotPrice='0.10', ClientToken='string', InstanceCount=1, Type='one-time', LaunchSpecification={ 'ImageId': 'ami-fce3c696', 'KeyName': 'awskey.pem', 'SecurityGroups': ['sg-709f8709'], 'InstanceType': 'm4.large', 'Placement': { 'AvailabilityZone': 'us-east-1a', }, 'BlockDeviceMappings': [ { 'Ebs': { 'SnapshotId': 'snap-f70deff0', 'VolumeSize': 100, 'DeleteOnTermination': True, 'VolumeType': 'gp2', 'Iops': 300, 'Encrypted': False }, }, ], 'EbsOptimized': True, 'Monitoring': { 'Enabled': True }, 'SecurityGroupIds': [ 'sg-709f8709', ] } ) </code></pre> <p>And I receive the following exception:</p> <pre><code>botocore.exceptions.ClientError: An error occurred (InvalidParameterValue) when calling the RequestSpotInstances operation: Value () for parameter groupId is invalid. The value cannot be empty </code></pre> <p>The thing is there is no groupId parameter in the request in the <a href="http://boto3.readthedocs.org/en/latest/reference/services/ec2.html#EC2.Client.request_spot_instances" rel="noreferrer">API documentation</a>. </p> <p>Am I missing something?</p>
<python><amazon-web-services><amazon-ec2><boto><boto3>
2016-03-01 11:22:44
HQ
35,722,093
Send multipart/form-data files with angular using $http
<p>I know there are a lot of questions about this, but I can't get this to work:</p> <p>I want to upload a file from input to a server in multipart/form-data</p> <p>I've tried two approaches. First:</p> <pre><code>headers: { 'Content-Type': undefined }, </code></pre> <p>Which results in e.g. for an image</p> <pre><code>Content-Type:image/png </code></pre> <p>while it should be multipart/form-data</p> <p>and the other: </p> <pre><code>headers: { 'Content-Type': multipart/form-data }, </code></pre> <p>But this asks for a boundry header, which I believe should not be manually inserted... </p> <p>What is a clean way to solve this problem? I've read that you can do </p> <pre><code>$httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8'; </code></pre> <p>But I don't want all my posts to be multipart/form-data. The default should be JSON</p>
<angularjs><http><file-upload><http-headers><multipartform-data>
2016-03-01 11:48:25
HQ
35,722,293
How to authenticate users for AWS API Gateway?
<p>I am creating a server less REST API using AWS API Gateway and AWS Lambda. While the end points have been created and linked with the corresponding Lambda functions, next step is to add authentication layer to authenticate users via email and password. From what I could understand from the documentation, API Gateway methods can support either API Key based access or IAM based access. But I could not understand how to securely implement the authentication using API keys. </p> <p>Will I have to create a server for doing the authentication and managing the users ? Is there any way this can be a complete server less end to end application ? Any resources for pointing in the right direction will be highly appreciated. I am looking at <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html" rel="noreferrer">this document</a> at the moment</p>
<aws-api-gateway>
2016-03-01 11:57:44
HQ
35,722,626
How to best program a and b or not a and c
What would be the best approach to set a boolean variable that is supposed to be true for **(a && b) || (!a && c)**. My first idea would be to simply write it down like that: $result = ($a && $b) || (!$a && $c); But would it be in any way better or more time efficient to do something like this: $result = false; if ( $a ) { $result = $b; } else { $result = $c; }
<php><logic>
2016-03-01 12:14:16
LQ_EDIT
35,722,675
Technology stack selection : PHP, Ruby on Rails with World Press
<p>I have to create a web site with the functionality of similar to some e-commerce website, but it will also have a user forum and the users will have ability to write blogs/articles. I will also have a mobile app (hybrid app for iOS and android), so I want my server side Rest APIs to be re-usable from my web front as well as from mobile app perspective (not 100% but at least the platform and technology I want to be same, so it will be easy for me to write back end code for my website and mobile app).</p> <p>With above in my mind, I would prefer to leverage something like world press , as it will save me a lot of design and tempting time for my website and it also have forum plugins etc. I am the single developer who will be doing everything.</p> <p>My questions are as below :</p> <ol> <li>If I go with World press, my only technology options are PHP/MySQL, is it correct? if yes, then how good the idea is to create REST APIs in PHP? up to what extend World press gives me option to write my custom code and customize my website from coding perspective?</li> <li>Is Ruby on Rails a better fit for this scenario? can I use RoR with World Press? How are RoR server side REST APIs in terms of performance?</li> <li>Not leaning towards the Node js solution as my use cases are not really heavily real time features, but more of a CRUD operations, and on top of that I will not be able to leverage any CMS such as World Press in this case.</li> <li>For forum, is it a good idea to leverage some plugin such as bb press, or vBulletin? any other better option? I think writing of all the forum functionality from scratch won’t be a good idea.</li> </ol> <p>Any guidance will be highly appreciated.</p> <p>Thanks.</p>
<php><ruby-on-rails><wordpress><forum><vbulletin>
2016-03-01 12:16:31
LQ_CLOSE
35,723,062
Get the percentage of a number with javascript
<p>So I am creating a web app and I get some data.</p> <p>There are points you have now (now=284), and total points (total=1000). So, The difference between them is dif=716.</p> <p>How do I use javascript to turn the difference in to a percentage value , for example 32% or whatever?</p> <p>Thanks</p>
<javascript><math><percentage>
2016-03-01 12:33:11
LQ_CLOSE
35,724,165
(405) Method Not Allowed. WCF WebService
<p>Introduction:</p> <p>Hello, I am trying to set up a WCF web service on my local IIS 7.5 server, however after I finish the basic configurations I am unable to send data with a WinForms test client and it returns the error mentioned in the titles. I have already searched similar threads on this problem but i did not find anything that would fit my problem.</p> <p>Data:</p> <p>-Both the Wcf WebService and the test client where provided from a 3rd party</p> <p>-They already work on another server and I am using the same versions</p> <p>-I am probably doing something wrong when I enable or configure IIS</p> <p>Request:</p> <p>-I need to know what IIS features I need to enable/disable in order to install it correctly so I can use the Wcf WebService.(If that's the case).</p> <p>-How to correctly configure the server in order to solve the above mentioned error.</p> <p>My Configurations:</p> <p>-After Installing IIS I changed the DefaulAppPool to .NET Framework v4.0.30.319; pipeline mode: Integrated. -Advanced Settings: Load User profile = False.</p> <p>-Created a new Website named "WcfMicrocontrollerService" using DefaultAppPool.Binding; Type:http, IP adress: , port: 80</p> <p>At this point I can access it trough a web browser, however when I use the test client to POST data to the service I get the following error: <em>"The remote server returned an unexpected response:(405) Method Not Allowed."</em></p> <p>Here are the data packets sent as recorded by Fiddler: Sent:</p> <pre><code>POST http://192.168.0.102/MicroControllerComSvc.svc HTTP/1.1 Content-Type: text/xml; charset=utf-8 SOAPAction: "http://tempuri.org/IMicroControllerComSvc/GetMicrocontrollerData" Host: 192.168.0.102 Content-Length: 237 Expect: 100-continue Accept-Encoding: gzip, deflate Connection: Keep-Alive &lt;s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;s:Body&gt;&lt;GetMicrocontrollerData xmlns="http://tempuri.org/"&gt;&lt;microControllerData&gt;1,1,1,1,2,2,1,0,100,300&lt;/microControllerData&gt;&lt;/GetMicrocontrollerData&gt;&lt;/s:Body&gt;&lt;/s:Envelope&gt; </code></pre> <p>Received: </p> <pre><code>HTTP/1.1 405 Method Not Allowed Cache-Control: private Allow: GET, HEAD, OPTIONS, TRACE Content-Type: text/html; charset=utf-8 Server: Microsoft-IIS/7.5 X-Powered-By: ASP.NET Date: Tue, 01 Mar 2016 10:44:44 GMT Content-Length: 5671 </code></pre> <p>And here's the body: <a href="https://dl.dropboxusercontent.com/u/2237590/405.html" rel="noreferrer">https://dl.dropboxusercontent.com/u/2237590/405.html</a></p> <p>This seems to indicate that I should take a look in handler mappings but I have no idea what to edit there.</p>
<asp.net><web-services><wcf><iis><http-status-code-405>
2016-03-01 13:25:02
HQ
35,724,420
Static class in typescript
<p>Is there any way to create an static class in typescript, node.js </p> <p>I want to create an static class to keep all constants and string in that.</p> <p>what could be the best way to do that ? </p>
<javascript><node.js><static><typescript>
2016-03-01 13:37:36
HQ
35,724,495
Divide oranges into different sized boxes. Java Puzzle
<p>Theres three boxes</p> <p>User inputs the number of oranges.</p> <p>Large box holds 20, medium 10 and the small 5 oranges. </p> <p>The shipping cost of a large box is $8.80, medium box, $6.00 and small box $4.50. </p> <p>The order is shipped in the least expensive manner. </p> <p>For example, the order of 52 oranges will be shipped in four boxes: two large, one medium, and one small. </p> <p>This is where it gets tricky.</p> <p>The rule for packing is to fill the large and medium boxes completely; that is, the box is fully packed. </p> <p>Only the small boxes can have empty spaces. For example, to ship 52 oranges, you could have used 3 large boxes, but that would leave the third box not fully packed.</p> <p>Shipping cost should be displayed and method should be used in java </p> <p>Anyone care to help an old guy learning java out?</p>
<java><methods>
2016-03-01 13:40:38
LQ_CLOSE
35,724,713
What is the better and secure way to login and logout in PHP?
<p>I'm a beginner in PHP. my login page is a <strong><em>login.html</em></strong> page and it posts inputted data to a <strong><em>logged.php</em></strong> page. and in this page it checks inputted data with my DB and if it was true, it showed this <strong><em>logedd.php</em></strong> page or if not, it returns to <strong><em>login.html</em></strong> page with the code below:</p> <pre><code>header('Location:Login.html'); </code></pre> <p>and also when I press Logout icon in <strong><em>logged.php</em></strong>, it returns to <strong><em>login.html</em></strong> by a href link in it. like this:</p> <pre><code>&lt;a href="login.php" target="_self"&gt; press to logout &lt;/a&gt; </code></pre> <p>Now my question is, Is this login and logout way secure or not? if not please describe why and how to make it secure? thanks.</p>
<php><html><login>
2016-03-01 13:50:18
LQ_CLOSE
35,725,174
Google Cloud SDK installer fails to complete component installation on Windows 7
<p>During installation I get a message:</p> <p>Unfortunately, the component installation did not complete successfully. Please check the detailed logs for the error message.</p> <p>I tried installing to all users, single user, many destinations and names.</p> <p>Details:</p> <p>Output folder: C:\Program Files (x86)\Google\Cloud SDK Downloading Google Cloud SDK core. Extracting Google Cloud SDK core. Create Google Cloud SDK bat file: C:\Program Files (x86)\Google\Cloud SDK\cloud_env.bat Installing components. The filename, directory name, or volume label syntax is incorrect. Failed to install.</p> <p>What to do?</p>
<windows><installation><google-cloud-sdk>
2016-03-01 14:10:32
HQ
35,726,635
How to solve in `block (2 levels) in <top (required)>' in Ruby
I am extracting a value from xml And I am using that value to check if it exists in a PDF file @reader = file('C:\Users\ecz560\Desktop\30004_Standard.pdf').parse_pdf @xml = file('C:\Users\ecz560\Desktop\30004Standard.xml').parse_xmlDoc @CustName = @xml.xpath("//Customer[RTLtr_Loancust='0163426']//RTLtr_CustomerName").map(&:text).to_s page_index = 0 @reader.pages.each do |page| page_index = page_index+1 if expect(page.text).to include @CustName valid_text = "Given text is present in -- #{page_index}" puts valid_text end end But I am getting a error ./features/step_definitions/Letters/Test1_Letters.rb:370:in `block (2 levels) in <top (required)>' ./features/step_definitions/Letters/Test1_Letters.rb:368:in `each' ./features/step_definitions/Letters/Test1_Letters.rb:368:in `/^I validate the PDF content$/' C:\Users\ecz560\Documents\GitHub\ATDD Local\features\FeatureFiles\Letters\Test1_Letters.feature:72:in `Then I validate the PDF content' How can I resolve this ?
<ruby><rspec><pdf-reader>
2016-03-01 15:17:38
LQ_EDIT
35,727,197
Importing CSV data into MYSQL via PHP
<p>I am working on a website which uses data from a CRM system, this data is in CSV format but when im trying to import into MYSQL via php something is corrupting and forcing a record to split and take 2 rows. Example of CSV field below - something in it is causing the error/split to another row in the database. It seems to be some kind of character but ive tried to replace the culprit ones. Any ideas would be GREATLY appreciated as I have spent ages trying to figure this out!! im using fgetcsv to import. I can import the csv file no problem via phpmyadmin</p> <p>"GREAT FIRST TIME PURCHASE TWO BED END TERRACED IN A POPULAR LOCATION. Pleased to have available this well presented two bed end terraced situated in an ideal location for all local amenities, just a short stroll to the Stretford Arndale Centre and close proximity to the Metrolink tram station for commuting into the city centre and Media city. The accommodation briefly comprising, lounge with staircase leading to first floor, kitchen/diner and cellar used for storage. Whilst to the first floor there are two double bedrooms and a family bathroom. OUTSIDE Enclosed Court yard to the rear. Private parking space."</p>
<php><mysql><csv>
2016-03-01 15:43:43
LQ_CLOSE
35,727,566
Convert string to date in sql
I am facing a problem where I need to convert a string to date like 11 years 10 months 12 days to a date in SQL. Please help any help would be appreciated.
<sql><sql-server>
2016-03-01 15:59:38
LQ_EDIT
35,727,697
How do I the site logo depending on the URL the request was made from?
<p>I created a product registration page using ASP.Net MVC. I need to implement the same product registration page for subsidiaries (maybe 3 or 4) with a few minor changes to the way the site looks. For example, the logo will be different and some text at the top of the page. What is the best way to use the same codebase?</p> <p>The best option I could come up with is passing HttpContext.Current.Request.URL to the view and using java script to update it. </p> <p>However, I know routing can be an option too.</p>
<asp.net-mvc><design-patterns>
2016-03-01 16:04:50
LQ_CLOSE
35,728,117
Difference between import http = require('http'); and import * as http from 'http';?
<p>I haven't been able to find a worthwhile NodeJS with Typescript tutorial out there so I'm diving in unguided and sure enough I have a question.</p> <p>I don't understand the difference between these two lines:</p> <pre><code>import * as http from 'http'; // and import http = require('http'); </code></pre> <p>They seem to function the same way but I imagine there's probably some nuance to their behavior or else one of them probably wouldn't exist.</p> <p>I do understand that the first approach could let me selectively import from a module but if I'm importing all of the module then is there a difference between the two? Is there a preferred way? What if I'm importing from my own files, does that change anything?</p>
<node.js><typescript>
2016-03-01 16:24:52
HQ
35,728,731
How to run a jquery function in Angular 2 after every component finish loading
<p>I have tried all the life cycle hooks but can't get to accomplish the needed result. The result that I need is triggering a function that initialize many jquery plugins used for different elements on a single page after every single one of these elements (components) is loaded.</p> <p>So lets say that you have this structure.</p> <p>Home Page Slider Widgets Product rotators ..etc</p> <p>Every one of these elements has it's own component and all are children of the Home page parent component.</p> <p>And what I need here is to know when all the children components and the parent component is loaded so I trigger one jquery function to initialize every plugin on the page. </p>
<jquery><components><angular><onload><document-ready>
2016-03-01 16:52:56
HQ
35,729,033
Convert a Windows Mobile 6.5 application to Android app with Xamarin
<p>I have a Windows Mobile 6.5 application that a customer are interested to have the same application for Android devices. I have thought with Xamarin to migrate the application to Android platform. Is it possible or exists some other way/tool to achieve that?</p> <p>I have read in this <a href="https://forums.xamarin.com/discussion/14475/windows-ce-and-windows-mobile-6-5-support" rel="nofollow">forum</a> that seems it isn't possible.</p>
<android><xamarin><cross-platform><windows-mobile-6.5>
2016-03-01 17:07:44
LQ_CLOSE
35,731,091
sum numbers in lines python
This is what I have to do: 1. Read content of a text file, where two numbers separated by comma are on each line (like 10, 5\n, 12, 8\n, …) 2. Make a sum of those two numbers 3. Write into new text file two original numbers and the result of summation = like 10 + 5 = 15\n, 12 + 8 = 20\n, … so far I have this: import os import sys relative_path = "Homework 2.txt" if not os.path.exists(relative_path): print "not found" sys.exit() read_file = open(relative_path, "r") lines = read_file.readlines() read_file.close() print lines path_output = "data_result4.txt" write_file = open(path_output, "w") for line in lines: line_array = line.split() print line_array
<python><file>
2016-03-01 18:55:39
LQ_EDIT
35,731,667
SQL-SERVER 2012 - Select querries leap year
Leap year! Arghhhhhhhh. I have a little issue with one my SELECT querries. The entire query is actually is a little long since it includes a UNION ALL. SELECT 'ITV' = CASE WHEN tblIntake.StaffID Is Null THEN '<Unknown>' ELSE (tblStaffMember.StaffLast + ', ' + tblStaffMember.StaffFirst + CASE WHEN tblStaffMember.StaffMI Is Null THEN '' ELSE ' ' + tblStaffMember.StaffMI END) END, tblMember.[LAST], tblMember.[FIRST], 'DueDate' = DATEADD(m, 6,CAST(CONVERT(Varchar(10), MONTH(tblIntake.EnrollDate)) + '/' + CONVERT(Varchar(10), DAY(tblIntake.EnrollDate)) + '/' + CONVERT(Varchar(10),YEAR(GETDATE()))As DateTime)), 'Type' = '6 Month Appt' From tblIntake LEFT JOIN tblStaffMember ON tblIntake.StaffID = tblStaffMember.StaffID LEFT JOIN tblMember ON tblIntake.KEY = tblMember.KEY Where tblIntake.UnEnrollDate Is Null AND DATEADD(m,6,CAST(CONVERT(Varchar(10),MONTH(tblIntake.EnrollDate)) + '/' + CONVERT(Varchar(10),DAY(tblIntake.EnrollDate)) + '/' + CONVERT(Varchar(10),YEAR(GETDATE()))As DateTime)) > GETDATE() AND DATEADD(m, 6,CAST(CONVERT(Varchar(10),MONTH(tblIntake.EnrollDate)) + '/' + CONVERT(Varchar(10),DAY(tblIntake.EnrollDate)) + '/' + CONVERT(Varchar(10),YEAR(GETDATE()))As DateTime)) <= DATEADD(d, 45, GETDATE()) SO i have this wonderful query. Everything was running Okay until a user entered a leap year date for ENROLLDATE in tblIntake. How would I go about fixing it? My other UNION do the same SELECT statements with the exception of for when it does CONVERT(VARCHAR(10),YEAR(GetDate()-1)) as DateTime > '4th line from the bottom CONVERT(VARCHAR(10),YEAR(GetDate()-1)) as DateTime > '2nd line from the bottom
<sql-server><date><datetime><select>
2016-03-01 19:24:58
LQ_EDIT
35,732,337
SSMS Snippets and Shortcuts
<p>I'm using SSMS 2014. I am able to insert a snippet but they don't seem to respond to shortcuts (ie crproc[tab])</p> <p>Is this feature known to work?</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&gt; &lt;CodeSnippet Format="1.0.0"&gt; &lt;Header&gt; &lt;Title&gt;prod1&lt;/Title&gt; &lt;Description&gt;testing&lt;/Description&gt; &lt;Author&gt; dale &lt;/Author&gt; &lt;SnippetTypes&gt; &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt; &lt;/SnippetTypes&gt; &lt;Shortcut&gt;crproc&lt;/Shortcut&gt; &lt;/Header&gt; &lt;Snippet&gt; &lt;Declarations&gt; &lt;Literal&gt; &lt;ID&gt;DatabaseName&lt;/ID&gt; &lt;ToolTip&gt;Name of database.&lt;/ToolTip&gt; &lt;Default&gt;DB&lt;/Default&gt; &lt;/Literal&gt; &lt;/Declarations&gt; &lt;Code Language="SQL"&gt; &lt;![CDATA[ ------------------------------------------------------ -- FILENAME: Template-Expansion.snippet -- PURPOSE: Template for Expansion (Insert) snippets. -- AUTHOR: Ken O. Bonn -- DATE: May 15, 2013 ------------------------------------------------------ SET NOCOUNT ON; EXEC SP_HELPDB $DatabaseName$; ]]&gt; &lt;/Code&gt; &lt;/Snippet&gt; &lt;/CodeSnippet&gt; &lt;/CodeSnippets&gt; </code></pre>
<sql-server><ssms><ssms-2014>
2016-03-01 20:01:28
HQ
35,732,776
Using cmake to create main and sub-projects, and be able to compile them individually
<p><strong>DISCLAIMER:</strong> I am new to CMakeLists.txt, I have a working implementation and would like to improve and enhance it, problem described below:</p> <p>If I want <code>root/sub-directories/</code> as separate sub-projects that can be compiled using the individual <code>CMakeLists.txts</code> in their folders I find myself literally copy pasting almost the entire root file <code>CMakeLists.txt</code> per sub-directory.</p> <p>I was wondering if there is a better way to have a main project and then sub-projects that get the shared dependencies from main project and can be compiled without <code>cmake</code>-ing the root <code>CMakeLists.txt</code>. My directory structure is;</p> <p>CMakeLists.txt (root project)<br> | __ sub_dir-1<br> | __ | __ CMakeLists.txt (sub-project)<br> | __ sub_dir-2<br> | __ | __ CMakeLists.txt (sub-project)<br> | __ sub_dir-3<br> | __ | __ CMakeLists.txt (sub-project)<br> ...<br></p> <p>Essentially, I want to be able to:</p> <ol> <li><code>cmake root/CMakeLists.txt</code>, which creates an entire project that includes the sub-projects (I already have this implemented using individual CMakeLists.txts inside sub-directories.</li> <li><p><code>cmake root/sub-dir/CMakeLists.txt</code> and <strong>only</strong> compile the sub-project, which essentially also finds the necessary dependencies and includes them from maybe <code>.cmake</code> includes or <code>root/CMakeLists.txt</code>. What is the best way to approach this structure;</p> <ul> <li>while retaining the first bullet point of having the ability to compile it as an entire project.</li> <li>And also not <em>crowding</em> the <code>sub-dir/CMakeLists.txt</code> too much with redundant code? </li> </ul></li> </ol> <p>Appreciate any suggestions! Thank you.</p>
<cmake>
2016-03-01 20:26:40
HQ
35,732,916
onmouseover not working with React.js
<p>The click event works fine, but the onmouseover event does not work. </p> <pre><code>ProfImage = React.createClass({ getInitialState: function() { return { showIcons: false }; }, onClick: function() { if(this.state.showIcons == true) { this.setState({ showIcons: false }); } else { this.setState({ showIcons: true }); } }, onHover: function() { this.setState({ showIcons: true }); }, render: function() { return ( &lt;div&gt; &lt;span className="major"&gt; &lt;img src="/images/profile-pic.png" height="100" onClick={this.onClick} onmouseover={this.onHover} /&gt; &lt;/span&gt; { this.state.showIcons ? &lt;SocialIcons /&gt; : null } &lt;/div&gt; ); } }); </code></pre>
<reactjs>
2016-03-01 20:33:58
HQ
35,732,995
Avoiding and renaming .x and .y columns when merging or joining in r
<p>Often I go about joining two dataframes together that have the same name. Is there a way to do this within the join-step so that I don't end up with a .x and a .y column? So the names might be 'original_mpg', and 'new_mpg'?</p> <pre><code> library(dplyr) left_join(mtcars, mtcars[,c("mpg",'cyl')], by=c("cyl")) names(mtcars) #ugh </code></pre>
<r><join><merge><rename><dplyr>
2016-03-01 20:38:16
HQ
35,733,138
Send cookie in HTTP POST Request in javascript
<p>I am trying to make a POST request to the server (Which is a REST service)via javascript,and in my request i want to send a cookie.My below code is not working ,as I am not able to receive cookie at the server side.Below are my client side and server side code.</p> <p><strong>Client side :</strong></p> <pre><code>var client = new XMLHttpRequest(); var request_data=JSON.stringify(data); var endPoint="http://localhost:8080/pcap"; var cookie="session=abc"; client.open("POST", endPoint, false);//This Post will become put client.setRequestHeader("Accept", "application/json"); client.setRequestHeader("Content-Type","application/json"); client.setRequestHeader("Set-Cookie","session=abc"); client.setRequestHeader("Cookie",cookie); client.send(request_data); </code></pre> <p><strong>Server Side:</strong></p> <pre><code>public @ResponseBody ResponseEntity getPcap(HttpServletRequest request,@RequestBody PcapParameters pcap_params ){ Cookie cookies[]=request.getCookies();//Its coming as NULL String cook=request.getHeader("Cookie");//Its coming as NULL } </code></pre>
<javascript><cookies><http-headers><http-post><httprequest>
2016-03-01 20:46:56
HQ
35,733,186
Angular2 UL/LI JSON-tree recursive in ngFor
<p>I'd like to convert JSON-trees into unordered lists in Angular2. I know the recursive directive solution from Angular1 and I am pretty sure the solution in Angular2 will be recursive too.</p> <pre><code> [ {name:"parent1", subnodes:[]}, {name:"parent2", subnodes:[ {name:"parent2_child1", subnodes:[]} ], {name:"parent3", subnodes:[ {name:"parent3_child1", subnodes:[ {name:"parent3_child1_child1", subnodes:[]} ] } ] } ] </code></pre> <p>to this unordered list</p> <pre><code>&lt;ul&gt; &lt;li&gt;parent1&lt;/li&gt; &lt;li&gt;parent2 &lt;ul&gt; &lt;li&gt;parent2_child1&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;parent3 &lt;ul&gt; &lt;li&gt;parent3_child1 &lt;ul&gt; &lt;li&gt;parent3_child1_child1&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>using <strong>Angular2</strong> and ngFor. Anyone got an idea? </p>
<json><tree><html-lists><angular>
2016-03-01 20:49:26
HQ
35,733,223
Matplotlib scatter plot with unknown error
<p>I am attempting to create a scatter plot. I have a list of numbers from 0 - 17 as well as an array with 18 values. I can plot the data as a line plot but when I try to plot as a scatter I get an error message I do not understand: <code>TypeError: ufunc 'sqrt' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''</code></p> <p>What does this error message mean and how can I get the data to plot as a scatter?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt y = [7316.0, 7453.25, 7518.25, 7711.5, 7448.0, 7210.25, 7416.75, 6960.75, 7397.75, 6397.5, 5522.75, 5139.0, 5034.75, 4264.75, 5106.0, 3489.5, 4712.0, 4770.0] x = np.arange(0,18,1) plt.rcParams['legend.loc'] = 'best' plt.figure(1) plt.xlim(0, 20) plt.ylim(0, 10000) plt.scatter(x, y, 'r') plt.show() </code></pre>
<python><numpy><matplotlib>
2016-03-01 20:51:13
HQ
35,733,846
How to spy a service call in Angular2
<p>Following the code example found on Ari Lerner ng-book2, and using Angular 2 beta 7, I'm trying to mock and spy a call to a service unsuccessfully.</p> <p>This is the main component using the service:</p> <p><em>user-list.component.ts</em></p> <pre class="lang-js prettyprint-override"><code>import {Component, OnInit} from 'angular2/core'; import {UserService} from './user.service'; import {IUser} from './user.model'; @Component({ selector: 'user-list', providers: [UserService], template: ` &lt;div *ngFor="#user of users" class="user"&gt; &lt;span class="username"&gt;Username: {{ user.username }}&lt;/span&gt;&lt;br&gt; &lt;span class="email"&gt;Email: {{ user.email }}&lt;/span&gt; &lt;/div&gt; ` }) export class UserListComponent implements OnInit { public users: IUser[]; private userService: UserService; constructor(userService: UserService) { this.userService = userService; } ngOnInit(): void { this.userService.getAllUsers().subscribe( (users: IUser[]) =&gt; { this.users = users; }, (error: any) =&gt; { console.log(error); } ); } } </code></pre> <p>And this is the service itself.</p> <p><em>user.service.ts</em></p> <pre class="lang-js prettyprint-override"><code>import {Injectable} from 'angular2/core'; import {Http} from 'angular2/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/Rx'; import {IUser} from './user.model'; @Injectable() export class UserService { private http: Http; private baseUrl: string = 'http://jsonplaceholder.typicode.com/users'; constructor(http: Http) { this.http = http; } public getAllUsers(): Observable&lt;IUser[]&gt; { return this.http.get(this.baseUrl) .map(res =&gt; res.json()); } } </code></pre> <p>In order to test the <code>UserListComponent</code>, I'm trying to mock the <code>UserService</code> and spy its method call <code>getAllUser</code> using the following code:</p> <p><em>user-list.component.spec.ts</em></p> <pre class="lang-js prettyprint-override"><code>import { describe, expect, it, injectAsync, TestComponentBuilder, ComponentFixture, setBaseTestProviders, } from 'angular2/testing'; import {SpyObject} from 'angular2/testing_internal'; import { TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS } from 'angular2/platform/testing/browser'; import {provide} from 'angular2/core'; import {UserListComponent} from './user-list.component'; import {UserService} from './user.service'; class SpyUserService extends SpyObject { public getAllUsers: Function; public fakeResponse: any = null; constructor() { super(UserService); this.getAllUsers = this.spy('getAllUsers').andReturn(this); } public subscribe(callback) { callback(this.fakeResponse); } public setResponse(data: any): void { this.fakeResponse = data; } } describe('When rendering the UserListComponent and mocking the UserService', () =&gt; { setBaseTestProviders(TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS); it('should show one mocked user', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) =&gt; { let spyUserService = new SpyUserService(); spyUserService.setResponse([{ username: 'ryan', email: 'ryan@gmail.com' }]); return tcb .overrideProviders(UserListComponent, [provide(UserService, {useValue: spyUserService})]) .createAsync(UserListComponent) .then((fixture: ComponentFixture) =&gt; { fixture.detectChanges(); expect(spyUserService.getAllUsers).toHaveBeenCalled(); }); })); }); </code></pre> <p>When using karma to run the test I'm getting the following console error:</p> <pre class="lang-sh prettyprint-override"><code>Chrome 48.0.2564 (Mac OS X 10.11.3) ERROR Uncaught TypeError: Cannot read property 'isSlow' of null at /Users/david/apps/sandbox/angular2-testing-cookbook/src/tests.entry.ts:19430 </code></pre> <p><strong>Do anybody know why is this error being thrown or the proper way to mock and spy a service for unit testing an Angular 2 component?</strong></p>
<unit-testing><angular>
2016-03-01 21:25:04
HQ
35,734,060
RxJava: How to convert List of objects to List of another objects
<p>I have the List of SourceObjects and I need to convert it to the List of ResultObjects.</p> <p>I can fetch one object to another using method of ResultObject:</p> <pre><code>convertFromSource(srcObj); </code></pre> <p>of course I can do it like this:</p> <pre><code>public void onNext(List&lt;SourceObject&gt; srcObjects) { List&lt;ResultsObject&gt; resObjects = new ArrayList&lt;&gt;(); for (SourceObject srcObj : srcObjects) { resObjects.add(new ResultsObject().convertFromSource(srcObj)); } } </code></pre> <p>but I will be very appreciate to someone who can show how to do the same using <strong>rxJava</strong>.</p>
<java><android><rx-java>
2016-03-01 21:39:00
HQ
35,734,366
typescript - can tsc be run against an entire folder?
<p>I'm pretty surprised this isn't in the docs that I could find - but is there any way to just tell <code>tsc</code> to run against all files in a directory and its children without going through a whole <code>tsconfig.json</code> setup?</p>
<typescript>
2016-03-01 21:56:06
HQ
35,734,941
How to combine multiple find() in jquery?
<p>I have these two conditions:</p> <p>1) Find all div with a "data-filter-program" attribute which equal to something 2) Find all div with a "data-filter-expertise" attribute which equal to something</p> <p>And I need to somehow combine these two into one statement in jquery. I would like something like this:</p> <pre><code>mentors = $("div").find("[data-filter-program*='"+selected_program+"']" &amp;&amp; "[data-filter-expertise*='"+selected_expertise+"']"); </code></pre> <p>How do I actually achieve this correctly in Jquery?</p> <p>Thanks!</p>
<javascript><jquery>
2016-03-01 22:32:43
LQ_CLOSE