title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Russian characters encoding in SQL Server
<p>I want to encode Russian Character correctly in SQL Server. I am using <code>fnEncodeURL</code> method of SQL Server.</p> <p>For example:</p> <pre><code>select dbo.fnEncodeURL('пвы Открытые панели для совместной работы .') </code></pre> <p>which shows me </p> <pre><code>%3F%3F%3F%20%3F%3F%3F%3F%3F%3F%3F%3F%20%3F%3F%3F%3F%3F%3F%20%3F%3F%3F%20%3F%3F%3F%3F%3F%3F%3F%3F%3F%3F%20%3F%3F%3F%3F%3F%3F%20. </code></pre> <p><code>%3F</code> means <code>?</code> so if we will decode it it would be "??? ???????? ?????? ??? ?????????? ?????? ." </p> <p>which is incorrect.</p> <p>So please let me know the correct way so that I could get russian characters in result instead of question marks.</p> <p>Thanks in advance</p>
1
CopyAllFilesToSingleFolderForPackageDependsOn and Web Deploy
<p>I am using Web Deploy feature of Visual Studio 2015 to deploy my Type Script SPA project to my staging server.</p> <p>I want the deployment process to copy (and rename) some deployment specific files from /Deployment folder of my project to other specific locations of the project.</p> <p>One such example is:</p> <p>[project_root]/Deployment/index.remote.debug.html ---> [project_root]/index.html</p> <p>I managed to achieve this using the following section in my publish profile (.pubxml):</p> <pre class="lang-xml prettyprint-override"><code>&lt;Target Name="index_html"&gt; &lt;ItemGroup&gt; &lt;_CustomFiles Include="Deployment/index.remote.debug.html" /&gt; &lt;FilesForPackagingFromProject Include="%(_CustomFiles.Identity)"&gt; &lt;DestinationRelativePath&gt;index.html&lt;/DestinationRelativePath&gt; &lt;/FilesForPackagingFromProject&gt; &lt;/ItemGroup&gt; &lt;/Target&gt; &lt;Target Name="extractor_config"&gt; &lt;ItemGroup&gt; &lt;_CustomFiles Include="Deployment/extractor.config.remote.debug.js" /&gt; &lt;FilesForPackagingFromProject Include="%(_CustomFiles.Identity)"&gt; &lt;DestinationRelativePath&gt;extractor.config.js&lt;/DestinationRelativePath&gt; &lt;/FilesForPackagingFromProject&gt; &lt;/ItemGroup&gt; &lt;/Target&gt; &lt;PropertyGroup&gt; &lt;CopyAllFilesToSingleFolderForPackageDependsOn&gt; index_html; $(CopyAllFilesToSingleFolderForPackageDependsOn); &lt;/CopyAllFilesToSingleFolderForPackageDependsOn&gt; &lt;CopyAllFilesToSingleFolderForPackageDependsOn&gt; extractor_config; $(CopyAllFilesToSingleFolderForPackageDependsOn); &lt;/CopyAllFilesToSingleFolderForPackageDependsOn&gt; &lt;/PropertyGroup&gt; </code></pre> <p>But this works only when publishing to file system with 'File System' option. When publishing to my staging server using 'Web Deploy' option, I see no effect. The application is correctly deployed but respective files don't get copied/renamed.</p> <p>There is also no error message in Visual Studio output related to such a web deploy.</p> <p>It makes no difference if I deploy as non-admin or admin.</p> <p>Does anybody know, where is the problem?</p> <p>With respect to MSBuild I am a total layman and this is my first encounter. I've put this together only with help of other people's online experience.</p>
1
Read data from text format into Python Pandas dataframe
<p>I am running Python 2.7 on Windows.</p> <p>I have a large text file (2 GB) that refers to 500K+ emails. The file has no explicit file type and is in the format:</p> <pre><code>email_message#: 1 email_message_sent: 10/10/1991 02:31:01 From: [email protected]| Tom Foo |abc company| To: [email protected]| Alex Dee |abc company| To: [email protected]| Ben For |xyz company| email_message#: 2 email_message_sent: 10/12/1991 01:28:12 From: [email protected]| Tim Tee |abc company| To: [email protected]| Tom Foo |abc company| To: [email protected]| Alex Dee |abc company| To: [email protected]| Ben For|xyz company| email_message#: 3 email_message_sent: 10/13/1991 12:01:16 From: [email protected]| Ben For |xyz company| To: [email protected]| Tom Foo |abc company| To: [email protected]| Tatiana Xocarsky |numbers firm | ... </code></pre> <p>As you can see, each email has the following data associated with it:</p> <p>1) the time it was sent</p> <p>2) the email address who sent it</p> <p>3) the name of the person who sent it</p> <p>4) the company that person works for </p> <p>5) every email address that received the email</p> <p>6) the name of every person who received the email</p> <p>7) the company of every person who received the email</p> <p>In the text files there are 500K+ emails, and emails can have up to 16K recipients. There is no pattern in the emails in how they refer to names of people or the company they work at. </p> <p>I would like to take this large file and manipulate it in <code>python</code> so that it ends up as a <code>Pandas</code> <code>Dataframe</code>. I would like the <code>pandas</code> <code>dataframe</code> in the format like the screenshot from <code>excel</code> below:</p> <p><a href="https://i.stack.imgur.com/C1a69.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C1a69.png" alt="Sample Data Structure"></a></p> <p><strong>EDIT</strong></p> <p>My plan to solve this is to write a "parser" that takes this text file and reads in each line, assigning the text in each line to a particular columns of a <code>pandas</code> <code>dataframe</code>.</p> <p>I plan to write something like the below. Can someone confirm that this is the correct way to go about executing this? I want to make sure I am not missing a built-in <code>pandas</code> function or function from a different <code>module</code>. </p> <pre><code>#connect to object data = open('.../Emails', 'r') #build empty dataframe import pandas as pd df = pd.DataFrame() #function to read lines of the object and put pieces of text into the # correct column of the dataframe for line in data: n = data.readline() if n.startswith("email_message#:"): #put a slice of the text into a dataframe elif n.startswith("email_message_sent:"): #put a slice of the text into a dataframe elif n.startswith("From:"): #put slices of the text into a dataframe elif n.startswith("To:"): #put slices of the text into a dataframe </code></pre>
1
sbt: cross-publish from build.sbt
<p>Currently, I'm using SBT scripted plugin for testing. To publish a plugin into the local repository, following code snippet in build.sbt is used:</p> <pre><code>crossScalaVersions := Seq(scalaVersion.value,"2.11.7") scriptedDependencies := { val local = publishLocal.value } </code></pre> <p>This way the artefact gets published into the local repository, but only for the version <code>scalaVersion.value</code>. I would like to have it cross-published for both scala versions. How can I do that?</p>
1
Related products by variant using metafields for Shopify Liquid
<p>I'm trying to build on caroline's solution for related products with metafields to build related product variants. I.e when you click on the white color variant for a desk, you will see the white variant of a chair as a related product. (As opposed to linking the desk product to the chair product regardless of variant.) Caroline's solution is here: <a href="https://gist.github.com/carolineschnapp/1003334" rel="nofollow">https://gist.github.com/carolineschnapp/1003334</a> and below is my code. Right now it's putting the same product twice on page load, and nothing happens when a different vairant is selected. The way I am formatting the metafield value for each variant is by putting "related-product-handle-1, variant-id-1, related-product-handle-2,variant-id-2, related-product-handle-3, variant-id-3" instead of just the product handles.</p> <pre><code>{% assign image_size = 'compact' %} {% assign heading = 'Related Products' %} {% if product.selected_or_first_available_variant.metafields.recommendations.productHandles %} &lt;h3&gt;{{ heading }}&lt;/h3&gt; &lt;ul class="related-products"&gt;&lt;/ul&gt; {% endif %} &lt;script&gt;!window.jQuery &amp;&amp; document.write('&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;\/script&gt;')&lt;/script&gt; {{ 'api.jquery.js' | shopify_asset_url | script_tag }} &lt;script type="text/javascript" charset="utf-8"&gt; $(document).ready(function(){ setTimeout(function() { var dd = $('.single-option-selector#product-select-option-0'); var vId = location.search.substring(9); switchRelated(vId); dd.on('change', function() { $('ul.related-products').empty(); var vId = location.search.substring(9); switchRelated(vId); }); function switchRelated(vId) { var list = $('ul.related-products'); var vIdd = parseInt(vId); {% for variant in product.variants %} {% if variantId == vIdd %} {% if variant.metafields.recommendations.productHandles %} recommendations = jQuery.trim({{ variant.metafields.recommendations.productHandles | json }}).split(/[\s,;]+/); for (var i=0; i &lt; (recommendations.length); i+=2 ) { var j = (i + 1); if (recommendations.length &amp;&amp; recommendations[i] &amp;&amp; recommendations[j] !== '') { jQuery.getJSON('/products/' + recommendations[i] + '.js', function(product) { product.variants.forEach(function(variant) { if (variant.id == parseInt(recommendations[j])) { list.append('&lt;li&gt;&lt;div class="image"&gt;&lt;a href="' + product.url + '?variant=' + recommendations[j] +'"&gt;&lt;img src="' + variant.featured_image.src + '" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;h4&gt;&lt;a href="' + product.url + '?variant=' + recommendations[j] + '"&gt;' + product.title + '&lt;/a&gt;&lt;/h4&gt;&lt;/li&gt;'); } }); }); } } {% endif %} {% endif %} {% endfor %} } }, 1); }); &lt;/script&gt; </code></pre> <p>Answer edited: The first was extremely helpful once I made some corrections to syntax errors and a couple of short additions. Here is my edited version of the answer for anyone who may need it: </p> <p>Product.liquid:</p> <pre><code> {% for variant in product.variants %} {% capture metafield_data %}{% endcapture %} {% assign related_products = variant.metafields.recommendations.productHandles | split: '|' %} {% for related_product in related_products %} {% assign metafield_items = related_product | split: ',' %} {% assign r_p = metafield_items[0] %} {% assign r_v = metafield_items[1] | plus: 0 %} {% assign r_n = all_products[r_p].title %} {% for related_variant in all_products[r_p].variants %} {% if related_variant.id == r_v %} {% assign r_i = related_variant.image.src | img_url: 'small' %} {% endif %} {% endfor %} {% capture metafield_data %}{{metafield_data}}{{ r_p }},{{ r_v }},{{ r_i }},{{ r_n }}{% unless forloop.last %}|{% endunless %}{% endcapture %} {% endfor %} &lt;option id="{{ variant.id }}" data-metafield="{{ metafield_data }}" {% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} value="{{ variant.id }}"&gt;{{ variant.title }} - {{ variant.price | money }}- {{ related_products.size }}&lt;/option&gt; {% endfor %} </code></pre> <p>And related-variants javascript snippet:</p> <pre><code>$(document).ready(function(){ setTimeout(function() { var dd = $('.single-option-selector#product-select-option-0'); if(location.search.substring(9) != ''){ var vId = location.search.substring(9); } else { var vId = {{ product.selected_or_first_available_variant.id }}; } switchRelated(vId); $('#product-select option').each(function(index, element){ $(".single-option-selector#product-select-option-0 option:eq(" + index + ")").attr('id', element.id); $('.single-option-selector#product-select-option-0 option:eq(' + index + ')').attr('data-metafield', $(element).attr("data-metafield")); $('#product-select option:eq(' + index + ')').attr('id', ''); }); dd.on('change', function() { var list = $('ul.related-products'); $(list).children().remove(); $(list).empty(); if(location.search.substring(9) != ''){ var vId = location.search.substring(9); } else { var vId = {{ product.selected_or_first_available_variant.id }}; } switchRelated(vId); }); function switchRelated(vId) { var list = $('ul.related-products'); $(list).children().remove(); $(list).empty(); var vIdd = parseInt(vId); console.log(vIdd) var variant_matches = $('#' + vId).attr('data-metafield').split('|'); for (var i=0; i &lt; variant_matches.length; i++) { var items = variant_matches[i].split(','); list.append('&lt;li&gt;&lt;div class="image"&gt;&lt;a href="/products/'+items[0]+'/?variant='+items[1]+'"&gt;&lt;img src="'+items[2]+'" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;h4&gt;&lt;a href="/products/' + items[0] + '?variant=' + items[2] + '"&gt;' + items[3].replace('_','') + '&lt;/a&gt;&lt;/h4&gt;&lt;/li&gt;'); } } }, 1); }); </code></pre> <p>The only thing I'm nervous about is the fact that I am copying over the data from the 'product-select' dropdown over to the 'single-option-selector' dropdown. I am doing this because there is no template for rendering the single-option-selector, it seems to be getting added through javascript. If anyone has any insight into manipulating the single-option-selector in liquid, please let me know. Thank you!!</p>
1
jQuery input number convert Persian/Arabic numbers to English numbers
<p>I have a input field of type <code>number</code>. I want to accept Persian/Arabic numbers as well in this field. I wanted to convert these numbers to English using jQuery, but it seems I can't retrieve these values.</p> <pre><code>jQuery('input[type=&quot;number&quot;]').on('input', function() { console.log(jQuery(this).val()); }); </code></pre> <p>For non-English numbers <code>val()</code> is empty string. Is there any way to get the value of a number input field, if the value is not a English number?</p> <p>UPDATE:</p> <pre><code>Persian numbers: ۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹ English numbers: 0 1 2 3 4 5 6 7 8 9 </code></pre> <p>UPDATE2:</p> <p>Looks like Firefox returns the correct <code>val</code> but Chrome returns empty string. So my question is applicable on Google Chrome.</p>
1
Get image dimensions (before uploading)
<p>in a project I work on I need to check image dimensions (width and height) before uploading them. </p> <p>I need 3 check points </p> <p>1-> if dimensions are less than 600 X 600 pixels don't accept the uploading </p> <p>1-> if dimensions are more than 600 x 600 pixels and less then 1200 X 1200 pixels accept with the warning the the quality is not good and </p> <p>3-> if dimensions are hier than 1200 X 1200 pixels, accept...</p> <p>I have the code you see.. but there are two issues 1 when an image is 550X700 return acceptable with warning this must be not acceptable... and the second issue when I try to change the image it keeps also the old values.. please check the code in: <a href="https://jsfiddle.net/timoleon/jukxjvdm/10/" rel="nofollow">jsfiddle</a></p> <pre><code>$("#file").change(function() { var file, img; if ((file = this.files[0])) { img = new Image(); /* img.onload = function() { alert(this.width + " " + this.height); }; img.onerror = function() { alert( "not a valid file: " + file.type); }; img.src = _URL.createObjectURL(file); */ } if ((file = this.files[0])) { img = new Image(); img.onload = function() { //green if (this.width &gt; 1200 &amp;&amp; this.height &gt; 1200){ $('.text1').css('visibility', 'visible'); $('.text1').append(this.width + "X &amp; " + this.height+ "Y"); $(".grey").addClass("green"); $('.textgreen').css('visibility', 'visible') } //red else if ((this.width &lt; 600) &amp;&amp; (this.height &lt; 600)){ $('.text1').css('visibility', 'visible'); $('.text1').append(this.width + "X &amp; " + this.height+ "Y"); $(".btn.btn-success.btn-xs").remove(); $(".grey").addClass("red"); $('.textred').css('visibility', 'visible'); } //yellow else if (($(this.width &gt; 600) &amp;&amp; $(this.width &lt;1200)) &amp;&amp; ($(this.height &gt; 600) &amp;&amp; $(this.height &lt;1200))){ $('.text1').css('visibility', 'visible'); $('.text1').append(this.width + "X &amp; " + this.height+ "Y"); $(".grey").addClass("yellow"); $('.textyellow').css('visibility', 'visible') } else { return; } }; img.src = _URL.createObjectURL(file); } });` </code></pre>
1
Blocking operation in Qt Quick
<p>I want to perform a long task when a button is clicked. I want this task to block the UI, because the application cannot function until the task is done. However, I want to indicate to the user that something is happening, so I have a <code>BusyIndicator</code> (that runs on the render thread) and is set to display before the operation begins. However, it never renders. Why?</p> <p><strong>main.cpp:</strong></p> <pre><code>#include &lt;QGuiApplication&gt; #include &lt;QQmlApplicationEngine&gt; #include &lt;QQmlContext&gt; #include &lt;QDateTime&gt; #include &lt;QDebug&gt; class Task : public QObject { Q_OBJECT Q_PROPERTY(bool running READ running NOTIFY runningChanged) public: Task() : mRunning(false) {} Q_INVOKABLE void run() { qDebug() &lt;&lt; "setting running property to true"; mRunning = true; emit runningChanged(); // Try to ensure that the scene graph has time to begin the busy indicator // animation on the render thread. Q_ASSERT(QMetaObject::invokeMethod(this, "doRun", Qt::QueuedConnection)); } bool running() const { return mRunning; } signals: void runningChanged(); private: Q_INVOKABLE void doRun() { qDebug() &lt;&lt; "beginning long, blocking operation"; QDateTime start = QDateTime::currentDateTime(); while (start.secsTo(QDateTime::currentDateTime()) &lt; 2) { // Wait... } qDebug() &lt;&lt; "finished long, blocking operation"; qDebug() &lt;&lt; "setting running property to false"; mRunning = false; emit runningChanged(); } bool mRunning; }; int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; Task task; engine.rootContext()-&gt;setContextProperty("task", &amp;task); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); } #include "main.moc" </code></pre> <p><strong>main.qml:</strong></p> <pre><code>import QtQuick 2.6 import QtQuick.Window 2.2 import Qt.labs.controls 1.0 Window { width: 600 height: 400 visible: true Shortcut { sequence: "Ctrl+Q" onActivated: Qt.quit() } Column { anchors.centerIn: parent spacing: 20 Button { text: task.running ? "Running task" : "Run task" onClicked: task.run() } BusyIndicator { anchors.horizontalCenter: parent.horizontalCenter running: task.running onRunningChanged: print("BusyIndicator running =", running) } } } </code></pre> <p>The debugging output looks correct in terms of the order of events:</p> <pre><code>setting running property to true qml: BusyIndicator running = true beginning long, blocking operation finished long, blocking operation setting running property to false qml: BusyIndicator running = false </code></pre>
1
Python 2.7: 'ascii' codec can't encode character u'\xe9' error while writing in file
<p>I know this question have been asked various time but somehow I am not getting results.</p> <p>I am fetching data from web which contains a string <strong>Elzéar</strong>. While going to read in CSV file it gives error which mentioned in question title.</p> <p>While producing data I did following:</p> <pre><code>address = str(address).strip() address = address.encode('utf8') return name+','+address+','+city+','+state+','+phone+','+fax+','+pumps+','+parking+','+general+','+entertainment+','+fuel+','+resturants+','+services+','+technology+','+fuel_cards+','+credit_cards+','+permits+','+money_services+','+security+','+medical+','+longit+','+latit </code></pre> <p>and writing it as:</p> <pre><code>with open('records.csv', 'a') as csv_file: print(type(data)) #prints &lt;unicode&gt; data = data.encode('utf8') csv_file.write(id+','+data+'\n') status = 'OK' the_file.write(ts+'\t'+url+'\t'+status+'\n') </code></pre> <p>Generates error as:</p> <blockquote> <p>'ascii' codec can't encode character u'\xe9' in position 55: ordinal not in range(128)</p> </blockquote>
1
Device compabilities issue in iOS
<p>We uploaded an app where in the first version we added to device capabilities “telephony” to restrict only iPhone devices in the info plist. In the second version we forgot to add “telephony” and we submitted to the App store. Third version we are planning to upload with device capabilities as “telephony” but while submitting to the App Store it shows the warning:</p> <blockquote> <p>This bundle is invalid. The key <code>UIRequiredDeviceCapabilities</code> in the Info.plist may not contain values that would prevent this application from running on devices that were supported by previous versions.</p> </blockquote> <p>How can we resolve this issue, if we require the device capability “telephony” for application lifetime, but due to my mistake on the second version we forgot to add the required device capabilities? What is the solution for it? </p> <p>Thanks in advance.</p>
1
If date is todays date display "today", or "yesterday"
<p>In my Shopify blog I can display the date of the posted article by the following code:</p> <pre><code>{{ article.created_at | date: "%A, %-d. %B" }} </code></pre> <p>It displays like this: Friday, 22. January. <a href="https://docs.shopify.com/themes/liquid-documentation/filters/additional-filters#date" rel="nofollow">See date desc from Shopify here.</a> </p> <p>Is it possible to make a script that checks if the date is today, then display the text "today" insted of the shopify date script? And "yesterday"?</p>
1
PUT request made with Python requests module has no data
<p>I am developing an Python REST api and for server side I'm using Django with django-rest-framework. I managed to successfully test my api with AdvancedRestClient in chrome, but I can't get it working with python requests.</p> <p>My ARC request looks like this: <a href="https://i.stack.imgur.com/am85h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/am85h.png" alt="enter image description here"></a></p> <p>And for my test Python request I wrote the following code:</p> <pre><code>import requests import json payload = {"TimeStamp": "2016-02-07T13:38:16Z", "DateInserted": "2016-02-07T13:38:18Z", "Value": 17.145, "Sensor": 1} url = "http://127.0.0.1:8000/api/Readings" headers = {"Content-Type": "application/json", "Authorization": "966271f8-94a3-4232-95f7-953f3b7989f3"} r = requests.put(url, data=json.dumps(payload), headers=headers) </code></pre> <p>I tried many different things as using <code>json=</code> instead of <code>data=</code> but my request always seem to have no data content when they arrive to my server side. I searched the web but couldn't find any viable examples of using POST with requests so I'm hoping someone has some first-hand experience in their sleeve to share with me.</p> <p><strong>Update:</strong> The following code now works with django-rest-framework.</p> <pre><code>payload = {"TimeStamp": "2016-02-07T13:38:16Z", "DateInserted": "2016-02-07T13:38:18Z", "Value": 12.123, "Sensor": 1} url = "http://127.0.0.1:8000/api/Readings/" headers = {"Content-Type": "application/json", "Authorization": "966271f8-94a3-4232-95f7-953f3b7989f3"} r = requests.put(url, data=json.dumps(payload), headers=headers) </code></pre>
1
Can't close Kivy app or avoid fullscreen
<p>I am new to Kivy and trying to find my way around. Whenever I create and run an app, it displays as a full-screen that I am unable to close without disconnecting the power (which I know is not ideal, but that's exactly why I am desperate to fix it!). </p> <p>Shortcuts that are suggested to work (Esc, Ctrl+C, Ctrl+Alt+break) don't. I have attempted changing the config settings at the beginning of the script as follows:</p> <pre><code>from kivy.config import Config Config.set('graphics', 'fullscreen', 0) Config.write() </code></pre> <p>I've also tried variations on the theme - 0 as a string, 1 as both an integer and string (and trying to provide a width and height for the window) but with no perceivable change. Even if this did work, it would not be the ideal fix given that I would probably want to be able to run things full-screen in the end!</p> <p>Given that each time I've tried changing something I've had to restart the pi by disconnecting the power, playing around has been quite time-consuming! Does anybody have any suggestions about how I should proceed?</p> <p>I'm currently using:<br> Raspberry Pi 2 Model B connected to normal TV (many people having problems have been using a touchscreen, but that is not true for me)<br> Raspbian Jessie, Linux 8<br> Python 2.7<br> I'm afraid I don't know how to check details about the Kivy module I have downloaded.</p> <p>I'm very new to this, so apologies if I don't manage to provide all of the relevant information.</p> <p>Full code I am trying to run (excluding the above config changes): </p> <pre><code>import kivy kivy.require('1.9.2') #may be part of the problem - not 100% sure this is correct from kivy.app import App from kivy.uix.label import Label class MyApp(App): def build(self): return Label(text='Hello world') if __name__ == '__main__': MyApp().run() </code></pre>
1
How to get files from SFTP using TSQL or SQL Server Agent?
<p>I need to get files from SFTP and stored them on server. Is there any way I can do that using TSQL or SQL Server Agent? I do not want to use Third party tools or SSIS or PowerShell Script or WinSCP.</p>
1
Chrome Custom Tabs, deep linking with Oauth2
<p>Hi I'm using Google Chrome Custom Tabs for a project and I have a few issues with deep linking. </p> <p>I need to authenticate the users through a oauth2 process using chrome custom tabs. The user is sent to the authentication form then types is login/password. Then it is redirected to a url like <code>myapp://something</code>. An intent is then triggered and the user is sent back to the app.</p> <p>The process is working well at first launch when the user is logging in through the authentication form. However, if I try to get another authentication code, I get an <code>ERR_UNKNOWN_URL_SCHEME</code> error and the app stays on the custom tabs.</p> <p>Here are the three cases I tested : </p> <p><strong>1st case : Chrome custom tab, forcing the user to use the authentication form</strong></p> <p>-The user is sent to the authentication form</p> <p>-A 302 redirect is done to a custom url</p> <p>-The user is switched to the app</p> <p><strong>2nd case : Chrome custom tab (using the session cookie)</strong></p> <p>-The user is sent to the authentication website</p> <p>-A 302 redirect is done to a custom url</p> <p>-An <code>ERR_UNKNOWN_URL_SCHEME</code> occurs</p> <p><strong>3rd case : Chrome browser (using the authentication form or the session cookie)</strong></p> <p>-The user is sent to the authentication website</p> <p>-A 302 redirect is done to a custom url</p> <p>-The user is switched to the app</p> <p>The full process is working with the chrome browser but I have to make it work with Custom Tabs. Is this behaviour normal ? I mean i read that a user interaction might be needed to use deep links but everything is working well with the chrome brower. Without this deep linking process, how is it possible to do SSO with custom tabs ?</p> <p>PS : Here's a video to explain my issue and the tests done <a href="https://www.youtube.com/watch?v=Y-4uLpUv1lA" rel="nofollow">https://www.youtube.com/watch?v=Y-4uLpUv1lA</a></p>
1
Variable two dimensional array printing "subscript of pointer to incomplete type" when accessed
<p>I am declaring a two dimensional array as such:</p> <pre><code>char arr[10][10]; arr[0][0] = 'X'; </code></pre> <p>Now I print in debugger;</p> <pre><code>(lldb) po arr[0][0] 'X' </code></pre> <p>Awesome!! No problem.</p> <p>Now I am declaring a two dimensional array as such:</p> <pre><code>int col = 10; int row = 10; char arr[row][col]; arr[0][0] = 'X'; </code></pre> <p>Now I print in debugger;</p> <pre><code>(lldb) po arr[0][0] error: subscript of pointer to incomplete type 'char []' error: 1 errors parsing expression </code></pre> <p>Why??</p>
1
Python montage a plot on OpenCV image and record as video
<p>Assume that you have a temperature data with sampling rate 512. I want to record this data by synchronized with the camera images. The resulting record going to be just a video file. </p> <p>I can plot this data with matplotlib and pyqtgraph. </p> <p>I did it with matplotlib but video sampling rate is decreasing. Here is the code with random incoming data.</p> <pre><code>import cv2 import numpy as np import matplotlib.pyplot as plt cap = cv2.VideoCapture(0) # video source: webcam fourcc = cv2.cv.CV_FOURCC(*'XVID') # record format xvid out = cv2.VideoWriter('output.avi',fourcc, 1, (800,597)) # output video : output.avi t = np.arange(0, 512, 1)# sample time axis from 1 to 512 while(cap.isOpened()): # record loop ret, frame = cap.read()# get frame from webcam if ret==True: nse = np.random.randn(len(t))# generate random data squence plt.subplot(1, 2, 1)# subplot random data plt.plot(t, nse) plt.subplot(1, 2, 2)# subplot image plt.imshow(frame) # save matplotlib subplot as last.png plt.savefig("last.png") plt.clf() img=cv2.imread("last.png") # read last.png out.write(img) # record last.png image to output.avi cv2.imshow('frame',img) if cv2.waitKey(1) &amp; 0xFF == ord('q'): # exit with press q button in frame window break else: break cap.release() # relase webcam out.release() # save video cv2.destroyAllWindows() # close all windows </code></pre>
1
Does a detached std::thread need to be deleted after it terminates?
<p>I create a <code>new</code> std::thread object, and then <code>detach()</code> it. The thread runs for an arbitrary amount of time, and then terminates itself. Since I created the object with <code>new</code>, do I need to <code>delete</code> it at some point to free up its resources? Or does the thread effectively <code>delete</code> itself upon termination?</p> <p>If it does effectively <code>delete</code> itself, will something bad happen if I explicitly <code>delete</code> it after it has terminated?</p>
1
Is this one-hot encoding in TensorFlow fast? Or flawed for any reason?
<p>There are a few stack overflow questions about computing one-hot embeddings with TensorFlow, and here is the accepted solution:</p> <pre><code>num_labels = 10 sparse_labels = tf.reshape(label_batch, [-1, 1]) derived_size = tf.shape(label_batch)[0] indices = tf.reshape(tf.range(0, derived_size, 1), [-1, 1]) concated = tf.concat(1, [indices, sparse_labels]) outshape = tf.reshape(tf.concat(0, [derived_size, [num_labels]]), [-1]) labels = tf.sparse_to_dense(concated, outshape, 1.0, 0.0) </code></pre> <p>This is almost identical to the code in an official tutorial: <a href="https://www.tensorflow.org/versions/0.6.0/tutorials/mnist/tf/index.html" rel="nofollow">https://www.tensorflow.org/versions/0.6.0/tutorials/mnist/tf/index.html</a></p> <p>To me it seems that since <code>tf.nn.embedding_lookup</code> exists, it's probably more efficient. Here's a version that uses this, and it supports arbitrarily-shaped inputs:</p> <pre><code>def one_hot(inputs, num_classes): with tf.device('/cpu:0'): table = tf.constant(np.identity(num_classes, dtype=np.float32)) embeddings = tf.nn.embedding_lookup(table, inputs) return embeddings </code></pre> <p>Do you expect this implementation to be faster? And is it flawed for any other reason?</p>
1
Unity3d Raycast on mesh position
<p>I want to hit a mesh with a raycast and get the mouse/screen coordinates of where the hit occurred.</p> <pre><code>public class GetCoordinates: MonoBehaviour { private GameObject _objectToHit; private RaycastHit hit; private Collider coll; private Ray ray; private float hitDistance = 200f; void Start() { coll = GetComponent&lt;Collider&gt;(); _objectToHit = GameObject.Find("Street"); } void Update() { ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (coll.Raycast(ray, out hit, hitDistance)) { Debug.Log(hit.point); } } } </code></pre> <p>Also I am not sure where to add the script, to the object being hit or to the camera?</p>
1
Rails initialization checksum error
<p>I'm trying to initialize a new rails app on windows, and running <code>rails new &lt;appname&gt;</code> generates everything up to <code>vendor/assets/stylesheets/.keep</code>, but when <code>bundle install</code> is run, rails generates this error:</p> <pre><code>Checksum of /versions does not match the checksum provided by server! Something is wrong. </code></pre> <p>I'm not sure what's causing this, as I've done nothing to rails itself. Any help is appreciated.</p> <p>Edit: If it's an error caused by windows being finicky, I have the option of moving to Linux, but I'd like to know what's wrong first.</p>
1
How to play RTMP video streaming in ios app?
<p>HI I'm developing Broadcast App for that I'm using Videocore library now how can i play that streaming video in ios app i tried with the MpMoviePlayer but it won't support the rtmp stream. so is there any third party libraries available for RTMP supported Players please help me </p>
1
Error "Expected invocation on the mock once, but was 0 times" when unit testing with moq
<p>I have the following class I want to test:</p> <pre><code>public interface ISqlServiceByModule { DataSet GetPagedAggregateData(int clientId, int moduleId, int billTypeId, PagedTable result); } public class IncidentModuleService : IIncidentModuleService { private readonly ISqlServiceByModule sqlServiceByModule; public IncidentModuleService(ISqlServiceByModule sqlServiceByModule) { if (sqlServiceByModule == null) throw new ArgumentNullException("sqlServiceByModule"); // Inject the ISqlServiceByModule dependency into the constructor this.sqlServiceByModule = sqlServiceByModule; } public PagedTable GetData(int clientId, int moduleId, int billTypeId, Dictionary&lt;string, string&gt; queryStringParameters) { PagedTable result = new PagedTable(queryStringParameters); DataSet dataSet = this.sqlServiceByModule.GetPagedAggregateData(clientId, moduleId, billTypeId, result); // Map the DatSet to a PagedTable if (dataSet == null || dataSet.Tables.Count == 0) { result.SetPagesFromTotalItems(0); } else { result.SetPagesFromTotalItems(Convert.ToInt16(dataSet.Tables[1].Rows[0][0])); result.Listings = dataSet.Tables[0]; } return result; } } </code></pre> <p>Specifically, I want to test the GetData method. My unit test looks like this:</p> <pre><code>[TestClass] public class IncidentModuleServiceUnitTest { private DataSet incidentsData; [TestInitialize] public void SetUp() { this.incidentsData = new DataSet(); } [TestMethod] public void GetDataTestGetPagedAggregateDataIsCalled() { //-- Arrange int billTypeId = 1; int clientId = 1; int moduleId = 1; Dictionary&lt;string, string&gt; queryStringParameters = new Dictionary&lt;string,string&gt;(); PagedTable tempResult = new PagedTable(queryStringParameters); DataSet dataSet = new DataSet(); dataSet.Tables.Add(new DataTable()); var mockSqlService = new Mock&lt;ISqlServiceByModule&gt;(); mockSqlService.Setup(r =&gt; r.GetPagedAggregateData(clientId, moduleId, billTypeId, tempResult)).Returns(this.incidentsData); IncidentModuleService target = new IncidentModuleService(mockSqlService.Object); //-- Act var actual = target.GetData(clientId, moduleId, billTypeId, queryStringParameters); //-- Assert Assert.IsNull(actual.Listings); mockSqlService.Verify(r =&gt; r.GetPagedAggregateData(clientId, moduleId, billTypeId, tempResult), Times.Once); } } </code></pre> <p>The error I am getting happens on the last line:</p> <pre><code>mockSqlService.Verify(r =&gt; r.GetPagedAggregateData(clientId, moduleId, billTypeId, tempResult), Times.Once); </code></pre> <p>And the exact error message is this:</p> <blockquote> <p>{"\r\nExpected invocation on the mock once, but was 0 times: r => r.GetPagedAggregateData(.clientId, .moduleId, .billTypeId, .tempResult</p> <p>Configured setups:\r\nr => r.GetPagedAggregateData(.clientId, .moduleId, .billTypeId, .tempResult), Times.Never</p> <p>Performed invocations:\r\nISqlServiceByModule.GetPagedAggregateData(1, 1, 1, PagedTable)"}</p> </blockquote> <p>Any idea why this is happening? It looks to me like the method in question is being called, but Moq doesn't like the parameters for some reason, even though they are the exact same ones in all three invocations, as far as I can tell.</p>
1
Certificate signature validation failed
<p>My website is hosted on Amazon. It is built on the microsoft version of java 1.4.2_13. I noticed emails were not going out. I had not made any changes to the code. I found <a href="http://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/use-sha256.html" rel="nofollow">this</a> document on amazon's site and followed their directions to find out that our java environment did not pass the test. So, I imported the new ssl root certificate. I can verify that it is in the keystore, but I get the following error message when I run their shaTest and emails are still not being sent. Any help is appreciated. Thanks!</p> <pre><code>Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: Certificate signature validation failed at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.a(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(Unknown Source) at com.sun.net.ssl.internal.ssl.SunJSSE_az.a(Unknown Source) at com.sun.net.ssl.internal.ssl.SunJSSE_az.a(Unknown Source) at com.sun.net.ssl.internal.ssl.SunJSSE_ax.a(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.j(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.b(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source) at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect (Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.URLConnection.getContent(Unknown Source) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getContent(Unknown Source) at java.net.URL.getContent(Unknown Source) at ShaTest.main(ShaTest.java:11) Caused by: sun.security.validator.ValidatorException: Certificate signature validation failed at sun.security.validator.SimpleValidator.engineValidate(Unknown Source) at sun.security.validator.Validator.validate(Unknown Source) at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source) at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(Unknown Source) ... 14 more Caused by: java.security.NoSuchAlgorithmException: 1.2.840.113549.1.1.11 Signature not available at java.security.Security.getEngineClassName(Unknown Source) at java.security.Security.getEngineClassName(Unknown Source) at java.security.Security.getImpl(Unknown Source) at java.security.Signature.getInstance(Unknown Source) at sun.security.x509.X509CertImpl.verify(Unknown Source) at sun.security.x509.X509CertImpl.verify(Unknown Source) ... 18 more </code></pre>
1
Laravel 5 UnsupportedLocaleException in LaravelLocalization.php
<p>I use Laravel 5.1 and I would like to use the following package: <a href="https://github.com/mcamara/laravel-localization" rel="nofollow">https://github.com/mcamara/laravel-localization</a></p> <p>I added this code to my route.php file:</p> <pre><code>Route::group(['prefix' =&gt; LaravelLocalization::setLocale()], function() { /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/ Route::get('/', function() { return View::make('hello'); }); Route::get('test',function(){ return View::make('test'); }); }); </code></pre> <p>When calling the url: localhost/test I get the following exception: UnsupportedLocaleException in LaravelLocalization.php line 119: Laravel default locale is not in the supportedLocales array</p> <p>Any ideas why? Thank you</p>
1
Pass variable as parameter on a Stored Procedure
<p>I have a stored procedure with a SELECT statement and two parameters. I want to call this stored procedure from another one that has a variable declared, and use this variable as one of the parameters.</p> <p>When I try this: </p> <pre><code>EXEC [dbo].[Testo] @cd_order = 23, @cd_substep = 33 </code></pre> <p>It returns some rows as result, but when I try this:</p> <pre><code>set @temp_var1 = ( Select cd_substep FROM ....Where...) EXEC [dbo].[Testo] @cd_order = 23, @cd_substep = @temp_var1 </code></pre> <p>The result is empty.</p> <p>The procedure will populate a table variable:</p> <pre><code>INSERT INTO @Var1Table EXEC [dbo].[Testo] 23, @cd_substep </code></pre> <p>It's working only when I use a static value. How do I use a variable as a parameter?</p>
1
Jenkins xUnit test result report
<p>I have a Jenkins job to copy some test reports(XML) to local and convert them to JUnit reports via xUnit.</p> <p>The issue is that there are no failed or skipped tests, but I always get</p> <pre><code> [xUnit] [INFO] - Check 'Failed Tests' threshold. [xUnit] [INFO] - Check 'Skipped Tests' threshold. [xUnit] [INFO] - Setting the build status to FAILURE [xUnit] [INFO] - Stopping recording. Finished: FAILURE </code></pre> <p>What causes this?</p>
1
How to call a function inside a dictionary in python
<p>I am creating a python shell script that will allow the user to enter commands that output a string. But also some commands will call a function, like <strong>help</strong>, or <strong>exit</strong> I know python does not have a switch case so I am using a dictionary instead, as I do not want to use if and else statements </p> <p><strong>The problem:</strong></p> <p>The problem is I cannot use a function call inside the dictionary with the way I have it implemented as it expects to output a string, so when I enter <strong>help</strong> I get an error</p> <pre><code> #!/usr/bin/python x = 0 while x == 0: def helpCommand(): print "this will help you" switcher = { "url": " the url is: ... ", "email": " my email is: ...", "help": helpCommand, "exit": exit, } choice = raw_input("enter your command choice: ") def outputChoice(choice) return switcher.get(choice) print outputChoice(choice) </code></pre> <p>I tried to solve this problem by using function call instead, but now I get an error when trying to call a string</p> <pre><code> def outputChoice(choice) return switcher[choice]() </code></pre> <blockquote> <p>TypeError: 'str' object is not callable</p> </blockquote> <p>How to fix this problem ?</p>
1
CMake dependency graph for custom targets
<p>Is the <code>--graphviz</code> option of CMake supposed to get the dependency on custom targets?</p> <p>Sample <code>CMakeLists.txt</code> file:</p> <pre><code>cmake_minimum_required(VERSION 2.8) add_executable(target0 test.cpp) add_dependencies(target0 target1) add_custom_target(target1 ALL COMMAND echo hello ) </code></pre> <p>The output file of "cmake --graphviz=test.dot ." would be:</p> <pre><code>digraph GG { node [ fontsize = "12" ]; "node3" [ label="target0" shape="house"]; } </code></pre> <p>There isn't any trace of <code>target1</code>.</p>
1
How to enter input to .exe file through command prompt on Windows?
<p>I have a .exe file that I have built from the makefile of a set of source .cpp files. It should take in a set of inputs and write the output to a .txt file. The manual I am following provides the following instruction for running it on linux: </p> <pre><code>./xyz -l4 -w6 -k4 -iSampleInputTJU.txt -oMyOutputFile.txt -p </code></pre> <p>But I need to run it on windows 10. So I typed in: </p> <pre><code>C:&gt;\Desktop\xyz -l4 -w6 -k4 -iSampleInputTJU.txt -oMyOutputFile.txt -p </code></pre> <p>However it tells me that it cannot open the input file. I am not sure what I am doing wrong. Please help. Any input will be appreciated. </p>
1
Too long saving time in Excel via VBA
<p>Some unusal phenomenon started affecting my macro. I have a relatively big (13MB) excel workbook. <code>ThisWorkbook.Save</code> worked just fine. It took like 10 seconds to save the workbook (without any data changes). Now it takes for 2 minutes. Same goes for <code>ThisWorkbook.Close SaveChanges:=True</code>. I am using <code>Excel 2010</code> on <code>Windows 7</code>.</p> <p>The strange thing is I can save the workbook manually without any issues, like <code>CTRL+S</code> or using the <code>Save icon</code> in the Excel menu. This way the saving procedure takes less than 10 seconds just as my code used to do it.</p> <p>The occurence of this unnecessary delay is really bugging me. Do you have any experience with an issue like this? I'm looking for tips to get an approach on the problem.</p> <hr> <p>EDIT:</p> <p>I've changed to <code>xlsb</code> format as was advised and went a little further with testing. There are some cases when the saving time looks appropiate:</p> <ul> <li>Significant data changes in lots of sheets (48s)</li> <li>The <code>Save</code> command is triggered from a newly created <code>module</code> without any other changes (5s)</li> <li>All my charts (150pcs) are deleted (1s). Apparently each chart gives about 1 extra second to the saving time. I know, i should use one dynamic but the damn label bugs... And it was totally fine before!</li> </ul> <hr> <p>EDIT 2:</p> <p>The issue has vanished today. <code>Save</code> command works properly again, saving takes for only a few seconds. Dunno what caused the problem, but I am affraid it will be back and will affect my macro some day again. Excel is definitely quirky!</p>
1
laravel uuid not showing in query
<p>I've a postgres database table that uses uuid's as its primary key, via the <strong>webpatser/laravel-uuid</strong> package, and 'readable' web ids via <strong>vinkla/hashids</strong>.</p> <p>When I query the database, if I <strong>dd()</strong> the response, I see the UUID in full, but if I simply <strong>return</strong>, I instead get an integer.</p> <p>Presume I've overlooking something obvious, so:</p> <p><strong>Migration</strong></p> <pre><code>$table-&gt;uuid('id'); $table-&gt;string('web_id'); $table-&gt;primary('id'); </code></pre> <p><strong>Model</strong></p> <pre><code>public function store() { $data = [ 'id' =&gt; Uuid::generate(4)-&gt;string, 'web_id' =&gt; Hashids::encode(mt_rand(1,1000000)), </code></pre> <p>I'm assuming something happens when the data is cast to json, but I'm not sure where'd I'd begin to tackle this...</p> <p>I also see the same behaviour in artisan tinker, fwiw:</p> <pre><code> &gt;&gt;&gt; $result = App\Model::firstOrFail() =&gt; App\Model {#675 id: "587bb487-881d-417e-8960-fbecaa3b270b", web_id: "Mxqv4LYP", created_at: "2016-01-25 15:52:25+00", updated_at: "2016-01-25 15:52:25+00", } &gt;&gt;&gt; $result-&gt;id =&gt; 587 </code></pre>
1
does not implement methodSignatureForSelector: Unrecognized selector (NSTimer)
<p>I am using an <code>NSTimer</code> in my Swift app in the following way:</p> <pre><code>func playEvent(eventIndex : Int){ if (eventIndex &lt; 2){ let currEvent = self.eventArray[eventIndex] currEvent?.startEvent() let nextIndex = eventIndex + 1 NSTimer.scheduledTimerWithTimeInterval((currEvent?.duration)!, target: self, selector: "playEvent(nextIndex)", userInfo: nil, repeats: true) } else if (eventIndex==2){ self.eventArray[eventIndex]?.startEvent() NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "finishSentence", userInfo: nil, repeats: true) } else{ //do nothing } } </code></pre> <p>I think the problem may be either that I am not property calling the selector method with a parameter. If that is impossible, how could I work around this? There is being called on the first <code>NSTimer</code> instance. Here is the full Swift class for reference: <a href="https://gist.github.com/ebbnormal/79941733b82f5fe58282" rel="nofollow">https://gist.github.com/ebbnormal/79941733b82f5fe58282</a></p>
1
Parse local HTML python (lxml)
<p>I'm trying to parse a local HTML with lxml, but I'm getting an error, but I don't know why (sorry in advance for the bad code, I'm new to this).</p> <pre><code>from lxml import etree, html from StringIO import StringIO parser = etree.HTMLParser() doc = etree.parse(StringIO("test1.html"), parser) tree = html.fromstring(doc) CCE = tree.xpath('//div[@data-reactid]/div[@class="browse-summary"]/h1') URL = tree.xpath('//a[@class="rc-OfferingCard"]/@href') print 'CCE:', CCE print 'URL:', URL </code></pre> <p>And here's the error:</p> <pre><code> File "test.py", line 8, in &lt;module&gt; tree = html.fromstring(doc) File "/usr/lib/python2.7/dist-packages/lxml/html/__init__.py", line 703, in fromstring is_full_html = _looks_like_full_html_unicode(html) TypeError: expected string or buffer </code></pre>
1
RestTemplate don't return value with Snake Case in Spring REST
<p>I have REST API with property in application.properties as below:</p> <pre><code>spring.jackson.property-naming-strategy: CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES </code></pre> <p>Everything is OK! But when I use RestTemplate to do as below, but I found all key in Snake Case is null (ex. nameEnglish), but regular key name are ok (ex. rank), how can I solve this problem?</p> <pre><code>@Data @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(exclude = {"id"}) @Entity public class Brand implements Serializable { private static final long serialVersionUID = 9165709510160554127L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Version private Integer version; private String nameChinese; private String nameEnglish; private String rank; } </code></pre> <p>I saved a data as below:</p> <pre><code>Saved Brand: Brand(id=1, version=1, nameChinese=乐高, nameEnglish=Lego, rank=Top) </code></pre> <p>But when I try code as below:</p> <pre><code>Brand brands = restTemplate.getForObject("http://localhost:8080/api/brand/lego", Brand.class); System.out.println(brands); </code></pre> <p>The result as below, you will see all Camel Case properties in null, though I set value to them:</p> <pre><code>Saved Brand: Brand(id=1, version=1, nameChinese=null, nameEnglish=null, rank=Top) </code></pre> <p>The Json format result form CocoaRestCLient</p> <pre><code>{ "id": 1, "country_chinese": "芬兰", "version": 1, "homepage_url": "http://www.lego.com", "country_english": "Finland", "name_english": "Lego", "rank": "Top", "name_chinese": "乐高" } </code></pre>
1
android.view.InflateException: Binary XML file line #1: Error inflating class fragment GOOGLE MAPS
<p>I simply created an activity using Google Maps activity template and put my API key and when I run it I am getting this error </p> <blockquote> <p>(android.view.InflateException: Binary XML file line #1: Error inflating class fragment ).</p> </blockquote> <p>This is my xml file:</p> <pre><code>&lt;fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:map="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity" android:name="com.google.android.gms.maps.SupportMapFragment" /&gt; </code></pre> <p>This is my activity:</p> <pre><code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); } } </code></pre>
1
Render and/or redirect called multiple times in action
<p>I'm using Devise and Pundit. To create a new profile page, the user has to be authorized to do so. This has been working fine since I first implemented it, but today it just started acting up with an error message:</p> <blockquote> <p>Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".</p> </blockquote> <p>Here's my code from my Application controller:</p> <pre><code> rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized ... private def user_not_authorized(exception) flash[:alert] = "Sorry, you are not authorized to perform this action." redirect_to(request.referrer || root_path) end </code></pre> <p>Here's my ProfilePage controller:</p> <pre><code>def new @profile_page = ProfilePage.new authorize @profile_page end def create @profile_page = ProfilePage.new(profile_page_params) respond_to do |format| if @profile_page.save format.html { redirect_to @profile_page, notice: 'Profile page was successfully created.' } format.json { render :show, status: :created, location: @profile_page } else format.html { render :new } format.json { render json: @profile_page.errors, status: :unprocessable_entity } end end authorize @profile_page end </code></pre> <p>Someone suggested that I add this line of code below <code>flash[:alert]</code>:</p> <pre><code>self.response_body = nil </code></pre> <p>But now my user is redirected to the 'new profile' page again, rather than the successful profile page. It also tells the user that they are not authorized to complete this action, despite the fact that it HAS authorized them to do so.</p>
1
How to load a local json file in Xcode for unit test purposes?
<p>So I have added the file <code>testJson1.json</code> to my project. </p> <p>Within the unit test I have tried to get the filepath without any luck:</p> <pre><code>NSBundle *bundle = [NSBundle bundleForClass:[self class]]; NSString *filepath = [bundle pathForResource:@"testJson1.json" ofType:@"json"]; </code></pre> <p>When I look at the project file, I can oddly enough see that the file is added to the resources, I thought unit test files would not be added to the resource to keep the app size down.</p> <pre><code>8AA238811C5565E80031648E /* testJson1.json in Resources */ = {isa = PBXBuildFile; fileRef = 8AA2387F1C5565E80031648E /* testJson1.json */; }; </code></pre> <p>What am I missing please?</p> <p><a href="https://i.stack.imgur.com/aO03Y.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aO03Y.png" alt="enter image description here"></a></p>
1
Retrieve paginated data recursively using promises
<p>I'm using a function which returns data in a paginated form. So it'll return max 100 items and a key to retrieve the next 100 items. I want to retrieve all the items available.</p> <p>How do I recursively achieve this? Is recursion a good choice here? Can I do it any other way without recursion?</p> <p>I'm using Bluebird 3x as the promises library.</p> <p>Here is a snippet of what I'm trying to achieve:</p> <pre><code>getEndpoints(null, platformApplication) .then(function(allEndpoints) { // process on allEndpoints }); function getEndpoints(nextToken, platformApplication) { var params = { PlatformApplicationArn: platformApplication }; if (nextToken) { params.NextToken = nextToken; } return sns.listEndpointsByPlatformApplicationAsync(params) .then(function(data) { if (data.NextToken) { // There is more data available that I want to retrieve. // But the problem here is that getEndpoints return a promise // and not the array. How do I chain this here so that // in the end I get an array of all the endpoints concatenated. var moreEndpoints = getEndpoints(data.NextToken, platformApplication); moreEndpoints.push.apply(data.Endpoints, moreEndpoints); } return data.Endpoints; }); } </code></pre> <p>But the problem is that if there is more data to be retrieved (see <code>if (data.NextToken) { ... }</code>), how do I chain the promises up so that in the end I get the list of all endpoints etc.</p>
1
How to cancel execution of a long-running async task in a C# Winforms app
<p>I'm a quite inexperienced c# programmer and need help on managing the flow of my program. It is a WinFormApp that asks for multiple user inputs and then uses them to establish serial communication with a device in order to make measurements. The measurements are made in an async method that takes about 20 minutes to run. So I'm using </p> <pre><code> void main() { //Setup } private void button1_Click(object sender, EventArgs e) { await measurements(); //Plot results } private async Task measurements() { while(true){ //Make some measurements await Task.Delay(120000); //Make measurements, present data in the UI form. //return if done } } </code></pre> <p>Now I need to make a button which enables the user to cancel the measurements in order to change some input or parameter and then restart the measurements. So I added a "Cancel"-button. </p> <pre><code> private void button7_Click(object sender, EventArgs e) { textBox64.Enabled = true; button6.Enabled = true; button5.Enabled = true; textBox63.Enabled = true; button3.Enabled = true; trackBar1.Enabled = true; timer.Enabled = true; button7.Enabled = false; clearData(); // measurement.Stop(); } </code></pre> <p>Now I do not know how to manage the flow of the program. I have tried to make a <code>try-catch</code> structure in <code>button1_Click()</code> and throw an Exception from <code>button7_Click</code>, but it doesn't get through to <code>button1_Click()</code>.<br> Then I tried to run <code>measurements()</code> on a new thread. But the thread does not have access to 70-ish UI items on my main form.<br> And even I wont sink as low as trying Goto. </p> <p>What I need is advice on how you would program in this situation in order to get a good control of the application and not compromise the flow of the program with risky stuff like exceptions and Goto.</p>
1
Swift UINavigationBar background color is different from main one
<p>The problem is that color that I set for the UINavigationBar is different from the same color, which I have set for the layer. I want it to be the same! :) (see image)</p> <p>AppDelegate.swift</p> <pre><code>UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().setBackgroundImage(UIImage.imageWithColor(primaryColor), forBarMetrics: .Default) UINavigationBar.appearance().barTintColor = primaryColor UINavigationBar.appearance().tintColor = UIColor.whiteColor() UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(17), NSForegroundColorAttributeName:UIColor.whiteColor()] </code></pre> <p>MyController.swift in viewDidLoad()</p> <pre><code>view.backgroundColor = primaryColor </code></pre> <p>Extensions.swift</p> <pre><code>let primaryColor = UIColor(red: 132/255, green: 205/255, blue: 93/255, alpha: 1) extension UIImage { class func imageWithColor(color: UIColor) -&gt; UIImage { let rect = CGRectMake(0.0, 0.0, 1.0, 1.0) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } </code></pre> <p><a href="https://i.stack.imgur.com/Hdb6C.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Hdb6C.png" alt="enter image description here"></a></p> <p>I think the problem is in UIImage extension. Please help me to solve this problem. </p> <p><strong>Solved</strong></p> <pre><code>UINavigationBar.appearance().translucent = false </code></pre>
1
Exclude null value during full outer join
<p>How to join these two tables with excluding all null values?</p> <p>And Instead of UserId in 2nd table I want the user name from first table information.</p> <p><a href="https://i.stack.imgur.com/evCI6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/evCI6.png" alt="enter image description here" /></a></p>
1
How to tap-to-focus with react-native-camera
<p>I would like to let the user focus to take picture. But I don't know how it works.</p> <p>I found on the documentation the section related to the problem : <a href="https://github.com/lwansbrough/react-native-camera#onfocuschanged" rel="noreferrer" title="gog">react-native-camera</a> But is there any example to view how it works ? I don't any idea to implement this.</p> <p>Furthermore, the <a href="https://github.com/lwansbrough/react-native-camera#defaultonfocuscomponent" rel="noreferrer">default option</a> didn't seem to work. I didn't have any visual feedback when I pressure camera's screen and it didn't seems to focus.</p> <p>Someone can help me on this point ?</p> <p><strong>Update : Solution</strong></p> <p>It appears a bug was fix since long time, but at this time, the dependencie isn't up-to-date, so the feature didn't work. As a workaround before a new release <code>&gt; 0.38.0</code>, add this link <code>https://github.com/lwansbrough/react-native-camera.git#8f37727be69132cdbfed95255c8bd010a1db5c7d</code> (with the hash of the last commit on master) to your <code>package.json</code>.</p> <p>After this, add to the <code>&lt;camera /&gt;</code> component <code>defaultOnFocusComponent={ true } onFocusChanged={ this.state.handleFocusChanged }</code> and <code>handleFocusChanged: () =&gt; {},</code> as an initial state</p>
1
CURL & PHP SSLv3 Error and Can't Get TLS to Work
<p>I am trying to connect to PayPal sandbox using CURL. I've searched both this website and many others trying to find the right answer however, none, and I mean none, have worked for me and I still get the error:</p> <blockquote> <p>SetExpressCheckout failed: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure ( 35 )</p> </blockquote> <p>I have the following CURL and PHP installed (It is bought and shared hosting so I cannot upgrade anything).</p> <ul> <li><strong>Curl Verison:</strong> 7.36.0</li> <li><strong>SSL Version:</strong> OpenSSL/0.9.8b </li> <li><strong>PHP Version:</strong> 5.4.45</li> </ul> <p>The code I am currently using:</p> <pre><code>class MyPayPal { function PPHttpPost($methodName_, $nvpStr_, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode) { // Set up your API credentials, PayPal end point, and API version. $API_UserName = urlencode($PayPalApiUsername); $API_Password = urlencode($PayPalApiPassword); $API_Signature = urlencode($PayPalApiSignature); $paypalmode = ($PayPalMode=='sandbox') ? '.sandbox' : ''; $API_Endpoint = "https://api-3t".$paypalmode.".paypal.com/nvp"; $version = urlencode('109.0'); // Set the curl parameters. $ch = curl_init(); curl_setopt($ch, CURLOPT_SSLVERSION, 4); curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, 'TLSv1'); curl_setopt($ch, CURLOPT_URL, $API_Endpoint); curl_setopt($ch, CURLOPT_VERBOSE, 1); // Turn off the server and peer verification (TrustManager Concept). curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); // Set the API operation, version, and API signature in the request. $nvpreq = "METHOD=$methodName_&amp;VERSION=$version&amp;PWD=$API_Password&amp;USER=$API_UserName&amp;SIGNATURE=$API_Signature$nvpStr_"; // Set the request as a POST FIELD for curl. curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq); // Get response from the server. $httpResponse = curl_exec($ch); if(!$httpResponse) { exit("&lt;span style='font-family: Verdana'&gt;&lt;strong&gt;$methodName_ failed: &lt;/strong&gt;".curl_error($ch).'&lt;strong&gt; (&lt;/strong&gt; '.curl_errno($ch).' &lt;strong&gt;)&lt;/strong&gt;&lt;/span&gt;'); } // Extract the response details. $httpResponseAr = explode("&amp;", $httpResponse); $httpParsedResponseAr = array(); foreach ($httpResponseAr as $i =&gt; $value) { $tmpAr = explode("=", $value); if(sizeof($tmpAr) &gt; 1) { $httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1]; } } if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) { exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint."); } return $httpParsedResponseAr; } } </code></pre> <p>It doesn't matter what I do, I cannot seem to conquer this error. :( Any guidance will be helpful.</p>
1
Are there any code samples for spring integration dsl error handling?
<p>The JmsTests.java was very helpful in understanding ways to structure my code. Code is at <a href="https://github.com/spring-projects/spring-integration-java-dsl/blob/master/src/test/java/org/springframework/integration/dsl/test/jms/JmsTests.java" rel="nofollow">https://github.com/spring-projects/spring-integration-java-dsl/blob/master/src/test/java/org/springframework/integration/dsl/test/jms/JmsTests.java</a> </p> <p>But, for error handling, I am kind of figuring it out as we go. Are there any tests or reference code that show good ways to structure error channels or using sub-flows to delegate error handling? </p> <p><strong>Adding more context to the question:</strong></p> <ol> <li>jmsMessageDrivenFlow: reads from incoming queue and prints payload. If there is an error, then it is sent to errorChannel()</li> <li>handleErrors(): Is supposed to listen to errorChannel and send anything there to the fatalErrorQueue</li> </ol> <p>jmsMessageDrivenFlow() works fine and prints the message. I am expecting the error handler to be called only if there is an error during the jmsMessageDrivenFlow. However, the errorhandler() also gets called, and it puts a 'Dispatcher failed to deliver Message' message in the fatal queue. </p> <p>I am hoping that the error channel shouldn't even be invoked in this scenario since jmsMessageDrivenFlow() didn't create any errors. Obviously, if I leave out .errorChannel(errorChannel()) in the jmsMessageDrivenFlow(), the error flow is not invoked and I get only jmsMessageDrivenFlow() executing as expected. </p> <pre><code>@EnableIntegration @IntegrationComponentScan @Component @Configuration public class MessageReceiver { private static final Logger logger = LoggerFactory.getLogger(MessageReceiver.class); String fatalErrorQueue = "fatal"; String incomingQueue = "incoming"; @Autowired private JmsMessagingTemplate jmsMessagingTemplate; @Bean public Queue incomingQueue() { return new ActiveMQQueue(incomingQueue); } @Bean public MessageChannel errorChannel() { return new DirectChannel(); } @Bean public IntegrationFlow handleErrors() { return IntegrationFlows .from("errorChannel") .handle((payload,headers) -&gt; { System.out.println("processing error: "+payload.toString()); return payload; }) .handle(Jms.outboundAdapter(jmsMessagingTemplate.getConnectionFactory()).destination(fatalErrorQueue)) .get(); } @Bean public IntegrationFlow jmsMessageDrivenFlow() { return IntegrationFlows .from( Jms.messageDriverChannelAdapter(jmsMessagingTemplate.getConnectionFactory()) .destination(incomingQueue) .errorChannel(errorChannel()) ) .handle((payload,headers) -&gt;{ System.out.println("processing payload: "+payload.toString()); return payload; }) .get(); } } </code></pre> <p>Log of the execution: </p> <pre><code>2016-01-22 10:18:20,531 DEBUG DefaultMessageListenerContainer-1 ServiceActivatingHandler.handleMessage - ServiceActivator for [org.springframework.integration.dsl.LambdaMessageProcessor@522d5d91] (org.springframework.integration.handler.ServiceActivatingHandler#1) received message: GenericMessage [payload=SAMPLE QUEUE MESSAGE, headers={jms_redelivered=false, jms_correlationId=, jms_type=, id=78d5456e-4442-0c2b-c545-870d2c177802, priority=0, jms_timestamp=1453479493323, jms_messageId=ID:crsvcdevlnx01.chec.local-47440-1453310266960-6:2:1:1:1, timestamp=1453479500531}] processing payload: SAMPLE QUEUE MESSAGE 2016-01-22 10:18:20,535 DEBUG DefaultMessageListenerContainer-1 DirectChannel.send - preSend on channel 'errorChannel', message: ErrorMessage [payload=org.springframework.messaging.MessagingException: Dispatcher failed to deliver Message; nested exception is org.springframework.messaging.core.DestinationResolutionException: no output-channel or replyChannel header available, headers={id=dc87f71d-a38c-4718-a2e9-2fba2a7c847c, timestamp=1453479500535}] 2016-01-22 10:18:20,535 DEBUG DefaultMessageListenerContainer-1 ServiceActivatingHandler.handleMessage - ServiceActivator for [org.springframework.integration.dsl.LambdaMessageProcessor@5545b00b] (org.springframework.integration.handler.ServiceActivatingHandler#0) received message: ErrorMessage [payload=org.springframework.messaging.MessagingException: Dispatcher failed to deliver Message; nested exception is org.springframework.messaging.core.DestinationResolutionException: no output-channel or replyChannel header available, headers={id=dc87f71d-a38c-4718-a2e9-2fba2a7c847c, timestamp=1453479500535}] processing error: org.springframework.messaging.MessagingException: Dispatcher failed to deliver Message; nested exception is org.springframework.messaging.core.DestinationResolutionException: no output-channel or replyChannel header available 2016-01-22 10:18:20,535 DEBUG DefaultMessageListenerContainer-1 DirectChannel.send - preSend on channel 'handleErrors.channel#0', message: ErrorMessage [payload=org.springframework.messaging.MessagingException: Dispatcher failed to deliver Message; nested exception is org.springframework.messaging.core.DestinationResolutionException: no output-channel or replyChannel header available, headers={id=f434348c-f659-1e88-2eba-3d467761ab47, timestamp=1453479500535}] 2016-01-22 10:18:20,535 DEBUG DefaultMessageListenerContainer-1 JmsSendingMessageHandler.handleMessage - org.springframework.integration.jms.JmsSendingMessageHandler#0 received message: ErrorMessage [payload=org.springframework.messaging.MessagingException: Dispatcher failed to deliver Message; nested exception is org.springframework.messaging.core.DestinationResolutionException: no output-channel or replyChannel header available, headers={id=f434348c-f659-1e88-2eba-3d467761ab47, timestamp=1453479500535}] 2016-01-22 10:18:20,537 DEBUG DefaultMessageListenerContainer-1 DynamicJmsTemplate.execute - Executing callback on JMS Session: ActiveMQSession {id=ID:MACD13-60edd8d-49463-1453479492653-1:1:1,started=true} java.lang.Object@858db12 2016-01-22 10:18:20,568 DEBUG DefaultMessageListenerContainer-1 DynamicJmsTemplate.doSend - Sending created message: ActiveMQObjectMessage {commandId = 0, responseRequired = false, messageId = null, originalDestination = null, originalTransactionId = null, producerId = null, destination = null, transactionId = null, expiration = 0, timestamp = 0, arrival = 0, brokerInTime = 0, brokerOutTime = 0, correlationId = null, replyTo = null, persistent = false, type = null, priority = 0, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = org.apache.activemq.util.ByteSequence@559da78d, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 0, properties = {timestamp=1453479500535}, readOnlyProperties = false, readOnlyBody = false, droppable = false, jmsXGroupFirstForConsumer = false} 2016-01-22 10:18:20,570 DEBUG DefaultMessageListenerContainer-1 DirectChannel.send - postSend (sent=true) on channel 'handleErrors.channel#0', message: ErrorMessage [payload=org.springframework.messaging.MessagingException: Dispatcher failed to deliver Message; nested exception is org.springframework.messaging.core.DestinationResolutionException: no output-channel or replyChannel header available, headers={id=f434348c-f659-1e88-2eba-3d467761ab47, timestamp=1453479500535}] 2016-01-22 10:18:20,571 DEBUG DefaultMessageListenerContainer-1 DirectChannel.send - postSend (sent=true) on channel 'errorChannel', message: ErrorMessage [payload=org.springframework.messaging.MessagingException: Dispatcher failed to deliver Message; nested exception is org.springframework.messaging.core.DestinationResolutionException: no output-channel or replyChannel header available, headers={id=dc87f71d-a38c-4718-a2e9-2fba2a7c847c, timestamp=1453479500535}] </code></pre>
1
TextInputLayout error text padding
<p>I am using <strong>TextInputLayout</strong> with <strong>AppCompatEditText</strong> having a custom xml shape based background for <strong>AppCompatEditText</strong>. Whenever i set some error , the error line starts from beginning of layout. Is there any way to give padding to that error line. </p> <p><a href="https://i.stack.imgur.com/BW0NY.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/BW0NY.jpg" alt="enter image description here"></a></p>
1
How to sort array in alphabetical order without using Array.sort:Java
<p>I want to sort values of an array in alphabetical order in Java.I am stuck at going over the array again and get the output. My intention is to : Go over the words array, Find the largest string (lexicographically), Once it is found, insert the word at the end of the sortedWords array, Shift the sortedArray's index by one position to the left, Reduce the original array by removing the word already found, Loop again to find the next word....</p> <p>Thanks for your help.</p> <p>Following is what I have done so far. </p> <p>public class Main {</p> <pre><code>public static void main(String[] args) { String[] words = {"bob","alice","keith","zoe","sarah","gary"}; String[] sortedWords = new String[words.length]; // Copy of the original array for(int i = 0; i &lt; sortedWords.length;i++){ sortedWords[i]= words[i]; } for (int i = 0; i &lt; words.length - 1; i++) { int currentSize = words.length; int position = 0; boolean found = false; while (position &lt; currentSize &amp;&amp; !found) { if (words[i].equals(largestAlphabetically(words))) { found = true; } else { position++; } } if(found){ insertAtEnd(words,largestAlphabetically(words)); shiftLeft(sortedWords,i); shorterArray(words); } } for(int i = 0;i &lt; sortedWords.length;i++){ System.out.println(sortedWords[i]); } } /** * This method inserts the largest string lexicographically at the end of the array * @param words * @param wordToInsert * @return an array with string at the end */ public static String [] insertAtEnd(String[] words, String wordToInsert) { for (int i = 0; i &lt; words.length; i++) { int currentSize = words.length - 1; wordToInsert = largestAlphabetically(words); if (currentSize &lt; words.length) { currentSize++; words[currentSize - 1] = wordToInsert; } } return words; } /** * This method determines the largest string in an array * @param words * @return largest string lexicographically */ public static String largestAlphabetically(String[] words) { String searchedValue = words[0]; for (int i = 0; i &lt; words.length; i++) { for (int j = 0; j &lt; words.length; j++) { if (words[i].compareToIgnoreCase(words[j]) &lt; 0) { searchedValue = words[j]; } } } return searchedValue; } /** * To shift the array index to the left * @param dest * @param from */ public static void shiftLeft(String[] dest, int from) { for (int i = from + 1; i &lt; dest.length; i++) { dest[i - 1] = dest[i]; } dest[dest.length - 1] = dest[0]; } /** * Remove the largest word from a string while maintaining the order of the array * @param words * @return return a shorter array */ public static String [] shorterArray(String[] words) { String [] shorterArray = new String[words.length]; int currentSize = words.length; String searchedValue = largestAlphabetically(words); int position = 0; boolean found = false; while (position &lt; currentSize &amp;&amp; !found) { if (words[position] == searchedValue) { found = true; } else { position++; } } if (found) { for (int i = position + 1; i &lt; currentSize; i++) { words[i - 1] = words[i]; } currentSize--; shorterArray = words; } return shorterArray; } </code></pre> <p>}</p>
1
Django makemessage command not processing app
<p>I'm trying to internationalize a django application. I followed the tutorial, but when i run ...</p> <pre><code>./manage.py makemessages --all </code></pre> <p>... django only creates a .po file that contains the translations of my settings.py (see below). It completely ignores anything inside my app and its templates.</p> <p>This is my file structure:</p> <pre><code>myproject |- myproject |- course |- templates |- static |- ... |- apps.py |- models.py |- views.py |- ... |- locale |- myproject |- settings.py |- ... |- manage.py </code></pre> <p>My settings file looks like this:</p> <pre><code>from django.utils.translation import ugettext_lazy as _ ... INSTALLED_APPS = [ ... 'course.apps.CourseConfig', ] MIDDLEWARE_CLASSES = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'CET' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', _('English')), ('kr', _('Korean')), ('cn', _('Chinese')), ('pt', _('Portuguese')), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) </code></pre> <p>My templates contain translation texts:</p> <pre><code>{% extends "course/base.html" %} {% load i18n %} {% trans "Back to modules" %} ... </code></pre> <p>If I run the 'makemessages' command, the only thing that's being included in the .po file is the language names in the settings.py file, but not the template variables or anything I translated with ugettext in a view.</p> <pre><code># SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR &lt;EMAIL@ADDRESS&gt;, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-01-30 20:25+0100\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME &lt;EMAIL@ADDRESS&gt;\n" "Language-Team: LANGUAGE &lt;[email protected]&gt;\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: myproject/settings.py:146 msgid "English" msgstr "" #: myproject/settings.py:147 msgid "Korean" msgstr "" #: myproject/settings.py:148 msgid "Chinese" msgstr "" #: myproject/settings.py:149 msgid "Portuguese" msgstr "" </code></pre> <p>Can anyone tell what I'm missing? The app works just fine, all templates are found at runtime. Thanks a lot.</p>
1
Boost asio non-blocking IO without callbacks
<p>Is it possible to use Boost's asio to do non-blocking IO <em>without using async callbacks?</em> I.e. equivalent to the <code>O_NONBLOCK</code> socket option.</p> <p>I basically want this function:</p> <pre><code>template&lt;typename SyncWriteStream, typename ConstBufferSequence&gt; std::size_t write_nonblock( SyncWriteStream &amp; s, const ConstBufferSequence &amp; buffers); </code></pre> <blockquote> <p>This function will write as many bytes as it can and return immediately. It may write 0 bytes.</p> </blockquote> <p>Is it possible?</p>
1
await GetByteArrayAsync in asp.net not returning
<p>The following code just hangs when called from an ASP.NET app:</p> <pre><code>private async Task&lt;XPathNavigator&gt; UspsCreateAndPostRequest(string sUrl) { HttpClient client = new HttpClient(); byte[] urlContents = await client.GetByteArrayAsync(sUrl); string sResponse = System.Text.Encoding.UTF8.GetString(urlContents); ... //more code to return XPathNavigator object based on response } </code></pre> <p>If I change to following it works fine:</p> <pre><code>private async Task&lt;XPathNavigator&gt; UspsCreateAndPostRequest(string sUrl) { HttpClient client = new HttpClient(); byte[] urlContents = null; var task = Task.Run(async () =&gt; { urlContents = await client.GetByteArrayAsync(strUrl); }); task.Wait(); string sResponse = System.Text.Encoding.UTF8.GetString(urlContents); ... //more code to return XPathNavigator object based on response } </code></pre> <p>Is the fact that method signature return is a Task&lt;XPathNavigator&gt; causing the issue? Thank you.</p>
1
Does the "?." operator do anything else apart from checking for null?
<p>As you might know, <code>DateTime?</code> does not have a parametrized <code>ToString</code> (for the purposes of formatting the output), and doing something like</p> <pre><code>DateTime? dt = DateTime.Now; string x; if(dt != null) x = dt.ToString("dd/MM/yyyy"); </code></pre> <p>will throw</p> <blockquote> <p>No overload for method 'ToString' takes 1 arguments</p> </blockquote> <p>But, since C# 6.0 and the Elvis (<code>?.</code>) operator, the above code can be replaced with </p> <pre><code>x = dt?.ToString("dd/MM/yyyy"); </code></pre> <p>which.... works! Why?</p>
1
Java URLDecoder decode Percentage Symbol as error
<p>I need to allow user to input various special characters, so i use the java URLDeacoder.decode() method, i tested using println. There is no problem with other special character except this Percentage symbol, it has error during execute. Why is that? I understand that % is being used for URL encoding, is this the reason?</p> <p>java.lang.IllegalArgumentException: URLDecoder: Incomplete trailing escape (%) pattern</p> <pre><code>System.out.println(URLDecoder.decode("%", "UTF-8")); </code></pre>
1
How to remove random number of nodes from a network graph?
<pre><code>import networkx as nx import itertools import numpy as np import os import sys import pylab as pl g = nx.read_edgelist('/home/suman/Desktop/dataset/Email-Enron.txt', create_using=None, nodetype=int, edgetype=int) n = nx.number_of_nodes(g) print n </code></pre>
1
How do I check if a network is contained in another network in Python?
<p>How can I check if a network is wholly contained in another network in Python, e.g. if <code>10.11.12.0/24</code> is in <code>10.11.0.0/16</code>? </p> <p>I've tried using <code>ipaddress</code> but it doesn't work:</p> <pre><code>&gt;&gt;&gt; import ipaddress &gt;&gt;&gt; ipaddress.ip_network('10.11.12.0/24') in ipaddress.ip_network('10.11.0.0/16') False </code></pre>
1
Is this the correct way to wrap readFileSync in a Promise
<p>The reason for the below code is to get rid of <code>callback hell</code>/<code>pyramid of doom</code>. I don't fully understand <code>i/o blocking</code> though yet.</p> <pre><code>'use strict'; var fs = require('fs'); var co = require('co'); co(function* () { var fileName = 'readme.txt'; var str = yield new Promise(function (resolve, reject) { var result; try { result = fs.readFileSync(fileName, 'utf8'); } catch (err) { reject(err); } resolve(result); }); console.log('result readFileSync: ' + str); }); </code></pre> <p>All I'm expecting is a <code>yes</code> or <code>no</code> answer to be honest. Hope fully if no could someone give some details as I'm trying to learn properly about JavaScript sync/async and how to harness the power of Promises.</p>
1
idHTTP.Post Error HTTP/1.1 401
<p>I am trying to access the idHTTP Delphi in a json server without success. I've tried all the alternatives and always got the same error: "HTTP / 1.1 401 Unauthorized".</p> <p>JSON format for testing: </p> <blockquote> <p>{"http":{"method":"POST","header":"access_token:55b3ce85b47629eeee778c0f0c9be450f1b1bc84cc377975f2d3d0d3808a4636", "content":"name=TEST&amp;[email protected]&amp;phone=1147001211&amp;mobilePhone=11992329909&amp;address=Rua+Jose+Ricardo &amp;addressNumber=55&amp;province=Test&amp;notificationDisabled=True&amp;city=Sao+Paulo&amp;state=SP&amp;country=Brasil&amp;postalCode=05567210 &amp;cpfCnpj=11111111111&amp;personType=FISICA"}}</p> </blockquote> <p>Url for testing:</p> <blockquote> <p><a href="http://homolog.asaas.com/api/v2/customers" rel="nofollow">http://homolog.asaas.com/api/v2/customers</a></p> </blockquote> <p>Procedure for testing:</p> <pre><code>procedure TForm4.Button2Click(Sender: TObject); var sResponse: string; EnvStr : TStringList; begin EnvStr := TStringList.Create; EnvStr.AddStrings(Memo.Lines); try idHTTP.Request.ContentType := 'application/json'; idHTTP.Request.Method:='POST'; idHTTP.Request.AcceptCharSet := 'utf-8'; try sResponse := idHTTP.Post(EditURL.Text,EnvStr); except on E: Exception do ShowMessage('Error on request: '#13#10 + e.Message); end; finally MemoRet.Lines.Clear; MemoRet.Lines.add(sResponse); end; end; </code></pre> <p>The same format sent in PHP works perfectly, but with idHTTP returns the error: "HTTP / 1.1 401 Unauthorized".</p> <p>PHP works perfectly</p> <pre><code>&lt;?php $api_url = "http://homolog.asaas.com/api/v2"; $api_key = "55b3ce85b47629eeee778c0f0c9be450f1b1bc84cc377975f2d3d0d3808a4636"; $url_cus = $api_url."/customers"; $param = array( 'name' =&gt; utf8_encode('Test'), 'email' =&gt; '[email protected]', 'phone' =&gt; '1147001211', 'mobilePhone' =&gt; '11992329909', 'address' =&gt; utf8_encode('Rua Jose Ricardo'), 'addressNumber' =&gt; '55', 'province' =&gt; 'Test', 'notificationDisabled' =&gt; 'True', 'city' =&gt; 'Sao Paulo', 'state' =&gt;'SP', 'country' =&gt; 'Brasil', 'postalCode' =&gt; '05567210', 'cpfCnpj' =&gt; '11111111111', 'personType' =&gt; 'FISICA' ); $req = http_build_query($param); $ctx = stream_context_create( array( "http" =&gt; array( "method" =&gt; "POST", "header" =&gt; "access_token: $api_key", "content" =&gt; $req ) ) ); $res = file_get_contents($url_cus, true, $ctx); //PHP Object $obj = json_decode($res); //get id of register $id=utf8_decode("$obj-&gt;id"); // return result // return $id; ?&gt; </code></pre>
1
Calling Python functions/methods with zero arguments
<p>According to <a href="https://rads.stackoverflow.com/amzn/click/com/0132350882" rel="nofollow noreferrer" rel="nofollow noreferrer">Clean Code</a>, a function should take zero arguments when at all possible.</p> <p>If we take a trivial example in Python with a function that does nothing more than add 2 to whatever is passed to it:</p> <pre><code>def add_two(x): return x + 2 &gt;add_two(1) 3 </code></pre> <p>The only way I can see that such a function can have zero arguments passed to it is by incorporating it into a class:</p> <pre><code>class Number(object): def __init__(self, x): self.x = x def add_two(self): return self.x + 2 &gt;n = Number(1) &gt;n.add_two() 3 </code></pre> <p>It hardly seems worth the effort. Is there another way of achieving the no-argument function in this example?</p>
1
Change .exe with hexeditor
<p>I wrote a little program in C++:</p> <pre><code>#include &lt;iostream&gt; int main() { int input; std::cin &gt;&gt; input; if(input == 5){ std::cout &lt;&lt; "Input == 5"; } else{ std::cout &lt;&lt; "Input != 5"; } return 0; } </code></pre> <p>I have already built the program. The working program is in the <code>Release</code> folder. Now I want to change the <code>if</code> statement, without changing the C++ code. I downloaded a hex editor and opened the file. Inside the <code>.exe</code> is a lot. I googled for the problem and found this very nice image:</p> <p><a href="https://i.stack.imgur.com/Q8mkC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q8mkC.png" alt=""></a></p> <p>I searched inside the hex editor for my output <code>Input == 5</code>. I found it. When I change it to something different and execute the file, the program displays the new entered message, not the old one.</p> <p><a href="https://i.stack.imgur.com/EKmw2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EKmw2.png" alt=""></a></p> <p>But now I want to change the structure of the code (the <code>if</code> statement). I searched for <code>if</code>, but didn't find anything. So, where is the <em>code section</em> (image)?</p>
1
add and remove class on same button or element
<p>I'm looking for a way to add and remove class on the same button. So far this is my work in progress. The concept is when I click on the menu button it shows the menu. When I tap on the menu button again. The menu hides</p> <pre><code>$(document).ready(function(){ $('button.toggle-portfolio').on('click', function(e){ $('.portfolio-contact-form-wrap').addClass('show'); }); }); </code></pre>
1
Illustrate mean and standard deviation in ggplot2 density plot
<p>I'm trying to construct a plot where I plot normally distributed variables showing their mean on the x-axis and the standard deviation (SD) on the y-axis. Kinda like a density plot, but instead of having the density on the y-axis I want to have the SD (value).</p> <p>I'm working with the data below,</p> <pre><code>set.seed(1) mu1 &lt;- rnorm(10^5, mean = 1, sd = 1) mu3 &lt;- rnorm(10^5, mean = 3, sd = 2) </code></pre> <p>two normally distributed variables. Here their mean and sd, </p> <pre><code># install.packages("tidyverse", dependencies = TRUE) require(tidyverse) tibble(mu1, mu3) %&gt;% summarise_all(funs(mean, sd)) #&gt; # A tibble: 1 x 4 #&gt; mu1_mean mu3_mean mu1_sd mu3_sd #&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; #&gt; 1 0.9993454 3.000825 0.9982848 1.998234 </code></pre> <p>I've played around with <a href="/questions/tagged/ggplot2" class="post-tag" title="show questions tagged &#39;ggplot2&#39;" rel="tag">ggplot2</a>, and other <a href="/questions/tagged/tidyverse" class="post-tag" title="show questions tagged &#39;tidyverse&#39;" rel="tag">tidyverse</a> packages, to get closer to what I want. I've also tried copying <a href="http://statistic-on-air.blogspot.com/2014/02/boxplot-with-mean-and-standard.html" rel="nofollow noreferrer">this function</a> from a box-plot doing something similar, having succeeded yet.</p> <p>Here is my start,</p> <pre><code>tibble(mu1, mu3) %&gt;% gather() %&gt;% ggplot() + geom_density(aes(x = value, colour = key)) + labs(x = 'mean', y = 'currently density, but I would like sd') </code></pre> <p><a href="https://i.stack.imgur.com/wFnWH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wFnWH.png" alt="plot"></a></p>
1
what's the difference of double in mysql and java?
<p>Have a table,</p> <pre><code>CREATE TABLE `double_test` ( `price` double(11,2) DEFAULT NULL ) </code></pre> <p>and there are two records:</p> <pre><code>select * from double_test; +---------+ | price | +---------+ | 1100.00 | | 1396.32 | +---------+ </code></pre> <p>and sum them:</p> <pre><code>select sum(price) from double_test; +------------+ | sum(price) | +------------+ | 2496.32 | +------------+ </code></pre> <p>And sum the two double in Java , </p> <pre><code>System.out.println(1100.00 + 1396.32); //2496.3199999999997 System.out.println((1100.00 + 1396.32) == 2496.32); //false </code></pre> <p>So both are double why in mysql could get correct result? and what's the difference of double type in mysql and java?</p> <p>In java if use BigDecimal could get correct result, e.g.</p> <pre><code> System.out.println(BigDecimal.valueOf(1100.00).add(BigDecimal.valueOf(1396.32)).equals(BigDecimal.valueOf(2496.32)));//true </code></pre> <p>Is actually double in mysql equal to BigDecimal in Java? </p>
1
Terraform with Azure Marketplace
<p>I've started to get into <a href="https://www.terraform.io/" rel="nofollow">Terraform</a> and am loving it, since for cost reasons I have my services across a number of infrastructure providers, so it makes it easy to replicate full services without issues across IaaS providers.</p> <p>I use some third-party services through the Azure marketplace, similar to Heroku's Add-Ons. I see a facility in Terraform for Heroku Add-On declarations, but not for Azure marketplace subscriptions. How can I do this?</p> <p><strong>Update:</strong> How do I create an Azure marketplace order/subscription via Terraform?</p>
1
Symfony2 The Response content must be a string or object implementing __toString(), "boolean" given
<p>I am trying render a modal window dynamic, the problem is when return my response Json, i get the next error:</p> <pre><code>The Response content must be a string or object implementing __toString(), "boolean" given. </code></pre> <p>This is my controller:</p> <pre><code>use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\JsonResponse; //Some Code... public function detallesAction($id) { $em = $this-&gt;getDoctrine()-&gt;getManager(); $articulo = $em-&gt;getRepository("FicherosBundle:Articulo")-&gt;find($id); $html = $this-&gt;render('FicherosBundle:Articulos:detalles.html.twig', array( "articulo" =&gt; $articulo ))-&gt;getContent(); $response = new Response(json_encode(array( "detalles" =&gt; $html ))); $response-&gt;headers-&gt;set('Content-Type', 'application/json'); return $response; } </code></pre> <p>And this my template detalles.html.twig:</p> <pre><code>&lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal"&gt;&lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;&lt;span class="sr-only"&gt;Close&lt;/span&gt;&lt;/button&gt; &lt;h4 class="modal-title"&gt;Detalles&lt;/h4&gt; &lt;small class="font-bold"&gt;En esta ventana se ve reflejada toda la información del articulo.&lt;/small&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; Hello world &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-white" data-dismiss="modal"&gt;Cerrar&lt;/button&gt; &lt;/div&gt; </code></pre> <p>And this is my call to AJAX from index.html.twig:</p> <pre><code>$('.detalles').click(function () { var id = $(this).data("id"); var url = Routing.generate('articulos_detalles', { id: id }); $.ajax({ url: url, cache: false, success: function(response) { $(".modal-content").html(response.detalles); $("#myModal2").modal("show"); }, error: function(XMLHttpRequest, textStatus, errorThrown) { } }) }); </code></pre> <p>Where is the problem? :/</p>
1
Dynamically change cursor size in c#
<p>I created a <code>.cur</code> file with a simple cursor filled ellipse inside.</p> <p>I wish this <code>Cursor</code> to act like a "Brush Cursor" meaning that if I change thickness of the brush, the size of the <code>Cursor</code> will change (I would also like to change the color of the <code>Cursor</code>).</p> <p>Here's the code I'm using:</p> <pre><code>var customCursor = new Cursor(@"CustomCursor.cur"); Mouse.OverrideCursor = currentCursor; </code></pre> <p>Can such thing be done? Is there any better way to do it?</p>
1
Selenium WebDriver. Select element from div list
<p>I have the following area on the <code>HTML</code> page: </p> <pre><code>&lt;div class="t2-selector"&gt; &lt;div class=""&gt; USA &lt;div&gt; &lt;div&gt; &lt;div&gt; &lt;div class="selected" asset-id="129"&gt;Google&lt;/div&gt; &lt;div asset-id="130"&gt;Microsoft&lt;/div&gt; &lt;div asset-id="126"&gt;Apple&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="inactive"&gt; Europe &lt;div&gt; &lt;div&gt; &lt;div&gt; &lt;div class="inactive" asset-id="127"&gt;BT&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=""&gt; Currencies &lt;div&gt; &lt;div&gt; &lt;div&gt; &lt;div asset-id="135"&gt;EUR/USD&lt;/div&gt; &lt;div asset-id="136" class=""&gt;GBP/USD&lt;/div&gt; &lt;div asset-id="137" class=""&gt;USD/JPY&lt;/div&gt; &lt;div asset-id="138" class="selected"&gt;USD/CHF&lt;/div&gt; &lt;div asset-id="139"&gt;AUD/USD&lt;/div&gt; &lt;div asset-id="140"&gt;USD/CAD&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>So I need to select desired element from one of the groups (that should not be inactive, OK).<br> When I'm selecting a group nothing occurs, no error and I don't see the the selected group opens. Even for a moment.<br> But when I'm trying to select an element in previously clicked group I receive </p> <pre><code>org.openqa.selenium.ElementNotVisibleException: element not visible </code></pre> <p>error.<br> So I understand that in the moment I'm clicking on desired element it is not visible since the group not appears open.<br> But why?<br> And what can I do to resolve this problem?<br> Currently I'm using following code: </p> <pre><code>String selectedGroup = getValue("group",'o'); String xpath1 = "//div[contains(text(),'" + selectedGroup + "')]"; driver.findElement(By.xpath(xpath1)).click(); webElement = driver.findElement(By.xpath(xpath1)); String className = webElement.getAttribute("class"); if(className.contentEquals("inactive")) throw new ElementInactiveException("Selected group appears inactive. Exiting the test"); String optionAssetID = getValue("assetID",'o'); String xpath2 ="//div[@asset-id='" + optionAssetID + "']"; driver.findElement(By.xpath(xpath2)).click(); </code></pre> <p>the error occur on the following line: </p> <pre><code>driver.findElement(By.xpath(xpath2)).click(); </code></pre> <p>When clicking on a Group or hovering over it it looks in the following way:<br> As you can see from the code the selected / opened group receives "group-visible" class parameter. </p> <p><a href="https://i.stack.imgur.com/4wihk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4wihk.png" alt="When clicked on a Group or hovered over it it looks so:"></a> </p>
1
How to check a check box in Capybara test when using simple_form
<p>Trying to test some functionality in a simple page and I am getting this error when using page.check:</p> <pre><code> Failures: 1) searching for stores serving a taco and a sauce: Adobada tacos with Chile de Arbol sauce Failure/Error: page.check 'Adobada' Capybara::ElementNotFound: Unable to find checkbox "Adobada" # ./spec/views/store_search_spec.rb:8:in `block (2 levels) in &lt;top (required)&gt;' </code></pre> <p>Here is my HTML:</p> <pre><code>&lt;%= simple_form_for :stores, url: stores_path, method: :get do |f| %&gt; &lt;%= f.label :tacos, 'Select Tacos to Find: ', class: 'label' %&gt; &lt;div class='taco-select checkboxes'&gt; &lt;%= f.collection_check_boxes :tacos, Taco.order(:name), :id, :name, :include_hidden =&gt; false, :item_wrapper_class =&gt; 'checkbox_container' %&gt; &lt;/div&gt; &lt;%= f.label :salsa, 'Select Sauces to Find: ', class: 'label' %&gt; &lt;div class='salsa-select checkboxes'&gt; &lt;%= f.collection_check_boxes :salsas, Salsa.order(:name), :id, :name, :include_hidden =&gt; false, :item_wrapper_class =&gt; 'checkbox_container' %&gt; &lt;/div&gt; &lt;%= f.submit 'Search!' %&gt; &lt;% end %&gt; </code></pre> <p>And this is my test:</p> <pre><code>require 'rails_helper' feature 'searching for stores', %(serving a taco and a sauce:) do scenario 'Adobada tacos with Chile de Arbol sauce' do visit root_path page.check 'Adobada' page.check 'Chile de Arbol' click_button 'Search!' expect(page).to have_content "Store" expect(page).to have_content 'City' end end </code></pre> <p>I would like to test that when some checkboxes are set to true a certain content is rendered in the page. Don't know how to fix this.</p>
1
Add 5 days from current date and skip weekends
<p>I have a code where it just simply adds 5 days from the current date. How can I make it skip Saturday and Sunday? </p> <pre><code>date_default_timezone_set('Asia/Manila'); $current_date = date('Y-m-d'); $hearing = date('Y-m-d', strtotime("$current_date +5 days")); </code></pre> <p>It's January 27, Wednesday. Adding 5 days to this skipping the weekends would yield the answer February 3, Wednesday. How can I do that? Thank you for your help.</p>
1
How to duplicate value of an array n number of times in C#
<p>I have an <code>array</code></p> <pre><code>string[] AddrArray = new string[] { truncString }; </code></pre> <p>which contains only one value <code>&lt;Addr&gt;{Addr : n}&lt;/Addr&gt;</code></p> <p>how can I duplicate this value <code>n</code> number of times inside the same <code>array</code>. Thanks in advance </p>
1
java.io.IOException: An established connection was aborted by the software in your host machine
<p>I am using the wAsync library, Websocket protocol and Atmosphere to send request, by following this article: <a href="https://github.com/Atmosphere/wasync/wiki/Getting-Started-with-wAsync" rel="nofollow">https://github.com/Atmosphere/wasync/wiki/Getting-Started-with-wAsync</a></p> <p>Here is what I have implemented:</p> <pre><code> try { AtmosphereClient client = ClientFactory.getDefault().newClient(AtmosphereClient.class); RequestBuilder&lt;?&gt; requestBuilder = client.newRequestBuilder() .method(Request.METHOD.GET) .uri(url) .trackMessageLength(false) .transport(Request.TRANSPORT.WEBSOCKET) // Try Websocket. .transport(Request.TRANSPORT.LONG_POLLING); // Fall back to Long pooling. final Socket socket = client.create(); socket.open(requestBuilder.build()).fire(pMessage); socket.close(); } catch (Exception e) { } </code></pre> <p>The <code>socket.fire</code> works successfully. </p> <p>But sometimes I receive the following error:</p> <pre><code>15:11:36,467 ERROR [org.atmosphere.container.JSR356Endpoint] (http-localhost/127.0.0.1:8080-79) : java.io.IOException: An established connection was aborted by the software in your host machine at sun.nio.ch.WindowsAsynchronousSocketChannelImpl.write0(Native Method) [rt.jar:1.7.0_76] at sun.nio.ch.WindowsAsynchronousSocketChannelImpl.access$900(WindowsAsynchronousSocketChannelImpl.java:43) [rt.jar:1.7.0_76] at sun.nio.ch.WindowsAsynchronousSocketChannelImpl$WriteTask.run(WindowsAsynchronousSocketChannelImpl.java:777) [rt.jar:1.7.0_76] at sun.nio.ch.WindowsAsynchronousSocketChannelImpl.implWrite(WindowsAsynchronousSocketChannelImpl.java:914) [rt.jar:1.7.0_76] at sun.nio.ch.AsynchronousSocketChannelImpl.write(AsynchronousSocketChannelImpl.java:381) [rt.jar:1.7.0_76] at sun.nio.ch.AsynchronousSocketChannelImpl.write(AsynchronousSocketChannelImpl.java:398) [rt.jar:1.7.0_76] at org.apache.tomcat.util.net.NioChannel.write(NioChannel.java:978) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1] at org.apache.coyote.http11.InternalNioOutputBuffer$1.completed(InternalNioOutputBuffer.java:231) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1] at org.apache.coyote.http11.InternalNioOutputBuffer$1.completed(InternalNioOutputBuffer.java:200) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1] at sun.nio.ch.Invoker.invokeUnchecked(Invoker.java:126) [rt.jar:1.7.0_76] at sun.nio.ch.Invoker$2.run(Invoker.java:218) [rt.jar:1.7.0_76] at sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112) [rt.jar:1.7.0_76] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_76] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_76] at org.apache.tomcat.util.net.NioEndpoint$DefaultThreadFactory$1$1.run(NioEndpoint.java:1249) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1] at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_76] 15:11:36,469 ERROR [org.atmosphere.container.JSR356Endpoint] (http-localhost/127.0.0.1:8080-79) : java.io.IOException: An established connection was aborted by the software in your host machine at sun.nio.ch.WindowsAsynchronousSocketChannelImpl.write0(Native Method) [rt.jar:1.7.0_76] at sun.nio.ch.WindowsAsynchronousSocketChannelImpl.access$900(WindowsAsynchronousSocketChannelImpl.java:43) [rt.jar:1.7.0_76] at sun.nio.ch.WindowsAsynchronousSocketChannelImpl$WriteTask.run(WindowsAsynchronousSocketChannelImpl.java:777) [rt.jar:1.7.0_76] at sun.nio.ch.WindowsAsynchronousSocketChannelImpl.implWrite(WindowsAsynchronousSocketChannelImpl.java:914) [rt.jar:1.7.0_76] at sun.nio.ch.AsynchronousSocketChannelImpl.write(AsynchronousSocketChannelImpl.java:381) [rt.jar:1.7.0_76] at sun.nio.ch.AsynchronousSocketChannelImpl.write(AsynchronousSocketChannelImpl.java:398) [rt.jar:1.7.0_76] at org.apache.tomcat.util.net.NioChannel.write(NioChannel.java:978) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1] at org.apache.coyote.http11.InternalNioOutputBuffer$1.completed(InternalNioOutputBuffer.java:231) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1] at org.apache.coyote.http11.InternalNioOutputBuffer$1.completed(InternalNioOutputBuffer.java:200) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1] at sun.nio.ch.Invoker.invokeUnchecked(Invoker.java:126) [rt.jar:1.7.0_76] at sun.nio.ch.Invoker$2.run(Invoker.java:218) [rt.jar:1.7.0_76] at sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112) [rt.jar:1.7.0_76] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_76] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_76] at org.apache.tomcat.util.net.NioEndpoint$DefaultThreadFactory$1$1.run(NioEndpoint.java:1249) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1] at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_76] </code></pre> <p>This error can't be caught by try-catch block.</p> <p>If I remove <code>socket.close()</code>, this error never occurs.</p> <p>Anybody knows why? How should I solve this? Or is there a way to catch this exception?</p> <p>Thanks in advance!</p> <p>***************** <strong>UPDATE</strong> **********************</p> <p>The socket needs to be closed.</p> <p>Is there a callback method that I can invoke when the fire operation completes?</p>
1
Incomplete type error when using std::vector with structs
<p>I'm working with c++ STL vectors, and have a vector of structures called <em>projectileList.</em> I'm trying to iterate through the vector, getting and setting values in the struts as I iterate, but my code refuses to compile, with the error 'Incomplete type is not allowed.'</p> <p>Can anyone please point out what I'm doing wrong:</p> <p>Code:</p> <p>ProjectHandeler.h:</p> <pre><code>#include "stdafx.h" #include "DataTypes.h" #include &lt;vector&gt; class ProjectileHandeler { private: int activeObjects; std::vector&lt;projectile&gt; projectileList; void projectileUpdater(); public: ProjectileHandeler(projectile* input[], int projectileCount); ~ProjectileHandeler(); }; #endif </code></pre> <p>projectileHandeler.cpp</p> <pre><code>#include "stdafx.h" #include "DataTypes.h" #include "ProjectHandeler.h" #include &lt;vector&gt; ProjectileHandeler::ProjectileHandeler(projectile* input[], int projectileCount) { for (int i = 0; i &lt; projectileCount; i++) { projectileList.push_back(*input[i]); activeObjects += 1; } //NO extra slots. Not that expensive. projectileList.resize(projectileList.size()); } void ProjectileHandeler::projectileUpdater() { while (true) { for (unsigned int i = 0; i &lt; projectileList.size(); i++) { if (projectileList[i].isEditing == true) break; } } } </code></pre>
1
Google Cloud Pub/Sub Node.js Sample: TypeError: Cannot read property 'on' of null
<p>I'm using GCP and I want to use Cloud Pub/Sub. I got this error below when I tried Node.js sample. Does anyone knows how to fix it?</p> <pre><code>/private/tmp/pubsub/pubsubsample.js:26 subscription.on('error', onError); ^ TypeError: Cannot read property 'on' of null at /private/tmp/pubsub/pubsubsample.js:26:15 at /private/tmp/pubsub/node_modules/gcloud/lib/pubsub/index.js:474:7 at Object.handleResp (/private/tmp/pubsub/node_modules/gcloud/lib/common/util.js:113:3) at /private/tmp/pubsub/node_modules/gcloud/lib/common/util.js:422:12 at Request.onResponse [as _callback] (/private/tmp/pubsub/node_modules/gcloud/node_modules/retry-request/index.js:106:7) at Request.self.callback (/private/tmp/pubsub/node_modules/gcloud/node_modules/request/request.js:198:22) at emitTwo (events.js:87:13) at Request.emit (events.js:172:7) at Request.&lt;anonymous&gt; (/private/tmp/pubsub/node_modules/gcloud/node_modules/request/request.js:1035:10) at emitOne (events.js:82:20) </code></pre> <p><a href="https://github.com/GoogleCloudPlatform/gcloud-node" rel="nofollow noreferrer">https://github.com/GoogleCloudPlatform/gcloud-node</a></p> <pre><code>var gcloud = require('gcloud'); // Authenticating on a per-API-basis. You don't need to do this if you // auth on a global basis (see Authentication section above). var pubsub = gcloud.pubsub({ projectId: 'xxxxx', keyFilename: 'xxx.json' }); // Reference a topic that has been previously created. var topic = pubsub.topic('info'); // Publish a message to the topic. topic.publish({ data: 'New message!' }, function(err) {}); // Subscribe to the topic. topic.subscribe('new-subscription', function(err, subscription) { // Register listeners to start pulling for messages. function onError(err) {} function onMessage(message) {} subscription.on('error', onError); subscription.on('message', onMessage); // Remove listeners to stop pulling for messages. subscription.removeListener('message', onMessage); subscription.removeListener('error', onError); }); </code></pre> <p>... I'm using now PubSub but I'm thinking whether I can do same thing by using Google Cloud PubSub.</p> <p>This post may be relevant. <a href="https://stackoverflow.com/questions/30677889/node-js-on-google-cloud-platform-pub-sub-tutorial-worker-is-failing-with-typeer">Node.js on Google Cloud Platform Pub/Sub tutorial worker is failing with &quot;TypeError: Cannot call method &#39;on&#39; of null&quot;</a></p> <hr> <p>Update 1</p> <p>I changed to this code but same error was showed. </p> <p>(error)</p> <pre><code>subscription.on('error', onError); ^ TypeError: Cannot read property 'on' of null </code></pre> <p>(code)</p> <pre><code>// Subscribe to the topic topic.subscribe('new-subscription', function(err, subscription) { if( err ) { // something went wrong, react! return; } // Register listeners to start pulling for messages. function onError(err) {} function onMessage(message) {} subscription.on('error', onError); subscription.on('message', onMessage); // Remove listeners to stop pulling for messages. subscription.removeListener('message', onMessage); subscription.removeListener('error', onError); }); </code></pre> <hr> <p>Update 2</p> <p>My expectation is this below.</p> <ol> <li>execute "node pubsub.js"</li> <li>I can see the sample message 'New message!'</li> </ol>
1
How do I run maven-jdeps-plugin on a pom.xml?
<p>In my <code>pom.xml</code> I've added the maven-jdeps-plugin:</p> <pre><code>&lt;project ...&gt; &lt;groupId&gt;org.optaplanner&lt;/groupId&gt; &lt;artifactId&gt;optaplanner-examples&lt;/artifactId&gt; &lt;!-- packaging is the default, so "jar" --&gt; ... &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-jdeps-plugin&lt;/artifactId&gt; &lt;version&gt;3.0.0&lt;/version&gt; &lt;goals&gt; &lt;goal&gt;jdkinternals&lt;/goal&gt; &lt;goal&gt;test-jdkinternals&lt;/goal&gt; &lt;/goals&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>but when I run this with JDK 8 and maven 3.3.3, <strong>the jdeps plugin does not do any checks</strong>:</p> <pre><code>$ mvn clean install -DskipTests | grep plugin [INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ optaplanner-examples --- [INFO] --- maven-enforcer-plugin:1.4:enforce (enforce-plugin-versions) @ optaplanner-examples --- [INFO] --- maven-enforcer-plugin:1.4:enforce (enforce-java-version) @ optaplanner-examples --- [INFO] --- maven-enforcer-plugin:1.4:enforce (enforce-maven-version) @ optaplanner-examples --- [INFO] --- maven-enforcer-plugin:1.4:enforce (ban-uberjars) @ optaplanner-examples --- [INFO] --- maven-checkstyle-plugin:2.15:check (validate) @ optaplanner-examples --- [INFO] --- maven-enforcer-plugin:1.4:enforce (no-managed-deps) @ optaplanner-examples --- [INFO] --- buildnumber-maven-plugin:1.3:create (get-scm-revision) @ optaplanner-examples --- [INFO] --- build-helper-maven-plugin:1.9.1:add-source (default) @ optaplanner-examples --- [INFO] --- build-helper-maven-plugin:1.9.1:parse-version (default) @ optaplanner-examples --- [INFO] --- maven-resources-plugin:2.7:resources (default-resources) @ optaplanner-examples --- [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ optaplanner-examples --- [INFO] --- maven-enforcer-plugin:1.4:enforce (enforce-direct-dependencies) @ optaplanner-examples --- [INFO] --- maven-resources-plugin:2.7:testResources (default-testResources) @ optaplanner-examples --- [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ optaplanner-examples --- [INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ optaplanner-examples --- [INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ optaplanner-examples --- [INFO] --- maven-jar-plugin:2.6:test-jar (test-jar) @ optaplanner-examples --- [INFO] --- maven-source-plugin:2.4:jar-no-fork (attach-sources) @ optaplanner-examples --- [INFO] --- maven-source-plugin:2.4:test-jar-no-fork (attach-test-sources) @ optaplanner-examples --- [INFO] --- maven-failsafe-plugin:2.18.1:integration-test (default) @ optaplanner-examples --- [INFO] --- maven-failsafe-plugin:2.18.1:verify (default) @ optaplanner-examples --- [INFO] --- maven-install-plugin:2.5.2:install (default-install) @ optaplanner-examples --- </code></pre> <p>Extra info:</p> <pre><code>$ echo $JAVA_HOME /usr/lib/jvm/java-openjdk $ /usr/lib/jvm/java-openjdk/bin/java -version openjdk version "1.8.0_71" OpenJDK Runtime Environment (build 1.8.0_71-b15) OpenJDK 64-Bit Server VM (build 25.71-b15, mixed mode) </code></pre>
1
How to Create CaffeDB training data for siamese networks out of image directory
<p>I need some help to create a CaffeDB for siamese CNN out of a plain directory with images and label-text-file. Best would be a python-way to do it.<br> The problem is not to walk through the directory and making pairs of images. My problem is more of making a CaffeDB out of those pairs.<br> So far I only used <a href="https://stackoverflow.com/a/31431716/1714410"><code>convert_imageset</code></a> to create a CaffeDB out of an image directory.<br> Thanks for help!</p>
1
100% Width of a table not filling the page
<p>I've made a table to act as a frame to lay my website out on but when I set the width of it to 100% and put a background on it I have an edge on the right hand side that won't fill.</p> <p>Checkout my website linked to my profile and click on the altwebsite 2 link for what im getting.</p> <p>Here is the code:</p> <pre><code>&lt;table id="maintable"&gt; &lt;tr id="firstrow"&gt; &lt;th id="header" colspan="3"&gt; &lt;/th&gt; &lt;/tr&gt; &lt;tr id="menu" colspan="3"&gt; &lt;td&gt; &lt;?php include 'pagecontent/link.php'; ?&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr id="secondrow"&gt; &lt;td id="leftcol"&gt; &amp;nbsp; &lt;/td&gt; &lt;td id="maincol"&gt; &lt;?php include 'pagecontent/main.php'; ?&gt; &lt;/td&gt; &lt;td id="rightcol"&gt; &amp;nbsp; &lt;/td&gt; &lt;td id="footer" colspan="3"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>and the css:</p> <pre><code>html, body { height: 100%; margin: 0; padding: 0; text-align: center; } table { text-align: center; border-width: 0; border-style: none; border-spacing: 0; border-collapse: collapse; padding: 0; width: 100%; } </code></pre> <p>I'am trying to keep it all in a separate stylesheet.</p> <p>Any help would be brilliant thanks</p>
1
django cannot connect to RDS postgresql
<p>My Django application cannot connect to RDS PostgreSQL when it deployed to EC2. but oddly, it works fine when it running in my desktop.</p> <p>EC2 server and desktop were configured with python3, django1.9, apache2, and mod_wsgi_py3</p> <p>here is my <code>settings.py</code> database settings:</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'some_name', 'PASSWORD': 'some_password', 'HOST': 'myhostname.cltlezrr85xn.ap-northeast-1.rds.amazonaws.com', 'PORT': 5432, } } </code></pre> <p>and error.log from apache2:</p> <pre><code>Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.4/dist-packages/django/db/backends/postgresql/base.py", line 175, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.4/dist-packages/psycopg2/__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) psycopg2.OperationalError: could not connect to server: Connection timed out Is the server running on host "myhostname.cltlezrr85xn.ap-northeast-1.rds.amazonaws.com" (172.--.--.---) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.4/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.4/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 52, in execute return super(Command, self).execute(*args, **options) File "/usr/local/lib/python3.4/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.4/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 86, in handle default_username = get_default_username() File "/usr/local/lib/python3.4/dist-packages/django/contrib/auth/management/__init__.py", line 189, in get_default_username auth_app.User._default_manager.get(username=default_username) File "/usr/local/lib/python3.4/dist-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py", line 381, in get num = len(clone) File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py", line 240, in __len__ self._fetch_all() File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py", line 1074, in _fetch_all self._result_cache = list(self.iterator()) File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py", line 52, in __iter__ results = compiler.execute_sql() File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/compiler.py", line 846, in execute_sql cursor = self.connection.cursor() File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", line 204, in _cursor self.ensure_connection() File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/usr/local/lib/python3.4/dist-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python3.4/dist-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.4/dist-packages/django/db/backends/postgresql/base.py", line 175, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.4/dist-packages/psycopg2/__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "myhostname.cltlezrr85xn.ap-northeast-1.rds.amazonaws.com" (172.--.--.---) and accepting TCP/IP connections on port 5432? </code></pre> <p>thanks for suggestions..</p>
1
Bind or "connect" QUdpSocket to remote host and port?
<p>I would like to "connect" QUdpSocket to a remote host-port, but fail to do so. Is it possible?</p> <p>The scenario I would like to implement is the following:</p> <p>1) The server binds to localhost/port:</p> <pre><code>// On server side, let server IP be "192.168.0.235" serverUdpSocket-&gt;connectToHost(QHostAddress(QHostAddress::LocalHost), 44444); ... // check if connection is ok, etc serverUdpSocket-&gt;write(someByteArray); </code></pre> <p>2) The client reads data from server, I tried:</p> <pre><code>// bind fails with SocketAddressNotAvailableError udpSocket-&gt;bind(QHostAddress("192.168.0.235"), 44444); </code></pre> <p>and this way:</p> <pre><code>udpSocket-&gt;connectToHost(QHostAddress("192.168.0.235"), 44444, QIODevice::ReadOnly); // State becomes "Connected", but I don't get any data and `readyRead()` // is never emitted, though I connected to it. </code></pre> <p>but it doesn't work.</p> <p>I know that UDP is a connectionless protocol. A also managed to do it vice versa - bind to local host and send data to this host from another. But I'm interested in this way of doing it, as remote host might be a server providing audio stream, that I want to read with my code.</p> <p>In examples and tutorials I only see binding to local port and reading data from it. No examples with binding to remote host-port provided.</p>
1
Uncaught TypeError: Cannot read property 'split' of undefined in jquery call back function
<p>I have very big trouble with <code>$.post()</code> callback. This function return some value, but when I look for its type (<code>back.type</code>) it returns "defined" and I have error loop that increase every second and it cause problems.</p> <pre><code>function upMessage() { var id = $(".id").val(); var data = "id=" + id; $.post("ajax/upMessage.php", { id: id }, function(back) { back = back.split(","); for (var i = 0; i &lt;= (parseInt(back.length)) + 1; i++) { var backing = back[i]; backing = backing.split("*"); if (backing != "he," &amp;&amp; backing != undefined &amp;&amp; backing != "") { var id = backing[0]; var oxu = backing[1]; if (oxu == "he") { oxu = "&lt;i class=\"fa fa-check\" style=\"color:#2B85DB;margin-right:-7px\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-check\" style=\"color:#2B85DB;\"&gt;&lt;/i&gt;"; } else { oxu = "&lt;i class=\"fa fa-check\" style=\"margin-right:-7px\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-check\"&gt;&lt;/i&gt;"; } $("span#r" + id + ".i").html(oxu); } } }); } setInterval(upMessage, 700); </code></pre> <p>I have error loop in page. For example. <a href="http://masters.az" rel="nofollow">http://masters.az</a> login:leo pass:12345</p>
1
C code to check if command line is redirected to /dev/null
<p>I'm writing a C program that outputs to <code>stdout</code> and errors to <code>stderr</code>. The program takes a command such as:</p> <pre><code>./myprogram function_to_run file_to_read </code></pre> <p>My program can either output to <code>stdout</code> or be directed to output a file, but it must not be redirected to <code>/dev/null</code>. For example:</p> <pre><code>./myprogram function_to_run file_to_read //OK ./myprogram function_to_run file_to_read &gt; file.txt //OK ./myprogram function_to_run file_to_read &gt; /dev/null // NOT OK, should produce error in stderr </code></pre> <p>I tried to use <code>isatty(1)</code>, but it only can detect if <code>stdout</code> is outputting to a terminal. Therefore, it fails for the case where <code>stdout</code> is redirected to a file, which is acceptable in my case</p> <p>Is there a way to check for this in C? If not, any suggestion how I could check for the /dev/null scenario?</p>
1
Spring JSP Checkboxes on List Object
<p>I am trying to use the <code>&lt;checkboxes&gt;</code> tag on a List Object. But despite reading the mykong tutorial and searching elsewhere, i can't figure out how that is done.</p> <p>So here is what i want to do: I have a class like</p> <pre><code> class Person{ List&lt;IceCreams&gt; creams; } </code></pre> <p>So now i want to give my User a form where he can choose which IceCreams he likes. </p> <p>Controller:</p> <pre><code>@Controller public class IceCreamController{ @RequestMapping(value="icecream", method=RequestMethod.GET) public String showPage(Model model){ Person person = repository.getPerson(); //Returns a Person, "creams" is not empty model.addAttribute("creams", person.getIceCreams(); } @RequestMapping(value="icecream", method=RequestMethod.POST) public String showPage( @ModelAttribute("teilnehmer") List&lt;IceCreams&gt; likedCreams, Model model){ //do something with selected iceCreams } </code></pre> <p>Now i don't understand how to continue in the JSP. I know i have to use the checkboxes tag, but i do not know what it returns on submit or if i use it correctly.</p> <pre><code>&lt;form:form&gt; &lt;form:checkboxes path="creams" items="${creams}"/&gt; &lt;input type="Submit" value="Submit"&gt; &lt;/form:form&gt; </code></pre> <p>So the question is: What do I write in the JSP and what will be returned to the controller?</p> <p>Added after comment: IceCream class:</p> <pre><code> public class IceCream{ private long id; private String creamName; </code></pre> <p>//+getters/setters }</p> <hr> <p>EDIT: After a helpful answer i tried this: Adding those to the model: </p> <pre><code>model.addAttribute("person", person); model.addAttribute("creams", person.getCreams()); </code></pre> <p>and in the JSP i did </p> <pre><code>&lt;form:checkboxes path="teilnehmer" items="${creams}" itemValue="id" itemLabel="creamName" /&gt; </code></pre> <p>So in the POST-Method i take a ModelAttribute Person.</p> <p>added to Controller: </p> <pre><code>@InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { binder.registerCustomEditor(IceCream.class, new IceCreamsPropertyEditor()); </code></pre> <p>and the new Editor class:</p> <pre><code>public class ContactsPropertyEditor extends PropertyEditorSupport{ @Autowired IceCreamRepository creamrep; @Override public void setAsText(String text) throws IllegalArgumentException { Integer creamId = new Integer(text); IceCream cream = creamrep.findOne(creamId); super.setValue(con); } } </code></pre> <p>Sadly the result is Error 400.</p>
1
Copy merged cells VBA
<p>I am trying to copy entire rows onto a new worksheet, but only copy those rows where a childs age is above 20.</p> <p>I have not yet written the If statements to select these rows, but have written code to import the data and fill in various columns in order to get the 20th birthday from the birth date.</p> <p>My problem is that the cells in the columns that are on the imported worksheet are merged. This is merged because one person may have more than one child, so in this case, the cells regarding the parent are merged. It won't let me copy the merged cells.</p> <p>For now I'm just trying to work out how to copy the entire sheet just so I know how to copy merged cells, before doing the If statement.</p> <p>This is what I have so far (bold bit at bottom is where I'm trying to copy merged cells. I'm getting an error on the line with ActiveSheet.Range("**").MergeArea.Copy</p> <pre><code>Option Explicit Sub ImportActiveList() Dim FileName As String Dim WS1 As Worksheet Dim WS2 As Worksheet Dim ActiveListWB As Workbook Set WS2 = ActiveWorkbook.Sheets("Sheet1") FileName = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*),*.xls*", _ Title:="Select Active List to Import", _ MultiSelect:=False) If FileName = "False" Then Exit Sub Else Set ActiveListWB = Workbooks.Open(FileName) End If Set WS1 = ActiveListWB.Sheets("Page1-1") WS1.UsedRange.Copy WS2.Range("A1") ActiveWorkbook.Close False End Sub Sub CalculateBirthday() Dim lastrow As Long lastrow = Range("X" &amp; Rows.Count).End(xlUp).Row ActiveSheet.Range("A5:AA291").AutoFilter ActiveSheet.Range("$A$5:$AA$291").AutoFilter Field:=24, Criteria1:="Child" Range("AB5") = "Today's Age Year/Month" Range("AB7:AB" &amp; lastrow).Formula = "=DATEDIF(RC[-2],TODAY(),""Y"") &amp; "" Years, "" &amp; DATEDIF(RC[-2],TODAY(),""YM"") &amp; "" Months """ Columns("AB:AB").EntireColumn.AutoFit Range("AC5") = "Today's Age Year Only" Range("AC7:AC" &amp; lastrow).Formula = "=DATEDIF(RC[-3],TODAY(),""Y"")" Columns("AC:AC").EntireColumn.AutoFit Range("AD5") = "Child 20th Birthday" Range("AD7:AD" &amp; lastrow).Formula = "=DATE(YEAR(R[-1]C[-4])+20, MONTH(R[-1]C[-4]),DAY(R[-1]C[-4]))" Columns("AD:AD").EntireColumn.AutoFit ActiveSheet.Range("A5:AA291").MergeArea.Copy 'copies the merged cells Sheet2.Range("A1").PasteValues ' pastes what was copied into A1 on Sheet 2 and any merged cells** End Sub </code></pre>
1
Multiple Slim routes with the same signature
<p>We are looking at using Slim 3 as the framework for our API. I have searched SO and the Slim docs, but cannot find an answer to the issue. If we have different route files (e.g. v1, v2, etc.) and if two routes have the same signature, an error is thrown. Is there any way to cascade the routes so that the last loaded route for a particular signature is used?</p> <p>For example, say v1.php has a route for <code>GET ("/test")</code> and v2.php also contains this route, can we use the latest version? Even simpler would be if a file of routes contains two routes with the same signature, is there a way of the latter method being used (and no error being thrown)?</p> <p>A similar question is asked <a href="http://help.slimframework.com/discussions/questions/2634-overwrite-applied-routes-before-run" rel="nofollow">here</a> but this uses hooks (which have been removed from Slim 3 as per <a href="http://www.slimframework.com/docs/start/upgrade.html" rel="nofollow">here</a>)</p>
1
Excel VBA loop through a string of numbers until a letter is found
<p>I have a string in a cell, lets say it says "Client Ref: F123456PassPlus". It's possible the string not have a letter before the numbers, it's possible there is a symbol in the numbers and it's possible there is a space between the letter and the numbers. I need to extract only the numbers as a variable. I have the code to do it, but it doesn't know when to stop looping through the string. It should stop when there is something other than a number or symbol but it carries on instead.</p> <pre><code>IsNumber = 1 ref = "" If branch = "" Then e = b Else e = b + 1 End If f = 1 While IsNumber = 1 For intpos = 1 To 15 ref = Mid(x, e, f) f = f + 1 Select Case Asc(ref) Case 45 To 57 IsNumber = 1 Case Else IsNumber = 0 Exit For End Select Next IsNumber = 0 Wend </code></pre> <p>Any variable letters there that don't have definitions have been previously defined, e tells the code where to start copying and x is the cell that contains the string. For now, it all works fine, it starts at the number and copies them and builds them into a bigger and bigger string, but it will only stop when intpos reaches 15.</p>
1
HTML range element to control volume of audio element
<p>I'm trying to use the HTML range element to control the volume of an HTML audio element but running into some problems. </p> <p>The setVolume function below is only one line and seemed to work in another answer on this site, and alongside the error I am getting ("Uncaught ReferenceError: setVolume is not defined") I feel like I am having trouble activating the function in the first place. </p> <p>Anyone have any ideas?</p> <p>Relavent HTML:</p> <pre><code>&lt;div class="slides"&gt; &lt;div class="slider-cont"&gt; &lt;input type="range" onchange="setVolume()" id='volume1' min=0 max=1 step=0.01 value='0.30'&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Script for the audio player:</p> <pre><code>window.onload = function() { var audioPlayer = function() { var rainPlaying = false; var playRain = document.getElementById('playRain'); var rainAudio = new Audio('audio/rain1.ogg'); rainAudio.id = "rainLoop"; rainAudio.loop = true; playRain.addEventListener('click', function() { if (rainPlaying) { rainPlaying = false; rainAudio.pause(); } else { rainPlaying = true; rainAudio.play(); } }, false); var setVolume = function() { rainAudio.volume = document.getElementById("volume1").value; }; }(); }; </code></pre>
1
Selecting characters in string numpy array (Python)
<p>I have a numpy.ndarray of strings like that</p> <pre><code>HHMM = ['0000' '0001' '0002' '0003' '0004' '0005' '0006' '0007' '0008' '0009' ...] </code></pre> <p>Here the first two elements are the hour and the last two the minute. In order to convert to time format (using datetime), I want to separate this characters.</p> <p>I tried doing </p> <pre><code>hour = HHMM[::][0:2] minute = HHMM[::][2:4] </code></pre> <p>but the result is this</p> <pre><code>print hour ['0000' '0001'] print minute ['0002' '0003'] </code></pre>
1
how to make custom keyboard with multiple language..?
<p>I want to make custom keyboard in my app that supports multiple languages. By clicking the language button, it shows a particular language keyboard and display it in chat.</p>
1
Inline assembler: Pass a constant
<p>I have the following problem: I want to use the following assembler code from my C source files using inline assembler:</p> <pre><code>.word 1 </code></pre> <p>The closest I've gotten is using this inline assembler code:</p> <pre><code>asm(".word %0\n": : "i"(1)); </code></pre> <p>However, this results in the following code in the generated assembler file:</p> <pre><code>.word #1 </code></pre> <p>So I need a way to pass a constant that is known at compile time without adding the '#' in front of it. Is this possible using inline assembler?</p> <p><strong>Edit:</strong></p> <p>To make it more clear why I need this, this is how it will be used:</p> <pre><code>#define LABELS_PUT(b) asm(".word %0\n": : "i"((b))); int func(void) { LABELS_PUT(1 + 2); return 0; } </code></pre> <p>I can't use ".word 1" because the value will be different every time the macro LABELS_PUT is called.</p>
1
HTML5 video screenshot via canvas using CORS
<p>I have an issue getting screenshots of videos in Chrome, and I've exhausted all the internets and all Stackoverflow answers on it; no luck.</p> <p>No matter what I try, when I try to use the <code>canvas</code> element to take a screenshot of a video that is on a different domain, or even just a different port, then I end up with a <code>Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.</code> error.</p> <p>Here is my setup:</p> <p><strong>Web app URL</strong><br/> <a href="http://client.myapp.com/home.html" rel="noreferrer">http://client.myapp.com/home.html</a></p> <p><strong>CDN URLs (I've tried both)</strong><br/> <a href="http://client.myapp.com:8181/somevideo.mp4" rel="noreferrer">http://client.myapp.com:8181/somevideo.mp4</a><br/> <a href="http://cdn.myapp.com/somevideo.mp4" rel="noreferrer">http://cdn.myapp.com/somevideo.mp4</a></p> <p>Headers sent back with MP4 from CDN:</p> <pre><code>Accept-Ranges:bytes Access-Control-Allow-Origin:* Access-Control-Expose-Headers:x-ms-request-id,Server,x-ms-version,Content-Type,Last-Modified,ETag,x-ms-lease-status,x-ms-lease-state,x-ms-blob-type,Accept-Ranges,Content-Length,Date,Transfer-Encoding Content-Length:5253832 Content-Range:bytes 48-5253879/5253880 Content-Type:video/mp4 Date:Sat, 06 Feb 2016 17:24:05 GMT ETag:"0x8D32E3EDB17EC00" Last-Modified:Fri, 05 Feb 2016 15:13:08 GMT Server:Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0 x-ms-blob-type:BlockBlob x-ms-lease-state:available x-ms-lease-status:unlocked x-ms-request-id:88d3aaef-0629-4316-995f-021aa0153c32 x-ms-version:2015-04-05 </code></pre> <p>I have:</p> <ul> <li>Added <code>crossOrigin="anonymous"</code> to the video element, but this just makes the video fail to load altogether</li> <li>Tried even the same domain on a different port (as above)</li> <li>Ensured that <code>Access-Control-Allow-Origin</code> is coming back with <code>*</code> (as above)</li> <li>I don't believe it is DRM as the screenshot works fine if I copy the exact same video file to the web app and load it locally</li> <li>Run through all answers to <a href="https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror">this question</a>, but this is for images not videos anyway and the answers only describe all the previous points</li> </ul> <p>Yet, still the blasted error.</p> <p><strong>Edit</strong><br/> Added code:</p> <pre><code>var getScreenshotDataUrl = function(video, canvas, type) { type = type || "image/jpeg"; var context = canvas.getContext("2d"); var w = video.videoWidth; var h = video.videoHeight; canvas.width = w; canvas.height = h; context.fillRect(0, 0, w, h); context.drawImage(video, 0, 0, w, h); video.crossorigin = "anonymous";// makes no difference return canvas.toDataURL(type); } </code></pre> <p>Please help.</p>
1
Laravel 5.2 Login Event Handling
<p>In the database I have a table users with column last_login_at. Everytime when some user logs in - I want to uptade <em>last_login_at</em>. </p> <p>So, I created app/Listeners/<strong>UpdateLastLoginOnLogin.php</strong>:</p> <pre><code>namespace App\Listeners; use Carbon\Carbon; class UpdateLastLoginOnLogin { public function handle($user, $remember) { $user-&gt;last_login_at = Carbon::now(); $user-&gt;save(); } } </code></pre> <p>In app/Providers/EventServiceProvider:</p> <pre><code> protected $listen = [ 'auth.login' =&gt; [ 'App\Listeners\UpdateLastLoginOnLogin', ], ]; </code></pre> <p>BUT this doesn't work, event is not handled. The same problem has already been mentioned here: <a href="https://stackoverflow.com/questions/34974192/eventserviceprovider-mapping-for-laravel-5-2-login">EventServiceProvider mapping for Laravel 5.2 login</a> but without solution. I have tried to do like this:</p> <p>...</p> <pre><code>use Illuminate\Auth\Events\Login; class UpdateLastLoginOnLogin { public function handle(Login $event) { $event-&gt;user-&gt;last_login_at = Carbon::now(); $event-&gt;user-&gt;save(); } } </code></pre> <p>and:</p> <pre><code>protected $listen = [ 'Illuminate\Auth\Events\Login' =&gt; [ 'App\Listeners\UpdateLastLoginOnLogin', ], ]; </code></pre> <p>But it doesn't work.</p> <p>Also, I checked this: <a href="https://laracasts.com/discuss/channels/general-discussion/login-event-handling-in-laravel-5" rel="nofollow noreferrer">https://laracasts.com/discuss/channels/general-discussion/login-event-handling-in-laravel-5</a> but <strong>php artiasn clear-compiled</strong> didn't solve the problem.</p> <p><strong>EDIT:</strong> FOR OTHER DETAILS, HERE'S A LINK TO THE PROJECT which is actually exactly the same (it is done in the same way): <a href="https://github.com/tutsplus/build-a-cms-with-laravel" rel="nofollow noreferrer">https://github.com/tutsplus/build-a-cms-with-laravel</a></p>
1
Successful Ajax call not returning data
<p>I'm trying to work on a simple Ajax call and I'm unable to figure out what's gone wrong. The ajax call is successful but nothing is alerting. When I console.log(myStats), it displays the JSON in my console though.</p> <pre><code>var main = function(){ $.ajax({ type: 'GET', url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&amp;appid=2de143494c0b295cca9337e1e96b00e0', success: function(data) { var myStats = JSON.parse(data); alert(myStats); }, error: function(){ alert('error'); } }); }; $(document).ready(main); </code></pre>
1
Jquery check for multiple classes (All must be present) in an element
<p>Hi I am trying to check if an element has the classes I am finding ex:</p> <pre><code>&lt;span class="foo bar me"&gt;&lt;/span&gt; </code></pre> <p>I want to check if the <code>foo</code> and <code>me</code> class is present on that element so I used this:</p> <pre><code>$('body span').hasClass('me', 'foo') </code></pre> <p>this foo and me is stored in an array but this one didn't work:</p> <pre><code>var arrayName = ['me', 'foo']; $('body span').hasClass(arrayName) </code></pre> <p>the classes I am finding is dynamic that's why it is stored in an array, how can pass the dynamic array like the this one <code>'me', 'foo'</code> to the hasClass function?</p> <p><strong><em>Note:</em></strong> the array can have 2-4 values in it.</p> <p>I had my work here: <a href="https://jsfiddle.net/pcbttntk/" rel="nofollow">https://jsfiddle.net/pcbttntk/</a></p> <p>Thanks in Advance.</p> <p><strong><em>Update:</em></strong> <code>$('body span').hasClass('me', 'foo')</code> is not working, thanks to brett and Roko, it only checks the first class passed to it.</p>
1
Elasticsearch to index RDBMS data
<p>These are three simple questions which was surprisingly hard to find definite answers. </p> <ol> <li>Does ElasticSearch support indexing data in RDBMS tables ( Oracle/SQLServer/Informix) out of the box?</li> <li>If yes, can you please point me to documentation on how to do it</li> <li>If not, what are alternate ways (plugins like Rivers - deprecated) with good reputation</li> </ol>
1
GetElementById in AngularJS
<p>What is the equivalent of <code>document.getElementByName</code> AngularJS ? I'm doing the edit portion of the form using AngularJS, and wanted to inject the values ​​obtained od database within an input . After that would edit the input content and subsequently perform <code>ALTER TABLE</code>. The backend is in PHP.</p> <p><strong>EDit</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html ng-app="myCrud"&gt; &lt;head&gt; &lt;title&gt;CRUD AngularJS&lt;/title&gt; &lt;meta charset="utf-8" /&gt; &lt;meta name="format-detection" content="telephone=no" /&gt; &lt;meta name="msapplication-tap-highlight" content="no" /&gt; &lt;!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 --&gt; &lt;meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /&gt; &lt;script type="text/javascript" src="angular/angular.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" type="text/css" href="bootstrap/bootstrap.css"&gt; &lt;style&gt; .jumbotron { text-align: center; margin-left: auto; margin-right: auto; } .table { margin-top: 20px; } .form-control { margin-bottom: 5px; } &lt;/style&gt; &lt;script type="text/javascript"&gt; angular.module("myCrud", []); angular.module("myCrud").controller("myCrudCtrl", function ($scope, $http) { $scope.tit = "CRUD AngularJS e PHP"; $scope.adicionarUsuario = function (usuario) { $http.post("salvar.php", usuario).success(function (data){ delete $scope.usuario; $scope.usuarioForm.$setPristine(); carregarUsuario(); }); }; var carregarUsuario = function () { $http.get("buscar.php").then(function (retorno){ console.log(retorno.data); $scope.usuarios = retorno.data; }); }; $scope.editarUsuario = function (usuario){ $scope.messagem = usuario.nome; /* $http.post("editar.php", usuario).success(function (data){ delete $scope.usuario; $scope.usuarioForm.$setPristine(); carregarUsuario(); }); */ //////////////////////////////////THE QUESTION POINT }; $scope.apagarUsuario = function (usuario) { $http.delete("apagar.php", {params: {id: usuario}}).success(function (data, status){ carregarUsuario(); $scope.messagem(data.msg); }); }; $scope.ordenarPor = function (campo) { $scope.criterioDeOrdenacao = campo; $scope.direcaoDaOrdenacao = !$scope.direcaoDaOrdenacao; }; carregarUsuario(); }); &lt;/script&gt; &lt;/head&gt; &lt;body ng-controller="myCrudCtrl"&gt; &lt;div class="jumbotron"&gt; &lt;h4&gt;{{tit}}&lt;/h4&gt; &lt;h6&gt;{{messagem}}&lt;/h6&gt; &lt;input class="form-control" type="text" ng-model="criterioDeBusca" placeholder="O que você está buscando?"/&gt; &lt;table class="table"&gt; &lt;tr&gt; &lt;td&gt;&lt;a href="" ng-click="ordenarPor('nome')"&gt;&lt;b&gt;Nome&lt;/b&gt;&lt;/a&gt;&lt;/td&gt; &lt;td&gt;&lt;a href="" ng-click="ordenarPor('email')"&gt;&lt;b&gt;Email&lt;/b&gt;&lt;/a&gt;&lt;/td&gt; &lt;td&gt;&lt;b&gt;Password&lt;/b&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr ng-repeat="usuario in usuarios | filter:criterioDeBusca | orderBy:criterioDeOrdenacao:direcaoDaOrdenacao"&gt; &lt;td&gt;{{usuario.nome}}&lt;/td&gt;&lt;!-- &lt;a href="#" editable-text="usuario.name"&gt;{{ usuario.name || "empty" }}&lt;/a&gt;--&gt; &lt;td&gt;{{usuario.email}}&lt;/td&gt; &lt;td&gt;{{usuario.pass}}&lt;/td&gt; &lt;td&gt;&lt;button class="btn btn-xs btn-alert" ng-click="editarUsuario(usuario)"&gt;Editar&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button class="btn btn-xs btn-danger" ng-click="apagarUsuario(usuario.id)"&gt;Apagar&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;hr&gt; &lt;form name="usuarioForm"&gt; &lt;input class="form-control" id="inputnome" type="text" ng-model="usuario.nome" placeholder="Nome"&gt; &lt;input class="form-control" type="text" ng-model="usuario.email" placeholder="Email"&gt; &lt;input class="form-control" type="text" ng-model="usuario.pass" placeholder="Senha"&gt; &lt;/form&gt; &lt;button class="btn btn-primary" ng-click="adicionarUsuario(usuario)"&gt;Adicionar&lt;/button&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1
How to benefit from GPU with PYMC3
<p>I see zero difference in PYMC3 speed when using GPU vs. CPU.</p> <p>I am fitting a model that requires 500K+ samples to converge. Obviously it is very slow, so I tried to speed things up with GPU (using GPU instance on EC2). Theano reports to be using GPU, so I believe CUDA/Theano are configured correctly. However, I strongly suspect that Pymc3 is not utilising GPU.</p> <ul> <li>do I need to set my variables to TensorType(float32, scalar) explicitly? Currently, they are float64.</li> <li>Are only some samplers/likelihoods can benefit from CUDA? I am fitting Poisson-based model and so using Metropolis sampler, not NUTS</li> <li>is there a way to check that pymc3 is using GPU?</li> </ul>
1
Realm not auto-deleting database if migration needed
<p>We are in development and db schema changes occur often. Since we are not live, migrations are not needed. I therefor configured Realm as follows:</p> <pre><code>RealmConfiguration config = new RealmConfiguration.Builder(context) .name("jt.realm") .schemaVersion(1) .deleteRealmIfMigrationNeeded() // todo remove for production .build(); Realm.setDefaultConfiguration(config); </code></pre> <p>However, when the schema is changed, an exception is thrown: <code>RealmMigration must be provided</code></p> <p>My understanding from the docs are that the Realm should auto-delete the db since deleteRealmIfMigrationNeeded() is present in the config, but this does not seem to be happening. Why is this occurring?</p> <p><strong>Android Studio Dependency</strong></p> <p>compile 'io.realm:realm-android:0.86.1'</p>
1
Jacoco coverage for switch statement
<p>I am working to get 100% code coverage for a library I am working on and I seem to have some issues with a switch statement and the coverage which I simply don't understand.</p> <p>I am currently using Jacoco 0.7.2 because every newer version seems to break with Robolectrics.</p> <p>I test a simple switch statement:</p> <pre><code>public enum Type { NONE, LEGACY, AKS } private static Class&lt;?&gt; getCipherClass(Type type) { switch (type) { case LEGACY: return CipherWrapperLegacy.class; case AKS: return CipherWrapperAks.class; default: return null; } } </code></pre> <p>The test I wrote contains the following checks (I have to use reflection as the method is private):</p> <pre><code>final CipherWrapper instance = CipherWrapper.createInstance(mockContext, CipherWrapper.Type.LEGACY, ALIAS); assertNotNull(instance); Method getCipherMethod = TestUtils.makeMethodAccessible(CipherWrapper.class, "getCipherClass", CipherWrapper.Type.class); assertNull(getCipherMethod.invoke(instance, CipherWrapper.Type.NONE)); assertEquals(CipherWrapperAks.class, getCipherMethod.invoke(instance, CipherWrapper.Type.AKS)); assertEquals(CipherWrapperLegacy.class, getCipherMethod.invoke(instance, CipherWrapper.Type.LEGACY)); </code></pre> <p>The result is not what I have expected:</p> <p><a href="https://i.stack.imgur.com/bVOE5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bVOE5.png" alt="Jacoco code coverage result"></a></p> <p>The image is a bit confusing as the yellow line suggests that there is something missing. The green icon tells me that 3 of 3 branches are covered.</p> <p>I also tested to extend the switch case with <code>case NONE</code> and a fall through but it didn't change anything.</p> <p>The only thing I can do is to replace the switch with if/else and then I get 100% coverage.</p> <p>Currently I have 98% coverage but I nothing is missed based on the overview: <a href="https://i.stack.imgur.com/vcR86.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vcR86.png" alt="Jacoco overall coverage"></a></p>
1
Batch file to set a PowerShell variable
<p>For some reason i simply can't understand most of the sites who explain this question. So i'll try to ask here, if i'm am in the wrong place, just tell me in the comments and i'll put this in another forum and delete this question.</p> <p>Let's say that i have 2 files, <code>Batch.bat</code> and <code>PowerShell.ps1</code>. </p> <p><strong><em>Batch.bat:</em></strong></p> <pre><code>set A="ThisIsSuchVar!" </code></pre> <p><strong><em>PowerShell.ps1:</em></strong></p> <pre><code>$B = "Well, i don't know what to do here" </code></pre> <p>What can i do to the <code>B</code> variable be the same as the <code>A</code> variable?</p> <p>Remember: I want the Batch variable to go to the PowerShell file. It's an one-way script. I want to use the built-in windows sources. And please, consider that i am a complete newbie in programming and don't speak english very well, so be the simplest possible, please.</p>
1
Create new column from an existing column with pattern matching in R
<p>I'm trying to add a new column based on another using pattern matching. I've read <a href="https://stackoverflow.com/questions/29566343/create-a-new-column-in-a-r-dataframe-using-pattern-matching">this post</a>, but not getting the desired output. </p> <p>I want to create a new column (SubOrder) based on the GreatGroup column. I have tried the following: </p> <pre><code>SubOrder &lt;- rep(NA_character_, length(myData)) SubOrder[grepl("udults", myData, ignore.case = TRUE)] &lt;- "Udults" SubOrder[grepl("aquults", myData, ignore.case = TRUE)] &lt;- "Aquults" SubOrder[grepl("aqualfs", myData, ignore.case = TRUE)] &lt;- "aqualfs" SubOrder[grepl("humods", myData, ignore.case = TRUE)] &lt;- "humods" SubOrder[grepl("udalfs", myData, ignore.case = TRUE)] &lt;- "udalfs" SubOrder[grepl("orthods", myData, ignore.case = TRUE)] &lt;- "orthods" SubOrder[grepl("udalfs", myData, ignore.case = TRUE)] &lt;- "udalfs" SubOrder[grepl("psamments", myData, ignore.case = TRUE)] &lt;- "psamments" SubOrder[grepl("udepts", myData, ignore.case = TRUE)] &lt;- "udepts" SubOrder[grepl("fluvents", myData, ignore.case = TRUE)] &lt;- "fluvents" SubOrder[grepl("aquods", myData, ignore.case = TRUE)] &lt;- "aquods" </code></pre> <p>For example, I'm looking for "udults" inside any word, such as Hapludults or Paleudults, and return just "udults". </p> <p>EDIT: If anyone wants to take a shot at alistaire's comment, this is the search patterns I would use. </p> <pre><code> subOrderNames &lt;- c("Udults", "Aquults", "Aqualfs", "Humods", "Udalfs", "Orthods", "Psamments", "Udepts", "fluvents") </code></pre> <p>Example data below. </p> <pre><code>myData &lt;- dput(head(test)) structure(list(1:6, SID = c(200502L, 200502L, 200502L, 200502L, 200502L, 200502L), Groupdepth = c(11L, 12L, 13L, 14L, 21L, 22L ), AWC0to10 = c(0.12, 0.12, 0.12, 0.12, 0.12, 0.12), AWC10to20 = c(0.12, 0.12, 0.12, 0.12, 0.12, 0.12), AWC20to50 = c(0.12, 0.12, 0.12, 0.12, 0.12, 0.12), AWC50to100 = c(0.15, 0.15, 0.15, 0.15, 0.15, 0.15), Db3rdbar0to10 = c(1.43, 1.43, 1.43, 1.43, 1.43, 1.43), Db3rdbar10to20 = c(1.43, 1.43, 1.43, 1.43, 1.43, 1.43), Db3rdbar20to50 = c(1.43, 1.43, 1.43, 1.43, 1.43, 1.43), Db3rdbar50to100 = c(1.43, 1.43, 1.43, 1.43, 1.43, 1.43), HydrcRatngPP = c(0L, 0L, 0L, 0L, 0L, 0L), OrgMatter0to10 = c(1.25, 1.25, 1.25, 1.25, 1.25, 1.25), OrgMatter10to20 = c(1.25, 1.25, 1.25, 1.25, 1.25, 1.25), OrgMatter20to50 = c(1.02, 1.02, 1.02, 1.02, 1.02, 1.02), OrgMatter50to100 = c(0.12, 0.12, 0.12, 0.12, 0.12, 0.12), Clay0to10 = c(8, 8, 8, 8, 8, 8), Clay10to20 = c(8, 8, 8, 8, 8, 8), Clay20to50 = c(9.4, 9.4, 9.4, 9.4, 9.4, 9.4 ), Clay50to100 = c(40, 40, 40, 40, 40, 40), Sand0to10 = c(85, 85, 85, 85, 85, 85), Sand10to20 = c(85, 85, 85, 85, 85, 85 ), Sand20to50 = c(83, 83, 83, 83, 83, 83), Sand50to100 = c(45.8, 45.8, 45.8, 45.8, 45.8, 45.8), pHwater0to20 = c(6.3, 6.3, 6.3, 6.3, 6.3, 6.3), Ksat0to10 = c(23, 23, 23, 23, 23, 23 ), Ksat10to20 = c(23, 23, 23, 23, 23, 23), Ksat20to50 = c(19.7333, 19.7333, 19.7333, 19.7333, 19.7333, 19.7333), Ksat50to100 = c(9, 9, 9, 9, 9, 9), TaxClName = c("Fine, mixed, semiactive, mesic Oxyaquic Hapludults", "Fine, mixed, semiactive, mesic Oxyaquic Hapludults", "Fine, mixed, semiactive, mesic Oxyaquic Hapludults", "Fine, mixed, semiactive, mesic Oxyaquic Hapludults", "Fine, mixed, semiactive, mesic Oxyaquic Hapludults", "Fine, mixed, semiactive, mesic Oxyaquic Hapludults"), GreatGroup = c("Hapludults", "Hapludults", "Hapludults", "Hapludults", "Hapludults", "Hapludults" )), .Names = c("", "SID", "Groupdepth", "AWC0to10", "AWC10to20", "AWC20to50", "AWC50to100", "Db3rdbar0to10", "Db3rdbar10to20", "Db3rdbar20to50", "Db3rdbar50to100", "HydrcRatngPP", "OrgMatter0to10", "OrgMatter10to20", "OrgMatter20to50", "OrgMatter50to100", "Clay0to10", "Clay10to20", "Clay20to50", "Clay50to100", "Sand0to10", "Sand10to20", "Sand20to50", "Sand50to100", "pHwater0to20", "Ksat0to10", "Ksat10to20", "Ksat20to50", "Ksat50to100", "TaxClName", "GreatGroup"), class = c("tbl_df", "data.frame"), row.names = c(NA, -6L)) </code></pre>
1
Symfony2 send a POST request to an external API and parse its XML response?
<p>How to send a POST request to an external API and parse its XML response?</p> <p>Normally using only php and xml I would do <a href="https://gist.github.com/gghhh456/d7ebc23c7c43a3697b74" rel="nofollow">something like </a>. But i am not sure how can I to do the same using Symfony.</p> <p>Also please note that the content inside the xml file is dynamic like "Itemnumber", "quantity" etc</p> <p><strong>Moreinfo:</strong></p> <p>I am trying to send the xml data to our third party client system(they just work with XML so no JSON response) and parse this XML response and show it to our customers. Well since customer request are dynamic so does the contents inside the .xml file changes every-time. So i need to figure out</p> <ol> <li>Load this dynamic .xml file.</li> <li>Make the connection using POST.</li> <li>Read the Parse Xml data which i receive from our client(which can be done easily).</li> </ol>
1
Javascript - Adding new label and data to existing array
<p>As I know, it is possible to push more data into an array. Fe, I have an array: </p> <pre><code>G = [12, 34, 5]. </code></pre> <p>Right now, I can access the nth element like this: </p> <pre><code>G[n] </code></pre> <p>I'd now like to push new data in it with a label, so I want the array to look like </p> <pre><code>G = [12, 34, 5, label:567856, other: Infinity] </code></pre> <p>where I can get 567856 by calling </p> <pre><code>G["label"] //(or Infinity by calling G["other"]). How can I achieve this? </code></pre> <p>I've found </p> <pre><code>G[i].push({ label:567856, other: Infinity }) </code></pre> <p>but this way it adds it as a whole new element, and I'm only able to call G[4]["other"], instead of G["other"]. How can I add the element as I've described?</p> <p>Thank you!</p>
1
ASP.NET: How to create a search function just using a textbox?
<p>I would like to have suggestions with regards to having a search function in my website. It will be to find the registered customers so that it will be easier for the admin to look for a specific customer.</p> <p>Can you give sample code snippets so that I can accomplish this specific search function? </p> <p>Thank you.</p> <p>Here is my .aspx code</p> <pre><code> &lt;asp:TextBox ID="txtSearch" runat="server" BorderStyle="Solid" Width="218px" ontextchanged="txtSearch_TextChanged"&gt;&lt;/asp:TextBox&gt; &amp;nbsp;&lt;asp:Button ID="btnSearch" runat="server" Text="Search" /&gt; &lt;/p&gt; &lt;div style="overflow-x:auto; width:1200px"&gt; &lt;asp:GridView ID="gvCustomer" runat="server" AutoGenerateColumns="False" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" Caption="Customer Profile" CellPadding="4" CellSpacing="2" DataSourceID="SqlDataSourceBM" ForeColor="Black" onrowcommand="gvCustomer_RowCommand" DataKeyNames="ApplicantUsername" &gt; &lt;Columns&gt; &lt;asp:BoundField DataField="Branch" HeaderText="Branch" SortExpression="Branch" /&gt; &lt;asp:BoundField DataField="ApplicantUsername" HeaderText="Username" SortExpression="ApplicantUsername" ReadOnly="True" /&gt; &lt;asp:BoundField DataField="NoAFirstName" HeaderText="First Name" SortExpression="NoAFirstName" /&gt; &lt;asp:BoundField DataField="NoALastName" HeaderText="Last Name" SortExpression="NoALastName" /&gt; &lt;asp:ButtonField CommandName="View Profile" HeaderText="Customer Profile" Text="View" /&gt; &lt;asp:ButtonField CommandName="Edit" HeaderText="Customer Profile" Text="Edit" /&gt; &lt;asp:ButtonField CommandName="View CR" HeaderText="Credit Report" Text="View" /&gt; &lt;/Columns&gt; &lt;FooterStyle BackColor="#CCCCCC" /&gt; &lt;HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" /&gt; &lt;PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" /&gt; &lt;RowStyle BackColor="White" /&gt; &lt;SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" /&gt; &lt;SortedAscendingCellStyle BackColor="#F1F1F1" /&gt; &lt;SortedAscendingHeaderStyle BackColor="#808080" /&gt; &lt;SortedDescendingCellStyle BackColor="#CAC9C9" /&gt; &lt;SortedDescendingHeaderStyle BackColor="#383838" /&gt; &lt;/asp:GridView&gt; &lt;asp:SqlDataSource ID="SqlDataSourceBM" runat="server" ConnectionString="&lt;%$ ConnectionStrings:PFCIConnectionString %&gt;" SelectCommand="SELECT [ApplicantUsername], [Branch], [NoALastName], [NoAFirstName] FROM [CustomerRegistration] WHERE (([Branch] = @Branch) AND ([NoALastName] LIKE '%' + @NoALastName + '%'))"&gt; &lt;SelectParameters&gt; &lt;asp:SessionParameter Name="Branch" SessionField="ApplicantUsername" Type="String" /&gt; &lt;asp:ControlParameter ControlID="txtSearch" Name="NoALastName" PropertyName="Text" Type="String" /&gt; &lt;/SelectParameters&gt; &lt;/asp:SqlDataSource&gt; </code></pre>
1