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
39,948,757
How to delete rows in python pandas DataFrame using regular expressions?
<p>I have a pattern:</p> <pre><code>patternDel = "( \\((MoM|QoQ)\\))"; </code></pre> <p>And I want to delete all rows in pandas dataframe where column <code>df['Event Name']</code> matches this pattern. Which is the best way to do it? There are more than 100k rows in dataframe.</p>
<python><regex><pandas>
2016-10-09 21:31:40
HQ
39,950,065
How to change directory and run command on that directory?
<p>Example: I want to change directory to : C:/temp/hacking/passsword and execute a command like that : java Helloworld arg1 arg2 How can I do this with java?</p>
<java><cmd>
2016-10-10 01:04:01
LQ_CLOSE
39,951,081
Ckeditor show block element html
I'm using Ckeditor 4.5 version. I want to config same this images. Please help me [Block html][1] [1]: http://i.stack.imgur.com/ezjxL.png
<javascript><ckeditor>
2016-10-10 03:53:06
LQ_EDIT
39,951,986
Python Delete not working
<p><strong><em>I don't know Syntax Error. and if can't delete then rollback data.maybe you can advise me</em></strong></p> <pre><code>#!/usr/bin/python import mysql.connector conn= mysql.connector.connect(host='localhost',user='user',passwd='pwd',db='dest') cursor = conn.cursor() sql = "DELETE FROM dt WHERE user1 &gt; "%d" % (60) try: try: cursor.execute(sql) conn.commit() except: conn.rollback() except: print "Error connect" if conn: conn.close() </code></pre>
<python><mysql>
2016-10-10 05:50:13
LQ_CLOSE
39,952,356
While i am Loging In SqlServer Shoing This Error Plz Help Me Out How To resolve It
[Sql Server Error[\]\[1\]][1] [1]: http://i.stack.imgur.com/xjFhQ.jpg While i am Loging In SqlServer Shoing This Error Plz Help Me Out How To resolve It
<sql-server>
2016-10-10 06:24:56
LQ_EDIT
39,952,498
how to get the outuput in the correct format
def read_ndfa(file : open) -> {str:{str:{str}}}: pass file = start;0;start;1;start;0;near \n near;1;end \n end correct output = {'end': {}, 'start': {'1': {'start'}, '0': {'start', 'near'}}, 'near': {'1': {'end'}}} I need to write a function that takes a file as an input to get the correct output as above. however, I have no idea how to create the inner dictionary by using zip function. can someone show me the correct way to do it? Many thanks.
<python>
2016-10-10 06:37:00
LQ_EDIT
39,952,559
Defaulting to last part of else if statement in java
<p>I am writhing a code to find the distance between 2 places where the user inputs different cities. i need to get the longitude and latitude of the two places, so i tried writing the code like this, but for some reason that i do not know, it always uses the coordinantes for orlando no matter what. Could anyone please help me?</p> <p>(The latitudeStringOfQ is what the user entered)</p> <pre><code>if (latitudeStringOfQ.equals(city1)) { latitudeOfQ = latitudeOfBarrow; longitudeOfQ = longitudeOfBarrow; } else if (latitudeStringOfQ.equals(city2)) { latitudeOfQ = latitudeOfBrisbane; longitudeOfQ = longitudeOfBrisbane; } else if (latitudeStringOfQ.equals(city3)) { latitudeOfQ = latitudeOfDuluth; longitudeOfQ = longitudeOfDuluth; } else if (latitudeStringOfQ.equals(city4)) { latitudeOfQ = latitudeOfLondon; longitudeOfQ = longitudeOfLondon; } else if(latitudeStringOfQ.equals(city5)); { latitudeOfQ = latitudeOfOrlando; longitudeOfQ = longitudeOfOrlando; } System.out.print(latitudeOfQ); System.out.print(longitudeQ); </code></pre>
<java>
2016-10-10 06:41:47
LQ_CLOSE
39,953,542
AOF and RDB backups in redis
<p>This question is about Redis persistence. </p> <p>I'm using redis as a 'fast backend' for a social networking website. It's a single server set up. I've been transferring PostgreSQL responsibilities to Redis steadily. Currently in <code>etc/redis/redis.conf</code>, the appendonly setting is set to <code>appendonly no</code>. Snapshotting settings are <code>save 900 1</code>, <code>save 300 10</code>, <code>save 60 10000</code>. All this is true for production and development both. As per production logs, <code>save 60 10000</code> gets invoked heavily. Does this mean that practically, I'm getting backups every 60 seconds?</p> <p>Some literature suggests using AOF and RDB backups together. Thus I was weighing in on turning <code>appendonly on</code> and using <code>appendfsync everysec</code>. For anyone who has had experience of both sides of the coin:</p> <p>1) Will using <code>appendonly on</code> and <code>appendfsync everysec</code> cause a performance downgrade? Will it hit the CPU? The write load is on the high side.</p> <p>2) Once I restart the redis server with these new settings, I'll still lose the last 60 secs of my data, correct? </p> <p>3) Are restart times something to worry about? My <code>dump.rdb</code> file is small; ~90MB.</p> <p>I'm trying to find out more about redis persistence, and getting my expectations right. Personally, I'm fine with losing 60s of data in the case of a catastrophe, thus whether I should use AOF is also something I'm pondering. Feel free to chime in. Thanks!</p>
<redis>
2016-10-10 07:49:51
HQ
39,953,671
Perl regex first word
<p>I am very new to regex in perl and I have the following line:</p> <pre><code>MD5ajdhe728ndsdhsds83ndsds /some/path/ </code></pre> <p>and I just want to get the MD5 value (the number/letter combination after "MD5"). How do I do that? I have kind of troubles fetching the first word.</p> <p>Thank you in advance.</p>
<regex><perl>
2016-10-10 07:57:48
LQ_CLOSE
39,953,933
Dagger 2 - two provides method that provide same interface
<p>lets say I have:</p> <pre><code>public interface Shape {} public class Rectangle implements Shape { } public class Circle implements Shape { } </code></pre> <p>and I have a <strong>ApplicationModule</strong> which needs to provides instances for both <strong>Rec</strong> and <strong>Circle</strong>:</p> <pre><code>@Module public class ApplicationModule { private Shape rec; private Shape circle; public ApplicationModule() { rec = new Rectangle(); circle= new Circle (); } @Provides public Shape provideRectangle() { return rec ; } @Provides public Shape provideCircle() { return circle; } } </code></pre> <p>and <strong>ApplicationComponent</strong>:</p> <pre><code>@Component(modules = ApplicationModule.class) public interface ApplicationComponent { Shape provideRectangle(); } </code></pre> <p>with the code the way it is - it won't compile. error saying </p> <blockquote> <p>Error:(33, 20) error: Shape is bound multiple times.</p> </blockquote> <p>It makes sense to me that this can't be done, because the component is trying to find a <code>Shape</code> instance, and it finds two of them, so it doesn't know which one to return.</p> <p>My question is - how can I handle this issue?</p>
<java><android><dependency-injection><dagger-2><dagger>
2016-10-10 08:13:00
HQ
39,954,099
Hi all, I am having an issue in mysql query
I am having an issue in MySQL query that i have to pull some record from a view with the order by clause from attended_date, but even there might be some data without attended_date filled so how can i get it done example : SELECT * FROM vw_getengineerreview WHERE reference_number ='xxs/xxx/00256' ORDER BY attended_date ASC; this gives the record what is available (thats correct) but the null recorded value print in top, but i want to have in the bottom (when the attended_date is null) Output is below **Technician Name** **Start Date / Time** **End Date / Time** **Technician Remarks** Kasun Chathuranga 2016-10-04 - 10:49:13 - Kasun Chathuranga 2016-09-06 - 17:17:02 2016-09-22-02:16:23 not powerning
<php><mysql>
2016-10-10 08:23:52
LQ_EDIT
39,954,678
Difference between execution policies and when to use them
<p>I noticed that a majority (if not all) functions in <code>&lt;algorithm&gt;</code> are getting one or more extra overloads. All of these extra overloads add a specific new parameter, for example, <code>std::for_each</code> goes from:</p> <pre><code>template&lt; class InputIt, class UnaryFunction &gt; UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f ); </code></pre> <p>to:</p> <pre><code>template&lt; class ExecutionPolicy, class InputIt, class UnaryFunction2 &gt; void for_each( ExecutionPolicy&amp;&amp; policy, InputIt first, InputIt last, UnaryFunction2 f ); </code></pre> <p>What effect does this extra <code>ExecutionPolicy</code> have on these functions?</p> <p>What are the differences between:</p> <ul> <li><code>std::execution::seq</code></li> <li><code>std::execution::par</code></li> <li><code>std::execution::par_unseq</code></li> </ul> <p>And when to use one or the other?</p>
<c++><c++17>
2016-10-10 08:59:01
HQ
39,955,391
Selenium Error: java Script
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Element is not clickable at point (413, 63). Other element would receive the click: <div id="wait" width="100%" height="100%" class="wait" style="position: absolute; top: 0px; left: 0px; height: 666px; width: 1366px; display: block; cursor: wait;">...</div> (Session info: chrome=53.0.2785.143) (Driver info: chromedriver=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 94 milliseconds Build info: version: 'unknown', revision: 'c7b525d', time: '2016-09-01 14:52:30 -0700' System info: host: 'ICDVM', ip: '10.0.0.11', os.name: 'Windows Server 2012 R2', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_102' Driver info: org.openqa.selenium.chrome.ChromeDriver Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf), userDataDir=C:\Users\ADMINI~1\AppData\Local\Temp\scoped_dir16420_7494}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=53.0.2785.143, platform=WIN8_1, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}] Session ID: e24f7435d75ad5ddbecb362090ddb0a3 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206) at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:631) at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:284) at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:84) at script.Script.main(Script.java:78)
<selenium>
2016-10-10 09:38:13
LQ_EDIT
39,956,486
JS lodash [1, 2] => {1: 'test', 2: 'test'}
<p>There is an array:</p> <pre><code>var array = [{test: 1}, {test: 2}, {test: 3}] </code></pre> <p>I need to get:</p> <pre><code>{1: 'random_value', 2: 'random_value', 3: 'random_value'} </code></pre> <p>I'm doing:</p> <pre><code>var values_test = _.map(array, 'test'); </code></pre> <p>What to do next?</p>
<javascript><lodash>
2016-10-10 10:45:02
LQ_CLOSE
39,956,497
Pandoc convert docx to markdown with embedded images
<p>When converting .docx file to markdown, the embedded image is not extracted from the docx archive, yet the output contains <code>![](media/image1.png){width="6.291666666666667in" height="3.1083333333333334in"}</code> </p> <p>Is there a parameter that needs to be set in order to get the embedded pictures extracted?</p>
<pandoc>
2016-10-10 10:45:40
HQ
39,957,789
i want apply different width in option menu but it's take first
i want to apply different width in different option menu but when page load my js is run and take default 25% width in all page option menu i need 25% width in header file and header include in all file so header first js is run and page option menu take also 25% width so what i do for assign different width in header and also page he my js and css is given and i try to apply inline css it's not working and also make different class and different js but its also not working because first run header js and it's width 25% so what i do for solve this issue. pls help me. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> this one is my js file ! function(t) { var e = t('<div class="stb-select-container"><span class="selected"></span></div>'), n = t('<ul class="stb-select" style="display:none;"></ul>'); t.fn.stbDropdown = function() { var i = t(this); i.hide(), i.each(function(i, a) { var o = e.clone(), s = n.clone(), r = t(a), c = r.find("option"); r.after(o), r.appendTo(o), s.appendTo(o), c.each(function(e, n) { var i = t(n), a = t("<li></li>"), o = i.prop("attributes"); a.prop("attributes", o), t.each(o, function(t, e) { a.attr(e.name, e.value) }), a.append(i.text()), s.append(a) }); var l, p = r.children("option").filter(function(e, n) { return t(n).is("[selected]") }); l = 0 == p.length ? c.first() : p.first(), o.find(".selected").text(l.text()), o.on("click.stb.select", function() { var e = t(this), n = t.grep(t(".stb-select-container"), function(n) { return !e.is(t(n)) }); t(n).find("ul").hide(), e.find("ul").toggle() }), o.on("click.stb.option", "li", function(e) { e.stopPropagation(); var n = t(this), i = n.parents(".stb-select-container"), a = i.find("span.selected"); a.text(n.text()), n.parents("ul").toggle(); var o = i.find("select"); o.val(n.attr("value")).change(), n.siblings().removeAttr("selected"), n.attr("selected", "selected") }), r.on("DOMNodeInserted", function(e) { var n = t(e.target); if (n.is("option")) { var i = t("<li></li>"), a = n.prop("attributes"); i.prop("attributes", a), t.each(a, function(t, e) { i.attr(e.name, e.value) }), i.append(n.text()), s.append(i) } }), r.on("DOMNodeRemoved", function(e) { var n = t(e.target); n.is("option") && s.find("li:contains('" + n.text() + "')").remove() }) }) } }(jQuery); <!-- language: lang-css --> .stb-select-container { font-family: inherit; /*border-radius: 4px;*/ width: 25%; /*width: 100%;*/ display: inline-block; outline: 0; box-shadow: none; border-right: 1px solid #ccc; /*border: solid thin rgba(0, 0, 0, 0.24);*/ padding: 14px 16px; /* margin: 4px 8px;*/ outline: 0; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; position: relative; text-align: left; cursor: pointer } .stb-select-container ul { list-style-type: none; margin: 0; padding: 0 } .stb-select-container select { display: none } .stb-select-container .stb-select { position: absolute; background: white; left: -1px; top: 50px; padding: 8px 16px; border: solid thin rgba(0, 0, 0, 0.24); border-top: 0; z-index: 10; max-height: 200px; width: 100%; overflow-x: auto; -webkit-border-bottom-left-radius: 4px; -moz-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; -webkit-border-bottom-right-radius: 4px; -moz-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px } .stb-select-container span { opacity: .54 } .stb-select-container::after { opacity: .54; content: "v"; position: absolute; right: 8px; -ms-transform: scaleY(0.5); -webkit-transform: scaleY(0.5); transform: scaleY(0.5) } .stb-select-container .stb-select li { opacity: .7 } .stb-select-container .stb-select li:first-of-type { /* opacity: .34*/ } .stb-select-container .stb-select li+li { margin-top: 10px } .stb-select-container .stb-select li:hover{ color:#3EA9D8; } @media screen and (max-width: 768px) { .stb-select-container { font-family: inherit; font-size: 16px; /*border-radius: 4px;*/ width: 100%; display: inline-block; outline: 0; box-shadow: none; border: 2px solid #e9e9e9; /*border: solid thin rgba(0, 0, 0, 0.24);*/ padding: 12px 12px; /* margin: 4px 8px;*/ outline: 0; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; position: relative; text-align: left; cursor: pointer } } this one is my html code <!-- language: lang-html --> <select name="city" id="city_result" style="height: 50px; width:100%; margin: 0px; padding: 10px; box-shadow: 0px 0px 0px white; border: none;"> <option>Your city</option> </select> <!-- end snippet -->
<javascript><php><jquery><css><codeigniter>
2016-10-10 11:59:35
LQ_EDIT
39,958,709
What does using a shift operator(<<) before a variable implies in C?
<p>I read a code to convert a number to its binary equivalent, where the following statement was used:</p> <pre><code>1&lt;&lt;j </code></pre> <p>What is the use of such a statement?</p>
<c><operators>
2016-10-10 12:49:54
LQ_CLOSE
39,958,776
C++ How do I fill in two-dimensional array
<p>I just want to fill in two-dimensional array string values. e.g: array[5][6] </p> <pre><code>.X.... X..... XX.... .....X ...X.. </code></pre> <p>I tried to use <code>getline(cin, array)</code> but it makes cells:</p> <pre><code>. X . . . . etc </code></pre> <p>Also, I tried to use <code>_getch();</code> but it doesn't output values I just entered. So, is there a way that makes input clearner?</p>
<c++><arrays><input><output>
2016-10-10 12:53:58
LQ_CLOSE
39,959,224
Transpiling SASS on the fly with SystemJS
<p>I read a lot of blogs that say SystemJS and SASS transpiling works, but every example I see online appears to handle the SASS processing up front (via a gulp-like task runner), and the JavaScript code then imports the generated CSS.</p> <p>What I'm hoping to be able to do is to have my JavaScript files import the SASS files directly (and have my SystemJS loader transpile into CSS on-the-fly). This is just for development purposes, for production, I plan to build a single static file with everything in it. Is this possible? If so, how is this typically done?</p> <p>Additional info: I am using Angular2 and Typescript as well.</p> <p>Thanks.</p>
<angular><typescript><sass><systemjs>
2016-10-10 13:16:23
HQ
39,959,272
How does the Shouldly assertion library know the expression the assertion was applied to?
<p>The <a href="http://shouldly.readthedocs.io/en/latest/">Shouldly assertion library for .NET</a> somehow knows what expression the assertion method was called on so it is able to display it into the message. I tried to find out how it works but got lost in the source code. I suspect it looks into the compiled code but I would really like to see how this happens. From the documentation</p> <pre><code>map.IndexOfValue("boo").ShouldBe(2); // -&gt; map.IndexOfValue("boo") should be 2 but was 1 </code></pre> <p>Somehow Shouldly knows the expression map.IndexOfValue("boo") and was able to display it in the test failure message. Does anyone know how this happens?</p>
<c#><.net><shouldly>
2016-10-10 13:19:08
HQ
39,959,417
What is the maximum length of an FCM registration ID token?
<p>Working with the "new" Firebase Cloud Messaging, I would like to reliably save client device <code>registration_id</code> tokens to the local server database so that the server software can send them push notifications.</p> <p><strong>What is the smallest size of database field that I should use to save 100% of client registration tokens generated?</strong></p> <p>I have found two <a href="https://github.com/Chitrank-Dixit/django-fcm/blob/master/fcm/models.py#L26">different</a> <a href="https://github.com/xtrinch/fcm-django/blob/master/fcm_django/models.py#L74">libraries</a> that use <code>TextField</code> and <code>VarChar(255)</code> but nothing categorically defining the max length. In addition, I would like the server code to do a quick length check when receiving tokens to ensure they "look" right - what would be a good min length and set of characters to check for?</p>
<firebase><firebase-cloud-messaging>
2016-10-10 13:26:13
HQ
39,959,514
Remove the following redirect chain if possible from Google
<p>We have recently started using <strong>Google Analytics</strong> and activated Google Re Marketting on <strong>Analytics panel</strong> </p> <p>Now we are seeing the following error messages when testing with <strong>Pingdom</strong>:</p> <p>Its says Remove the following redirect chain if possible:</p> <pre><code>https://www.google-analytics.com/r/collect?v=1&amp; ... https://stats.g.doubleclick.net/r/collect?v=1&amp;a ... https://www.google.com/ads/ga-audiences?v=1&amp;aip ... https://www.google.se/ads/ga-audiences?v=1&amp;aip= ... </code></pre> <p>How Can we fix this <a href="https://i.stack.imgur.com/0nYQK.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/0nYQK.jpg" alt="enter image description here"></a></p> <p>Using PingDom, We just scored an "F" from "Minimizing Redirects" , How can I fix the redirect chain that was pointed out to us by the pingdom tool?</p> <blockquote> <p><strong>PS</strong>: We are not locally hosting the Analytics.js</p> </blockquote>
<redirect><google-analytics><server><adsense><pingdom>
2016-10-10 13:31:58
HQ
39,960,133
Catchable fatal error: Object of class mysqli could not be converted to string on line 8
<p>I tried checking many time , still gives me this error. Actually i am trying to create a php file with the contents of $output in it .</p> <pre><code>&lt;?php include 'dbconfig.php'; $rand = $_GET['rand']; $filename = $rand.".php"; $output = "&lt;?php"; $output .="include '../dbconfig.php';"; $output .="$myself = basename(__FILE__, '.php'); "; $output .="$query = mysqli_query($dbconfig,\"Select command from records where token = '$myself'\");"; $output .="if(mysqli_num_rows($query) &gt; 0)"; $output .="{"; $output .="while($row=$query-&gt;fetch_assoc())"; $output .="{"; $output .="$command = $row[command];"; $output .="}"; $output .="echo 'exec $command endexec';"; $output .="}"; $output .="?&gt;"; $file = fopen("puppet\$filename","w"); fwrite($file,$putput); $check = "Select * from records where usertoken = $rand"; $check1 = mysqli_query($dbconfig,$check); if(mysqli_num_rows($check1)== 0){ $ins = "Insert into records (usertoken)Values('$rand')"; if(mysqli_query($dbconfig,$ins)){ $success=true; } }else{ $success=false; } ?&gt; </code></pre>
<php><mysqli>
2016-10-10 14:03:30
LQ_CLOSE
39,960,173
Run custom shell script with CMake
<p>I am having the following directory structure:</p> <pre><code>/CMakeLists.txt /component-a/CMakeLists.txt /... /component-b/CMakeLists.txt /... /doc/CMakeLists.txt /create-doc.sh </code></pre> <p>The shell script <code>create-doc.sh</code> creates a documentation file (<code>doc.pdf</code>). How can I use CMake to execute this shell script at build time and copy the file <code>doc.pdf</code> to the build directory?</p> <p>I tried it by using <code>add_custom_command</code> in the <code>CMakeLists.txt</code> file inside the directory <code>doc</code>:</p> <pre><code>add_custom_command ( OUTPUT doc.pdf COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/create-doc.sh WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/) </code></pre> <p>Unfortunately the command is never run.</p> <p>I also tried <code>execute_process</code>:</p> <pre><code>execute_process ( COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/create-doc.sh WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ ) </code></pre> <p>Now the script is executed during the configuration phase, but not at build time.</p>
<cmake>
2016-10-10 14:05:25
HQ
39,960,322
power shell script to get drive space ( percentage used and free )
<p>I am trying to get DISK SPACE (Windows) in Percentage used and free.</p> <p>Script from which I get the space, </p> <pre><code> get-psdrive | where Free* </code></pre>
<shell><powershell><command-line><powershell-2.0><powershell-3.0>
2016-10-10 14:12:30
LQ_CLOSE
39,960,821
Inherited layout in ASP.NET MVC
<p>I have default layout _Layout.cshtml for the most pages. However for some group of pages I would like to have slightly modified default layout. I know I could just copy that file a modified it a bit, but it would mean to duplicate the code and maintain two layout with 99% of same code.</p> <p>I would like to inherit the layout from the default like this:</p> <p>LayoutInherited.cshtml:</p> <pre><code>Layout = "~/Views/Shared/_Layout.cshtml"; ViewBag.BodyContentClassSpecial = ""; @section header{ &lt;style&gt; #body-content { width: 90%; margin: 0 auto; } &lt;/style&gt; </code></pre> <p>}</p> <p>It is possible to do something like this?</p>
<asp.net-mvc><layout><nested>
2016-10-10 14:39:16
HQ
39,961,220
C++, Plotting points using Nested For Loops
wondering if someone can help me. I'm relatively new to C++ and we have been given this task to do: **Write a C++ program which asks the user for a number n between 1 and 10. The program should then print out n lines. Each should consist of a number of stars of the same number as the current line number. For example: Please enter a number: 5 * ** *** **** ***** The problem I am having is that when I use the code I've written it displays wrong. [enter image description here][1] [1]: http://i.stack.imgur.com/pxTZL.png The code I have right now reads like this: #include<iostream> using namespace std; int main() { int n; cout << "Please enter a number between 1 and 10:" << endl; cin >> n; for (int x = 0; x <= n; x++) { for (int y = 0; y <= n; y++) { cout << "*" ; } cout << "*" << endl; cin.get(); } return 0; } Any help would really be appreciated! Thanks a lot.
<c++>
2016-10-10 15:00:47
LQ_EDIT
39,961,329
Why is there a random bracket, "]", above the canvas element on my web app?
<p><a href="https://i.stack.imgur.com/qtJXb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qtJXb.png" alt="Web App with random bracket in the left corner"></a></p> <p>Above is an image that contains the random bracket I ram referring to. You can see in the developer tools at the bottom, that the bracket seems to be inserted at the top of the <code>body</code> tag. I have been doing a little research, but I cannot figure out why this random bracket is there. My code is below.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;First Game&lt;/title&gt;] &lt;meta charset="utf-8"&gt; &lt;style type="text/css"&gt; * { padding: 0; margin: 0; } canvas { background: #eee; display: block; margin: 0 auto; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;canvas id="myCanvas" width="480" height="320"&gt;&lt;/canvas&gt; &lt;script type="text/javascript"&gt; var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.rect(10, 40, 50, 50); ctx.fillStyle = "#eee"; ctx.fill(); ctx.closePath(); &lt;/script&gt; &lt;/body&gt; </code></pre> <p></p> <p>As you can see, there is not a stray square bracket in the code. I am not sure why this is appearing. As a side note, this bracket is making the red square, and any other code, to not show up in the canvas. Any ideas?</p>
<javascript><html>
2016-10-10 15:06:30
LQ_CLOSE
39,961,690
c++ char* + std::vector memory leak
<p>The following code is reading a big object collection (95G of compressed objects that are uncompressed via the WriteObject streamer) from disk and prints their content as strings.</p> <p>object.cxx:</p> <pre><code>std::vector&lt;char&gt; ObjectHandler::GetObject(const std::string&amp; path) { TFile *file = new TFile(path.c_str()); // If file was not found or empty if (file-&gt;IsZombie()) { cout &lt;&lt; "The object was not found at " &lt;&lt; path &lt;&lt; endl; } // Get the AliCDBEntry from the root file AliCDBEntry *entry = (AliCDBEntry*)file-&gt;Get("AliCDBEntry"); // Create an outcoming buffer TBufferFile *buffer = new TBufferFile(TBuffer::kWrite); // Stream and serialize the AliCDBEntry object to the buffer buffer-&gt;WriteObject((const TObject*)entry); // Obtain a pointer to the buffer char *pointer = buffer-&gt;Buffer(); // Store the object to the referenced vector std::vector&lt;char&gt; vector(pointer, pointer + buffer-&gt;Length()); // Release the open file delete file; delete buffer; return vector; } </code></pre> <p>main.cxx:</p> <pre><code>ObjectHandler objHandler; boost::filesystem::path dataPath("/tmp"); boost::filesystem::recursive_directory_iterator endIterator; if (boost::filesystem::exists(dataPath) &amp;&amp; boost::filesystem::is_directory(dataPath)) { for (static boost::filesystem::recursive_directory_iterator directoryIterator(dataPath); directoryIterator != endIterator; ++directoryIterator) { if (boost::filesystem::is_regular_file(directoryIterator-&gt;status())) { cout &lt;&lt; directoryIterator-&gt;path().string() &lt;&lt; endl; std::vector&lt;char&gt; vector = objHandler.GetObject(directoryIterator-&gt;path().string()); cout &lt;&lt; vector &lt;&lt; endl; } } } </code></pre> <p>1) Is calling by value the correct way to implement this method? Am i doing additional copies that could be avoided if calling by reference?</p> <p>2) This code is leaking and i am suspecting that either the <em>char *pointer</em> is to blame, or the actual <em>std::vector</em> that is returned by the <em>ObjectHandler::GetObject()</em> method. I've tested the implementation with the following code:</p> <pre><code>struct sysinfo sys_info; sysinfo (&amp;sys_info); cout &lt;&lt; "Total: " &lt;&lt; sys_info.totalram *(unsigned long long)sys_info.mem_unit / 1024 &lt;&lt; " Free: " &lt;&lt; sys_info.freeram *(unsigned long long)sys_info.mem_unit/ 1024 &lt;&lt; endl; </code></pre> <p>and the free ram is continuously reduced, until it reaches 0 and the program is killed. </p>
<c++><vector><memory-leaks><std>
2016-10-10 15:27:40
LQ_CLOSE
39,961,906
Can I prevent Babel from traversing code inserted by a plugin?
<p>I'm building a plugin that inserts <code>enterFunction()</code> in front of every existing function call by calling <code>path.insertBefore</code>. So my code is transformed from:</p> <pre><code>myFunction(); </code></pre> <p>To:</p> <pre><code>enterFunction(); myFunction(); </code></pre> <p>The problem is that when I insert the node Babel once again traverses the inserted node. Here's the logging output:</p> <blockquote> <p>'CallExpression', 'myFunction'<br> 'CallExpression', 'enterFunction'</p> </blockquote> <p>How can I prevent Babel from entering the <code>enterFunction</code> call expression and its children?</p> <p>This is the code I'm currently using for my Babel plugin: </p> <pre><code>function(babel) { return { visitor: { CallExpression: function(path) { console.log("CallExpression", path.node.callee.name) if (path.node.ignore) { return; } path.node.ignore = true var enterCall = babel.types.callExpression( babel.types.identifier("enterFunction"), [] ) enterCall.ignore = true; path.insertBefore(enterCall) } } } } </code></pre>
<babeljs>
2016-10-10 15:41:59
HQ
39,962,284
Gson Deserialization with Kotlin, Initializer block not called
<p>My initializer block is working perfectly fine when I create my Object</p> <pre><code>class ObjectToDeserialize(var someString: String = "") : Serializable { init{ someString += " initialized" } } </code></pre> <p>this way:</p> <pre><code>@Test fun createObject_checkIfInitialized() { assertEquals("someString initialized",ObjectToDeserialize("someString").someString) } </code></pre> <p>But when I deserialize the object with Gson, the initializer block does not get executed:</p> <pre><code>@Test fun deserializeObject_checkIfInitialized(){ val someJson: String = "{\"someString\":\"someString\" }" val jsonObject = Gson().fromJson(someJson, ObjectToDeserialize::class.java) assertEquals("someString initialized",jsonObject.someString) // Expected :someString initialized // Actual :someString } </code></pre> <p>I think that gson is creating the object in a different way than by executing the primary constructor. Is it nevertheless possible to have something similar like initializer blocks?</p> <hr>
<gson><kotlin>
2016-10-10 16:03:37
HQ
39,962,413
CSS table td color
<p>Am using this in Wordpress Tablepress plugin.</p> <p>I have these codes to highlight the table rows. Is there anyway I can merge them into single row to reduce the repeated codes?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.tablepress-id-1 .row-2 td { background-color: #000000; color: #ffffff; } .tablepress-id-1 .row-13 td { background-color: #000000; color: #ffffff; } .tablepress-id-1 .row-15 td { background-color: #000000; color: #ffffff; } .tablepress-id-1 .row-19 td { background-color: #000000; color: #ffffff; } .tablepress-id-1 .row-23 td { background-color: #000000; color: #ffffff; } .tablepress-id-1 .row-26 td { background-color: #000000; color: #ffffff; } .tablepress-id-1 .row-35 td { background-color: #000000; color: #ffffff; } .tablepress-id-1 .row-35 td { background-color: #000000; color: #ffffff; }</code></pre> </div> </div> </p>
<html><css>
2016-10-10 16:10:24
LQ_CLOSE
39,962,757
Prevent scrolling using CSS on React rendered components
<p>So I render a component via React within my <code>html</code> like so:</p> <pre><code> &lt;html&gt; &lt;body&gt; &lt;div id=app&gt;${appHtml}&lt;/div&gt; &lt;script src="/bundle.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Within my app I have a burger button, that <code>onClick</code> goes full screen.</p> <p>However, the body is scrollable. I'd normally add a class to the <code>body</code> tag and make it <code>overflow: hidden</code> to prevent this. However, my react component is rendered within the <code>body</code> tag so I have no control over toggling classes based on a click within a react component.</p> <p>Has anyone got any ideas/advice on how i'd achieve what i'm looking for.</p> <p>Thanks!</p>
<javascript><html><css><reactjs>
2016-10-10 16:30:46
HQ
39,962,867
How do I add a description to a field in "GraphQL schema language"
<p>I have a graphql schema, a fragment of which looks like this:</p> <pre><code>type User { username: String! password: String! } </code></pre> <p>In graphiql, there is a description field, but it always says "self-descriptive". How do I add descriptions to the schema? </p>
<javascript><graphql><apollo-server>
2016-10-10 16:37:08
HQ
39,962,999
Is stack unwinding with exceptions guaranteed by c++ standard?
<p>Concerning the stack unwinding, the c++ standard says: </p> <blockquote> <p>An exception is considered uncaught after completing the initialization of the exception object ([except.throw]) until completing the activation of a handler for the exception ([except.handle]). This includes stack unwinding. </p> </blockquote> <p>at <a href="http://eel.is/c++draft/except#uncaught-1">par 15.5.3</a> of the current standard. I was trying to understand what the latest sentence (<code>This includes stack unwindings</code>) is referring to:</p> <ul> <li>is it supposed that the compiler must take care of unwinding the stack?</li> <li>or, is it saying that it is compiler-dependent whether to unwind or not the stack?</li> </ul> <p>The question arises from the following snippet:</p> <pre><code>#include &lt;iostream&gt; #include &lt;exception&gt; struct S{ S() { std::cout &lt;&lt; " S constructor" &lt;&lt; std::endl; } virtual ~S() { std::cout &lt;&lt; " S destructor" &lt;&lt; std::endl; } }; void f() { try{throw(0);} catch(...){} } void g() { throw(10); } int main() { S s; f(); //g(); } </code></pre> <p>Now: </p> <ol> <li>if you run it as-is (catching the exception), you have a hint of the stack unwinding</li> <li>if you comment <code>f();</code> and uncomment <code>g();</code> (not catching the exception), you have hint of stack not being unwound</li> </ol> <p>So, the two experiments seem to be in favor of the first bullet above; both clang++ and g++ agree on the result (but it is not a discriminant). </p> <p>Also, it seems to me very strange that the standard, which is really careful in specifying the object <em>live time</em> and <em>duration</em> is leaving a shadow here.</p> <p>May anyone clarify? Is stack unwinding for uncaught exceptions guaranteed by the standard? If yes, where? If not, why?</p>
<c++><c++11><language-lawyer>
2016-10-10 16:45:21
HQ
39,963,175
Hello, I need help on creating a Star Wars name generator using specific instructions.
I'm struggling with a specific method which takes in a String parameter. The promptString method will print its parameter to the user as a prompt, and then return a String that is the result of reading the console via the nextLine() method. For this program you will use nextLine() exclusively. I've prompted the user with a question using a parameter, and then used nextLine to read the string but after that im a bit lost how can i get the method to print to the console, i seem to only be able to return which only stores the string. import java.util.*; public class StarWarsName{ public static void main(String[]args){ promptString("Enter your first name: "); } public static String promptString(String n){ Scanner console = new Scanner(System.in); String first = console.nextline(); return first.trim(); } }
<java><parameters><trim><next>
2016-10-10 16:56:27
LQ_EDIT
39,963,501
How can i return words from a string array one by one
I want to return words from a String array one after the other. public String CurrentString(int move) { int currentString = 0; currentString ; EditText ed = (EditText) findViewById(R.id.ed); String[] strings = ed.getText().toString().split(" "); int newString = currentString move; if (newString >= strings.length) { // if the new position is past the end of the array, go back to the beginning newString = 0; } if (newString < 0) { // if the new position is before the beginning, loop to the end newString = strings.length - 1; } currentString = newString; Toast.makeText(getApplicationContext(), strings[currentString],Toast.LENGTH_LONG).show(); return strings[currentString]; } the problem is that my above code doesn't return all texts. Please help.
<java><android>
2016-10-10 17:17:54
LQ_EDIT
39,964,436
How to learn qt, entirely in C++ - without touching qt designer?
<p>So i am basically a newbie when it comes to qt. I want to learn it ,but entirely in C++ and without even touching desinger because for me it's not coding anymore. The problem is that every single tutorial/guide/book uses it and the API documentation is just (for me) overwhelming - i dont know where to start. </p>
<c++><qt>
2016-10-10 18:21:17
LQ_CLOSE
39,964,803
Select pound sign and all the text after it in url
How do I remove a URL's pound sign and the text after it with jQuery on click? For example, the URL is http://www.website.com/home#content I want the whole *#content* text to be removed.
<javascript><jquery><html>
2016-10-10 18:46:12
LQ_EDIT
39,965,659
storing 64*64 integers from a file into a 2D array
<p>If i have a file that has a table of 64*64 integers. (The first 64 will be row 0; the next 64 will be row 1, and so on..). How do I store that table into a 2D array. Here is my code </p> <pre><code> #include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std; int main() { ifstream infile; infile.open("table.txt"); if (infile.fail()) { cout &lt;&lt; "could not open file" &lt;&lt; endl; exit(6); } int array[63][63]; while (!infile.eof()) { infile &gt;&gt; array[63][63]; } cout &lt;&lt; array[63][63] &lt;&lt; endl; return 0; } </code></pre> <p>when this is executed I only get "1"</p>
<c++><arrays>
2016-10-10 19:46:32
LQ_CLOSE
39,965,807
python log formatter that shows all kwargs in extra
<p>I hope to add the following log points to my application and display the full contents of <code>extra</code> on console, e.g., </p> <pre><code>logger.info('Status', extra={'foo':data}) logger.info('Status', extra={'bar':data}) logger.info('Status', extra={'foo':data, 'bar':data}) </code></pre> <p>and I hope to see:</p> <pre><code>2016-10-10 15:28:31,408, INFO, Status, foo=data 2016-10-10 15:38:31,408, INFO, Status, bar=data 2016-10-10 15:48:31,408, INFO, Status, foo=data, bar=data </code></pre> <p>Is this even possible? According to official logging documentation, the <code>Formatter</code> must be set up with a format string that expects <code>foo</code> and <code>bar</code> but in my case all I want is to dump out the entire kwargs of <code>extra</code> without prior knowledge of <code>foo</code> and <code>bar</code>.</p>
<python><logging>
2016-10-10 19:56:14
HQ
39,966,083
docker-machine: no machine name, no "default" exists
<p>I downloaded and installed Docker for Windows 1.12.1 which in turn installed the docker-machine and docker-compose. I did not install "Docker Toolbox" since its a duplicate of what was installed and my system meets the <a href="https://docs.docker.com/docker-for-windows/#/what-to-know-before-you-install" rel="noreferrer">requirements</a>.</p> <p>Everything seems to work fine except for docker-machine, I'm running through a tutorial and when I run various docker-machine commands like "ip" or "env" I get the following message.</p> <pre><code>Error: No machine name(s) specified and no "default" machine exists. </code></pre> <p>So when I do a "docker-machine ls" there is nothing in the list even though I do have a Hyper-V docker machine installed and docker commands work fine.</p> <pre><code>C:\tmp&gt;docker-machine ls NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS C:\tmp&gt; </code></pre> <p>Am I missing something here? Did I miss something in the documentation? If so can someone please point me in the right direction to fix this?</p> <p>Thanks for any help,</p> <p>Jim</p>
<windows><docker><boot2docker><hyper-v><docker-machine>
2016-10-10 20:16:32
HQ
39,967,602
While doesn't approve true requirement
<p>Variable i will be 0 in the end. Am I having serious problem in visual studio or in my brain? </p> <pre><code>double value = 0.0001; int i = 0; while(value &lt; 0) { value *= 10; i++; } Console.WriteLine(i); Console.ReadLine(); </code></pre>
<c#>
2016-10-10 22:18:09
LQ_CLOSE
39,967,608
"type" object is not subscriptable python selenium
im a newbie to python selenium environment. this is my piece of code. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait import unittest class LoginTest(unittest.TestCase): def setUp(self): self.driver= webdriver.Firefox() self.driver.get("https://www.facebook.com/") def test_Login(self): driver=self.driver facebookUsername ="somoe@gmail.com" facebookPassword ="basabasa" emailFieldID = "email" passFieldID = "pass" loginButtonXpath = "//input[@value= 'Log In']" fbLogoXpath = "(//a[contains(href , 'logo')])[1]" emailFieldElement = WebDriverWait[driver, 10].until(lambda driver:driver.find_element_by_id(emailFieldID)) passwordFieldElement = WebDriverWait[driver, 10].until(lambda driver:driver.find_element_by_id(passFieldID)) loginButtonElement = WebDriverWait[driver, 10].until(lambda driver:driver.find_element_by_xpath(loginButtonXpath)) emailFieldElement.clear() emailFieldElement.send_keys(facebookUsername) passFieldElement.clear() passFieldElement.send_keys(facebookPassword) loginButtonElement.click() loginButtonElement=WebDriverWait[driver, 10].until(lambda driver : driver.find_element_by_xpath(fbLogoXpath)) def tearDown(self): self.driver.quit() if __name__=='__main__': unittest.main() this code loads facebook when it runs but does not autofill the email and password area and returns with the error mentioned above. i need urgent help in this if possible. thank you.
<python><python-3.x><selenium>
2016-10-10 22:18:30
LQ_EDIT
39,968,328
Check how many digits in Java program & and terminate if not 5 digits?
<p>I am trying to complete an assignment, and I have almost fully completed it but I am have some trouble figuring out the last part. </p> <p>How to: Check whether the number you received has five digits or not. Terminate gracefully if it doesn’t by notifying that the number should have 5 digits.</p> <p>I've tried some stuff but I cannot get it to check correctly.</p> <p>Here is my code:</p> <pre><code>import java.util.Scanner; public class Five { public static void main( String args[] ) { Scanner input = new Scanner( System.in ); int number; int digit1; int digit2; int digit3; int digit4; int digit5; System.out.print( "Enter a five digit integer: " ); number = input.nextInt(); digit1 = number / 10000; digit2 = number % 10000 / 1000; digit3 = number % 10000 % 1000 / 100; digit4 = number % 10000 % 1000 % 100 / 10; digit5 = number % 10000 % 1000 % 100 % 10; System.out.printf( "Digits in %d are %d %d %d %d %d/n", number, digit1, digit2, digit3, digit4, digit5 ); } } </code></pre> <hr> <p>Thank you</p>
<java>
2016-10-10 23:34:33
LQ_CLOSE
39,968,344
nginx 'invalid number of arguments in "map" directive'
<p>I'm trying to reverse-proxy a websocket, which I've done with nginx before with no issue. Weirdly, I can't seem to re-create my prior success with something so simple. I've been over and over the config file but can't seem to find my error.</p> <p>Here's my full <code>default.conf</code>:</p> <pre><code>map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; location /api/ { proxy_pass ${API_LOCATION}; } location / { proxy_pass ${UI_LOCATION}; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } } </code></pre> <p>The error I'm getting:</p> <pre><code>2016/10/10 23:30:24 [emerg] 8#8: invalid number of arguments in "map" directive in /etc/nginx/conf.d/default.conf:1 nginx: [emerg] invalid number of arguments in "map" directive in /etc/nginx/conf.d/default.conf:1 </code></pre> <p>And the exact Dockerfile that I'm using, in case you want to replicate my setup (save <code>default.conf</code> as <code>conf.templates/default.conf</code> relative to the Dockerfile:</p> <pre><code>FROM nginx COPY conf /etc/nginx/conf.templates CMD /bin/bash -c "envsubst &lt; /etc/nginx/conf.templates/default.conf &gt; /etc/nginx/conf.d/default.conf &amp;&amp; nginx -g 'daemon off;'" </code></pre>
<nginx><configuration><reverse-proxy>
2016-10-10 23:35:41
HQ
39,968,864
Writing to a txt file without clearing the previous content
<p>I want to know how do I write a line to a file without clearing or flushing it. What classes and packages do I need? I've tried with FileOutputStream and PrintStream (using println) and with BufferedWriter and OutputStreamWriter (using write) but they erase the previous content from the file. </p> <pre><code>try { File txt = new File("marcos.txt"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); writer.write(registro); writer.newLine(); writer.close(); } catch(Exception e) { System.out.println("Error en la escritura al archivo."); } </code></pre>
<java><file>
2016-10-11 00:47:40
LQ_CLOSE
39,968,922
Convert Date to DateTime using Joda
<p>Is there a way to convert a date in the format "YYYY-MM-dd" to "YYYY-MM-dd HH:mm:ss" using Joda?</p> <p>Eg: "2016-01-21" to "2016-01-21 00:00:00"</p>
<java><jodatime>
2016-10-11 00:55:33
LQ_CLOSE
39,969,308
Finding avg of n numbers in a list in Python
Everything is working except when the user types N to end the while loop, it doesn't go to the For Statement (this happens when you run the program, works fine in the shell and in the py). potato = [] kount = 0 avg = 0 question = input('Finding averages, continue? Y or N: ') while question == 'Y' and kount <= 12: num = int(input('Enter a number: ')) potato.append(num) kount += 1 question = input('Continue? Y or N: ') for fries in potato: avg = sum(potato)/kount print(fries,fries-avg) print('average is: ' + str(avg))
<python><python-3.x><input>
2016-10-11 01:47:09
LQ_EDIT
39,969,670
How would improve this O(n^2 ) string manipulation solution?
Write a function that takes in an input of a string and returns the count of tuples. Tuples in the form (x,y) where x = index of 'a', y = index of 'b' and x < y. Examples: For “aab” the answer is two For "ababab" the answer is six It can be done in O(n^2) by simply looking for the number of b's after each 'a' but I'm not sure how to do it in O(n). I've tried traversing the string with 2 pointers but I keep missing some tuples. I'm not sure if this can be done in O(n) time.
<algorithm>
2016-10-11 02:33:05
LQ_EDIT
39,969,772
Using php in python language is really a good practice?
<p>I'm a PHP Developer, i have some projects in python.</p> <p>But already i done some core concepts in PHP. so is it good for reuse the those php code in python by calling via "php file.php" to return the output.</p> <p>Is it's really a good practice ?</p> <p>Or I should develop from scratch ?</p>
<php><python><python-3.x><project>
2016-10-11 02:47:20
LQ_CLOSE
39,970,210
Send Apple push notification from a Go appengine site
<p>I'm trying to send an Apple push notification from a Go appengine site. I'm using the <a href="https://godoc.org/github.com/sideshow/apns2" rel="noreferrer">apns2 library</a> as follows:</p> <pre><code>cert, err := certificate.FromPemFile(pemFile, "") if err != nil { log.Fatalf("cert error: %v", err) } client := apns2.NewClient(cert).Development() n := &amp;apns2.Notification{...} if res, err := client.Push(n); err != nil { ... } </code></pre> <p>On a local development server, it works fine; but in production I'm seeing:</p> <pre><code>Post https://api.development.push.apple.com/3/device/995aa87050518ca346f7254f3484d7d5c731ee93c35e3c359db9ddf95d035003: dial tcp: lookup api.development.push.apple.com on [::1]:53: dial udp [::1]:53: socket: operation not permitted </code></pre> <p>It looks like appengine expects you to use its own <a href="https://cloud.google.com/appengine/docs/go/outbound-requests" rel="noreferrer">urlfetch library</a> when sending outbound requests, so I tried setting the underlying <code>HTTPClient</code> to use that:</p> <pre><code>client.HTTPClient = urlfetch.Client(ctx) </code></pre> <p>However, the response from the Apple server is now</p> <pre><code>@@?HTTP/2 client preface string missing or corrupt. Hex dump for received bytes: 504f5354202f332f6465766963652f393935616138373035 </code></pre> <p>I believe the problem is that Apple push notifications <a href="https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html" rel="noreferrer">require HTTP/2</a>, but urlfetch only implements HTTP/1.1.</p> <p>How do I solve this problem? Is there a way for an appengine app to send an HTTP/2 request?</p>
<ios><google-app-engine><go><push-notification>
2016-10-11 03:44:41
HQ
39,970,606
gaierror: [Errno 8] nodename nor servname provided, or not known (with macOS Sierra)
<p>socket.gethostbyname(socket.gethostname()) worked well on OS X El Capitan. However, it's not working now after the Mac updated to macOS Sierra.</p> <p>Thanks!</p> <pre><code>import socket socket.gethostbyname(socket.gethostname()) Traceback (most recent call last): File "&lt;pyshell#26&gt;", line 1, in &lt;module&gt; socket.gethostbyname(socket.gethostname()) gaierror: [Errno 8] nodename nor servname provided, or not known </code></pre>
<python><sockets>
2016-10-11 04:41:45
HQ
39,971,762
Add class to body on Angular2
<p>I have three components. These are HomeComponent, SignInComponent and AppComponent. My Home Page (HomeComponent) is showing when the application opened. I clicked the "Sign In" button by signin page opens.I want "signin-page" class to body while opening it.</p> <p>How can I do it?</p> <pre><code>// AppComponent import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'app', template: '&lt;router-outlet&gt;&lt;/router-outlet&gt;' }) export class AppComponent {} // SignInComponent import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'signin', templateUrl: './signin.component.html', styleUrls: ['./signin.component.css'] }) export class SignInComponent {} // HomeComponent import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'home', templateUrl: './home.component.html' }) export class HomeComponent { } // Part of index.html &lt;body&gt; &lt;app&gt; &lt;div class="spinner"&gt; &lt;div class="bounce1"&gt;&lt;/div&gt; &lt;div class="bounce2"&gt;&lt;/div&gt; &lt;div class="bounce3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/app&gt; &lt;/body&gt; </code></pre>
<javascript><angular>
2016-10-11 06:48:11
HQ
39,972,087
C++ error: redefinition of class
<p><strong>Note:</strong> I have searched thoroughly on SO and the solutions posted for other's with similar questions are not working for me here.</p> <p>I am writing my own custom 'string-like' class in C++, and am encoutering the following errors when compiling:</p> <blockquote> <p>./PyString.h:8:11: error: out-of-line declaration of 'PyString' does not match any declaration in 'PyString' PyString::PyString (char*); ^</p> <p>./PyString.h:9:11: error: definition of implicitly declared destructor PyString::~PyString (void);</p> <p>pystring.cpp:4:7: error: redefinition of 'PyString' class PyString {</p> </blockquote> <p>As for the first and second errors, moving around the destructor into the class definition itself in the <code>cpp</code> file did not work.</p> <p>As for the third error, I can't seem to fix it - I'm not redefining the class!</p> <p>Here is <code>pystring.h</code>:</p> <pre><code>#ifndef PYSTRING_INCLUDED #define PYSTRING_INCLUDED class PyString { char* string; }; PyString::PyString (char*); PyString::~PyString (void); #endif </code></pre> <p>Here is <code>pystring.cpp</code>:</p> <pre><code>#include "PyString.h" #define NULL 0 class PyString { char* string = NULL; public: PyString(char inString) { string = new char[inString]; }; ~PyString(void) { delete string; }; }; </code></pre> <p>For reference, here is the compile output as a screenshot: <a href="https://i.stack.imgur.com/hPrq8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hPrq8.png" alt="Compiler output screenshot"></a></p> <p>Any help is greatly appreciated.</p>
<c++><class><compiler-errors><g++>
2016-10-11 07:12:19
LQ_CLOSE
39,972,135
How does the Gerrit server intercept commits. Looking for technical details
<p>I understand that Gerrit receives git commits (using the <code>update</code> hook perhaps), and write them on a fake ref somewhere until the peer review is done, but how exactly does that process work in terms of the technical implementation? And what Git commands are involved?</p>
<git><server><gerrit>
2016-10-11 07:15:39
HQ
39,972,402
how to make pairs using nested loop in lisp
I am trying to make pairs function in lisp. Pairs function gets 2 inputs then makes pair each other and make one list. Here is my code. (defun npair (s1 s2) (let ((result '())) (cond ((null s1) s2) ((null s2) s1) (t (loop (when (null s1) (return result)) (while (not (null s2)) (setq result (cons (list (car s1) (car s2)) result)) (setq s2 (cdr s2)) ) (setq s1 (cdr s1)) ) ) ) ) ) This function should have returned like (npair '(a b c) '(1 2)) -> ((a 1) (a 2) (b 1) (b 2) (c 1) (c 2)) But my result is only ((a 1) (a 2)) Please help!!
<loops><while-loop><lisp>
2016-10-11 07:35:10
LQ_EDIT
39,972,962
equivalent of "canvas" in React Native
<p>I am currently working on an image processing mobile App based on React-Native. However, I can't find any related documents about the image crop, zoom, pan, and save functions (which can be easily achieved by the HTML5 canvas element) on the React-Native official site. </p> <p>I also do some google searches, but only find an "unmaintained" react-native-canvas (<a href="https://github.com/lwansbrough/react-native-canvas" rel="noreferrer">https://github.com/lwansbrough/react-native-canvas</a>). Is there any equivalent of the "canvas" in React Native? </p>
<canvas><react-native>
2016-10-11 08:11:27
HQ
39,972,990
How to explicitly set the storage path of an image clicked using Cordova API?
I am extremely new to Cordova and I'm working on the Android platform, and need to store the image at a custom location. The 'navigator.camera.getPicture' method stores the clicked image in the cache, but I need to store that image at a custom folder in the root. How to do that?
<android><image><cordova><path><location>
2016-10-11 08:13:07
LQ_EDIT
39,974,210
Why componentDidMount gets called multiple times in react.js & redux?
<p>I read <code>componentDidMount</code> gets called only once for initial rendering but I'm seeing it's getting rendered multiple times.</p> <p>It seems I created a recursive loop.</p> <ul> <li>componentDidMount dispatches action to fetch data</li> <li>upon receiving the data, it fires success action to store the data in redux state.</li> <li>a parent react component is connected to redux store and has <code>mapStateToProps</code> for the entry that just changed in the above step</li> <li>parent renders child components (which is programmatically selected via variable)</li> <li>the child component's componentDidMount gets called again</li> <li>it dispaches action to fetch data</li> </ul> <p>I think that's what's happening. I may be wrong. </p> <p>How can I stop the loop?</p> <p>Here's the code for programmatically rendering child components.</p> <pre><code> function renderSubviews({viewConfigs, viewConfig, getSubviewData}) { return viewConfig.subviewConfigs.map((subviewConfig, index) =&gt; { let Subview = viewConfigRegistry[subviewConfig.constructor.configName] let subviewData = getSubviewData(subviewConfig) const key = shortid.generate() const subviewLayout = Object.assign({}, subviewConfig.layout, {key: key}) return ( &lt;div key={key} data-grid={subviewLayout} &gt; &lt;Subview {...subviewData} /&gt; &lt;/div&gt; ) }) } </code></pre>
<reactjs><redux><react-redux>
2016-10-11 09:27:21
HQ
39,974,292
I am getting Null Pointer Exception in my Selenium Script?
<pre><code> enter code here import java.util.ArrayList; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class ArrayLiist { public static void main(String[] args) { launchBrowser("CH"); WebDriver driver=null; driver.findElement(By.id("user_login")).sendKeys("admin"); driver.findElement(By.id("user_pss")).sendKeys("demo123"); driver.findElement(By.id("wp-submit")).click(); } public static void launchBrowser(String bn) { if(bn=="CH") { System.setProperty("webdriver.chrome.driver","E:\\Selenium Downloaded\\chrome\\chromedriver.exe"); ChromeDriver driver = new ChromeDriver(); driver.get("http://demosite.center/wordpress/wp-admin/plugins.php"); } } } </code></pre> <p>i think driver is not being identified ? i have institiated webdriver =null , still it is showing null pointer exception</p> <p>Exception in thread "main" java.lang.NullPointerException at ArrayLiist.main(ArrayLiist.java:13)</p>
<java><selenium>
2016-10-11 09:31:57
LQ_CLOSE
39,975,001
Runtime exception while table creation in SQLite(Create table has stoped)
> This is my on create DatabaseHelper calss public class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABAE_NAME = "Student.db"; public static final String TABLE_NAME= "Student_table"; public static final String COL_1="ID"; public static final String COL_2="NAMME"; public static final String COL_3="SURNAME"; public static final String COL_4="MARKS"; public DatabaseHelper(Context context) { super(context, DATABAE_NAME, null, 1); SQLiteDatabase db=this.getWritableDatabase(); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table" + TABLE_NAME+" (ID INTEGER PRIMARY KEY ,NAME TEXT,SURNAME TEXT,MARKS INTEGER)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME); onCreate(db); } } > this is my main class public class MainActivity extends AppCompatActivity { DatabaseHelper myDB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myDB =new DatabaseHelper(this); } } > This is logcat 10-11 15:34:25.793 3807-3807/user_profile.createtable E/AndroidRuntime: FATAL EXCEPTION: main Process: user_profile.createtable, PID: 3807 java.lang.RuntimeException: Unable to start activity ComponentInfo{user_profile.createtable/user_profile.createtable.MainActivity}: android.database.sqlite.SQLiteException: near "tableStudent_table": syntax error (code 1): , while compiling: create tableStudent_table (ID INTEGER PRIMARY KEY ,NAME TEXT,SURNAME TEXT,MARKS INTEGER) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413) at android.app.ActivityThread.access$800(ActivityThread.java:155) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5343) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700) Caused by: android.database.sqlite.SQLiteException: near "tableStudent_table": syntax error (code 1): , while compiling: create tableStudent_table (ID INTEGER PRIMARY KEY ,NAME TEXT,SURNAME TEXT,MARKS INTEGER) at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58) at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31) at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674) at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605) at user_profile.createtable.DatabaseHelper.onCreate(DatabaseHelper.java:26) at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251) at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163) at user_profile.createtable.DatabaseHelper.<init>(DatabaseHelper.java:21) at user_profile.createtable.MainActivity.onCreate(MainActivity.java:13) at android.app.Activity.performCreate(Activity.java:6010) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)  at android.app.ActivityThread.access$800(ActivityThread.java:155)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5343)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)  10-11 15:39:26.133 3807-3807/user_profile.createtable I/Process: Sending signal. PID: 3807 SIG: 9
<android><sqlite><android-sqlite>
2016-10-11 10:11:45
LQ_EDIT
39,976,418
Get Json value where key1=value1 and key2=value2
I'm trying to parse a more complex Json with ruby: "data": [{ "resourceId": 381, "resourceName": "Admin.Config", "resourceDesc": "Correspondence Admin -> Configuration", "permissions": [{ "id": 1081, "operation": "Update", "assignedToRoleFlag": false }, { "id": 1071, "operation": "Read", "assignedToRoleFlag": false }], "productName": "Doc" }, { "resourceId": 391, "resourceName": "Admin.Usage", "resourceDesc": "Correspondence Admin -> Usage", "permissions": [{ "id": 1091, "operation": "Read", "assignedToRoleFlag": false }], "productName": "Doc" }, ...................................... } The issue is that I want to parse this to get ['data']['permissions']['id'] where ['data']['resourceName'] = Admin.Config and ['data']['permissions']['operation'] = Read for example.
<json><ruby>
2016-10-11 11:39:06
LQ_EDIT
39,976,756
The max_connections in MySQL 5.7
<p>I met a problem, the value of max_connction in MySQL is 214 after I set it 1000 via edit the my.cnf, just like below:</p> <pre><code>hadoop@node1:~$ mysql -V mysql Ver 14.14 Distrib 5.7.15, for Linux (x86_64) using EditLine wrapper </code></pre> <p>MySQL version: 5.7</p> <p>OS version : ubuntu 16.04LTS</p> <pre><code>mysql&gt; show variables like 'max_connections'; +-----------------+-------+ | Variable_name | Value | +-----------------+-------+ | max_connections | 151 | +-----------------+-------+ 1 row in set (0.00 sec) </code></pre> <p>As we can see, the variable value of max_connections is 151. Then , I edit the configuration file of MySQL.</p> <pre><code>yang2@node1:~$ sudo vi /etc/mysql/my.cnf [mysqld] character-set-server=utf8 collation-server=utf8_general_ci max_connections=1000 </code></pre> <p>Restart MySQL service after save the configraion.</p> <pre><code>yang2@node1:~$ service mysql restart ==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units === Authentication is required to restart 'mysql.service'. Multiple identities can be used for authentication: 1. yangqiang,,, (yang2) 2. ,,, (hadoop) Choose identity to authenticate as (1-2): 1 Password: ==== AUTHENTICATION COMPLETE === yang2@node1:~$ </code></pre> <p>Now, we guess the max_connection is 1000, really?</p> <pre><code>mysql&gt; show variables like 'max_connections'; +-----------------+-------+ | Variable_name | Value | +-----------------+-------+ | max_connections | 214 | +-----------------+-------+ 1 row in set (0.00 sec) </code></pre> <p>It is 214. I do not really understand this result, who can help me? thx!</p>
<mysql><max><connection>
2016-10-11 11:59:45
HQ
39,976,841
Trying to parse on a hash of symbol in ruby
I try to downcase a parsed option to match only symbol in downcase format because when I match A UPPERCASE OR meltedCASE , my parser return me a nil value :( Don't want to have a heavy hash like [:ens, :ENS, :eNS, :enS ... etc etc opts.on("-i", "--instance [INSTANCE]", [:ens, :etu], "Selectionnez l'instance de Gitlab (etu, ens)") do |instance| # puts instance.inspect Options[:instance] = instance end
<ruby><parsing><hash><command-line-interface><symbols>
2016-10-11 12:04:48
LQ_EDIT
39,976,917
can someone explain output of this program?
output of this program is: XBCDO HELLE can someone explain why this is so? #include<stdio.h> void swap(char ** p,char **q){ char *temp=*p; *p=*q; *q=temp; } int main(){ int i=10; char a[10]="HELLO"; char b[10]="XBCDE"; swap(&a,&b); printf("%s %s",a,b); }
<c>
2016-10-11 12:09:02
LQ_EDIT
39,977,760
How to check if used paginate in laravel
<p>I have a custom view and in some functions, I used <code>paginate</code> and other functions I don't use <code>paginate</code>. now how can I check if I used <code>paginate</code> or not ?</p> <pre><code>@if($products-&gt;links()) {{$products-&gt;links()}} @endif // not work </code></pre> <p>of course that I know I can use a variable as true false to will check it, But is there any native function to check it ?</p>
<laravel><laravel-5><pagination>
2016-10-11 12:55:45
HQ
39,978,092
Xcode playground gets stuck on 'Running playground' or 'Launching simulator' and won't run the code, what to do?
<p>Every time I create a new playground in order to test some code, Xcode gets stuck and won't run the code. It simply presents 'Running playground' or 'Launching simulator' statement at the top of the screen with the loading icon promisingly spinning next to it but nothing happens. Sometimes this continues indefinitely and sometimes Xcode halts and prints this to console :</p> <pre><code>Playground execution failed: error: Couldn't lookup symbols: __swift_FORCE_LOAD_$_swiftCoreImage __swift_FORCE_LOAD_$_swiftFoundation _playground_log_hidden _playground_logger_initialize _playground_log_postprint thread #1: tid = 0xc0cd0, 0x000000010ea7c3c0 MyPlayground`executePlayground, queue = 'com.apple.main-thread', stop reason = breakpoint 1.2 frame #0: 0x000000010ea7c3c0 MyPlayground`executePlayground frame #1: 0x000000010ea7b9c0 MyPlayground`__37-[XCPAppDelegate enqueueRunLoopBlock]_block_invoke + 32 frame #2: 0x000000010f59625c CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12 frame #3: 0x000000010f57b304 CoreFoundation`__CFRunLoopDoBlocks + 356 frame #4: 0x000000010f57aa75 CoreFoundation`__CFRunLoopRun + 901 frame #5: 0x000000010f57a494 CoreFoundation`CFRunLoopRunSpecific + 420 frame #6: 0x0000000114985a6f GraphicsServices`GSEventRunModal + 161 frame #7: 0x0000000110124f34 UIKit`UIApplicationMain + 159 frame #8: 0x000000010ea7b6e9 MyPlayground`main + 201 frame #9: 0x0000000112ad268d libdyld.dylib`start + 1 frame #10: 0x0000000112ad268d libdyld.dylib`start + 1 </code></pre> <p>I am running Xcode 8.0 (8A218a) on macOS Sierra 10.12. <br></p> <p><strong>Hardware</strong>: <br> MacBook Pro (13" Mid-2012) <br> 2,5 GHz Intel Core i5 <br> 4 GB 1600 MHz Ram DDR3</p> <p>I have looked around but at least neither of these threads have provided an answer: <br> <a href="https://forums.developer.apple.com/thread/5902" rel="noreferrer">https://forums.developer.apple.com/thread/5902</a> <br> <a href="https://github.com/jas/playground/issues/9" rel="noreferrer">https://github.com/jas/playground/issues/9</a></p> <p>Things I have already tried with zero success:</p> <ul> <li>Restarting Xcode</li> <li>Reinstalling Xcode (downgraded to 7.3 but since that didn't help I upgraded back to 8.0)</li> <li>Restarting the machine</li> <li>Creating a new playground</li> </ul> <p>Do you have any ideas on how to solve this problem? I am new to programming and eagerly trying to learn Swift but Xcode is making it practically impossible...</p> <p>Thank you in advance, cheers.</p>
<ios><xcode><xcode8>
2016-10-11 13:13:04
HQ
39,978,856
Unable to change source branch in GitHub Pages
<p>I have created a simple web site for GitHub Pages. The source of the site is in the "master" branch and the generated web site (what I want to see published) is under the "gh-pages" branch.</p> <p><a href="https://i.stack.imgur.com/NQQpR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NQQpR.png" alt="Branches"></a></p> <p>I was expecting to be able to change the source of the site in the settings. However, the setting is grayed out? I cannot change it (see screenshot below). What am I doing wrong? How do I switch to the "gh-pages" branch?</p> <p><a href="https://i.stack.imgur.com/rwWY9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rwWY9.png" alt="enter image description here"></a></p>
<github><github-pages>
2016-10-11 13:50:59
HQ
39,979,831
Angular 2 - with ngFor, is it possible to update values without rebuilding the dom?
<p>I have a component 'bar' inside ngFor. I want to update its width with animation starting from the previous value to new one. </p> <p>html : </p> <pre><code>&lt;div *ngFor="let station of stations" class="station"&gt; &lt;bar [perc]="station.perc" class="bar"&gt;&lt;/bar&gt; &lt;/div&gt; </code></pre> <p>ParentComponent : </p> <pre><code>ngOnInit(){ setInterval(() =&gt; this.updateData(), 10000); } updateData(){ const url = 'http://....'; this.http.get(url) .map(res =&gt; res.json()) .subscribe(data =&gt; { this.stations = data; }); } </code></pre> <p>BarComponent</p> <pre><code>export class BarComponent { @Input() perc; constructor(private element: ElementRef){} ngOnChanges(changes: any): void { let perc = changes.perc.currentValue; TweenMax.to(this.element.nativeElement, 1, { width: perc + '%' }); } } </code></pre> <p>But on each updateData() it looks like ngFor recreates the dom and BarComponent is constructed again. So even if 'station.perc' is the same, ngOnChanges() is fired.</p> <p>And the transition keeps on restarting from 0 instead of starting from the previous value...</p> <p>I probably miss a crucial point here but whats the clean workaround?</p>
<angular>
2016-10-11 14:37:48
HQ
39,980,098
How to program an <ul> image gallery, where the hover effect impacts more than 1 element?
<p>I'd like to program an image gallery, which looks like this one: <a href="http://www.volkswagen.de/de.html" rel="nofollow">http://www.volkswagen.de/de.html</a> By default, all buttons have the same size. </p> <p>When the user hovers over the button, its size increases, meanwhile, all other buttons (aside from the one on the left and right of the button which the user hovers overs) are shrunk.</p> <p>I assume that it's a mix of CSS and Javascript, but I can't figure out how it works, especially given how the buttons move left and right depending on what's being hovered over.</p> <p>Could someone please help me?</p>
<javascript><html><css><hover><image-gallery>
2016-10-11 14:49:42
LQ_CLOSE
39,980,383
Numpy 2 column n rows array- operation on elemts of two columsn in each row
I am very new to Python and Numpy. I have an array of n rows and two columns (array). I have another variable (a) which I am using as reference. for a between (1-10000) if column1 of ARRAY<= a <= column2 of the ARRAY save the tuple (a, YES) This resultant tuple I will use for further operation
<python><arrays><numpy>
2016-10-11 15:02:30
LQ_EDIT
39,981,650
Limit Kafka batches size when using Spark Streaming
<p>Is it possible to limit the size of the batches returned by the Kafka consumer for Spark Streaming?</p> <p>I am asking because the first batch I get has hundred of millions of records and it takes ages to process and checkpoint them.</p>
<apache-spark><apache-kafka><spark-streaming><kafka-consumer-api>
2016-10-11 15:59:49
HQ
39,981,800
How to achieve test isolation with Symfony forms and data transformers?
<p><strong><em>Note:</strong> This is Symfony &lt; 2.6 but I believe the same overall issue applies regardless of version</em></p> <p>To start, consider this form type that is designed to represent one-or-more entities as a hidden field (namespace stuff omitted for brevity)</p> <pre><code>class HiddenEntityType extends AbstractType { /** * @var EntityManager */ protected $em; public function __construct(EntityManager $em) { $this-&gt;em = $em; } public function buildForm(FormBuilderInterface $builder, array $options) { if ($options['multiple']) { $builder-&gt;addViewTransformer( new EntitiesToPrimaryKeysTransformer( $this-&gt;em-&gt;getRepository($options['class']), $options['get_pk_callback'], $options['identifier'] ) ); } else { $builder-&gt;addViewTransformer( new EntityToPrimaryKeyTransformer( $this-&gt;em-&gt;getRepository($options['class']), $options['get_pk_callback'] ) ); } } /** * See class docblock for description of options * * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver-&gt;setDefaults(array( 'get_pk_callback' =&gt; function($entity) { return $entity-&gt;getId(); }, 'multiple' =&gt; false, 'identifier' =&gt; 'id', 'data_class' =&gt; null, )); $resolver-&gt;setRequired(array('class')); } public function getName() { return 'hidden_entity'; } /** * {@inheritdoc} */ public function getParent() { return 'hidden'; } } </code></pre> <p>This works, it's straightforward, and for the most part looks like like all the examples you see for adding data transformers to a form type. Until you get to unit testing. See the problem? The transformers can't be mocked. "But wait!" you say, "Unit tests for Symfony forms are integration tests, they're supposed to make sure the transformers don't fail. Even says so <a href="http://symfony.com/doc/current/form/unit_testing.html" rel="noreferrer">in the documentation</a>!"</p> <blockquote> <p>This test checks that none of your data transformers used by the form failed. The isSynchronized() method is only set to false if a data transformer throws an exception</p> </blockquote> <p>Ok, so then you live with the fact you can't isolate the transformers. No big deal? </p> <p>Now consider what happens when unit testing a form that has a field of this type (assume that <code>HiddenEntityType</code> has been defined &amp; tagged in the service container)</p> <pre><code>class SomeOtherFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder -&gt;add('field', 'hidden_entity', array( 'class' =&gt; 'AppBundle:EntityName', 'multiple' =&gt; true, )); } /* ... */ } </code></pre> <p>Now enters the problem. The unit test for <code>SomeOtherFormType</code> now needs to implement <code>getExtensions()</code> in order for the <code>hidden_entity</code> type to function. So how does that look?</p> <pre><code>protected function getExtensions() { $mockEntityManager = $this -&gt;getMockBuilder('Doctrine\ORM\EntityManager') -&gt;disableOriginalConstructor() -&gt;getMock(); /* Expectations go here */ return array( new PreloadedExtension( array('hidden_entity' =&gt; new HiddenEntityType($mockEntityManager)), array() ) ); } </code></pre> <p>See where that comment is in the middle? Yeah, so for this to work correctly, all of the mocks and expectations that are in the unit test class for the <code>HiddenEntityType</code> now effectively need to be duplicated here. I'm not OK with this, so what are my options?</p> <ol> <li><p>Inject the transformer as one of the options</p> <p>This would be very straightforward and would make mocking simpler, but ultimately just kicks the can down the road. Because in this scenario, <code>new EntityToPrimaryKeyTransformer()</code> would just move from one form type class to another. Not to mention that I feel form types <em>should</em> hide their internal complexity from the rest of the system. This option means pushing that complexity outside the boundary of the form type.</p></li> <li><p>Inject a transformer factory of sorts into the form type</p> <p>This is a more typical approach to removing "newables" from within a method, but I can't shake the feeling that this is being done just to make the code testable, and is not actually making the code better. But if that was done, it would look something like this</p> <pre><code>class HiddenEntityType extends AbstractType { /** * @var DataTransformerFactory */ protected $transformerFactory; public function __construct(DataTransformerFactory $transformerFactory) { $this-&gt;transformerFactory = $transformerFactory; } public function buildForm(FormBuilderInterface $builder, array $options) { $builder-&gt;addViewTransformer( $this-&gt;transformerFactory-&gt;createTransfomerForType($this, $options); ); } /* Rest of type unchanged */ } </code></pre> <p>This feels ok until I consider what the factory will actually look like. It will need the entity manager injected, for starters. But what then? If I look further down the road, this supposedly-generic factory could need all sorts of dependencies for creating data transformers of different kinds. That is clearly not a good long-term design decision. So then what? Re-label this as an <code>EntityManagerAwareDataTransformerFactory</code>? It's starting to feel messy in here.</p></li> <li><p>Stuff I'm not thinking of...</p></li> </ol> <p>Thoughts? Experiences? Solid advice?</p>
<php><unit-testing><symfony><symfony-forms>
2016-10-11 16:07:55
HQ
39,982,067
Whats the idea behind task clean on gradle android projects
<p>When I create a new project on android studio I see in <code>gradle.build</code>:</p> <pre><code>task clean(type: Delete) { delete rootProject.buildDir } </code></pre> <p>Whats the idea behind it? </p>
<android-gradle-plugin><build.gradle>
2016-10-11 16:22:50
HQ
39,982,396
How to Run private class method.in same class in java
Can figure why it won't allow me to run the displaymainMethod because its private even though i know i can run it from from same class. is there a way to do this without using reflective API. import java.util.*; public class LoginPrototype { public static void main(String[] args) { ArrayList<Credentials> allUsers = new ArrayList<Credentials>(); displayMainMenu mainMenu = new displayMenu(); } private void displayMainMenu() { int input; do { System.out.println("Menu Options"); System.out.println("[1] Login"); System.out.println("[2] Register"); System.out.println("[0] Quit");//5 Displaying Main Menu Options Scanner sc = new Scanner(System.in); input = sc.nextInt(); if (input > 2) { System.out.println("Please enter a value of [0] - [2]"); } else if (input == 1){ System.out.println("Login"); } else if (input == 2){ System.out.println("Register"); } else if (input == 0){ System.out.println("Thank you. bye."); } }while(input >= 2); } }
<java><oop><private><main>
2016-10-11 16:42:37
LQ_EDIT
39,983,561
Swift 3 silently allows shadowing a parameter
<p>I'm switching to Swift, and I'm really not happy that the following code compiles without a warning:</p> <pre><code>func f(_ x: inout Int?) { var x: Int? // &lt;-- this declaration should produce a warning x = 105 if x! &lt; 1000 {} } var a: Int? = 3 f(&amp;a) print("\(a)") </code></pre> <p>and, of course, outputs <code>Optional(3)</code> upon execution.</p> <p>In this example, the <code>x</code> local variable shadows the <code>x</code> function parameter.</p> <p>Turning on the <code>Hidden Local Variables</code> warning (<code>GCC_WARN_SHADOW</code>) in the project settings doesn't cause a warning to be produced either.</p> <p><strong>Question:</strong> How should I proceed to make the Swift 3 compiler warn me about such shadowing?</p>
<swift>
2016-10-11 17:53:14
HQ
39,983,946
TIC TCP Conn Error on iOS 10 logs
<p>Is anyone getting the following CFNetwork notices in their iOS 10 logs?</p> <pre><code>(CFNetwork)[1142] &lt;Notice&gt;: TIC TCP Conn Event [28:0x1741845e0]: 1 Err(0) (CFNetwork)[1142] &lt;Notice&gt;: TIC TCP Conn Connected [28:0x1741845e0]: Err(0) (CFNetwork)[1142] &lt;Notice&gt;: TIC TCP Conn Cancel [28:0x1741845e0] </code></pre> <p>I don't get any of these in my iOS 9 logs. It's not clear if this is causing anything to break. Any ideas what this is, what it's breaking or how to fix it?</p>
<ios><ios10>
2016-10-11 18:15:06
HQ
39,984,433
whats wrong with my android studios gradle?
Error:No cached version of com.android.databinding:compilerCommon:1.0-rc5 available for offline mode. <a href="toggle.offline.mode">Disable Gradle 'offline mode' and sync project</a> even in the preview part , there is no phone screen
<android><android-studio><android-gradle-plugin>
2016-10-11 18:41:40
LQ_EDIT
39,984,443
Why should optional<T&> rebind on assignment?
<p>There is an ongoing debate about what <code>optional</code> and <code>variant</code> should do with reference types, particularly with regards to assignment. I would like to better understand the debate around this issue. </p> <pre><code>optional&lt;T&amp;&gt; opt; opt = i; opt = j; // should this rebind or do i=j? </code></pre> <p>Currently, the decision is to make <code>optional&lt;T&amp;&gt;</code> ill-formed and make <code>variant::operator=</code> ill-formed if any of the types is a reference type - to sidestep the argument and still give us most of the functionality. </p> <p>What is the argument that <code>opt = j</code> <em>should</em> rebind the underlying reference? In other words, why <em>should</em> we implement <code>optional</code> like this:</p> <pre><code>template &lt;class T&gt; struct optional&lt;T&amp;&gt; { T* ptr = nullptr; optional&amp; operator=(T&amp; rhs) { ptr = &amp;rhs; return *this; } }; </code></pre>
<c++><reference><optional><c++17>
2016-10-11 18:42:24
HQ
39,985,048
Kafka Streaming Concurrency?
<p>I have some basic Kafka Streaming code that reads records from one topic, does some processing, and outputs records to another topic.</p> <p>How does Kafka streaming handle concurrency? Is everything run in a single thread? I don't see this mentioned in the documentation.</p> <p>If it's single threaded, I would like options for multi-threaded processing to handle high volumes of data.</p> <p>If it's multi-threaded, I need to understand how this works and how to handle resources, like SQL database connections should be shared in different processing threads.</p> <p>Is Kafka's built-in streaming API not recommended for high volume scenarios relative to other options (Spark, Akka, Samza, Storm, etc)?</p>
<apache-kafka><apache-kafka-streams>
2016-10-11 19:20:07
HQ
39,985,150
Compare two strings and output result where both are equal
<p>I have two strings, and I want to output one string where both give the same values. e.g.</p> <pre><code>var string1 = "ab?def#hij@lm"; var string2 = "abcd!f#hijkl]"; //expected output would be "abcdef#hijklm" </code></pre> <p>I have thought a way to do this would be to assign each character to an array, then compare each character individually but that seems inefficient, as I'm going to pass this through strings with tens of thousands of characters.</p> <p>Any help is appreciated, doesn't have to be code, just to guide me in the general direction. </p>
<javascript>
2016-10-11 19:26:57
LQ_CLOSE
39,985,844
Get DateTime From Internet in C#
<p>I am new in programming and I'm practicing with a project and I need a DateTime for it. But as you know windows DateTime can be changed by user so I need a more solid time. So far I found this two different codes. (I don't need local time. I need a time that no matter where your location is it gives you the same time.)</p> <p><strong>So here is first way to get time :</strong></p> <pre><code>private void button1_Click(object sender, EventArgs e) { DateTime dateTime = DateTime.MinValue; HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://nist.time.gov/actualtime.cgi?lzbc=siqm9b"); request.Method = "GET"; request.Accept = "text/html, application/xhtml+xml, */*"; request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"; request.ContentType = "application/x-www-form-urlencoded"; request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { StreamReader stream = new StreamReader(response.GetResponseStream()); string html = stream.ReadToEnd(); string time = Regex.Match(html, @"(?&lt;=\btime="")[^""]*").Value; double milliseconds = Convert.ToInt64(time) / 1000.0; textBox1.Text = new DateTime(1970, 1, 1).AddMilliseconds(milliseconds).ToString(); } </code></pre> <p><strong>Here is the second way :</strong></p> <pre><code>private void button2_Click(object sender, EventArgs e) { var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com"); var response = myHttpWebRequest.GetResponse(); string todaysDates = response.Headers["date"]; DateTime dateTime = DateTime.ParseExact(todaysDates, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal); textBox2.Text = dateTime.ToString(); response.Close(); } </code></pre> <p><strong>So here is the questions :</strong></p> <p>Which one of this codes you recommend me to use? (I really appreciate it if you give me a better code)</p> <p>Is that code requires any changes?</p> <p>Is the code no matter what your location is it still gives you the same time?</p> <p>Is the code always and on every computer works? (I'v read some comments about port 13 and how the code might not work depends on its status)</p>
<c#>
2016-10-11 20:08:19
LQ_CLOSE
39,986,178
Testing React: Target Container is not a DOM element
<p>I'm attempting to test a React component with Jest/Enzyme while using Webpack.</p> <p>I have a very simple test @</p> <pre><code>import React from 'react'; import { shallow } from 'enzyme'; import App from './App'; it('App', () =&gt; { const app = shallow(&lt;App /&gt;); expect(1).toEqual(1); }); </code></pre> <p>The relative component it's picking up is :</p> <pre><code>import React, { Component } from 'react'; import { render } from 'react-dom'; // import './styles/normalize.css'; class App extends Component { render() { return ( &lt;div&gt;app&lt;/div&gt; ); } } render(&lt;App /&gt;, document.getElementById('app')); </code></pre> <p>However, running <code>jest</code> causes a failure:</p> <p><code>Invariant Violation: _registerComponent(...): Target container is not a DOM element.</code></p> <p>With errors @ </p> <p><code>at Object.&lt;anonymous&gt; (src/App.js:14:48) at Object.&lt;anonymous&gt; (src/App.test.js:4:38) </code></p> <p>The test files references line 4, which is the import of <code>&lt;App /&gt;</code>, that causes a fail. The stack trace says line 14 of <code>App.js</code> is the reason for the failure -- which is nothing more than the render call from <code>react-dom</code>, something I've never had a challenge with (the app renders properly from my Webpack setup).</p> <p>For those interested (Webpack code):</p> <pre><code>module.exports = { entry: './src/App', output: { filename: 'bundle.js', path: './dist' }, module: { loaders: [ { test: /\.js?$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['react', 'es2015'] } }, { test: /\.css$/, loader: 'style!css-loader?modules&amp;importLoaders=1&amp;localIdentName=[name]__[local]___[hash:base64:5]' }, { test: /\.scss$/, loader: 'style!css-loader?modules&amp;importLoaders=1&amp;localIdentName=[name]__[local]___[hash:base64:5]!sass' } ] } } </code></pre> <p>And my <code>package.json</code>:</p> <pre><code>{ "name": "tic-tac-dux", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack-dev-server --devtool eval --progress --colors --inline --hot --content-base dist/", "test": "jest" }, "jest": { "moduleNameMapper": { "^.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "&lt;rootDir&gt;/__mocks__/fileMock.js", "^.+\\.(css|sass)$": "&lt;rootDir&gt;/__mocks__/styleMock.js" } }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "babel-core": "^6.17.0", "babel-jest": "^16.0.0", "babel-loader": "^6.2.5", "babel-polyfill": "^6.16.0", "babel-preset-es2015": "^6.16.0", "babel-preset-react": "^6.16.0", "css-loader": "^0.25.0", "enzyme": "^2.4.1", "jest": "^16.0.1", "jest-cli": "^16.0.1", "node-sass": "^3.10.1", "react-addons-test-utils": "^15.3.2", "react-dom": "^15.3.2", "sass-loader": "^4.0.2", "style-loader": "^0.13.1", "webpack": "^1.13.2", "webpack-dev-server": "^1.16.2" }, "dependencies": { "react": "^15.3.2", "react-dom": "^15.3.2" } } </code></pre> <p>Oh, and if anyone is going to say that the div element isn't being loaded before the script, here's my <code>index.html</code>:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;App&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="app"&gt;&lt;/div&gt; &lt;script src="/bundle.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What could be the reason for this peculiar rendering problem? Something to do with a new Jest update to 15.0?</p>
<javascript><reactjs><ecmascript-6><tdd>
2016-10-11 20:29:10
HQ
39,986,185
libc++ vs libstdc++ std::is_move_assignable: Which is the most correct?
<p>I'm trying to get a deeper understanding of C++ by reading the C++14 standard along with the source of libc++ and libstdc++. The implementation of various <code>type_traits</code> items varies between the two, particularly <code>is_move_assignable</code>, and I'm trying to figure out which of them is "more correct."</p> <p>libc++:</p> <pre><code>template &lt;class _Tp&gt; struct is_move_assignable : public is_assignable&lt;typename add_lvalue_reference&lt;_Tp&gt;::type, const typename add_rvalue_reference&lt;_Tp&gt;::type&gt; {}; </code></pre> <p>libstdc++:</p> <pre><code>template&lt;typename _Tp, bool = __is_referenceable&lt;_Tp&gt;::value&gt; struct __is_move_assignable_impl; template&lt;typename _Tp&gt; struct __is_move_assignable_impl&lt;_Tp, false&gt; : public false_type { }; template&lt;typename _Tp&gt; struct __is_move_assignable_impl&lt;_Tp, true&gt; : public is_assignable&lt;_Tp&amp;, _Tp&amp;&amp;&gt; { }; template&lt;typename _Tp&gt; struct is_move_assignable : public __is_move_assignable_impl&lt;_Tp&gt; { }; </code></pre> <p>The standard states:</p> <blockquote> <p>For a referenceable type <code>T</code>, the same result as <code>is_assignable&lt;T&amp;, T&amp;&amp;&gt;::value</code>, otherwise <code>false</code>.</p> </blockquote> <p>The first thing I noted is that libc++ applies <code>const</code> to the second template parameter, which doesn't seem right since the move assignment operator takes a non-const rvalue. libstdc++ also uses <code>__is_referenceable</code>, which follows the wording of the standard, but libc++ doesn't. Is that requirement covered by libc++'s use of <code>add_lvalue_reference</code> and <code>add_rvalue_reference</code>, which both enforce <code>__is_referenceable</code> on their own?</p> <p>I would really appreciate any insight into why each project chose their solutions!</p>
<c++><c++11><c++14><libstdc++><libc++>
2016-10-11 20:29:35
HQ
39,987,121
JQuery, Javascript, HTML Checkbox Price Quote
Ok, I have been trying to figure this out for about a day now. What I am trying to do is to create a form. The first question and the only question that they will see is a drop down that allows them to pick a state. Once they picked a state, pending on their selection, it will pick a check list according to their selection. Check list will have roughly 20 selections, but for now, it just six. The user can then go through the check list and check the items they wanted. Once an item been checked, another div will appear below it prompting the user to put in how many years they want to purchase this item for and the quantity. Which is the part that I got to so far. But Now, here is where I am stuck at and what I am trying to do... I did add hidden input values of service fee, license fee, and training hours. Once the user checks on an item... I want to use jquery to calculate the service fee times years to get the total_service. then add total_service plus the license fee to get the item_cost. Then the item_cost times the quantity which I will then get the total_item_cost. I then want to get and display, show, or list out the item description, service fee, years, license fee, quantity and training hours into a line, div, or table, kinda of like a shopping cart. And each time an item is checked, it will show each item below. Finally, at the bottom of list, I want to have the total cost of the items and total training times. Right now I am having issues with the dropdown of years, it seems to reset itself. And issues with the calculations. As far as the form, once I submit the form it will go to people emails and etc. just trying to get the jquery code to work first. Any advice is great. Code is below... <style> .box { display: none; } </style> <form name="" id="myForm" method="post" class="" action="http://demo.camavision.com/VCSWeb/remarks-look-up/" > <div class="tx-row" style="width:100%; float:left; clear:right;"> <div style="float:left; margin-top:-20px; "> <label> <strong style="font-size:14px;">State:</strong> <span style="font-size:10px; color:#ff0000;">(required)</span><br /> <select style= "width:90%; height:35px; font-size:18px; border: 1px #396ba5 solid;" id="state" name="state" required> <option value="" selected="selected" >Select State</option> <option value="IlIaNd" >Iowa</option> <option value="IlIaNd" >Illinois</option> <option value="Minnesota" >Minnesota</option> <option value="Missouri" >Missouri</option> <option value="Nebraska" >Nebraska</option> <option value="IlIaNd" >North Dakota</option> <option value="SouthDakota" >South Dakota</option> </select> </label> </div> </div> <script> $(document).ready(function(){ $("select").change(function(){ $(this).find("option:selected").each(function(){ if($(this).attr("value")=="IlIaNd"){ $(".box").not(".IlIaNd").hide(); $(".IlIaNd").show(); }else if($(this).attr("value")=="Minnesota"){ $(".box").not(".Minnesota").hide(); $(".Minnesota").show(); }else if($(this).attr("value")=="Missouri"){ $(".box").not(".Missouri").hide(); $(".Missouri").show(); }else if($(this).attr("value")=="Nebraska"){ $(".box").not(".Nebraska").hide(); $(".Nebraska").show(); }else if($(this).attr("value")=="SouthDakota"){ $(".box").not(".SouthDakota").hide(); $(".SouthDakota").show(); }else{ $(".box").hide(); } }); }).change(); }); </script> <div style="width: 100%; float:left; clear:both; height:25px;" > </div> <div style="border-bottom: 1px solid #cccccc; width: 100%; float:left; clear:both;" > </div> <div style="width: 100%; float:left; clear:both; height:25px;" > </div> <div style="width: 100%; float:left; clear:both;" class="IlIaNd box"> <div class="tx-column tx-column-size-1-3" > <input type="checkbox" name="description" id="chk10" value="Advanced Scheduler" > Advanced Scheduler <div id="sb10" style="width:100%;"> <div style='width:50%; float:left;'> Years: <select name='Years'> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> <option value=\"5\">5</option> </select> </div> <div style='width:50%; float:left;'> Quantity: <select name='Qty'> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> <option value=\"5\">5</option> </select> </div> <input type='hidden' name='servicefee' value="1000"> <input type='hidden' name='licensefee' value="1500"> <input type='hidden' name='traininghrs' value="8" > </div> <input type="checkbox" name="description" id="chk11" value="Advanced Printer" > Advanced Printer <div id="sb11" style="width:100%;"> <div style='width:50%; float:left;'> Years: <select name='Years'> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> <option value=\"5\">5</option> </select> </div> <div style='width:50%; float:left;'> Quantity: <select name='Qty'> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> <option value=\"5\">5</option> </select> </div> <input type='hidden' name='servicefee' value="1000"> <input type='hidden' name='licensefee' value=""> <input type='hidden' name='traininghrs' value="10" > </div> </div> <div class="tx-column tx-column-size-1-3" > <input type="checkbox" name="description" id="chk12" value="Advanced Reader" > Advanced Reader <div id="sb12" style="width:100%;"> <div style='width:50%; float:left;'> Years: <select name='Years'> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> <option value=\"5\">5</option> </select> </div> <div style='width:50%; float:left;'> Quantity: <select name='Qty'> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> <option value=\"5\">5</option> </select> </div> <input type='hidden' name='servicefee' value="1200"> <input type='hidden' name='licensefee' value="2000"> <input type='hidden' name='traininghrs' value="8" > </div> <input type="checkbox" name="description" id="chk13" value="Advanced Organizer" > Advanced Organizer <div id="sb13" style="width:100%;"> <div style='width:50%; float:left;'> Years: <select name='Years'> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> <option value=\"5\">5</option> </select> </div> <div style='width:50%; float:left;'> Quantity: <select name='Qty'> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> <option value=\"5\">5</option> </select> </div> <input type='hidden' name='servicefee' value=" "> <input type='hidden' name='licensefee' value="3000"> <input type='hidden' name='traininghrs' value="10" > </div> </div> <div class="tx-column tx-column-size-1-3" > <input type="checkbox" name="description" id="chk14" value="Advanced TaskMaster" > Advanced TaskMaster <div id="sb14" style="width:100%;"> <div style='width:50%; float:left;'> Years: <select name='Years'> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> <option value=\"5\">5</option> </select> </div> <div style='width:50%; float:left;'> Quantity: <select name='Qty'> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> <option value=\"5\">5</option> </select> </div> <input type='hidden' name='servicefee' value="1000"> <input type='hidden' name='licensefee' value="2000"> <input type='hidden' name='traininghrs' value="10" > </div> <input type="checkbox" name="description" id="chk15" value="Advanced Viewer" > Advanced Viewer <div id="sb15" style="width:100%;"> <div style='width:50%; float:left;'> Years: <select name='Years'> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> <option value=\"5\">5</option> </select> </div> <div style='width:50%; float:left;'> Quantity: <select name='Qty'> <option value=\"1\">1</option> <option value=\"2\">2</option> <option value=\"3\">3</option> <option value=\"4\">4</option> <option value=\"5\">5</option> </select> </div> <input type='hidden' name='servicefee' value="1200"> <input type='hidden' name='licensefee' value="1000"> <input type='hidden' name='traininghrs' value="0" > </div> </div> </div> <div style="width: 100%; float:left; clear:both;" class="Minnesota box" > <p>Minnesota test 2</p> </div> <div style="width: 100%; float:left; clear:both;" class="Missouri box"> <p>Missouri test 3</p> </div> <div style="width: 100%; float:left; clear:both;" class="Nebraska box" > <p>Nebraska test 4</p> </div> <div style="width: 100%; float:left; clear:both;" class="SouthDakota box"> <p>SouthDakota test 5</p> </div> <div id="total_fees"></div> <script> $(document).ready(function() { //hide all contents $('div[id^=sb]').hide(); $('input[id^=chk]').change(function(){ // get checkbox index var index = $(this).attr('id').replace('chk',''); //show respective contents if($(this).is(':checked')) $('#sb'+index).show(); else $('#sb'+index).hide(); }); }); $(document).ready(function() { $(".calculate-fees").click(function() { var descr = $('input[name="description"]').val(); var service = $('input[name="servicefee"]').val(); var years = $('input[name="Years"]').val(); var license = $('input[name="licensefee"]').val(); var qty = $('input[name="Qty"]').val(); if (qty == " "){ var qty = "1"; } var training = $('input[name="traininghrs"]').val(); var servicefee = service * years; var fees = servicefee + license; var total_fees = fees * quantity; $("#total_fees").html(descr + "Sevice Fees: " + service + "Years: " + years + "License Fee: " +license + "Quantity: " + qty + "Training Hours: " + training + "Item Cost: " + total_fees ); }); }); </script> </form>
<javascript><php><jquery><html><css>
2016-10-11 21:33:38
LQ_EDIT
39,988,120
Changing ASP.NET Identity Password
<p>I have a class that creates a user by searching for the email and making sure it doesn't exist and it creates a user:</p> <pre><code>public async Task EnsureSeedDataAsync() { if (await _userManager.FindByEmailAsync("test@theworld.com") == null) { // Add the user. var newUser = new CRAMSUser() { UserName = "test", Email = "test@crams.com" }; await _userManager.CreateAsync(newUser, "P@ssw0rd!"); } } </code></pre> <p>I am trying create another class to change the password, with the same method but I am confused as to how to create a currentUser object to be passed into the RemovePassword and AddPassword calls. This is what I have so far :</p> <pre><code> public async Task ChangePassword() { if (await _userManager.FindByEmailAsync("test@theworld.com") != null) { _userManager.RemovePasswordAsync(currentUser); _userManager.AddPasswordAsync(currentUser, "newPassword"); } } </code></pre> <p><strong>Can someone please direct me in the right direction as I am new to this and don't know how to transfer the currentUser object, that contains the email that is being searched.</strong></p>
<c#><asp.net-core><asp.net-identity>
2016-10-11 23:06:22
LQ_CLOSE
39,988,590
Stop PyCharm If Error
<p>In PyCharm debugging mode, is there way to let it stop right after it hits an error but not exit and highlight the offending line? The analogous feature I have in mind is "dbstop if error" of Matlab.</p>
<debugging><pycharm><breakpoints>
2016-10-12 00:06:49
HQ
39,988,844
docker-compose up vs docker-compose up --build vs docker-compose build --no-cache
<p>I couldn't figure out what the difference between those.</p> <ul> <li><p><code>docker-compose up</code> </p></li> <li><p><code>docker-compose up --build</code></p></li> <li><p><code>docker-compose build --no-cache</code></p></li> </ul> <p>Is there any command for <code>up</code>without cache?</p>
<docker><docker-compose>
2016-10-12 00:43:01
HQ
39,988,848
Trying to do a bulk upsert with Mongoose. What's the cleanest way to do this?
<p>I have a collection that holds documents that contains three fields: first_name, last_name, and age. I'm trying to figure out what query in Mongoose I can use to do a bulk upsert. My app is occasionally receiving a new array of objects with those same three fields. I want the query to check if the first AND last name already exist within a document, and if they do - update the age if it's different. Otherwise, if the first and last name don't exist, insert a new document.</p> <p>Currently, I'm only doing the import - and haven't yet built out the logic for this upsert piece. </p> <pre><code>app.post('/users/import', function(req, res) { let data = req.body; let dataArray = []; data.forEach(datum =&gt; { dataArray.push({ first: datum.first, last: datum.last, age: datum.age }) }) User.insertMany(dataArray, answer =&gt; { console.log(`Data Inserted:`,answer) }) </code></pre> <p>`</p> <p>And my User model looks like this:</p> <pre><code>const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ first: String, last: String, age: Number, created_at: { type: Date, default: Date.now } }); var User = mongoose.model('User', userSchema); module.exports = User; </code></pre>
<node.js><mongodb><mongoose>
2016-10-12 00:43:12
HQ
39,989,027
In TypeScript, why is it not an error to access (get) property that only has a setter?
<p>Why does this compile? (TS v2.0.3)</p> <pre><code>class SetterOnly { set prop(v) { let x = this.prop; } } </code></pre> <p>I would expect <code>this.prop</code> to generate a compile-time error ...</p>
<typescript>
2016-10-12 01:09:47
HQ
39,989,550
Trouble writing If-Statements
//main code\\ <html> <head> <script language="javascript" type="text/javascript" src="codeChallenge3.js"></script> </head> <body> <head>CONDITIONALS CODE </head> <p></p> <hr/> <h2>Task #1</h2> <script> //#2 var phoneNum = "555-5555"; document.write("Check the following phone number: ", phoneNum, " = ", validPhone(phoneNum)); </script> </body> </html> //function\\ function validPhone(phoneNum) var if () { return "True" } else() { return "False"; } I have trouble writing if statements so can someone help me by giving me hints to determine if a number is a valid home phone number (without area code)
<javascript>
2016-10-12 02:25:28
LQ_EDIT
39,992,372
sql matching strings with given all letters anyware
i want to match the words with given all characters and characters can be anywhere in the word but all of given characters should be include in the matching string Ex : 1 BMW 4 LAND ROVER 6 VOLVO 9 IVECO 14 VOLKSWAGEN 20 CHEVROLET given word is "VW" then result should be 14 VOLKSWAGEN
<sql><sql-server>
2016-10-12 07:00:52
LQ_EDIT
39,992,477
Integrating Facebook Web SDK with ReactJS Component State
<p>I'm getting started with ReactJS, NodeJS, Webpack, and the Facebook SDK for user authentication. All these technologies and their associated software engineering principles/best practices are relatively new to me (even JavaScript is pretty new to me).</p> <p>I've followed the tutorial here <a href="https://developers.facebook.com/docs/facebook-login/web" rel="noreferrer">https://developers.facebook.com/docs/facebook-login/web</a> and I've got Facebook authentication working great! But the way this tutorial content is structured, it looks to me like the SDK is designed only to expect the FB status response handlers to be included in the raw page HTML just inside the <code>&lt;body&gt;</code> tag. The following in particular references this:</p> <pre><code> // Load the SDK asynchronously (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </code></pre> <p>This strategy strikes me as imperfect and hard to integrate with React components. Is there a way to relocate the Facebook login/authentication code and Facebook status update handlers from the HTML, for example, into scripts being bundled with React code via Webpack? Is it possible? Part of the reason for my question is that if I understand correctly, for my Facebook status update handler to be able to update my React components' state, that handler needs to be part of a component to have access to the relevant React component <code>this.setState(...)</code> function.</p> <p>Am I even thinking about this correctly?</p>
<javascript><facebook><reactjs><webpack>
2016-10-12 07:07:03
HQ
39,992,770
str_replace php a string
<p>I have a string</p> <blockquote> <p>X_HD003_0</p> </blockquote> <p>I have a function PHP</p> <pre><code>str_replace() </code></pre> <p>Ugh......</p> <p>My result that i want:</p> <blockquote> <p>HD003</p> </blockquote> <p>^^, some funny from PPAP song, but some string is: X_HD01_1, X_HD0003_2, X_HD12/12/2016/1_01, this string create by: </p> <blockquote> <p>"X_" + String + "_Number"</p> </blockquote> <p>I want to replace X_ and _Number with str_replace(). Hope everyone can help me! Thank you so much! </p>
<php><str-replace>
2016-10-12 07:24:47
LQ_CLOSE
39,992,841
When you create an adapter, the markup is displayed incorrectly
**Code Java** listView.setAdapter(new BaseAdapter() { @Override public int getCount() { return 10; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView=getActivity().getLayoutInflater().inflate(R.layout.fragment_my_auto_adap,parent,false); return convertView; } }); **Code XML** <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.CardView android:layout_height="100dp" tools:layout_constraintTop_creator="1" tools:layout_constraintRight_creator="1" android:layout_marginStart="10dp" android:layout_marginEnd="10dp" app:layout_constraintRight_toRightOf="parent" android:layout_marginTop="10dp" tools:layout_constraintLeft_creator="1" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:id="@+id/cardView" android:layout_width="match_parent"> <android.support.constraint.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="64dp" android:layout_height="64dp" app:srcCompat="@drawable/car_item_r" android:id="@+id/imageView" android:adjustViewBounds="true" android:layout_marginStart="16dp" app:layout_constraintLeft_toLeftOf="parent" android:layout_marginLeft="16dp" android:layout_marginTop="16dp" app:layout_constraintTop_toTopOf="parent"/> <TextView android:layout_height="0dp" android:id="@+id/line" android:layout_marginStart="8dp" app:layout_constraintLeft_toRightOf="@+id/imageView" android:layout_marginLeft="8dp" app:layout_constraintTop_toTopOf="@+id/imageView" app:layout_constraintBottom_toBottomOf="@+id/imageView" android:background="#F38C8D" android:layout_width="1dp"/> <TextView android:text="Nisan Teana" android:layout_width="wrap_content" android:layout_height="17dp" android:id="@+id/textViewName" app:layout_constraintBottom_toBottomOf="@+id/imageView" app:layout_constraintTop_toTopOf="@+id/imageView" app:layout_constraintLeft_toRightOf="@+id/line" android:layout_marginStart="5dp" android:layout_marginLeft="5dp"/> <ImageView android:layout_height="wrap_content" app:srcCompat="@drawable/chat" android:id="@+id/imageView3" android:adjustViewBounds="true" tools:layout_editor_absoluteY="16dp" android:layout_marginEnd="32dp" app:layout_constraintRight_toRightOf="parent" android:layout_marginRight="32dp" android:layout_width="48dp"/> <TextView android:text="Лайкнуть кампанию" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView2" android:textSize="8sp" app:layout_constraintTop_toBottomOf="@+id/imageView3" app:layout_constraintBottom_toBottomOf="parent" android:layout_marginBottom="16dp" app:layout_constraintRight_toRightOf="@+id/imageView3" app:layout_constraintLeft_toLeftOf="@+id/imageView3"/> </android.support.constraint.ConstraintLayout> </android.support.v7.widget.CardView> </LinearLayout> **Result ((** [enter image description here][1] [1]: https://i.stack.imgur.com/cfd3H.png Marking is not displayed properly. What can I do to work properly. If you use RelativeLayout everything works. What is wrong I do not understand Marking is not displayed properly. What can I do to work properly. If you use RelativeLayout everything works. What is wrong I do not understand
<android><android-studio>
2016-10-12 07:28:33
LQ_EDIT
39,993,809
Simple way to use looping in java
<p>This is example for my looping code:</p> <pre><code>int outsideLoop = 0; for (int i = 1; i &lt; 11; i++) { outsideLoop += i; System.out.println("Count is: " + i); } System.out.println("Outside loop is: " + outsideLoop); </code></pre> <p>My friend is said that using <code>int i = 1; i &lt; 11; i++</code> is a primitive ways. is there any quick way to looping than to use this code?</p>
<java><for-loop>
2016-10-12 08:22:26
LQ_CLOSE
39,993,867
Android Studio Logcat colors best practice
<p>It is really hard to follow up Android logcat output all in a same color. is there any best practice for changing different logs color?</p>
<android><android-studio><intellij-idea><ide><logcat>
2016-10-12 08:25:39
HQ
39,993,973
asp net mvc dropdownlist get selected item in controller
i wante to get selected item from dropdownlist in controller Here is my code @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.DropDownListFor(model => model.td_company_name, ViewBag.Listcompany as IEnumerable<SelectListItem>, new { @class = "form-control" }) }
<asp.net-mvc>
2016-10-12 08:31:28
LQ_EDIT
39,994,587
Spark train test split
<p>I am curious if there is something similar to sklearn's <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html" rel="noreferrer">http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html</a> for apache-spark in the latest 2.0.1 release.</p> <p>So far I could only find <a href="https://spark.apache.org/docs/latest/mllib-statistics.html#stratified-sampling" rel="noreferrer">https://spark.apache.org/docs/latest/mllib-statistics.html#stratified-sampling</a> which does not seem to be a great fit for splitting heavily imbalanced dataset into train /test samples.</p>
<apache-spark><apache-spark-mllib><train-test-split>
2016-10-12 09:02:38
HQ