input
stringlengths
51
42.3k
output
stringlengths
18
55k
Sublime 3 - Add specific plugin syntax highlight for no file type <p>I'm trying to implement the solution I found here: <a href="http://stackoverflow.com/questions/38737683/how-to-change-the-default-syntax-for-new-files-in-sublime-text-3">How to change the default Syntax for new files in Sublime Text 3?</a></p> <p>But what I am unable to do is apply the specific syntax I need to use. I need the Bash Shell syntax highlighting, which sublime refers to as Shell-Unix-Generic. However when I adjust this setting outlined in the link above to "Shell-Unix-Generic" it doesn't work. I've also tried "Shell-Unix-Generic/Shell-Unix-Generic"</p> <p>Any ideas? The goal is to have every new file open with Shell syntax highlighting, instead of the default plain text.</p>
<p>The correct path to use for ApplySyntax for the bash shell syntax highlighting is <code>ShellScript/Shell-Unix-Generic</code>, as per the Package path: <a href="https://github.com/sublimehq/Packages/blob/master/ShellScript/Shell-Unix-Generic.sublime-syntax" rel="nofollow">https://github.com/sublimehq/Packages/blob/master/ShellScript/Shell-Unix-Generic.sublime-syntax</a></p> <p>In Sublime Text, a package can have multiple syntax definitions, and just knowing the name of the definition isn't enough. Essentially, you need to know the path to the package file, although ApplySyntax seems to not require the <code>Packages/</code> folder root or the <code>.sublime-syntax</code> prefix. See <a href="http://facelessuser.github.io/ApplySyntax/usage/#syntax" rel="nofollow">http://facelessuser.github.io/ApplySyntax/usage/#syntax</a> for more information.</p>
javascript starnage issue , return undefined if block statements are used <pre><code>function ok(){ return { home : "OK" }; } </code></pre> <p>when i code like this the function will return <code>undefined</code></p> <p><a href="https://i.stack.imgur.com/G1YCn.png" rel="nofollow"><img src="https://i.stack.imgur.com/G1YCn.png" alt="enter image description here"></a></p> <p>but if i just shift the <code>{</code> it starts working</p> <pre><code>function ok(){ return { home : "OK" }; } </code></pre> <p><a href="https://i.stack.imgur.com/xbREH.png" rel="nofollow"><img src="https://i.stack.imgur.com/xbREH.png" alt="enter image description here"></a></p> <p>Is this somekind of auto adding ';' at the end of line ?</p>
<p>Javascript engines insert semicolons at certain newline positions. So, your first code is really this:</p> <pre><code>return; { home : "OK" }; </code></pre> <p>And it returns nothing.</p>
autoComplete (jquery.auto-complete.js) categories with label metadata <p>I am able to do basic labels and categories using </p> <blockquote> <p><a href="http://jqueryui.com/autocomplete/#categories" rel="nofollow">http://jqueryui.com/autocomplete/#categories</a></p> </blockquote> <p>but my need without using </p> <blockquote> <p>$.widget( "custom.catcomplete", $.ui.autocomplete, {});</p> </blockquote> <p>how i am able to do this using </p> <blockquote> <p>jQuery( ".class" ).autoComplete({ });</p> <p><a href="https://goodies.pixabay.com/jquery/auto-complete/demo.html" rel="nofollow">https://goodies.pixabay.com/jquery/auto-complete/demo.html</a></p> </blockquote> <p>However, I was wondering if its possible to attach some <strong>metadata</strong> with label. For example...</p> <pre><code>"[{ label: \"labelname1\", category: \"cat1\" },{ label: \"labelname2\", category: \"cat1\" }, { label: \"labelname3\", category: \"cat2\" },{ label: \"labelname4\", category: \"cat2\" }, { label: \"labelname5\", category: \"cat2\" }, ];" </code></pre> <p>I want to something like :</p> <p>cat1</p> <p>-labelname1</p> <p>-labelname2</p> <p>cat2</p> <p>-labelname3</p> <p>-labelname4</p> <p>-labelname5 </p> <p>Note: only use by jQuery( ".class" ).autoComplete({ });</p> <p>ref : > <a href="https://goodies.pixabay.com/jquery/auto-complete/demo.html" rel="nofollow">https://goodies.pixabay.com/jquery/auto-complete/demo.html</a> </p>
<p>I guess is this you are looking for:</p> <pre><code>jQuery(document).ready(function($) { $( ".class" ).autocomplete({ source: [ { label: "labelname1", category: "cat1" }, { label: "labelname2", category: "cat2" }, { label: "labelname3", category: "cat3" } ], select: function( event, ui ) { $( ".class" ).val( ui.item.label ); return false; } }) .data( "ui-autocomplete" )._renderItem = function( ul, item ) { return $( "&lt;li&gt;" ) .data( "ui-autocomplete-item", item ) .append( "&lt;a&gt;" + item.category + "&lt;br&gt;" + item.label + "&lt;/a&gt;" ) .appendTo( ul ); }; }); </code></pre> <p>I hope it helps</p>
Lua reference function from inside table inside of the table (Using "self" inside of table) <p>Let's say I have a table A and functions C and B inside of it,can I call table A function B inside of function C, by referencing self?</p> <pre><code>A = { B = function() print("I am B") end, C = function() print("I am C\nand") __self.B(); end, } A.C(); </code></pre> <p>Thank you for your time.</p>
<p>Yes, using the <code>:</code> method call.</p> <pre><code>A:C() </code></pre> <p><code>:</code> is the equivalent of <code>A.C(A)</code>, but it's safer (pass the exact table reference as first argument).</p> <p>Since you're defining <code>A.C</code> method inside a table constructor expression and you can't use this syntax:</p> <pre><code>function table:prop </code></pre> <p>you must declare the self feature (used as <code>__self</code> in your code) as the first parameter of the function.</p> <pre><code>A = { B = function() print("I am B") end, C = function(__self) print("I am C\nand") __self.B(); end }; </code></pre> <p>If you don't want to specify <code>__self</code> as the first parameter, define <code>A.C</code> after assigning <code>A</code>, with this special function syntax:</p> <pre><code>function A:C() print("I am C\nand"); self.B(); end </code></pre> <p>This makes the first parameter be <code>self</code>.</p>
Javascript loop to count each specified field and count totals of each <p>I am using the following code when filters a specified carmake and counts how many there are.</p> <p>Here is the data and code:</p> <pre><code>var obj = obj = { "garages": [{ "id": "1", "carId": "1", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "2", "carId": "1", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "3", "carId": "2", "tags": { "484": "carmake2", "485": "carmake3" } }, { "id": "4", "carId": "2", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "5", "carId": "3", "tags": { "484": "carmake2", "485": "carmake3" } }, ] }; count = obj.garages.filter(function(item) { return item.tags[483] === "carmake1" }).length; console.log(count); </code></pre> <p>What I need to do it to create a loop that will basically check all tags and count how many there are of each.</p> <p>I know how to manually specify each but how can I do this automatically so that it will just scan the tags and count them ?</p> <p>The final result I'd like the have is to end up with an array containing all the totals.</p>
<p>You can count manually instead of filter:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var obj={garages:[{id:"1",carId:"1",tags:{483:"carmake1",485:"carmake3"}},{id:"2",carId:"1",tags:{483:"carmake1",485:"carmake3"}},{id:"3",carId:"2",tags:{484:"carmake2",485:"carmake3"}},{id:"4",carId:"2",tags:{483:"carmake1",485:"carmake3"}},{id:"5",carId:"3",tags:{484:"carmake2",485:"carmake3"}}]}; var r = {}; obj.garages.forEach(function(o) { for (var t in o.tags) { r[t] = (r[t] || 0) + 1 } }) console.log(r)</code></pre> </div> </div> </p>
Django AppsNotLoaded <p>I'm trying to make a python script to put some things in my database;</p> <pre><code>from django.conf import settings settings.configure() import django.db from models import Hero #Does not work..? heroes = [name for name in open('hero_names.txt').readlines()] names_in_db = [hero.hero_name for hero in Hero.objects.all()] #ALready existing heroes for heroname in heroes: if heroname not in names_in_db: h = Hero(hero_name=heroname, portraid_link='/static/heroes/'+heroname) h.save() </code></pre> <p>The import throws the following</p> <pre><code>Traceback (most recent call last): File "heroes_to_db.py", line 4, in &lt;module&gt; from models import Hero File "C:\Users\toft_\Desktop\d2-patchnotes-master\dota2notes\patch\models.py", line 5, in &lt;module&gt; class Hero(models.Model): File "C:\Python27\lib\site-packages\django\db\models\base.py", line 105, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "C:\Python27\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. </code></pre> <p>I know I can do <code>python manage.py --shell</code> and write the code for hand but to be honest, I dont want to. What am I missing ?</p>
<p>Django must configure all installed applications before you can use any models. To do this you must call <code>django.setup()</code></p> <pre><code>import django django.setup() </code></pre> <p><a href="https://docs.djangoproject.com/en/1.10/ref/applications/#how-applications-are-loaded" rel="nofollow">From the documentation:</a></p> <blockquote> <p>This function is called automatically:</p> <ul> <li>When running an HTTP server via Django’s WSGI support.</li> <li>When invoking a management command.</li> </ul> <p>It must be called explicitly in other cases, for instance in plain Python scripts.</p> </blockquote>
Geting the file object from a form in Symfony <p>I have a scenario where I have to make use of a form the old fashioned why like this;</p> <pre><code>&lt;form action="{{ path('admin_app_address_import') }}" method="post" name="form_import"&gt; &lt;div class="form-group"&gt; &lt;label for="inputFile"&gt;File input&lt;/label&gt; &lt;input type="file" id="inputFile" accept="text/csv" name="inputFile"&gt; &lt;p class="help-block"&gt;Select a CSV file to import.&lt;/p&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>And then get the parameters from the form like this inside my action;</p> <pre><code>public function importAction(Request $request) { $file = $request-&gt;files-&gt;get('inputFile'); var_dump($file);exit; //... } </code></pre> <p>But I keep on getting null. How can I get the file I try to read from? I don't need to store it in a database whatsoever, I just need to read the content to upload that to the database. I'm making a CSV import action, but I can't seem to get the file object.</p> <p>When doing <code>var_dump($request-&gt;request-&gt;all());</code> I do get the filename, but that won't work right?</p>
<p>When allowing file uploads, the encoding type of the form must be set to <code>multipart/form-data</code>:</p> <pre><code>&lt;form ... enctype="multipart/form-data"&gt; </code></pre>
@keyframes for GaussianBlur (svg) <p>i am creating animation based on GaussianBlur (attribute "stdDeviation"), inside tag "animate" all is working, but i'm trying to use css animation. And it's doesnt work. When i had put attribute "stdDeviation" inside @keyframes browser returned "unknown property name". working version of animation:</p> <pre><code>&lt;filter id="f2" width="250%" height="250%"&gt; &lt;feOffset result="offOut" in="SourceGraphic" dx=".5" dy=".5" /&gt; &lt;feGaussianBlur result="blurOut" in="offOut" stdDeviation="3" id="gauss"&gt; &lt;animate attributeName="stdDeviation" attributeType="XML" dur="2s" values="1 ; 1.5 ; 2 ; 2.5 ; 3 ; 2.5 ; 2 ; 1.5 ; 1 " keyTimes="0 ; .13 ; .26 ; .39 ; .52; .65 ; .78; .9; 1" repeatCount="indefinite"/&gt; &lt;/feGaussianBlur&gt; &lt;feBlend in="SourceGraphic" in2="blurOut" mode="normal" /&gt; &lt;/filter&gt; </code></pre> <p>@keyframes, they doesn't work:</p> <pre><code>#gauss { -webkit-animation: gauss_keys 3s ease-out forwards infinite; animation: gauss_keys 3s ease-out forwards infinite;} @keyframes gauss_keys { 0% { stdDeviation: 0; } 100% { stdDeviation: 2; }} </code></pre>
<p>stdDeviation is not a CSS property and can't be animated with CSS animations. You must use SMIL or JavaScript.</p>
ionic get Multi objects from array <p>i have ionic app that send order details by email the email include the item name and size and Qty but when there is multi items in the cart it only sends the last item in the car details here is my controller code </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>.controller('checkoutCtrl', ['$scope', '$state', '$ionicPopup','$http','SERVER','sharedCartService',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $state, $ionicPopup, $http, SERVER, sharedCartService) { $scope.cart=sharedCartService.cart; $scope.total_qty=sharedCartService.total_qty; $scope.total_amount=sharedCartService.total_amount; $scope.data = {}; var itemNames ={}; $scope.submit = function(){ var link = 'http://www.myweb.net/catzOrderEmail.php'; for( var i = 0, len = $scope.cart.length; i &lt; len; i++ ) { itemNames = $scope.cart[i].cart_item_title; alert(itemNames); } $http.post(link, { Item_Name : itemNames ,//$scope.itemName, Item_size : $scope.data.Size, Item_qty : $scope.data.Qty, total_qty : $scope.total_qty, total_amount : $scope.total_amount, FirstName : $scope.data.FirstName, LastName : $scope.data.LastName, Email : $scope.data.Email, Country : $scope.data.Country, City : $scope.data.City, Street : $scope.data.Street, Zip : $scope.data.Zip, Phone : $scope.data.Phone }).then(function (res){ this.myForm.reset(); $state.go('home'); }); }; }])</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?php require "phpmailer/class.phpmailer.php"; //include phpmailer class //require_once("geoiploc.php"); // Must include this require_once("conf.php"); //http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined $postdata = file_get_contents("php://input"); if (isset($postdata)) { $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $request = json_decode($postdata); $SubInput = "New Order"; $Item_Name = $request-&gt;Item_Name; $Item_size = $request-&gt;Item_size; $Item_qty = $request-&gt;Item_qty; $total_qty = $request-&gt;total_qty; $total_amount = $request-&gt;total_amount; $FirstName = $request-&gt;FirstName; $LastName = $request-&gt;LastName; $Email = $request-&gt;Email; $Country = $request-&gt;Country; $City = $request-&gt;City; $Street = $request-&gt;Street; $Zip = $request-&gt;Zip; $Phone = $request-&gt;Phone; $to = "info@catzgear.net"; $hourdiff = "3"; $timeadjust = ($hourdiff * 3600); $date = date("d-m-Y"); $MsTime = date("H:i:s",time() + $timeadjust); //$userip = $_SERVER['REMOTE_ADDR']; //$countryName = getCountryFromIP($userip, " NamE "); $message = "&lt;table width='100%' border='0' cellspacing='0' cellpadding='0'&gt; &lt;tr&gt; &lt;td align='center' valign='top' bgcolor='#ababab' style='background-color:#ababab;'&gt;&lt;br&gt; &lt;br&gt; &lt;table width='600' border='0' cellspacing='0' cellpadding='0'&gt; &lt;tr&gt; &lt;td align='left' valign='top'&gt;&lt;img src='http://www.metalvoice.tv/images/maintop.png' width='600' height='17' style='display:block;'&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align='left' valign='top' bgcolor='#ffffff' style='background-color:#ffffff;'&gt; &lt;table width='570' border='0' align='center' cellpadding='0' cellspacing='0' style='margin-bottom:15px;'&gt; &lt;tr&gt; &lt;td align='left' valign='middle' style='padding:10px;'&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table width='570' border='0' align='center' cellpadding='0' cellspacing='0' style='margin-bottom:15px;'&gt; &lt;tr&gt; &lt;td width='360' align='left' valign='middle' style='font-family:Arial, Helvetica, sans-serif; color:#4e4e4e; font-size:13px; padding-right:10px;'&gt; &lt;div style='font-size:20px;'&gt; Date: $date&lt;br&gt;&lt;br&gt; Time: $MsTime&lt;br&gt;&lt;br&gt; Item Name: $Item_Name&lt;br&gt;&lt;br&gt; Item size: $Item_size&lt;br&gt;&lt;br&gt; Item Qty: $Item_qty&lt;br&gt;&lt;br&gt; total qty: $total_qty&lt;br&gt;&lt;br&gt; total Amount: $total_amount&lt;br&gt;&lt;br&gt; First Name: $FirstName&lt;br&gt;&lt;br&gt; Last Name: $LastName&lt;br&gt;&lt;br&gt; Email: $Email&lt;br&gt;&lt;br&gt; Country : $Country&lt;br&gt;&lt;br&gt; City: $City&lt;br&gt;&lt;br&gt; Street: $Street&lt;br&gt;&lt;br&gt; Zip: $Zip&lt;br&gt;&lt;br&gt; Phone: $Phone &lt;br&gt; &lt;/div&gt; &lt;/td&gt; &lt;td align='right' valign='middle'&gt;&lt;table width='210' border='0' cellspacing='0' cellpadding='0'&gt; &lt;tr&gt; &lt;/tr&gt; &lt;tr&gt; &lt;/tr&gt; &lt;tr&gt; &lt;/tr&gt; &lt;/table&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tr&gt; &lt;/table&gt; &lt;br&gt; &lt;br&gt;&lt;/td&gt; &lt;/table&gt; "; // if ($Item_Name != "" || // $FirstName != "" || // $LastName != "" || // $Email != "" || // $Country != "" || // $City != "" || // $Street != "" || // $Zip != "" || // $Phone != "" // ) { // Instantiate Class $mail = new PHPMailer(); // Set up SMTP $mail-&gt;IsSMTP(); // Sets up a SMTP connection $mail-&gt;SMTPAuth = true; // Connection with the SMTP does require authorization // $mail-&gt;SMTPSecure = "ssl"; // Connect using a TLS connection $mail-&gt;Host = "mail.catzgear.net"; //Gmail SMTP server address $mail-&gt;Port = 25; //Gmail SMTP port $mail-&gt;Encoding = '7bit'; // Authentication $mail-&gt;Username = "info@catzgear.net"; // Your full Gmail address $mail-&gt;Password = $MyPass; // Your Gmail password // Compose $mail-&gt;SetFrom($Email, $FirstName); $mail-&gt;Subject = $SubInput; // Subject (which isn't required) $mail-&gt;MsgHTML($message); // Send To $mail-&gt;AddAddress($to, "Catz Gear"); // Where to send it - Recipient $result = $mail-&gt;Send(); // Send! $message = $result ? 'Successfully Sent!' : 'Sending Failed!'; unset($mail); } // else { // echo "Sending Failed!"; // } ?&gt;</code></pre> </div> </div> </p> <p>how can i get all the items names in the cart</p> <p>best regards </p>
<p>That is because you are only sending last element In you API, for loop is executing first , at the end there is only last element in itemNames , And you are sending that to php.</p> <p>So there are two things you can do , </p> <ol> <li><p>Call ajax inside loop (not good)</p></li> <li><p>Push all those elements together and then send it.</p> <p>itemNames.push($scope.cart[i].cart_item_title);</p></li> </ol> <p>for this make sure itemNames is an array . And Do your thing in php with this array object.</p> <p>Hopes It will make sense to you</p>
Installing image pgk on Octave on Mac <p>I installed GNU Octave, version 4.2.0-rc2 on my Mac[0] using Homebrew[1].</p> <p>But now I tried to install the image pkg[2].</p> <p>I tried downloading it and then using this line:</p> <pre><code>"pkg install image-2.6.0.tar.gz" </code></pre> <p>Then I tried installing it with this line of code: </p> <pre><code>"pkg install -forge image" </code></pre> <p>Both resulted in the following output:</p> <pre><code>configure: error: *** A compiler with support for C++11 is required checking for a sed that does not truncate output... /usr/local/bin/gsed checking for octave... /usr/local/Cellar/octave/4.2.0-rc2/bin/octave-4.2.0-rc2 checking for mkoctfile... /usr/local/Cellar/octave/4.2.0-rc2/bin/mkoctfile-4.2.0-rc2 checking whether the C++ compiler works... yes checking for C++ compiler default output file name... a.out checking for suffix of executables... checking whether we are cross compiling... no checking for suffix of object files... o checking whether we are using the GNU C++ compiler... yes checking whether clang++ -std=gnu++11 accepts -g... yes checking for clang++ -std=gnu++11 option to enable C++11 features... unsupported pkg: error running the configure script for image. error: called from install at line 200 column 5 pkg at line 392 column 9 </code></pre> <p>But I think I installed GCC correctly:</p> <pre><code>gcc -v </code></pre> <p>Has the following output:</p> <pre><code>Es werden eingebaute Spezifikationen verwendet. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc/x86_64-apple-darwin15.6.0/6.2.0/lto-wrapper Ziel: x86_64-apple-darwin15.6.0 Konfiguriert mit: ../gcc-6.2.0/configure --enable-languages=c++,fortran --with-gmp=/usr/local Thread-Modell: posix gcc-Version 6.2.0 (GCC) </code></pre> <p>What is my mistake? Or what have i done wrong?</p> <hr> <p>[1] <a href="http://wiki.octave.org/Octave_for_MacOS_X#Homebrew" rel="nofollow">http://wiki.octave.org/Octave_for_MacOS_X#Homebrew</a></p> <p>[2] <a href="http://octave.sourceforge.net/image/index.html" rel="nofollow">http://octave.sourceforge.net/image/index.html</a></p> <p>[0] Macbook Specifications: MacBook Pro (13-inch, Mid 2012)</p> <p>2,5 GHz Intel Core i5</p> <p>16 GB 1600 MHz DDR3</p> <p>macOS Sierra (Version 10.12)</p>
<p>I had the exact same problem. Just download the older version 2.4.1 of <code>image</code> and installation should work as expected.</p> <p>Download Link:</p> <p><a href="https://sourceforge.net/projects/octave/files/Octave%20Forge%20Packages/Individual%20Package%20Releases/image-2.4.1.tar.gz/download" rel="nofollow">https://sourceforge.net/projects/octave/files/Octave%20Forge%20Packages/Individual%20Package%20Releases/image-2.4.1.tar.gz/download</a></p>
Replacing Cookie by Token based authentication in ASP.NET OWIN OpenIdConnect code authorization flow <p>We have a web application written in ASP.NET that uses MVC for serving our Single Page Applications and Web API for ajax calls.</p> <p>The authentication uses <em>Microsoft.Owin</em> and <em>OpenIdConnect</em> with Azure AD for Authority. The OAUTH flow is server side code authorization. Then in <em>Startup.Auth.cs</em> we have</p> <pre><code> public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); var cookieAuthenticationOptions = new CookieAuthenticationOptions() { CookieName = CookieName, ExpireTimeSpan = TimeSpan.FromDays(30), AuthenticationType = CookieAuthenticationDefaults.AuthenticationType, SlidingExpiration = true, }; app.UseCookieAuthentication(cookieAuthenticationOptions); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { AuthorizationCodeReceived = (context) =&gt; { /*exchange authorization code for a token stored on database to access API registered on AzureAD (using ADAL.NET) */ }, RedirectToIdentityProvider = (RedirectToIdentityProviderNotification&lt;OpenIdConnectMessage, OpenIdConnectAuthenticationOptions&gt; context) =&gt; { /* Set the redirects URI here*/ }, }); } </code></pre> <p>When clicking on signin we navigate to an url whose routes map to the methods of the following MVC controller</p> <pre><code>public class AccountController : Controller { public void SignIn(string signalrRef) { var authenticationProperties = /* Proper auth properties, redirect etc.*/ HttpContext.GetOwinContext() .Authentication.Challenge(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); } public void SignOut(string signalrRef) { var authenticationProperties = /* Proper auth properties, redirect etc.*/ HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); } </code></pre> <p>Then the end-user connected to our application is authenticated between our client apps and the ASP.net server using an ASP.NET cookie. <strong>We would like to use Token Based approach instead</strong>. If you are interested <a href="https://github.com/Keluro/Office365-AddinWeb-SignInSample/issues/3" rel="nofollow">this is the reason</a>.</p> <p>I tried to replace the Nuget package <em>Microsoft.Owin.Security.Cookies</em> by <em>Microsoft.Owin.Security.OAuth</em> and in Startup.cs replacing </p> <p><code>app.UseCookieAuthentication(cookieAuthenticationOptions);</code> by <code>app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());</code></p> <p>and in my <em>AccountController</em> we changed the challenge from <code>HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);</code> to <code>HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, OAuthDefaults.AuthenticationType);</code></p> <p>The problem is that with Cookie the <em>set-cookie</em> was automatically sent in web request respond when the flow completes while redirecting to the url we specified. <strong>Where can I find the Bearer generated by OWIN with UseOAuthBearerAuthentication (if there is any) **, **Where and When should I send it back to my client SPAs</strong></p> <p><strong>Note:</strong> an open source sample of what we are trying to do can be found in <a href="https://github.com/Keluro/Office365-AddinWeb-SignInSample" rel="nofollow">this github repository</a>.</p>
<p>I think there are two approaches for you to consider.</p> <ol> <li>Use javascript libraries to perform sign-in &amp; token acquisition within your single page app. Then your backend is purely an web API, and can just use OAuth bearer middleware to authenticate requests. The backend doesn't know anything about signing the user in. We have a good sample that takes this approach <a href="https://github.com/Azure-Samples/active-directory-javascript-singlepageapp-dotnet-webapi" rel="nofollow">here</a>. If your backend needs to make API calls as well, you could consider the OnBehalfOf flow as well. I usually recommend this approach.</li> <li>Use the OpenIDConnect middleware in your server to perform user sign-in and token acquisition. You might even be able to omit the usage of the <code>CookieAuthenticationMiddleware</code> entirely (although I'm not 100% sure). You can capture the token in the <code>AuthorizationCodeReceived</code> notification as you mention, and you could redirect back to your SPA with the token in the fragment of the URL. You could also have some route which delivers the tokens (which are cached on your server) down to your javascript. In either case, you'll need to ensure that an outside caller can't get access to your tokens.</li> </ol> <p>The thing to keep in mind will be how you refresh tokens when they expire. If you use #1, most of it will be handled for you by libraries. If you use #2, you'll have to manage it more yourself.</p>
Syntax error in angularjs while Data binding <p>browserLink:37 Uncaught Error: Syntax error, unrecognized expression: input#{role}(…) </p> <p>//template </p> <pre><code>&lt;div ng-repeat="role in roles"&gt; &lt;input type="checkbox" id="{{role}}" value="{{role}}" ng-model="role" ng -checked="getCheckedTrue[{{role}}]" /&gt; {{role}} &lt;/div&gt; </code></pre> <p>//js</p> <pre><code>$scope.roles = [ 'Dentist', 'HeartSurgeon', 'Cance' ]; $scope.getCheckedTrue = function (data) { console.log(data); $http({ method: 'GET', url: '/Doctor/getType?searchString=' + $scope.role, }).then(function successCallback(responce) { $scope.Doctors = responce.data; }, function errorCallback(response) { alert("Error : " + response.data.ExceptionMessage); }); };` </code></pre> <p>//Controller</p> <pre><code> public JsonResult getType(string searchString) { var Doctor = db.DocMaster.Where(f =&gt; f.DocType.StartsWith(searchString)).ToList(); var JsonResult = Json(Doctor, JsonRequestBehavior.AllowGet); JsonResult.MaxJsonLength = int.MaxValue; return JsonResult; } </code></pre>
<p>Reference the input by name instead of input
How to get a MS Translator access token from Swift 3? <p>I am trying to work with a MS Translator API from Swift 3 (right now playing in playgrounds, but the target platform is iOS). However, I got stuck when I was trying to get an access token for OAuth2. I have following code (I tried to port the code from example at <a href="https://msdn.microsoft.com/en-us/library/hh454950.aspx" rel="nofollow" title="Obtaining an access token">Obtaining an access token</a>):</p> <pre><code>let clientId = "id".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let clientSecret = "secret".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let scope = "http://api.microsofttranslator.com".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let translatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13" let requestDetails = "grant_type=client_credentials&amp;client_id=\(clientId)&amp;client_secret=\(clientSecret)&amp;scope=\(scope)" let postData = requestDetails.data(using: .ascii)! let postLength = postData.count var request = URLRequest(url: URL(string: translatorAccessURI)!) request.httpMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("\(postLength)", forHTTPHeaderField: "Content-Length") request.httpBody = postData URLSession.shared.dataTask(with: webRequest) { (returnedData, response, error) in let data = String(data: returnedData!, encoding: .ascii) print(data) print("**************") print(response) print("**************") print(error) }.resume() </code></pre> <p>Of course, I used a valid clientId and a valid clientSecret.</p> <p>Now the callback prints following information. First, the returnedData contain a message that the request was invalid, along with a following message:</p> <pre><code>"ACS90004: The request is not properly formatted." </code></pre> <p>Second, the response comes with a 400 code (which fits the fact that the request is not properly formatted).</p> <p>Third, the error is nil.</p> <p>Now I was testing the call using Postman, and when I used the same URI, and put the requestDetails string as a raw body message (I added the <code>Content-Type</code> header manually), I got the same response. However, when I changed the body type in Postman UI to <code>application/x-www-form-urlencoded</code> and typed in the request details as key value pairs through its UI, the call succeeded. Now it seems that I am doing something wrong with the message formatting, or maybe even something bad with the Swift URLRequest/URLSession API, however, I cannot get a hold on to what. Can somebody help me out, please? Thanks.</p>
<p>OK, so after some more desperate googling and experimenting I have found my error. For the future generations:</p> <p>The problem resided in encoding the parameters in the body of the PUT http request. Instead of:</p> <pre><code>let scope = "http://api.microsofttranslator.com" .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! </code></pre> <p>I have to use the following:</p> <pre><code>let scope = "http://api.microsofttranslator.com" .addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: ";/?:@&amp;=$+{}&lt;&gt;,").inverted)! </code></pre> <p>Seems that the API (or the HTTP protocol, I am not an expert in this) have problems with <code>/</code> and <code>:</code> characters in the request body. I have to give credentials to Studiosus' answer on <a href="https://github.com/ayanonagon/Polyglot/issues/10" rel="nofollow">Polyglot issue report</a>.</p>
Predict multiple different equations at once <p>I have a set of interrelated equations. My goal is to get forecast for all LHS-variables simultaneously. Here is a brief example:</p> <pre><code>require('dyn') require('zoo') set.seed(1) y &lt;- zoo(rnorm(30,1)) x &lt;- zoo(rnorm(40,115)) z&lt;-zoo(0.3*rnorm(30,100,20)+0.7*(rnorm(30,50,2)^2)) myData&lt;-cbind(y,x,z) #Equations: eq1&lt;-dyn$lm(y~x+lag(y,-1)+lag(z,-1),myData[1:30]) eq2&lt;-dyn$lm(z~y+lag(x,-1),myData[1:30]) model.list&lt;-list(eq1,eq2) #Function for forecasting: fun1&lt;-function (equation,data=myData) { endog&lt;-substr(attr(equation$terms , "variables")[2],1, nchar(attr(equation$terms , "variables")[2])) for(i in 31:40) { # get prediction for ith value data[i, endog] &lt;- tail(predict(equation, data[1:i,]), 1) } data} </code></pre> <p>So here is my question: how can I apply my <code>fun1</code> to a list of equations. I would like to have a result as a dataset containing all predicted values.</p> <p><strong>upd</strong></p> <p>My solution. I wrote two new functions with for-loop and if-clause to solve the problem. First of all, I needed to write a function for getting the list of equations in the order which is needed for forecasting</p> <pre><code>#I need to get the list filled with unique elements (equations) BUT mind the order: #The equation that couldn't be assessed at once will be repeated #in the list for a couple of times #I need to get final list where all elements are in the same order #as their LAST duplicate fun3&lt;- function(list_eq=model.list,data=myData) { i&lt;-31 llength&lt;-length(list_eq) for (j in 1:llength) { endog &lt;- substr(attr(list_eq[[j]]$terms , "variables")[2], 1, nchar(attr(list_eq[[j]]$terms , "variables")[2])) data[i, endog] &lt;- tail(predict(list_eq[[j]], data[1:i]), 1) if (is.na(data[i, endog]) == TRUE) { list_eq&lt;-c(list_eq,list(list_eq[[j]])) } } rev(unique(rev(list_eq))) } fun3() eq.list&lt;-fun3() #Function for prediction fun4 &lt;- function(list_eq = eq.list, data = myData) { for (i in 31:40) { llength&lt;-length(list_eq) for (j in 1:llength) { #Get name of endogenous variable from jth equation endog &lt;-substr(attr(list_eq[[j]]$terms , "variables")[2], 1, nchar(attr(list_eq[[j]]$terms , "variables")[2])) # get prediction for ith value in jth equation data[i, endog] &lt;- tail(predict(list_eq[[j]], data[1:i]), 1) } data } data } fun4() </code></pre> <p>The solution is not elegant at all. But it gives the result and the result doesn't depend on the order of equations in the list which was crucial to me.</p> <p>If you have any other suggestions, you are welcome.</p>
<pre><code>results &lt;- lapply(model.list, fun1) results_with_id &lt;- mapply(model = seq_along(results), x = results, FUN = function(model, x) { cbind(model = model, as.data.frame(x)) }, SIMPLIFY = FALSE) predictions &lt;- Reduce("rbind", results_with_id) </code></pre>
Should REST reponse contain any query parameter? <p>should I include my input query parameter in the response?</p> <p>let's say that I have endpoint which returns people names, I am allowing my client to restrict the result by the country.</p> <p>I wonder should I include the country query param in the response or not .</p> <p>for example when the user sends the below request</p> <pre><code>rest/people?country=UK </code></pre> <p>should I return </p> <pre><code>[{"name":"tom"},{"name"="tim"}] </code></pre> <p>or</p> <pre><code>[{"name":"tom", "country":"UK"},{"name"="tim","country":"UK"}] </code></pre> <p>as the response?</p>
<p>Depends on what data the client needs.</p> <p>If you just want a way to tell the client what they requested, you could have some convention in your API that there's a top-level node that shows what the parameters in the request were that generated this reponse.</p> <p><code>{"requestParams":"country=UK&amp;city=London", data: [{"name":"tom", "street":"Wallaby"}, {"name":"tim", "street":"West"}]</code></p> <p>But you definitely don't want to risk returning sensitive information by returning the request params.</p>
Threat found on my wordpress website <p>Ever since i connected my website to the domain i started to get on some computers that are trying to visit the website this warring:</p> <p>Access to the web page was blocked. Show URL</p> <p>Threat: JS/TrojanDownloader.FakejQuery.B trojan</p> <p><a href="https://i.stack.imgur.com/2LMKV.png" rel="nofollow"><img src="https://i.stack.imgur.com/2LMKV.png" alt="enter image description here"></a></p> <p>what should i do?</p>
<p>If you're going through a host for your domain, I would contact them for an explanation. In the mean time/if you are hosting it yourself, I would try and run the Shodan extension for chrome on the site to check for other active ports that could be influencing the connecting clients. Double check all of your javascript files for something that could be fishy.</p> <p>This honestly looks fake in my experience. It looks more like something a ransomware would use instead of an actual trojan. If you dont have ANY javascript on your website, then I would almost guarantee that it's not real.</p>
Push one object property with the same object in javascript <p>I have to frame object structure like below dynamically.</p> <pre><code> "1":{ "A":"one.two.three" }, "2":{ "B":"three.four.five" }, "3":{ "c":"six.seven.eight" }, etc.... Obj ={ A: "123", B: "345", C :"678" } </code></pre> <p>EXPECTED OUTPUT SHOULD BE AS BELOW</p> <pre><code> "Parent" :{ "one":{ "two"{ "three" :"123" (from Obj A) } } "three": { "four":{ "five" :"345" (from Obj B) } } etc...` ` } </code></pre> <p>so i have tried the below approach. But it does not work.</p> <pre><code>Var temp = {} temp["one"] ="1"; temp["two"] = temp; (and) temp["one"] temp["three"] = temp; (and) temp["two"] </code></pre>
<p>You can do this:</p> <pre><code>var obj = {}; obj['temp'] = {}; obj['temp']['tree'] = {}; obj['temp']['tree']['two'] = {}; obj['temp']['tree']['two']['one'] = "1"; </code></pre>
How to show progress bar when uploading a file in android retrofit <p>I am developing an android app using retrofit. I want to upload any type of file to my server with parameters. For example in my app there is text field like email and file upload field. when i entered the fields and click the submit button. It shows the percentage of uploading file and send the file and data to server. when the uploading process going it want to shows the percentage of completed file. How it possible? Did any reference site or tutorial? Please help me?</p>
<p>create this interface</p> <pre><code>public interface ProgressListener { void transferred(long num); } </code></pre> <p>And this class</p> <pre><code> public class CountingTypedFile extends TypedFile { private static final int BUFFER_SIZE = 4096; private final ProgressListener listener; public CountingTypedFile(String mimeType, File file, ProgressListener listener) { super(mimeType, file); this.listener = listener; } @Override public void writeTo(OutputStream out) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; FileInputStream in = new FileInputStream(super.file()); long total = 0; try { int read; while ((read = in.read(buffer)) != -1) { total += read; out.write(buffer, 0, read); try{ if (this.listener != null) this.listener.transferred(total); }catch (Exception e){ } } } finally { in.close(); } } } </code></pre> <p>Define this method</p> <pre><code>@POST("/{path}") public JsonObject makeRequestForAttachmentsUpload(@Path(value = "path", encode = false) String path, @Body MultipartTypedOutput multipartTypedOutput); </code></pre> <p>then call upload method like this</p> <pre><code> RestClient restClient = new RestClient(); ApiService apiService = restClient.getApiService(); MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput(); // add and string parameters for (String key : requestParams.keySet()) { multipartTypedOutput.addPart(key, new TypedString(requestParams.get(key))); } // add attchments multipartTypedOutput.addPart(attachmentName, new CountingTypedFile(attachmentType, new File(attachmentPath), listener)); apiService.makeRequestForAttachmentsUpload(requestName, multipartTypedOutput); </code></pre> <p>and listen for progress by defining this listener</p> <pre><code>listener = new DPAPIService.ProgressListener() { @Override public void transferred(long num) { publishProgress(((num / (float) fileSize))); } }; </code></pre>
How to use Adobe afm fonts in matplotlib text? <p>I want to add a text to a figure using an AFM font. I know that I can pass the <code>fontproperties</code> or the <code>fontname</code> keyword argument when creating a text. </p> <p>Regarding the usage of AFM fonts in matplotlib, I found <a href="http://matplotlib.org/api/afm_api.html" rel="nofollow">this</a> and <a href="http://matplotlib.org/api/font_manager_api.html#matplotlib.font_manager.afmFontProperty" rel="nofollow">this</a>. </p> <p>I can't pass a Font instance create by <code>matplotlib.font_manager.afmFontProperty</code> as <code>fontproperties</code> kwarg.</p> <p>The font I intend to use is URW Chancery L and located in <code>/usr/share/fonts/type1/gsfonts/z003034l.afm</code>. How can I make matplotlib use this font?</p> <p>Also I looked for converters from afm to ttf but could not find any, maybe you have a suggestion?</p> <p>I'm using matplotlib 1.5.3 on Ubuntu 16.04.</p>
<p>What is an "AFM font"? AFM files are <strong>A</strong>dobe <strong>F</strong>ont <strong>M</strong>etrics files, which only contain metadata around glyph bounds, kerning pairs, etc. as a convenient lookup mechanism when you don't want to mine the real font file for that information (handy for typesetting, where having the metrics available as separate resource makes things a hell of a lot faster), they are not themselves fonts in any way. You would still need a (now mostly defunct) <code>.pfa</code> or <code>.pfb</code> font file ("printer font; ascii" and "printer font; binary", respectively) to do any kind of actual text rendering. Without those, all you can do is mark the appropriate region in which text <em>would</em> be drawn if you also had the font itself available =)</p> <p>(this is actually what TeX and PDF do - they use the font metrics to construct "empty boxes" inside of which text will ultimately be rendered once all the typesetting has been determined and the boxes no longer move around)</p>
IBM Worklight App Center not working by using latest version of Chrome APP on Android <p>As usual, user download .apk through IBM App Center, everything work fine until update Chrome app to version <strong>53.0.2785.124</strong></p> <p>Nothing happened when user click the download button.</p> <p>After that, we <strong>downgrade</strong> the Chrome back to the old version, and try it again, .apk downloaded perfectly.</p> <p>The issue <strong>only</strong> happened on Android device and only Chrome Browser with latest release version 53.0.2785.124 will cause the problem.</p> <p>( another app like native browser or firefox browser work fine )</p> <p>All I can do to resolve the problem is downgrade Chrome Browser to older version.</p> <p>Above all, please someone give some advise or instructions to figure out the problem.</p> <p>Thanks.</p>
<p>I'm sorry, but Stack Overflow is not the place for this kind of support for IBM Application Center. As an IBM customer, please open a PMR (support ticket) to contact and receive support from the development team for IBM Application Center.</p>
Compare two csv files containing similar columns, eliminate duplicate and output unique content in one file <p>I have two csv files (similar format)</p> <p>file1.csv </p> <pre><code> post_status post_type post_content post_title publish post paragraph one title one publish post paragraph two title two publish post paragraph three title three publish post paragraph four title four </code></pre> <p>file2.csv</p> <pre><code> post_status post_type post_content post_title publish post paragraph one title one publish post paragraph two title two publish post paragraph three title three publish post paragraph four title four publish post paragraph five title five publish post paragraph six title six </code></pre> <p>Desired-output.csv</p> <pre><code> post_status post_type post_content post_title publish post paragraph five title five publish post paragraph six title six </code></pre> <p>The solutions I have gotten so far are using Power Shell and this:</p> <pre><code>cat first.csv second.csv | sort -u &gt;result.csv </code></pre> <p>This produces results that don't maintain consistency of the original file.</p> <p>I am using Ubuntu and Windows. Looking for a simple elegant solution. Any and all help will be appreciated.</p>
<p>Try</p> <pre><code>$Content = Get-Content first.csv,second.csv $Content | Select-Object -Unique | Out-File result.csv </code></pre> <p>This solution is for Windows Powershell</p> <p>Actually, you can do all in one line:</p> <pre><code>Get-Content first.csv,second.csv | Select-Object -Unique | Out-File result.csv </code></pre> <p>The only difference between your version and mine (besides from using the linux aliases for the powershell cmds) is that you are using Sort-Object which will change the order of the entries.:)</p>
Android: How to code an AlertDialog with onClickListener and onLongClickListener <p>Like the title says. I have coded onClickListener to my AlertDialog but i don't know how to put there onLongClickListener.</p> <p>This is my code:</p> <pre><code>private void addRecipeMethod() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Title"); adapter = new ArrayAdapter&lt;&gt;(getBaseContext(), android.R.layout.simple_list_item_1, getArrayList("ListOfRecipes")); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { List&lt;String&gt; list = new ArrayList&lt;&gt;(getArrayList("ListOfRecipes")); getArrayListRecipes(list.get(which)); List&lt;String&gt; listMain = new ArrayList&lt;&gt;(getArrayList("ListMain")); listMain.addAll(getArrayListRecipes(list.get(which))); saveList(listMain, "ListMain"); adapter = new ArrayAdapter&lt;&gt;(getBaseContext(), android.R.layout.simple_list_item_1, getArrayList("ListMain")); listView.setAdapter(adapter); //Toast.makeText(getApplicationContext(), "you have clicked " + list.get(which) , Toast.LENGTH_SHORT).show(); } }); builder.show(); } </code></pre> <p>PS. void addRecipeMethod is called when Menu Item is clicked</p>
<p>Create <code>AlertDialog</code> with custom layout like this</p> <pre><code> AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // ...Irrelevant code for customizing the buttons and title LayoutInflater inflater = this.getLayoutInflater(); View dialogView = inflater.inflate(R.layout.alert_label_editor, null); dialogBuilder.setView(dialogView); Button button = (Button)dialogBuilder.findViewById(R.id.btnName); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Commond here...... } }); button.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { // TODO Auto-generated method stub return false; } }); AlertDialog alertDialog = dialogBuilder.create(); alertDialog.show(); </code></pre> <p>Add Button in <code>alert_label_editor</code> xml and add <code>setOnLongClickListener</code> for that Button</p> <pre><code> Button button = (Button)dialogBuilder.findViewById(R.id.btnName); button.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { // TODO Auto-generated method stub return false; } }); </code></pre>
while loop within a function - python <p>I'm quite new to writing code, so although some of you might find this easy, I don't. So would really appreciate some help from someone i bit more experienced than I am!</p> <p>This is the code that I am working on right now (it is part of a bigger script)</p> <pre><code>def createListOdd(): number = int(input("Type an odd number: ")) while number % 2 !=0: if number % 2 != 0: for element in range(number): listOdd = random.sample(range(tall),tall) break else: number = int(input("Please type an odd number: ")) return listOdd </code></pre> <p>However, I get get out of my function. Really hope someone can help me!</p>
<p>In your code, you're breaking from the for loop on the first iteration. Also, if you input an odd number, the line <code>number = int(input("Please type an odd number: "))</code> will never be run. </p> <p>Hope this helps! </p>
Sequelize join twice on two tables <p>I have two table: <code>Conversations</code> and <code>ConversationParticipants</code>. I need to get the list of conversations that both users <code>1</code> and <code>2</code> participate too. In <code>MySQL</code>, the query would be this:</p> <pre><code>SELECT conversation_participants.conversation_id FROM conversation_participants JOIN conversations t1 ON t1.conversation_id = conversation_participants.conversation_id AND conversation_participants.user_id = 11 JOIN conversation_participants t2 ON t1.conversation_id = t2.conversation_id AND t2.user_id = 2 </code></pre> <p>However, in Sequelize I cannot understand how to set models relations so that I can make a single query. I tried this without success (please note that this is almost pseudo code, reported as such for clarity):</p> <pre><code>var Conversation = sequelize.define('conversations', { conversationId: Sequelize.INTEGER.UNSIGNED, }); var ConversationParticipant = sequelize.define('conversation_participants', { participationId: Sequelize.INTEGER.UNSIGNED, userId: Sequelize.INTEGER.UNSIGNED, conversationId : Sequelize.INTEGER.UNSIGNED, }); Conversation.hasMany(ConversationParticipant, { as : 'Participants'}); </code></pre> <p>and then </p> <pre><code>ConversationParticipant.findAll({ where : { userId : 1 }, include : [{ model : Conversation, as : 'conversation', include : [{ model : ConversationParticipant, as : 'Participants', where : { userId : 2 } }] }] </code></pre> <p>I get the following error: <code>Error: conversation_participants is not associated with conversations!</code>. Any idea?</p>
<p>One way you could do it is find the conversations that have participants with user 1 or 2, and afterwards filter the conversations that have both of them:</p> <pre><code>const userIdsFilter = [1,2]; //find Conversations that have user 1 OR user 2 as participants, Conversation.findAll({ include : [{ model : ConversationParticipant, as : 'conversation_participants', where : { userId : { $in: userIdsFilter }} }] }).then((conversations) =&gt; { //filter the conversations that have the same length participants //as the userIdsFilter length (that way it excludes the ones //that have just one of the users as participants) return conversations.filter((conversation) =&gt; conversation.conversation_participants.length === userIdsFilter.length); }).then((conversations) =&gt; { //do what you need with conversations.. }) </code></pre>
STL list very bad performance <p>It's supposed that "push_back" and "pop_front" methods of a STL list (implemented as a double linked list) should be constant O(1). However we were having cpu issues in an application running on linux and we found that "pop_front" method is incredibly inefficient when using lists. Is this a list implementaion issue or is the expected behaviour?</p> <p>This is the example code:</p> <pre><code>class A { public: A() { mA = rand(); mB = rand(); mC = rand(); mD = rand(); } u32 mA; u32 mB; u32 mC; u32 mD; }; #define DELTA(t1, t0) ((t1.tv_sec - t0.tv_sec)*1000 + ((t1.tv_usec - t0.tv_usec)/1000)) int main(int argc, char* argv[]) { std::list&lt;A&gt; l; std::queue&lt;A&gt; q; std::deque&lt;A&gt; dq; printf("Creating nodes..."); std::vector&lt;A&gt; v; for (int i = 0; i &lt; 100000; ++i) { A a; v.push_back(a); } printf("OK\n"); timeval t0, t1; printf("std::deque test: push back..."); gettimeofday(&amp;t0, NULL); for (std::vector&lt;A&gt;::const_iterator iter = v.begin(); iter != v.end(); ++iter) { dq.push_back(*iter); } gettimeofday(&amp;t1, NULL); printf("Done in %d ms, size = %d\n", DELTA(t1, t0), dq.size()); printf("std::deque test: pop front..."); gettimeofday(&amp;t0, NULL); while (dq.size() &gt; 0) { A a = dq.front(); dq.pop_front(); } gettimeofday(&amp;t1, NULL); printf("Done in %d ms, size = %d\n", DELTA(t1, t0), dq.size()); printf("std::queue test: push back..."); gettimeofday(&amp;t0, NULL); for (std::vector&lt;A&gt;::const_iterator iter = v.begin(); iter != v.end(); ++iter) { q.push(*iter); } gettimeofday(&amp;t1, NULL); printf("Done in %d ms, size = %d\n", DELTA(t1, t0), q.size()); printf("std::queue test: pop front..."); gettimeofday(&amp;t0, NULL); while (q.size() &gt; 0) { A a = q.front(); q.pop(); } gettimeofday(&amp;t1, NULL); printf("Done in %d ms, size = %d\n", DELTA(t1, t0), q.size()); printf("std::list test: push back..."); gettimeofday(&amp;t0, NULL); for (std::vector&lt;A&gt;::const_iterator iter = v.begin(); iter != v.end(); ++iter) { l.push_back(*iter); } gettimeofday(&amp;t1, NULL); printf("Done in %d ms, size = %d\n", DELTA(t1, t0), l.size()); printf("std::list test: pop front..."); gettimeofday(&amp;t0, NULL); while (l.size() &gt; 0) { A a = l.front(); l.pop_front(); } gettimeofday(&amp;t1, NULL); printf("Done in %d ms, size = %d\n", DELTA(t1, t0), l.size()); return 0; } </code></pre> <p>For different number of nodes we get:</p> <p>5000 nodes:</p> <pre><code>std::deque test: push back...Done in 0 ms, size = 5000 std::deque test: pop front...Done in 0 ms, size = 0 std::queue test: push back...Done in 0 ms, size = 5000 std::queue test: pop front...Done in 0 ms, size = 0 std::list test: push back...Done in 0 ms, size = 5000 std::list test: pop front...Done in 202 ms, size = 0 </code></pre> <p>10000 nodes:</p> <pre><code>std::deque test: push back...Done in 0 ms, size = 10000 std::deque test: pop front...Done in 0 ms, size = 0 std::queue test: push back...Done in 0 ms, size = 10000 std::queue test: pop front...Done in 0 ms, size = 0 std::list test: push back...Done in 1 ms, size = 10000 std::list test: pop front...Done in 279 ms, size = 0 </code></pre> <p>100000 nodes:</p> <pre><code>std::deque test: push back...Done in 5 ms, size = 100000 std::deque test: pop front...Done in 4 ms, size = 0 std::queue test: push back...Done in 3 ms, size = 100000 std::queue test: pop front...Done in 4 ms, size = 0 std::list test: push back...Done in 12 ms, size = 100000 std::list test: pop front...Done in 31148 ms, size = 0 </code></pre> <p>Thanks!</p> <p>Vicente</p>
<p>If you want to check whether a container is nonempty, you should use <code>!c.empty()</code>, not <code>c.size() &gt; 0</code>.</p> <p>This is especially important for <code>std::list</code>, because in some implementations, <code>size</code> is a <em>linear time</em> operation, not a <em>constant time</em> operation.</p> <p>(although, as vsoftco notes in the comments, C++11 strengthens the requirement on <code>size</code> that it really is constant &mdash; if you have a compliant compiler/library, you can try enabling the options to compiling for that standard or later)</p>
NodeJS daemon not starting at startup on raspberry pi <p>I have created a little daemon that starts my nodejs API as a service using <code>forever</code>.</p> <p>Now that the service starts and stops without any problems, I want to make it start when the raspberry pi turns on. My raspberry pi is running on <code>Raspbian</code>.</p> <p>I've placed the service in the <code>/etc/init.d/</code> folder and executed <code>update-rc.d myServiceName defaults</code> but it doesn't start the service after booting...</p> <p>Can you help me? There's the script:</p> <pre><code>#!/bin/sh export PATH=$PATH:/usr/local/bin export NODE_PATH=$NODE_PATH:/usr/local/lib/node_modules case "$1" in start) exec forever --spinSleepTime 10000 --sourceDir=/var/domothink -p /var/run/forever start dist/server.js ;; stop) exec forever stop --sourceDir=/var/domothink dist/server.js ;; status) # TODO ;; default) # TODO ;; esac exit 0 </code></pre>
<p>I have found a good solution for creating a nodejs service on <code>Debian</code> / <code>Raspbian</code>.</p> <p>I installed the <code>forever-service</code> package with npm and create the service with this tool.</p> <p>It's a really good solution and it works really good: <a href="https://github.com/zapty/forever-service" rel="nofollow">https://github.com/zapty/forever-service</a></p>
need to plot a 2D graph of the gray image intensity in matlab <p>what I am trying is to compare two gray scale images by ploting their intensity into graph. The code is bellow is for single image. </p> <pre><code>img11 = imread('img.bmp'); [rows cols ColorChannels] = size(img11); for i=1:cols for j=1:rows intensityValue = img11(j,i); end end % below trying different plot method plot(intensityValue); plot(1:length(img11),img11); plot(img11(:)) </code></pre> <p>My expected result for two images is like below pictures:<a href="https://i.stack.imgur.com/zhbGu.png" rel="nofollow"> here</a></p> <p>not like this <a href="https://i.stack.imgur.com/GzjPl.png" rel="nofollow">here</a></p>
<p>Based on your code you should be able to do the following.</p> <pre><code>img11 = imread('img1.bmp'); img22 = imread('img2.bmp'); figure; imagesc(img11); % verify you image figure; plot(img11(:)); hold on; plot(img22(:)); </code></pre> <p>Using the command <code>(:)</code> will flatten a matrix into a single vector starting at the top left and going down in columns. If that is not the orientation that you want you try to rotate/transpose the image (or try using <code>reshape()</code>, but it might be confusing at the start). Additionally, if your image has large variations in the pixel intensity moving average filter can be useful.</p> <pre><code>Len = 128; smooth_vector = filter(ones(Len,1)/Len,1,double(img11(:))); figure; plot(smooth_vector); </code></pre>
How to replace multiple if-else statements to optimize code? <p>I want to know if there is any way i could optimize this code.</p> <pre><code>String[] array; for(String s:array){ if(s.contains("one")) //call first function else if(s.contains("two")) //call second function ...and so on } </code></pre> <p>The string is basically lines I am reading from a file.So there can be many number of lines.And I have to look for specific keywords in those lines and call the corresponding function.</p>
<p>This wont stop you code from doing many <code>String#contains</code> calls, however, it will avoid the <code>if/else</code> chaining.. </p> <p>You can create a key-function map and then iterate over the entries of this map to find which method to call.</p> <pre><code>public void one() {...} public void two() {...} private final Map&lt;String, Runnable&gt; lookup = new HashMap&lt;String, Runnable&gt;() {{ put("one", this::one); put("two", this::two); }}; </code></pre> <p>You can then iterate over the entry-set:</p> <pre><code>for(final String s : array) { for(final Map.Entry&lt;String, Runnable&gt; entry : lookup) { if (s.contains(entry.getKey())) { entry.getValue().run(); break; } } } </code></pre>
Select rows that have different values for a column, given another column <p>Given a table with 2 columns a, b.</p> <p>I want to select rows that for a given a, I can have different values of b.</p> <p>In this example, I want the first 2 lines</p> <pre><code>a | b ----- 1 | 1 1 | 2 2 | 1 2 | 1 3 | 1 </code></pre>
<p>Try this:</p> <pre><code>SELECT t1.* FROM mytable AS t1 JOIN ( SELECT a FROM mytable GROUP BY a HAVING COUNT(DISTINCT b) &gt; 1 ) AS t2 ON t1.a = t2.a </code></pre>
Laravel 5.3 - changing auth view paths <p>In my Laravel app I have different auth for administrators and users. So I have separete views as well. I have placed auth <code>views</code> folder inside <code>admin</code> folder, so that the view path to my admin auth is now <code>admin.auth.login</code> for example. Where can I change those paths so that I can use them for all the auth functions?</p>
<p>If you take a look at your <code>app\Http\Controllers\Auth\LoginController.php</code>, you will see:</p> <pre><code>use AuthenticatesUsers; </code></pre> <p>It's a <a href="http://php.net/manual/en/language.oop5.traits.php" rel="nofollow">traits</a>, you can find all the login related method over there in <code>use Illuminate\Foundation\Auth\AuthenticatesUsers.php</code>. </p> <p>There's a method in the trait which show the view as below:</p> <pre><code>public function showLoginForm() { return view('auth.login'); } </code></pre> <p>What you want to do is either:</p> <ul> <li>Copy the traits out to your own one and modify the <code>showLoginForm</code> method.</li> </ul> <p>or</p> <ul> <li>Override the method <code>showLoginForm</code> in your <code>LoginController.php</code>. See <a href="http://stackoverflow.com/questions/11939166/how-to-override-trait-function-and-call-it-from-the-overriden-function">this</a></li> </ul>
How can I save dragged & dropped elements VALUE after dropped all players (soccer manager) <p>i have a player soccer field and i want the user to create his own LineUp via Drag and Drop...</p> <p>have a look at my fiddle: <a href="https://jsfiddle.net/ahsce0oj/2/" rel="nofollow">https://jsfiddle.net/ahsce0oj/2/</a></p> <p>this is my js code and my fiddle:</p> <pre><code>$(function() { $("#draggable2").draggable({ appendTo: "body", cursorAt: { cursor: "move", top: 5, left: 0 }, helper: function(event) { return $("&lt;img width='5%' src='https://d34h6ikdffho99.cloudfront.net/uploads/real_team/shirt/1174/shirt-300.svg'&gt;"); } }); $("#droppable2").droppable({ accept: "#draggable2", classes: { "ui-droppable-active": "ui-state-default" }, drop: function(event, ui) { $(this).find("p").html("&lt;img width='100%' src='https://d34h6ikdffho99.cloudfront.net/uploads/real_team/shirt/1174/shirt-300.svg'&gt;"); } }); }); </code></pre> <p>(there is only one position at the moment, just a test) ----> You have to move the Text (right side) into the rectangle (mean position of my goalkeeper)</p> <p>but when i have my eleven positions and the "user" is done with his line up draft, how can I save his selection?</p> <p>with IDs? or every time directly after he dropped an element?</p> <p>thanks for any hints</p> <p>Edit: I would be really happy for any other hints how could I delete a dropped player (--> manipulate the DOM—for example delete his shirt and write "GOALKEPPER" instead into a DIV or a <code>&lt;p&gt;</code> Element)</p>
<p>There's a lot of ways to accomplish your goals (pun intended, ha!) here. I will what I would do:</p> <p>Working Example: <a href="https://jsfiddle.net/Twisty/54vgb8bx/4/" rel="nofollow">https://jsfiddle.net/Twisty/54vgb8bx/4/</a></p> <p><strong>HTML Snippet</strong></p> <pre><code> &lt;section id="content"&gt; &lt;div id="field"&gt; &lt;div id="goalie" class="drop center rear"&gt; &lt;p&gt;Goal Keep&lt;/p&gt; &lt;/div&gt; &lt;div id="rightback" class="drop right mid"&gt; &lt;p&gt;R. Back&lt;/p&gt; &lt;/div&gt; &lt;div id="leftback" class="drop center mid"&gt; &lt;p&gt;C. Back&lt;/p&gt; &lt;/div&gt; &lt;div id="leftback" class="drop left mid"&gt; &lt;p&gt;L. Back&lt;/p&gt; &lt;/div&gt; &lt;div id="rightforward" class="drop right for"&gt; &lt;p&gt;R. Forward&lt;/p&gt; &lt;/div&gt; &lt;div id="leftforward" class="drop left for"&gt; &lt;p&gt;L. Forward&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;!-- SIDBAR RIGHT --&gt; &lt;aside&gt; &lt;div id="item-1" data-type="shirt" class="drag"&gt; &lt;p&gt;Move me into the rectangle! ! !&lt;/p&gt; &lt;/div&gt; &lt;/aside&gt; </code></pre> <p><strong>CSS Snippet</strong></p> <pre><code>.drag { float: left; padding: 0% 1% 0%; margin-top: 1%; margin-right: 0%; width: 39%; color: white; background-color: black; } .drop { border: 2px solid white; height: 5vw; width: 5vw; color: white; font-size: 13px; text-align: center; } .rear { position: absolute; top: 0; } .mid { position: absolute; top: 150px; } .for { position: absolute; top: 300px; } .right { left: 135px; } .center { left: 273px; } .left { left: 403px; } #field span.remove:hover { background-color: #000; border-radius: 8px; } </code></pre> <p><strong>jQuery</strong></p> <pre><code>$(function() { $(".drag").draggable({ appendTo: "body", cursorAt: { cursor: "move", top: 5, left: 0 }, helper: function() { var displayImage = $("&lt;img&gt;", { width: "5%", src: 'https://d34h6ikdffho99.cloudfront.net/uploads/real_team/shirt/1174/shirt-300.svg' }).data("type", $(this).data("type")); return displayImage; } }); $(".drop").droppable({ accept: ".drag", classes: { "ui-droppable-active": "ui-state-default" }, drop: function(event, ui) { var removeButton = $("&lt;span&gt;", { class: "ui-icon ui-icon-circle-close remove" }); var dropImage = $("&lt;img&gt;", { width: "100%", src: ui.helper.attr("src") }); $(this) .data("type", ui.helper.data("type")) .data("title", $(this).text()) .find("p") .html(dropImage); removeButton.appendTo($(this).find("p")).position({ my: "left bottom", at: "right top", of: $(this).find("img") }); } }); $("#field").on("click", "span.remove", function() { var me = $(this).parent(); // p var parent = me.parent(); // div var title = parent.data("title"); parent.data("type", "").html("&lt;p&gt;" + title + "&lt;/p&gt;"); }); }); </code></pre> <p>First you will see I adjusted the <code>id</code> and <code>class</code> attributes. This allows the drag and drop elements to have much more specific IDs, and then can be styled via CSS in a more generalized manner. I also added more positions to flush out the example of how this can help when initializing the Draggable and Droppable portion.</p> <p>Second, you may notice I added a <code>data-type</code> attribute to our drag item. This can be a SKU or ID from a database, name of a product, whatever. We can also change the attribute to fit the data better. But this will be how we identify what the user has selected and what that have dropped it on later.</p> <p>Next, we update the CSS to work the way we might need. Making use of <code>position</code>, I can make the <code>#field</code> our boundary, so that each <code>absolute</code> element within is positioned exactly where it should be.</p> <p>Lastly, a lot of jQuery code. Not a lot of big changes to our draggables. Consider now that if you have more items, this will apply to each of them based on their class selector. When we make the helper, we tack on the data attribute so that we can tact it to the drop position.</p> <p>For the drop, we want to do more.</p> <ol> <li>Accept only a drag item</li> <li>Append in the <code>img</code></li> <li>Update the product / ID data</li> <li>Create a way for user to remove selection</li> <li>Store the original text if item is removed</li> </ol> <p>It was not clear if this should no longer be droppable, but you could easily add that in, such that you could not drop a new item onto it. But then initial drop again in the remove button.</p> <p>All this happens in the drop. To avoid confusion (around <code>$(this)</code>), I setup the remove button click function outside of the drop. </p> <p>This should be enough to get you well along. I suspect you'll make a save or complete button. In this I would advise iterating over each <code>.drop</code> and look for info in the <code>data-type</code> attribute for each as well as the <code>id</code> from the parent <code>div</code>. You can then build an object or array to send the data along to be processed. </p>
fatal error: Index out of range, when passing FirebaseData to tablviewCell <p>so I am working a food list project that I want to pass mealname/mealpic/mealDescription to my tableViewCell from FirebaseDatabase.</p> <p>it will be something looks like this <a href="https://i.stack.imgur.com/mo8J1.png" rel="nofollow">enter image description here</a></p> <p>here's my FirebaesDatabase Structure </p> <p><a href="https://i.stack.imgur.com/vkJbM.png" rel="nofollow">enter image description here</a></p> <p>and here's my code in the view controller</p> <pre><code> override func viewDidLoad() { super.viewDidLoad() WeekMenu.delegate = self WeekMenu.dataSource = self let url = GIDSignIn.sharedInstance().currentUser.profile.imageURL(withDimension: 100) let data = try? Data(contentsOf: url!) userpic.image = UIImage(data:data!) DataService.ds.REF_MENUDATA.observe(.value, with: { (snapshot) in if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] { for snap in snapshot { print("SNAP: \(snap)") if let menuDict = snap.value as? Dictionary&lt;String, AnyObject&gt; { let date = snap.key let menu = menuContnet(weekmenudate: date, menuData: menuDict as! Dictionary&lt;String, String&gt;) self.menus.append(menu) } } } }) self.WeekMenu.reloadData() } func numberOfSections(in tableView: UITableView) -&gt; Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { let menu = menus [indexPath.row] if let cell: WeekMenu = tableView.dequeueReusableCell(withIdentifier: "WeekMenu") as! WeekMenu { cell.configureCell(menu: menu) return cell } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "ToVari", sender: nil) } </code></pre> <p>It crashed at runtime and throws an "Index out of range" error at line <code>let menu = menus [indexPath.row]</code></p> <p>I know this Index out of range error question is kind of FAQ but I did some research myself and they don't really help </p> <p>could anyone possibly point out what might went wrong ? thanks </p> <p><strong>UPDATE</strong> </p> <p>now I successfully pass what I have in FirebaseDatabase into my tableview.</p> <p>but I have 5 nodes from Day1 to Day5 but my tableview shows only one (Day3)</p> <p>in my <code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return menus.count }</code></p> <p>why is that happening ?</p> <p>my class of content is like the following </p> <pre><code>class menuContnet { private var _menuKey: String! private var _mealDes : String! private var _mealPic : String! private var _mealname : String! private var _menuRef: FIRDatabaseReference! var menuKey: String{ return _menuKey } var mealDes : String { return _mealDes } var mealname : String { return _mealname } var mealPic : String { return _mealPic } init (mealDes: String, mealname: String, mealPic: String) { self._mealDes = mealDes self._mealname = mealname self._mealPic = mealPic } init (menuKey: String, menuData : Dictionary &lt;String, String&gt;) { self._menuKey = menuKey if let mealname = menuData["mealname"] { self._mealname = mealname } if let mealPic = menuData["mealPic"] { self._mealPic = mealPic } if let mealDes = menuData["mealDes"] { self._mealDes = mealDes } _menuRef = DataService.ds.REF_MENUS.child(_menuKey) } </code></pre> <p>}</p> <p><strong>UPDATE</strong></p> <pre><code>if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] { for snap in snapshot { print ("SNAP: \(snap.key)") if let menuDict = snap.value as? Dictionary&lt;String, String&gt; { let key = snap.key let menu = menuContnet(menuKey: key, menuData: menuDict) print (key) self.menus.append(menu) self.WeekMenu.reloadData() </code></pre> <p>so at print ("SNAP: (snap.key)") i get all nodes from Day1 to Day 5 </p> <p>but at print (key) i get only Day3 </p> <p>i think the "if let menuDict" statement is causing the problem </p> <p>and if i get rid of the "if" and make my code looks like this </p> <pre><code> let menuDict = snap.value as? Dictionary&lt;String, String&gt; let key = snap.key let menu = menuContnet(menuKey: key, menuData: menuDict) print (key) self.menus.append(menu) self.WeekMenu.reloadData() </code></pre> <p>it crashed at runtime throwing "unexpectedly found nil while unwrapping an Optional value" error </p> <p>I think I'm getting there, I will keep doing some more research </p> <p>any tips is appreciated</p>
<p>Try :- </p> <pre><code>DataService.ds.REF_MENUDATA.observe(.value, with: { (snapshot) in if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] { for snap in snapshot { print("SNAP: \(snap)") if let menuDict = snap.value as? Dictionary&lt;String, AnyObject&gt; { let date = snap.key let menu = menuContnet(weekmenudate: date, menuData: menuDict as! Dictionary&lt;String, String&gt;) self.menus.append(menu) self.WeekMenu.reloadData() // This will reload your table to show your newly appended cell one at a time. } /* if menus.count == snap.childrenCount { self.WeekMenu.reloadData() //Will only reload your table after your entire requested database has been retrieved } */ } } }) </code></pre> <p>And change your :- </p> <pre><code> func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return menus.count ?? 0 } </code></pre>
HTML Make code run independently from the rest of the page...iframe? <p>This is a little hard to explain. I'm creating a webpage that shows how other webpages will render in the browser. Here's a simplified version of the problem I'm having...</p> <pre><code>&lt;div id="test"&gt;This is an example of page 1&lt;/div&gt; &lt;div id="test"&gt;This is an example of page 2&lt;/div&gt; </code></pre> <p>As you can see, both divs have the same ID. I can't change the ID in my situation and it's causing problems. I'm having various other CSS and javascript problems also. Each section of code is conflicting with the other. So, I was looking for a way to have a section render independently of everything else. One way to do it would be to create an iframe for each section of code. But that would require me to create a separate webpage for each section, right? Or, is there a way for an iframe to work just by entering code into it, rather than a URL. </p>
<p>You can only have one id per element in an HTML document. So each div must have a different id, otherwise you <em>will</em> run into problems. If multiple elements need to have the same name, you can use classes <code>&lt;div class="test" id="unique-id"&gt;&lt;/div&gt;</code> and then <code>&lt;div class="test" id="another-id"&gt;&lt;/div&gt;</code>.</p> <p>To answer your question with regards to iframes, yes, you need a separate page for each iframe. It is not possible to write code within the iframe tags to execute separately. See the <a href="http://w3c.github.io/html/semantics-embedded-content.html#the-iframe-element" rel="nofollow">iframe spec</a>.</p> <p>Edit: After reading the iframe spec myself, it appears you can use the <code>srcdoc</code> attribute to overwrite what is in the <code>src</code> attribute, but it looks like <a href="http://caniuse.com/#search=srcdoc" rel="nofollow">this isn't entirely accepted across browsers</a>. <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-srcdoc" rel="nofollow">MDN has more information about the attribute.</a></p>
Python, scipy, curve_fit, bounds: How can I contstraint param by two intervals? <p>I`m using scipy.optimize.curve_fit for fitting a sigmoidal curve to data. I need to bound one of parammeters from [-3, 0.5] and [0.5, 3.0]</p> <p>I tried fit curve without bounds, and next if parameter is lower than zero, I fit once more with bounds [-3, 0.5] and in contrary with[0.5, 3.0]</p> <p>Is it possible, to bound function curve_fit with two intervals?</p>
<p>No, least_squares (hence curve_fit) only supports box constraints.</p>
dc:Creator string literal vs. regex FILTER in SPARQL <p>I am using <a href="http://sparql.europeana.eu/" rel="nofollow">Europeana's Virtuoso SPARQL Endpoint</a>.</p> <p>I have been trying to search in SPARQL for content about a specific contributor. To my understanding, this could be carried out this way:</p> <pre><code>PREFIX dc: &lt;http://purl.org/dc/elements/1.1/&gt; SELECT ?title WHERE { ?objectInfo dc:title ?title . ?objectInfo dc:creator 'Picasso' . } </code></pre> <p>Nevertheless, I get nothing in return. </p> <p>Alternatively, I used <strong>FILTER regex</strong> to search for the literal. </p> <pre><code>PREFIX dc: &lt;http://purl.org/dc/elements/1.1/&gt; SELECT ?title ?creator WHERE { ?objectInfo dc:title ?title . ?objectInfo dc:creator ?creator . FILTER regex(?creator, 'Picasso') } </code></pre> <p>This actually worked very well and returned correctly the results.</p> <p>My question is: Is it possible to produce the SPARQL query without using <strong>FILTER</strong> to search the work of a particular artist? </p> <p>Many thanks.</p>
<p>I don't think there are any objects with 'Picasso' literally as the creator. <strong>So a regex filter is a good choice, but slow.</strong> </p> <p>Here's a way to find the strings your regex is matching:</p> <pre><code>PREFIX dc: &lt;http://purl.org/dc/elements/1.1/&gt; SELECT ?creator, (count(?creator) as ?ccount) WHERE { ?objectInfo dc:title ?title . ?objectInfo dc:creator ?creator . FILTER regex(?creator, 'Picasso') } group by ?creator order by ?ccount </code></pre> <p>It might have been easier for you to see that if your had displayed all variables in the select statement:</p> <pre><code>PREFIX dc: &lt;http://purl.org/dc/elements/1.1/&gt; SELECT * WHERE { ?objectInfo dc:title ?title . ?objectInfo dc:creator ?creator . FILTER regex(?creator, 'Picasso') } </code></pre> <p>If you don't want to use a regex filter, you could enumerate all of the Picasso variants you are looking for:</p> <pre><code>PREFIX dc: &lt;http://purl.org/dc/elements/1.1/&gt; SELECT * WHERE { values ?creator { "Picasso, Pablo" "Pablo Picasso" } . ?objectInfo dc:title ?title . ?objectInfo dc:creator ?creator } </code></pre> <p>bif:contains works on this endpoint and is pretty fast:</p> <pre><code>PREFIX dc: &lt;http://purl.org/dc/elements/1.1/&gt; SELECT * WHERE { ?objectInfo dc:title ?title . ?objectInfo dc:creator ?creator . ?creator bif:contains 'Picasso' #FILTER regex(?creator, 'Picasso') } </code></pre>
How to resolve the maven dependency issue <p>when i tried to deploy my maven project into AEM 6.2 bundle remains in install state and its shows the following error</p> <p>com.day.cq.commons,version=[5.7,6) -- Cannot be resolved<br> com.day.cq.replication,version=[5.15,6) -- Cannot be resolved</p> <p>need help!!!</p>
<p>Following is available in AEM 6.2 and that's what your POM should reflect - </p> <p>For CQ Commons</p> <pre><code>&lt;groupId&gt;com.day.cq&lt;/groupId&gt; &lt;artifactId&gt;cq-commons&lt;/artifactId&gt; &lt;version&gt;5.9.22&lt;/version&gt; </code></pre> <p>For CQ Replication</p> <pre><code>&lt;groupId&gt;com.adobe.granite&lt;/groupId&gt; &lt;artifactId&gt;com.adobe.granite.replication.core&lt;/artifactId&gt; &lt;version&gt;6.0.14&lt;/version&gt; </code></pre>
Wallpaper changes every hour? <p>I searched all the internet I cant find a code or example for change the home screen wallpaper every hour or day or min I want something like bing wallpapers or some pictures I put in Drawable all I find live wallpapers or wallpaper service not app or 1 picture with button change the wallpaper I want to put lets say 10 pic and changes every 10 hours I tried this code but it's a service and didn't work because I don't have Activity to lunch so it didn't install please help me with a code or example for several pictures background ... please..!</p> <pre><code>public class MainActivity extends WallpaperService{ Handler handler; private boolean visible; public void onCreate() { super.onCreate(); } public void onDestroy() { super.onDestroy(); } public Engine onCreateEngine() { return new CercleEngine(); } class CercleEngine extends Engine { public Bitmap image1, image2, image3; CercleEngine() { image1 = BitmapFactory.decodeResource(getResources(), R.drawable.greenww); image2 = BitmapFactory.decodeResource(getResources(), R.drawable.redww); image3 = BitmapFactory.decodeResource(getResources(), R.drawable.screen3); } public void onCreate(SurfaceHolder surfaceHolder) { super.onCreate(surfaceHolder); } public void onOffsetsChanged(float xOffset, float yOffset, float xStep, float yStep, int xPixels, int yPixels) { drawFrame(); } void drawFrame() { final SurfaceHolder holder = getSurfaceHolder(); Canvas c = null; try { c = holder.lockCanvas(); if (c != null) { c.drawBitmap(image1, 0, 0, null); c.drawBitmap(image2, 0, 0, null); c.drawBitmap(image3, 0, 0, null); } } finally { if (c != null) holder.unlockCanvasAndPost(c); } handler.removeCallbacks(drawRunner); if (visible) { handler.postDelayed(drawRunner, 1000); // delay 1 sec } } private final Runnable drawRunner = new Runnable() { @Override public void run() { drawFrame(); } }; } </code></pre> <p>xml (Updated)</p> <pre><code>&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.mike.wallpaper2"&gt; &lt;uses-permission android:name="android.permission.SET_WALLPAPER" /&gt; &lt;application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"&gt; &lt;service android:name=".MainActivity" android:enabled="true"&gt; &lt;/service&gt; &lt;/application&gt; </code></pre> <p></p>
<p>Add following code in manifest</p> <pre><code>&lt;receiver android:enabled="true" android:name=".BootUpReceiver" android:permission="android.permission.RECEIVE_BOOT_COMPLETED"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.BOOT_COMPLETED" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; &lt;service android:name=".MainActivity" android:enabled="true" android:exported="true" &gt; &lt;/service&gt; </code></pre> <p>also create one new class </p> <pre><code>public class BootUpReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { /***** For start Service ****/ Intent myIntent = new Intent(context, MainActivity.class); context.startService(myIntent); } } </code></pre>
cannot understand this piece of c++ code <p>I am reading some c++ open source code and a beginner in c++, I found this piece of code is very hard to understand, I don't know what this code are doing and why should it be written in this way. Could any body give me any clue? (The question part is on <code>rndseq[k] = (rndseq[k] &lt;&lt; 8) | (rand() &amp; 0xff)</code>;)</p> <pre><code> static unsigned int rndseq[2048]; for (k = 0; k &lt; 2048; k++) { rndseq[k] = 0; for (i=0; i &lt; (int)sizeof(int); ++i) rndseq[k] = (rndseq[k] &lt;&lt; 8) | (rand() &amp; 0xff); } </code></pre>
<pre><code>(rndseq[k] &lt;&lt; 8) | (rand() &amp; 0xff) </code></pre> <p>these are binary-operation, (see bit-operations in C)</p> <p>it can be translated into</p> <pre><code>rndseq[k] * 256 + rand() % 256 </code></pre> <p>the idea behind the code is, to create a large array with random entries, but its way too complicated</p> <p>i hope, this helps you to understand the logic</p> <pre><code> //we want to fill this array with random numbers static unsigned int rndseq[2048]; // for each k-entry of the array for (k = 0; k &lt; 2048; k++) { // initialize k-entry with zero rndseq[k] = 0; // for each byte in the k-entry integer for (i=0; i &lt; (int)sizeof(int); ++i) //on the first iteration rndseq[k] is zero, so //(rndseq[k] &lt;&lt; 8) remains zero. //(rand() &amp; 0xff) creates a random number in the range [0,255] //-&gt; in the first iteration rndseq[k] will be set to a random number ([0,255]) //lets say, you have a int32 (4 bytes) //you need 1 byte to represent 255 //so you have 3 "empty" bytes and 1 filled //lets say, rand() got the number 1 //than rndseq would have the following value //0x00-0x00-0x00-0x01 //in the next iteration you shift 1 byte, so //you get from (rndseq[k] &lt;&lt; 8) //0x00-0x00-0x01-0x00 //the next random-number (still 1 byte) (lets say 2) //will be stored in now free last byte //result: //0x00-0x00-0x01-0x02 //now you repeat, until all bytes are set //result: //0x01-0x02-0x03-0x04 rndseq[k] = (rndseq[k] &lt;&lt; 8) | (rand() &amp; 0xff); } </code></pre>
rattle "Info" Score in Description of the dataset <p>Running descriptive statistics in rattle and need to know what "Info" is in the results. Have not been able to find any information in the vignette. Here is an example of what I'm speaking of:</p> <pre> Variable1 n missing unique <b><em>Info</em></b> Sum Mean 89588 0 2 <b><em>0.61</em></b> 25735 0.2873 </pre> <p>We believe it is a score of 0 to 1, but we are unable to find the exact definition.</p>
<p>The describe function used in Rattle comes from the package HMisc.</p> <p>In the documentation of HMisc::describe this is said about Info:</p> <blockquote> <p>For numeric variables, describe adds an item called Info which is a relative information measure using the relative efficiency of a proportional odds/Wilcoxon test on the variable relative to the same test on a variable that has no ties. Info is related to how continuous the variable is, and ties are less harmful the more untied values there are. The formula for Info is one minus the sum of the cubes of relative frequencies of values divided by one minus the square of the reciprocal of the sample size. The lowest information comes from a variable having only one unique values following by a highly skewed binary variable. Info is reported to two decimal places.</p> </blockquote>
set multi attributes at once without jquery <p>There is a way to write this code in shorter way instead of</p> <pre><code> var aTag = document.createElement('a'); aTag.setAttribute('href', oUrl.toString()); aTag.setAttribute('rel', "test"); aTag.setAttribute('target', "_blank"), ... </code></pre> <p>I try with the following which is not working...is it possible? I found in the net examples with Jquery but I don't want to use it now...</p> <pre><code> var aTag = document.createElement('a'), .setAttribute('href', oUrl.toString()), .setAttribute('rel', "test"), .setAttribute('target', "_blank"), ... </code></pre>
<p>Sure, you could use a loop.</p> <pre><code>function setAttributes(el, attrs) { Object.keys(attrs).forEach(function (attr) { el.setAttribute(attr, attrs[attr]); }); } var aTag = document.createElement('a'); setAttributes(aTag, { href: oUrl, rel: "test", target: "_blank" }); </code></pre>
Jupyter magic to handle notebook exceptions <p>I have a few long-running experiments in my Jupyter Notebooks. Because I don't know when they will finish, I add an email function to the last cell of the notebook, so I automatically get an email, when the notebook is done.</p> <p>But when there is a random exception in one of the cells, the whole notebook stops executing and I never get any email. <strong>So I'm wondering if there is some magic function that could execute a function in case of an exception / kernel stop.</strong></p> <p>Like</p> <pre><code>def handle_exception(stacktrace): send_mail_to_myself(stacktrace) %%in_case_of_notebook_exception handle_exception # &lt;--- this is what I'm looking for </code></pre> <p>The other option would be to encapsulate every cell in try-catch, right? But that's soooo tedious.</p> <p>Thanks in advance for any suggestions.</p>
<p>A such magic command does not exist, but you can write it.</p> <pre><code>from IPython.core.magic import register_cell_magic @register_cell_magic def handle(line, cell): try: exec(cell) except Exception as e: send_mail_to_myself(e) </code></pre> <p>It is not possible to load automatically the magic command for the whole notebook, you have to add it at each cell where you need this feature. </p> <pre><code>%%handle some_code() raise ValueError('this exception will be caught by the magic command') </code></pre>
converting float to sprintf <p>I'm trying to convert a float to char string I used sprintf, as the following</p> <pre><code> float temperature = getTemperature(); char array[15]; sprintf(array, "temperature %f", temperature); int length = strlen(array); protocol_WriteMessage(length,(unsigned char*)&amp;array); </code></pre> <p>but protocol_WriteMessage accepts unsigned char *, so I casted it, but the program crashes. </p> <pre><code>void protocol_WriteMessage( UINT16 wLen, UINT8 *pbData ) { UINT16 crc_calc; // Calculate transmitt CRC16 crc_calc = calc_crc16(&amp;pbData[COMM_POS_COMMAND1], wLen-COMM_POS_COMMAND1); comm_states.TxActive = true; // signal that the Tx_UART is working // write data without further checks hal_uart_WriteBuffer( wLen, pbData ); } </code></pre>
<p>First of all use a safer alternative like <a href="http://man7.org/linux/man-pages/man3/printf.3.html" rel="nofollow"><code>snprintf()</code></a>, and then remove the <code>&amp;</code> address of operator from the call.</p> <p>To use <code>snprintf()</code> you need to do something like this</p> <pre><code>int result; char array[32]; // This should be big enough result = snprintf(array, sizeof(array), "temperature %f", temperature); if ((result == -1) || (result &gt;= sizeof(array))) { // It means that array is too small, or some other error // occurred such that `snprintf' has returned -1 } protocol_WriteMessage(length, (unsigned char *) array); </code></pre> <p>since array is already a pointer to the first element of itself, which is of type <code>char</code> then it's type is <code>char *</code> when passed like that as a pointer, using the <code>&amp;</code> operator is clearly wrong and casting only hides the fact that you made a mistake.</p>
Remove warn message about hidden settings in sitecore 8 <p>Sitecore has a dozen of hidden settings, but I see WARN messages in log about wrong value in this fields, foe example</p> <p><em>11168 08:18:11 WARN The "EventQueue.Enabled" setting contains an invalid value. The default value is used instead. Invalid value: "". Default value: "True"</em></p> <p>or <em>11168 08:18:14 WARN The "Templates.MaxInheritanceDepth" setting contains an invalid value. The default value is used instead. Invalid value: "". Default value: "16"</em></p> <p>is is possible to hide this kind of messages ?</p> <p>I understand that I can add each of this settings to config file, but I am lazy is it any settings about it ?</p>
<p>No, there is no setting for that unless you change logging level to <code>ERROR</code> or <code>FATAL</code>.</p> <p>Looks like those settings are already in your config just with empty values. Maybe it's enough to remove line like that from your configs:</p> <pre class="lang-xml prettyprint-override"><code>&lt;setting name="EventQueue.Enabled" value=""/&gt; </code></pre> <p>If it's not in default <code>sitecore.config</code> file, check <code>/sitecore/admin/showconfig.aspx</code> for the information which patch this value comes from. There should be <code>patch:source</code> attribute (assuming you're using Sitecore 8.x).</p>
SQL Error: ORA-01841 <p>I am getting the following error when I run code in SQL Developer:</p> <blockquote> <p>SQL Error: ORA-01841: (full) year must be between -4713 and +9999, and not be 0 01841. 00000 - "(full) year must be between -4713 and +9999, and not be 0"</p> </blockquote> <p>I get this error when I try to create a table. Funnily when I just do the embedded select without the <code>create table</code> the code runs fine.</p> <p>the sentence is:</p> <pre><code> CREATE TABLE TEMP2 AS select LAST_DAY(TO_DATE(RDF.maxfiledate || '/01','yyyy/mm/dd')) as EXPOS from FOR_FRONTING3 FRO left join RDF_TEMP RDF on FRO.POLICYNO = RDF.POLICYNO and FRO.LASTRENW = RDF.LASTRENW; </code></pre> <p>Any ideas why simply wrapping the select in a <code>create table</code> causes this error?</p>
<p>First, believe the error. You have bad data.</p> <p>In all likelihood, you are looking at the results from running the query and not seeing it -- because you are only looking at the first few results. The <code>create table</code> is run over all the rows before it returns, so it will find the offending row.</p> <p>The cause would be this line:</p> <pre><code> then (LAST_DAY(TO_DATE(RDF.maxfiledate || '/01','yyyy/mm/dd')) - RDF.LASTRENW)/RDF.POL_DAYS_ERND </code></pre> <p>You should be able to find the offending line with something like:</p> <pre><code>SELECT * FROM RDF_TEMP RDF WHERE NOT REGEXP_LIKE(RDF.maxfiledate, '^[0-9]{4}/') </code></pre> <p>If the first four characters are digits, then Oracle shouldn't have a conversion problem with the <em>year</em>.</p>
How to connect to Microsoft SQL server using GORM in golang? <p>I'm trying to connect to a microsoft SQL server using GORM: <a href="https://github.com/jinzhu/gorm" rel="nofollow">https://github.com/jinzhu/gorm</a></p> <p>But I cannot seem to find any tables when I try using db.HasTable() and I checked the credentials which are fine. I did receive a message that GORM doesn't officially support MSSQL and it runs in compatibility mode but I also included an SQL driver: github.com/denisenkom/go-mssqldb that's used for MSSQL. Is there something I'm missing?</p>
<p>I found my error, I was importing the wrong MSSQL driver, gorm already has one import _ "github.com/jinzhu/gorm/dialects/mssql"</p>
Total users from serialized id field <p>I need a little help to get <strong>how many users are associated with a specific company</strong> from a serialized id field.</p> <pre><code>TABLE_USER user_id user_name user_companies &lt;- Serialized id field </code></pre> <p>If I have a INT field I can get value in this way:</p> <pre><code> SELECT * FROM table_user WHERE user_companies = 1 </code></pre> <p>But, how to get total users from serialized field? Any example would be appreciated</p> <p>TKS all</p>
<p>That's not the way to use a database. Ideally you should have a joined table with users and companies. It wouldn't be that difficult to run one script that selects, unserializes and inserts into a new table that you can join. But assuming that's how it is you have to do it in PHP:</p> <pre><code>// SELECT * FROM table_user $company_id = 1; while($row = your_fetch_array()) { if(in_array($company_id, unserialize($row['user_companies'])) { $results[] = $row; } } </code></pre> <p>To get the unserialized companies in the result array:</p> <pre><code>while($row = your_fetch_array()) { $companies = unserialize($row['user_companies']); if(in_array($company_id, $companies) { $results[] = array_merge($row, array('user_companies' =&gt; $companies)); } } </code></pre> <p>You don't mention your database or API, so query and fetch as you normally would.</p> <p>If you use JSON (still not recommended) then you may get some mileage out of <a href="https://dev.mysql.com/doc/refman/5.7/en/json-function-reference.html" rel="nofollow">MySQL JSON Functions</a>.</p>
How to sort associative arrays in descending order? <p>I know about rsort and array_reverse but I'd like to know how you could reverse all elements of an associative array as well as their index numbers. e.g.:</p> <p>Take <code>$age = array("x"=&gt;"35", "y"=&gt;"45", "z"=&gt;"55");</code></p> <p>and display it as</p> <p><code>z 55</code></p> <p><code>y 45</code></p> <p><code>x 35</code></p> <p>I tried this but it doesn't show what I want:</p> <pre><code>$age = array("x"=&gt;"35", "y"=&gt;"45", "z"=&gt;"55"); array_reverse($age); foreach($age as $x =&gt; $x_value){ echo $x . " " . $x_value; echo "&lt;br&gt;"; } </code></pre>
<p>I think you want to sort by key in decending order so you need to do flowing.Because <code>array_reverse()</code> function swap key with value in an array.</p> <pre><code>$age = array("x"=&gt;"35", "y"=&gt;"45", "z"=&gt;"55"); krsort($age); foreach($age as $x =&gt; $x_value){ echo $x . " " . $x_value; echo "&lt;br&gt;"; } </code></pre>
large data transformation in python <p>I have a large data set (ten 12gb csv files) that have 25 columns and would want to transform it to a dataset with 6 columns. the first 3 columns remains the same whereas the 4th one would be the variable names and the rest contains data. Below is my input:</p> <pre><code>#RIC Date[L] Time[L] Type L1-BidPrice L1-BidSize L1-AskPrice L1-AskSize L2-BidPrice L2-BidSize L2-AskPrice L2-AskSize L3-BidPrice L3-BidSize L3-AskPrice L3-AskSize L4-BidPrice L4-BidSize L4-AskPrice L4-AskSize L5-BidPrice L5-BidSize L5-AskPrice L5-AskSize HOU.ALP 20150901 30:10.8 Market Depth 5.29 50000 5.3 32000 5.28 50000 5.31 50000 5.27 50000 5.32 50000 5.26 50000 5.33 50000 5.34 50000 HOU.ALP 20150901 30:10.8 Market Depth 5.29 50000 5.3 44000 5.28 50000 5.31 50000 5.27 50000 5.32 50000 5.26 50000 5.33 50000 5.34 50000 HOU.ALP 20150901 30:12.1 Market Depth 5.29 50000 5.3 32000 5.28 50000 5.31 50000 5.27 50000 5.32 50000 5.26 50000 5.33 50000 5.34 50000 HOU.ALP 20150901 30:12.1 Market Depth 5.29 50000 5.3 38000 5.28 50000 5.31 50000 5.27 50000 5.32 50000 5.26 50000 5.33 50000 5.34 50000 </code></pre> <p>and I would transform it to:</p> <pre><code>#RIC Date[L] Time[L] level Bid_price bid_volume Ask_price Ask_volume HOU.ALP 20150901 30:10.8 L1 5.29 50000 5.3 50000 HOU.ALP 20150901 30:10.8 L2 5.28 50000 5.31 50000 HOU.ALP 20150901 30:12.1 L3 5.27 50000 5.32 50000 HOU.ALP 20150901 30:12.1 L4 5.26 50000 5.33 50000 HOU.ALP 20150901 30:12.1 L5 HOU.ALP 20150901 30:12.1 L1 5.29 50000 5.3 50000 HOU.ALP 20150901 30:12.1 L2 5.28 44000 5.31 50000 HOU.ALP 20150901 30:12.1 L3 5.27 48000 5.32 50000 HOU.ALP 20150901 30:12.1 L4 5.26 50000 5.33 50000 </code></pre> <p>Here is my attempt with the coding. I think I would have to use dictionary to write to a csv file</p> <pre><code>def depth_data_transformation(input_file_list, output_file): for file in input_file_list: file_to_open = '%s.csv' %file with open(file_to_open) as f, open(output_file, "w") as out: next(f) # skip header cols = ["#RIC", "Date[L]", "Time[L]", "level", "Bid_price", "bid_volume", "Ask_price", "Ask_volume"] wr = csv.writer(out) wr.writerow(cols) for row in csv.reader(f): # get all but first three cols it = row[4:] # zip_longest(*[iter(it)] * 4, fillvalue="") -&gt; group into 4's, add empty string for missing values for ind, t in enumerate(izip_longest(*[iter(it)] * 4, fillvalue=""), 1): # first 3 cols, level and group all in one row/list. wr.writerow(row[:3]+ ["l{}".format(ind)] + list(t)) </code></pre>
<p>You need to group the levels, i.e <code>L1-BidPrice L1-BidSize L1-AskPrice L1-AskSize</code> and write each to a new row :</p> <pre><code>import csv from itertools import zip_longest # izip_longest python2 with open("infile.csv") as f, open("out.csv", "w") as out: next(f) # skip header cols = ["#RIC", "Date[L]", "Time[L]", "level", "Bid_price", "bid_volume", "Ask_price", "Ask_volume"] wr = csv.writer(out) wr.writerow(cols) for row in csv.reader(f): # get all but first three cols. it = row[4:] # zip_longest(*[iter(it)] * 4, fillvalue="") -&gt; group into 4's, add empty string for missing values for ind, t in enumerate(zip_longest(*[iter(it)] * 4, fillvalue=""), 1): # first 3 cols, level and group all in one row/list. wr.writerow(row[:3]+ ["l{}".format(ind)] + list(t)) </code></pre> <p>Which would give you:</p> <pre><code>#RIC,Date[L],Time[L],level,Bid_price,bid_volume,Ask_price,Ask_volume HOU.ALP,20150901,30:10.8,l1,5.29,50000,5.3,32000 HOU.ALP,20150901,30:10.8,l2,5.28,50000,5.31,50000 HOU.ALP,20150901,30:10.8,l3,5.27,50000,5.32,50000 HOU.ALP,20150901,30:10.8,l4,5.26,50000,5.33,50000 HOU.ALP,20150901,30:10.8,l5,5.34,50000,, HOU.ALP,20150901,30:10.8,l1,5.29,50000,5.3,44000 HOU.ALP,20150901,30:10.8,l2,5.28,50000,5.31,50000 HOU.ALP,20150901,30:10.8,l3,5.27,50000,5.32,50000 HOU.ALP,20150901,30:10.8,l4,5.26,50000,5.33,50000 HOU.ALP,20150901,30:10.8,l5,5.34,50000,, HOU.ALP,20150901,30:12.1,l1,5.29,50000,5.3,32000 HOU.ALP,20150901,30:12.1,l2,5.28,50000,5.31,50000 HOU.ALP,20150901,30:12.1,l3,5.27,50000,5.32,50000 HOU.ALP,20150901,30:12.1,l4,5.26,50000,5.33,50000 HOU.ALP,20150901,30:12.1,l5,5.34,50000,, HOU.ALP,20150901,30:12.1,l1,5.29,50000,5.3,38000 HOU.ALP,20150901,30:12.1,l2,5.28,50000,5.31,50000 HOU.ALP,20150901,30:12.1,l3,5.27,50000,5.32,50000 HOU.ALP,20150901,30:12.1,l4,5.26,50000,5.33,50000 HOU.ALP,20150901,30:12.1,l5,5.34,50000,, </code></pre> <p>In <code>for ind, t in enumerate(zip_longest(*[iter(it)] * 4, fillvalue=""), 1)</code>, <em><code>enumerate</code></em> with a start index of 1 is keeping track of which <em>group/level</em> we are at.</p> <p><em><code>zip_longest(*[iter(it)] * 4, fillvalue="")</code></em> groups the cols into sections i.e <code>L1-BidPrice,L1-BidSize,L1-AskPrice,L1-AskSize</code>, <code>L2-BidPrice,L2-BidSize,L2-AskPrice,L2-AskSize</code> etc.. all the way to <code>Ln-..</code> </p> <p>You have <code>HOU.ALP 20150901 30:10.8 L1 5.29 50000 5.3 50000</code> in your expected output but 32000 is the value in your input for <code>L1-AskSize</code>, each row has 5 levels and you also have 8 columns so I presume your expected output is wrong.</p>
Python backtest using percentage based commission <p>I'm writing a script to backtest some strategies for a set of stocks using the bt framework for python. In the bt documentation (<a href="http://pmorissette.github.io/bt/bt.html#module-bt.backtest" rel="nofollow">backtest module</a>) it says: </p> <blockquote> <p>commission (fn(quantity)): The commission function to be used.</p> </blockquote> <p>So when I run my code </p> <pre><code>result = bt.Backtest(strategy, data, initial_capital= 100000.00, commissions=) </code></pre> <p>I want to pass a function that returns a percentage based commission e.g. 0.5 % of the transaction. Since I don't know the size of the transactions, is this even possible? How would it otherwise be solved, using a set commission?</p>
<p>Solved it by creating a function with parameters for quantity and price. Thus it was easy returning a percentage based on the transaction cost as follows:</p> <pre><code>def my_comm(q, p): return abs(q)*p*0.0025 </code></pre>
how to pass data between templates meteor js <p>i'm working with Meteor js and i'm trying to pass data from a template to another and this is my code :</p> <p><strong>BuildingsAction.js</strong></p> <pre><code> Template.BuildingsAction.viewmodel({ showExhibitions() { FlowRouter.go("/exhibitions"); },}) </code></pre> <p>Actually i would like to pass an _id from BuildingsAction to exhibitions</p> <pre><code> Template.exhibitions.viewmodel({ onCreated: function () { this.idItemParent(BuildingsAction_id)// here i whoud like to get the id })} </code></pre>
<p>There are two ways.</p> <p><strong>1. Using session.</strong></p> <pre><code>`Session.set('idVar',YourId);` </code></pre> <p>Get Session Value: <code>Session.get('idVar');</code></p> <p><strong>2. You can send the id in URL</strong></p> <p><code>FlowRouter.go("/exhibitions",{},{id:YourID});</code> </p> <p>Get queryparam Value: <code>FlowRouter.getQueryParam("id");</code></p>
Can you override an "onscroll" listener by using another? <p>I'm working on a problem where I want to override the global onscroll event listener with one specifically assigned to an element.</p> <p>Here is an example.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$("a").on('click', function(){ console.log('Clicked'); $('html,body').animate({scrollTop:50}, 1000); var count = 0; $(window).on('scroll', function(){ if(count &lt; 5) { console.log('Scrolling via link...'); } count++; }); }); var globalCount = 0; $(window).on('scroll', function(){ if(globalCount &lt; 5) { console.log('Scrolling...'); } globalCount++; });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body{min-height:2000px;}</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;a href="#"&gt;Link&lt;/a&gt;</code></pre> </div> </div> </p> <p>How do I <strong>prevent</strong> the <em>console.log('Scrolling...')</em> from running?</p>
<p>I don't really understand exactly what you're trying to do... but, you can unregister the scroll event handler that you attach at the bottom inside the click event handler, just before you attach your new one, by doing <code>$(window).off('scroll')</code></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$("a").on('click', function(){ console.log('Clicked'); $('html,body').animate({scrollTop:50}, 1000, attachGlobalListener); var count = 0; $(window).off('scroll'); //This removes the "global" event handler specified at the bottom of this snippet $(window).on('scroll', function(){ if(count &lt; 5) { console.log('Scrolling via link...'); } count++; }); }); function attachGlobalListener(){ var globalCount = 0; $(window).on('scroll', function(event){ if(globalCount &lt; 5) { console.log('Scrolling...'); } globalCount++; }); } //attach the listener to begin with attachGlobalListener();</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body{min-height:2000px;}</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;a href="#"&gt;Link&lt;/a&gt;</code></pre> </div> </div> </p>
Ramda: Call array of functions on array of values <p>If I have the array <code>data</code> and the array of functions <code>[fn1, fn2, fn3]</code>, what's the right way with Ramda to get</p> <pre><code>[fn1(data[0]), fn2(data[1], fn3(data[2]), ...] </code></pre> <p>Basically, I want to call each function with the value that shares an array index in the <code>data</code> as its parameter, and get an array of the results.</p>
<p>You'll want to use <a href="http://ramdajs.com/docs/#zipWith"><code>zipWith</code></a> with <a href="http://ramdajs.com/docs/#call"><code>call</code></a>:</p> <pre><code>R.zipWith(R.call, fns, data) </code></pre>
Insert variable in specific place using sed -i <p>i would insert two variable in sed command:</p> <pre><code>sed -i '39,41 s/^#//' file </code></pre> <p>i would</p> <pre><code>sed -i '$LINE,$LINE_INCREMENTED s/^#//' file </code></pre> <p>but return this:</p> <blockquote> <p>sed: -e expression #1, char 9: unknown command: `$'</p> </blockquote>
<p>drop the quotes for double quotes so environment variables are evaluated:</p> <pre><code>sed -i "$LINE,$LINE_INCREMENTED s/^#//" file </code></pre>
symmetricds: sym_data table in master node is filled but sym_data_event is empty <p>We have a problem, sym_data table in master node is filled with data but sym_data_event is empty and sym_outgoing_batch is empty too. No any error in log file, symmetricds version is 3.4.2. One day ago all works fine and symmetricds config files not changed.</p> <p>postgresql log:</p> <pre><code>23643 1 2016-10-18 17:20:38 MSK [unknown] [unknown] [unknown] 00000LOG: connection received: host=192.168.0.111 port=36888 23643 2 2016-10-18 17:20:38 MSK century symmetricds 192.168.0.111 [unknown] 00000LOG: connection authorized: user=symmetricds database=century 23643 3 2016-10-18 17:20:38 MSK century symmetricds 192.168.0.111 [unknown] 42P01ERROR: relation "gp_id" does not exist at character 20 23643 4 2016-10-18 17:20:38 MSK century symmetricds 192.168.0.111 [unknown] 42P01STATEMENT: select gpname from gp_id 23643 5 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 6 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(ROUTE) already exists. 23643 7 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 8 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 9 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(PULL) already exists. 23643 10 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 11 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 12 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(PUSH) already exists. 23643 13 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 14 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 15 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(HEARTBEAT) already exists. 23643 16 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 17 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 18 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(PURGE_INCOMING) already exists. 23643 19 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 20 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 21 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(PURGE_OUTGOING) already exists. 23643 22 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 23 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 24 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(PURGE_STATISTICS) already exists. 23643 25 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 26 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 27 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(SYNCTRIGGERS) already exists. 23643 28 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 29 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK"ф 23643 30 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(PURGE_DATA_GAPS) already exists. 23643 31 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 32 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 33 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(STAGE_MANAGEMENT) already exists. 23643 34 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 35 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 36 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(WATCHDOG) already exists. 23643 37 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 38 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 39 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(STATISTICS) already exists. 23643 40 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 41 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 42 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(FILE_SYNC_PULL) already exists. 23643 43 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 44 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 45 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(FILE_SYNC_PUSH) already exists. 23643 46 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 47 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 48 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(FILE_SYNC_TRACKER) already exists. 23643 49 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 50 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_lock_PK" 23643 51 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (lock_action)=(INITIAL_LOAD_EXTRACT) already exists. 23643 52 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_lock (lock_action) values($1) 23643 53 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_sequence_PK" 23643 54 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (sequence_name)=(outgoing_batch) already exists. 23643 55 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_sequence (sequence_name, current_value, increment_by, min_value, max_value, cycle, create_time, last_update_by, last_update_time) values($1,$2,$3,$4,$5,$6,current_timestamp,$7,current_timestamp) 23643 56 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505ERROR: duplicate key value violates unique constraint "sym_sequence_PK" 23643 57 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505DETAIL: Key (sequence_name)=(outgoing_batch_load_id) already exists. 23643 58 2016-10-18 17:20:43 MSK century symmetricds 192.168.0.111 [unknown] 23505STATEMENT: insert into sym_sequence (sequence_name, current_value, increment_by, min_value, max_value, cycle, create_time, last_update_by, last_update_time) values($1,$2,$3,$4,$5,$6,current_timestamp,$7,current_timestamp) </code></pre>
<p>It seems that symmetricds the engine is not working. sym_data table is populated by database triggers, symmetricds engine is not required to run. But to populate data event and outgoing batch tables symmetricds engine has to be running and routing extracted data</p>
Is there any way by which I can save files to icloud in Cordova <p>I'm using cordova-sqlite-plugin, according to its documentation, the database file will be backed up by iCloud if I put it to a right directory. But it's not working. I thought perhaps iCloud dosen't support sqlite file, so I dump the data into a sql file, and put it to Libary/Cloud directory, still not working.</p>
<p>Try adding this to your <code>config.xml</code>.</p> <p><code>&lt;preference name="BackupWebStorage" value="cloud" /&gt;</code></p>
How to exclude a supplier if it returns two values <p>I need to create a clause to restrict the data returned.</p> <p>if AUTHORIZATION_STATUS from PO_headers_all returns STATUS 'approved' and 'in process' then do not return supplier. however it it returns as 'approved' on its own I need the supplier to be returned.</p> <p>The purpose of this is to return suppliers that do not have outstanding PO against them.</p> <p>Is there a way of doing this? </p> <pre><code>Select company, vendor_site_code, vendor_name, segment1, Site_Type, Max_Invoice_Date, TEST From ( select inv.org_id company, ps.vendor_site_code, pv.vendor_name, pv.segment1, inv.org_id, -- CASE WHEN pha.AUTHORIZATION_STATUS IN ( 'APPROVED', 'IN PROCESS') THEN 'ACTIVE' -- ELSE 'IN ACTIVE' end AS TEST, ps.pay_group_lookup_code AS Site_Type, MAX (inv.gl_date) AS Max_Invoice_Date, 1 As unit_ from ap_invoices_all inv, po_vendors pv, po_vendor_sites_all ps, PO_headers_all pha where inv.vendor_id = pv.vendor_id and pv.vendor_id = ps.vendor_id and inv.vendor_site_id = ps.vendor_site_id and pha.vendor_id = pv.vendor_id and inv.org_id in (174,169,172) and ps.inactive_date is null and pv.END_DATE_ACTIVE is null GROUP BY inv.org_id, ps.vendor_site_code, pv.vendor_name, pv.segment1, ps.pay_group_lookup_code, inv.org_id, --CASE WHEN pha.AUTHORIZATION_STATUS IN ( 'APPROVED', 'IN PROCESS') THEN 'ACTIVE' -- ELSE 'IN ACTIVE' end ORDER BY vendor_name DESC ) WHERE Max_Invoice_Date &lt; TRUNC(ADD_MONTHS( SYSDATE, -12 ),'MONTH') </code></pre> <p>an example output is below; </p> <pre><code>172|UMANIS.201|UMANIS|COMPUTER|12988|EXPENSE|24-NOV-11|APPROVED 172|UMANIS.201|UMANIS|COMPUTER|12988|EXPENSE|24-NOV-11|IN PROCESS </code></pre> <p>I would like to exclude the supplier if the results are like the above. </p>
<p>Ok, let's dive in.</p> <p>But first a necessary pointer to <a href="http://stackoverflow.com/help/mcve">How to create a Minimal, Complete, and Verifiable example</a></p> <p>You can find (and hopefully, correct, complete and add into your question) an attempt of such an example in this answer (also on <a href="http://rextester.com/EORAT45177" rel="nofollow">rextester</a>). The example could be extensively simplified as lots of the fields don't really relate to your core question ("How can I filter records where the condition is the existence of two related records in another table?") but on your specific business requirements.</p> <p>I decided not to simplify anything, because I wanted to be able to test <em>exactly</em> the query you have put into the question.</p> <p>I've tried to recreate the sample data from what you said, from the query and the sample output.</p> <p>I've created 2 vendors: UMANIS (whose header status contains both "APPROVED" and "IN PROCESS", and thus it should be filtered out) and ROBOZ (whose header status contains only "APPROVED" and thus it should be returned).</p> <pre><code> create table ap_invoices_all ( org_id integer, gl_date date, vendor_id integer, vendor_site_id integer ); insert into ap_invoices_all (org_id, gl_date, vendor_id, vendor_site_id) values (172 , to_date('2015-04-27','YYYY-MM-DD'), 111, 201); insert into ap_invoices_all (org_id, gl_date, vendor_id, vendor_site_id) values (172 , to_date('2015-03-11','YYYY-MM-DD'), 222, 301); create table po_vendors ( vendor_name varchar2(20), segment1 varchar2(20), vendor_id integer, end_date_active date ); insert into po_vendors (vendor_id, vendor_name, segment1, end_date_active) values (111, 'UMANIS','SEGM1',null); insert into po_vendors (vendor_id, vendor_name, segment1, end_date_active) values (222, 'ROBOZ','SEGM1',null); create table po_vendor_sites_all ( vendor_site_code varchar2(20), pay_group_lookup_code varchar2(20), vendor_id integer, vendor_site_id integer, inactive_date date ); insert into po_vendor_sites_all (vendor_id, vendor_site_id, vendor_site_code, pay_group_lookup_code, inactive_date) values (111, 201, 'UMANIS.201', 'EXPENSE',null); insert into po_vendor_sites_all (vendor_id, vendor_site_id, vendor_site_code, pay_group_lookup_code, inactive_date) values (222, 301, 'ROBOZ.301', 'EXPENSE',null); create table po_headers_all ( vendor_id integer, AUTHORIZATION_STATUS varchar2(20) ); insert into po_headers_all (vendor_id, AUTHORIZATION_STATUS) values (111, 'APPROVED'); insert into po_headers_all (vendor_id, AUTHORIZATION_STATUS) values (111, 'IN PROCESS'); insert into po_headers_all (vendor_id, AUTHORIZATION_STATUS) values (222, 'APPROVED'); -- Original query Select company, vendor_site_code, vendor_name, segment1, Site_Type, Max_Invoice_Date, TEST From ( select inv.org_id company, ps.vendor_site_code, pv.vendor_name, pv.segment1, inv.org_id, CASE WHEN pha.AUTHORIZATION_STATUS IN ( 'APPROVED', 'IN PROCESS') THEN 'ACTIVE' ELSE 'IN ACTIVE' end AS TEST, ps.pay_group_lookup_code AS Site_Type, MAX (inv.gl_date) AS Max_Invoice_Date, 1 As unit_ from ap_invoices_all inv, po_vendors pv, po_vendor_sites_all ps, PO_headers_all pha where inv.vendor_id = pv.vendor_id and pv.vendor_id = ps.vendor_id and inv.vendor_site_id = ps.vendor_site_id and pha.vendor_id = pv.vendor_id and inv.org_id in (174,169,172) and ps.inactive_date is null and pv.END_DATE_ACTIVE is null GROUP BY inv.org_id, ps.vendor_site_code, pv.vendor_name, pv.segment1, ps.pay_group_lookup_code, inv.org_id, CASE WHEN pha.AUTHORIZATION_STATUS IN ( 'APPROVED', 'IN PROCESS') THEN 'ACTIVE' ELSE 'IN ACTIVE' end ORDER BY vendor_name DESC ) WHERE Max_Invoice_Date &lt; TRUNC(ADD_MONTHS( SYSDATE, -12 ),'MONTH'); -- proposed query Select company, vendor_site_code, vendor_name, segment1, Site_Type, Max_Invoice_Date, TEST From ( select inv.org_id company, ps.vendor_site_code, pv.vendor_name, pv.segment1, inv.org_id, CASE WHEN pha_app.vendor_id is not null or pha_proc.vendor_id is not null THEN 'ACTIVE' ELSE 'IN ACTIVE' end AS TEST, ps.pay_group_lookup_code AS Site_Type, MAX (inv.gl_date) AS Max_Invoice_Date, 1 As unit_ from ap_invoices_all inv inner join po_vendors pv on inv.vendor_id = pv.vendor_id inner join po_vendor_sites_all ps on inv.vendor_site_id = ps.vendor_site_id and pv.vendor_id = ps.vendor_id left join po_headers_all pha_app on pha_app.vendor_id = pv.vendor_id and pha_app.AUTHORIZATION_STATUS='APPROVED' left join po_headers_all pha_proc on pha_proc.vendor_id = pv.vendor_id and pha_proc.AUTHORIZATION_STATUS='IN PROCESS' where inv.org_id in (174,169,172) and ps.inactive_date is null and pv.END_DATE_ACTIVE is null and (pha_app.vendor_id is not null and pha_proc.vendor_id is null) GROUP BY inv.org_id, ps.vendor_site_code, pv.vendor_name, pv.segment1, ps.pay_group_lookup_code, inv.org_id, CASE WHEN pha_app.vendor_id is not null or pha_proc.vendor_id is not null THEN 'ACTIVE' ELSE 'IN ACTIVE' end ORDER BY vendor_name DESC ) WHERE Max_Invoice_Date &lt; TRUNC(ADD_MONTHS( SYSDATE, -12 ),'MONTH'); </code></pre> <p>the first query returns </p> <pre><code> COMPANY VENDOR_SITE_CODE VENDOR_NAME SEGMENT1 SITE_TYPE MAX_INVOICE_DATE TEST 172 UMANIS.201 UMANIS SEGM1 EXPENSE 27.04.2015 00:00:00 ACTIVE 172 ROBOZ.301 ROBOZ SEGM1 EXPENSE 11.03.2015 00:00:00 ACTIVE </code></pre> <p>the second one returns just ROBOZ</p> <pre><code> COMPANY VENDOR_SITE_CODE VENDOR_NAME SEGMENT1 SITE_TYPE MAX_INVOICE_DATE TEST 172 ROBOZ.301 ROBOZ SEGM1 EXPENSE 11.03.2015 00:00:00 ACTIVE </code></pre> <p>As for an explanation of the logic of the second query (my proposed solution), I'm so tired now (00:37 AM) that I just joined the pha_headers twice, once for "APPROVED" records and once for "IN PROCESS" records, so I could use them as simple joins, all on the same record. </p> <p>Other solutions are possible, without having to access the table twice ("pivoting" the table with aggregate function and CASE for example) </p>
TaskFactory handle exceptions <p>How can I easily handle all exceptions that happens inside the task that I am running without blocking the UI thread.</p> <p>I found a lot of different solutions but they all involve the <code>wait()</code> function and this blocks the whole program.</p> <p>The task is running async so it should just send a message to the UI thread saying that it has an exceptions so that the UI thread can handle it. (Maybe an event that I can hook on?)</p> <p>This is the code I have now that blocks the UI Thread:</p> <pre><code>var task = Task.Factory.StartNew(() =&gt; { if (_proxy != null) { _gpsdService.SetProxy(_proxy.Address, _proxy.Port); if (_proxy.IsProxyAuthManual) { _gpsdService.SetProxyAuthentication(_proxy.Username, StringEncryption.DecryptString(_proxy.EncryptedPassword, _encryptionKey).ToString()); } } _gpsdService.OnLocationChanged += GpsdServiceOnOnLocationChanged; _gpsdService.StartService(); }); try { task.Wait(); } catch (AggregateException ex) { if (ex.InnerException != null) { throw ex.InnerException; } throw; } </code></pre>
<p>You should not use <code>Task.Factory.StartNew</code> (use <code>Task.Run</code> instead). Also, do not use <code>ContinueWith</code> (use <code>await</code> instead).</p> <p>Applying both of these guidelines:</p> <pre><code>try { await Task.Run(() =&gt; { if (_proxy != null) { _gpsdService.SetProxy(_proxy.Address, _proxy.Port); if (_proxy.IsProxyAuthManual) { _gpsdService.SetProxyAuthentication(_proxy.Username, StringEncryption.DecryptString(_proxy.EncryptedPassword, _encryptionKey).ToString()); } } _gpsdService.OnLocationChanged += GpsdServiceOnOnLocationChanged; _gpsdService.StartService(); }); } catch (Exception ex) { // You're back on the UI thread here ... // handle exception } </code></pre>
Deadlock inserting into a table in SQLServer 2012 (10.50.6000.34) <p>I have a problem with a SQL Server where I change the requests to multithreaded and it executes this stored procedure on multiple connections to the database and results in a deadlock. I can't imagine how it is deadlocking. If I do it single threaded it runs fine. At one point (when I first wrote this), it worked inserting 22,000 records without a deadlock (table was empty, so no updates in that situation) The code looks like this:</p> <pre><code>Create Procedure InsertUpdateRecord @Email varchar(255), @State Varchar(50) -- Other parameters, shouldn't matter as Begin if (not exists (select * from [MyTable] WITH (NOLOCK) where email=@email)) begin insert into [MyTable] (email, state) values (@email, @state) end else begin update [MyTable] set state=@state where email=@email end end end </code></pre> <p>Pretty simple, and I don't see any way it could be doing anything other than simple row locking on the unique column 'email', and I don't see any way it could create a deadlock. Can someone explain this and offer a solution?</p>
<p>This is a typical case where you should consider <code>UPDLOCK</code> in your query:</p> <pre><code>begin tran if exists (select * from table with (updlock,serializable) where key = @key) begin update table set ... where key = @key end else begin insert into table (key, ...) values (@key, ...) end commit tran </code></pre> <p>The <code>UPDLOCK</code> will already claim a lock if you hit your record with your first select and avoid the case of several methods trying to claim the same lock. The <code>serializable</code> is used for:</p> <ul> <li>Statements cannot read data that has been modified but not yet committed by other transactions.</li> <li>No other transactions can modify data that has been read by the current transaction until the current transaction completes.</li> <li>Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.</li> </ul> <p>Just for completeness, your table is properly indexed and isn't a Heap, right?</p> <p>Also, if not present, try to add an index to your <code>MyTable</code>:</p> <pre><code>CREATE NONCLUSTERED INDEX [IX_MyTable_email] ON [dbo].[MyTable] ( [email] ASC ) </code></pre> <p>You could also go ahead and enable the following trace flags: </p> <pre><code>DBCC TRACEON (1204,-1) DBCC TRACEON (1222,-1) </code></pre> <p>This won't stop the deadlocks, but will provide more details about them in your SQL Server log. It'll tell you what locks your transactions are trying to claim and who was currently owning that lock.</p>
Multi Signer DocuSign Issue <p>I am trying to send docusign document to multiple signer .I have added two signer and call CreateEnvelope method to send documents .I am using .net framework to implement this .but the problem is mail delivered only first recipients .Can you please help me how can i send document to multiple signer .</p>
<p>Based on the code you've provided, it looks like you're specifying a <em>serial</em> routing order:</p> <ul> <li>first signer is routing order <strong>1</strong>: <code>signer1.RoutingOrder = "1";</code> </li> <li>second signer is routing order <strong>2</strong>: <code>signer2.RoutingOrder = "2";</code></li> </ul> <p>This is telling DocuSign to send <strong>signer1</strong> their signing invitation email first, and to send <strong>signer2</strong> their signing invitation email only once <strong>signer1</strong> has completed signing. </p> <p>If you do not care which person signs first (and want them both to receive the email right away when the envelope is sent), set <strong>RoutingOrder</strong> to <strong>1</strong> for both signers.</p> <pre><code>signer1.RoutingOrder = "1"; signer2.RoutingOrder = "1"; </code></pre>
how to add attribute for all subnodes of the xml in sql <p>I have a xml like below in a variable @xml</p> <pre><code>&lt;ContentTemplate&gt; &lt;Tab Title="Lesson"&gt; &lt;Section Title="Lesson Opening" /&gt; &lt;Section Title="Lesson/Activity" /&gt; &lt;/Tab&gt; &lt;Tab Title="Wrap Up and Assessment"&gt; &lt;Section Title="Lesson Closing" /&gt; &lt;Section Title="Tracking Progress/Daily Assessment" /&gt; &lt;/Tab&gt; &lt;Tab Title="Differentiated Instruction"&gt; &lt;Section Title="Strategies - Keyword" /&gt; &lt;Section Title="Strategies – Text" /&gt; &lt;Section Title="Resources" /&gt; &lt;Section Title="Acceleration/Enrichment" /&gt; &lt;/Tab&gt; &lt;Tab Title="District Resources"&gt; &lt;Section Title="Related Content Items" /&gt; &lt;Section Title="Other" /&gt; &lt;/Tab&gt; &lt;/ContentTemplate&gt; </code></pre> <p>I want to insert an attribute for all tab nodes in the above xml.. the output should be like below:</p> <pre><code>&lt;ContentTemplate&gt; &lt;Tab Title="Lesson" PortletName="CommunitiesViewer"&gt; &lt;Section Title="Lesson Opening" /&gt; &lt;Section Title="Lesson/Activity" /&gt; &lt;/Tab&gt; &lt;Tab Title="Wrap Up and Assessment" PortletName="CommunitiesViewer"&gt; &lt;Section Title="Lesson Closing" /&gt; &lt;Section Title="Tracking Progress/Daily Assessment" /&gt; &lt;/Tab&gt; &lt;Tab Title="Differentiated Instruction" PortletName="CommunitiesViewer"&gt; &lt;Section Title="Strategies - Keyword" /&gt; &lt;Section Title="Strategies – Text" /&gt; &lt;Section Title="Resources" /&gt; &lt;Section Title="Acceleration/Enrichment" /&gt; &lt;/Tab&gt; &lt;Tab Title="District Resources" PortletName="CommunitiesViewer"&gt; &lt;Section Title="Related Content Items" /&gt; &lt;Section Title="Other" /&gt; &lt;/Tab&gt; &lt;/ContentTemplate&gt; </code></pre> <p>i tried the following code to get the above xml</p> <pre><code>set @xml.modify( 'insert attribute PortletName {sql:variable("@PortletName")} into (ContentTemplate/Tab)[1]') </code></pre> <p>its just update the first sub node.</p> <p>how to update all the sub nodes of the xml..</p> <p>thanks in advance</p>
<p>Your XML in a variable</p> <pre><code>DECLARE @xml XML= N'&lt;ContentTemplate&gt; &lt;Tab Title="Lesson"&gt; &lt;Section Title="Lesson Opening" /&gt; &lt;Section Title="Lesson/Activity" /&gt; &lt;/Tab&gt; &lt;Tab Title="Wrap Up and Assessment"&gt; &lt;Section Title="Lesson Closing" /&gt; &lt;Section Title="Tracking Progress/Daily Assessment" /&gt; &lt;/Tab&gt; &lt;Tab Title="Differentiated Instruction"&gt; &lt;Section Title="Strategies - Keyword" /&gt; &lt;Section Title="Strategies – Text" /&gt; &lt;Section Title="Resources" /&gt; &lt;Section Title="Acceleration/Enrichment" /&gt; &lt;/Tab&gt; &lt;Tab Title="District Resources"&gt; &lt;Section Title="Related Content Items" /&gt; &lt;Section Title="Other" /&gt; &lt;/Tab&gt; &lt;/ContentTemplate&gt;'; </code></pre> <h2>1) <a href="https://msdn.microsoft.com/en-us/library/ms190945.aspx" rel="nofollow">FLWOR</a></h2> <p>The <code>.modify()</code>-statement allows you to change one decent point in your XML, but you'd need many calls to change many places. FLWOR allows you to re-build the XML out of itself:</p> <pre><code>SET @xml=@xml.query( '&lt;ContentTemplate&gt; { for $t in /ContentTemplate/Tab return &lt;Tab Title="{$t/@Title}" PortletName="CommunitiesViewer"&gt; {$t/*} &lt;/Tab&gt; } &lt;/ContentTemplate&gt;'); SELECT @xml </code></pre> <h2>2) Rebuild with <code>SELECT ... FOR XML PATH()</code></h2> <p>You'd reach the same with this approach: Again the XML is re-built, but this time it is shredded and used as a new <code>SELECT ... FOR XML PATH</code></p> <pre><code>SELECT tb.value('@Title','nvarchar(max)') AS [@Title] ,'CommunitiesViewer' AS [@PortletName] ,tb.query('*') FROM @xml.nodes('/ContentTemplate/Tab') AS A(tb) FOR XML PATH('Tab'),ROOT('ContentTemplate') </code></pre>
get select option value using $(document).ready function in jQuery from multiple dynamic record? <p>Here is my code</p> <pre><code>foreach($test as $val){ &lt;select name="change" id="change-&lt;?=$val['id']?&gt;" data-id="&lt;?php echo $val['id'];?&gt;"&gt; &lt;option value=""&gt;Select Value&lt;/option&gt; &lt;option value="1"&gt;one&lt;/option&gt; &lt;option value="2"&gt;two&lt;/option&gt; &lt;option value="3"&gt;three&lt;/option&gt; &lt;/select&gt; } </code></pre> <p>I want every different record blank value alert in every 3 min. so please help me. thanks! </p> <pre><code> $(document).ready(function(e) { var change = $('#change').val(); if (change == '') { alert('Please Select Shipping Destination!'); } }); </code></pre>
<p>For the interval you can use plain JavaScript's <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval" rel="nofollow">setInterval()</a> method.</p> <p>In order to find and iterate over all your <code>select</code> fields, you can use jQuery's "<a href="https://api.jquery.com/attribute-starts-with-selector/" rel="nofollow">starts with</a>" selector and <a href="https://api.jquery.com/each/" rel="nofollow"><code>.each()</code></a> method. </p> <p>This should work:</p> <pre><code>$(document).ready(function(e) { setInterval(function() { $("select[id^='change-']").each(function(i) { var value = $(this).val(); if (value == '') { alert('Please Select Shipping Destination!'); } }); }, 3 * 60 * 1000); }); </code></pre> <p>Note that this will create an alert for <strong>every</strong> <code>select</code> that is empty. Probably not very user friendly. </p>
Searching two column titles, comparing, and deleting duplicate rows from one sheet only. <p>Essentially the following searches column L in Sheet1, compares it to another column in a separate worksheet (e.g. Sheet2) and then deletes the whole row from Sheet1.</p> <p>I'm having trouble making it applicable to other situations. </p> <p>Instead of specifying column "L", can this be easily edited to search for a column title and continue with the same job? </p> <p>I understand that there are very similar questions out there, but haven't had any luck finding a solution to this particular situation.</p> <pre><code>Sub F_Check_List() 'Checks first sheet in workbook, column L for Headings matching Sheet2 column C and deletes those that match Dim LR As Long, i As Long With Sheets(1) LR = .Range("L" &amp; Rows.Count).End(xlUp).Row For i = LR To 1 Step -1 If IsNumeric(Application.Match(.Range("L" &amp; i).Value, Sheets(2).Columns("C"), 0)) Then .Rows(i).Delete Next i End With End Sub </code></pre> <p>Much appreciated.</p>
<p>Something like this should work for you:</p> <pre><code>Sub tgr() Dim wb As Workbook Dim ws1 As Worksheet Dim ws2 As Worksheet Dim rDel As Range Dim rHeader1 As Range Dim rHeader2 As Range Dim rCheck As Range Dim sHeader As String Set wb = ActiveWorkbook Set ws1 = wb.Sheets(1) Set ws2 = wb.Sheets(2) sHeader = "HeaderB" 'Change this to the header you are searching for Set rHeader1 = ws1.Rows(1).Find(sHeader, , xlValues, xlWhole) If rHeader1 Is Nothing Then Exit Sub 'Can't find header Set rHeader2 = ws2.Rows(1).Find(sHeader, , xlValues, xlWhole) If rHeader2 Is Nothing Then Exit Sub 'Can't find header For Each rCheck In ws1.Range(rHeader1.Offset(1), ws1.Cells(ws1.Rows.Count, rHeader1.Column).End(xlUp)).Cells If WorksheetFunction.CountIf(ws2.Columns(rHeader2.Column), rCheck.Value) &gt; 0 Then If rDel Is Nothing Then Set rDel = rCheck Else Set rDel = Union(rDel, rCheck) End If Next rCheck If Not rDel Is Nothing Then rDel.EntireRow.Delete xlShiftUp End Sub </code></pre>
How to group by looking at previous and next value in each row <p>Suppose I have a table with the following records...</p> <pre><code>ResumeId Action 39092 DEV 39092 C 39092 C 39096 C 39096 C 39098 CONF 39098 CONF </code></pre> <p>How can I group them so that the output would look like this? In the below case, since <code>ResumeId = 39092</code> has at least one <code>DEV</code> record then the grouping result should return <code>DEV</code>...</p> <pre><code>ResumeId Action 39092 DEV 39096 C 39098 CONF </code></pre>
<p>Here is one method:</p> <pre><code>select resumeid, (case when max(action) = min(action) then max(action) when sum(case when action = 'DEV' then 1 else 0 end) &gt; 0 then 'DEV' else '??' end) from t group by resumeid; </code></pre> <p>Your rules don't specify what to do if there are multiple <code>actions</code>, but none are <code>DEV</code>.</p>
ansible using multiple strategies with strategy plugin <p>I am using ansible 2.1 and would like to figure out how (if possible) to specify more than one strategy in the ansible.cfg file for running ansible playbooks. Currently, I am using <strong>debug</strong> strategy but would like to use <strong>free</strong> or other strategies as needed. </p> <pre><code>strategy: debug </code></pre>
<p>As per <a href="http://docs.ansible.com/ansible/playbooks_strategies.html" rel="nofollow">documentation</a> you can set strategy on per play basis:</p> <pre><code>- hosts: all strategy: free tasks: ... </code></pre>
MAGICS - undefined symbol: _ZTIN5eckit9ExceptionE <p>I'm stuck on a runtime error "undefined symbol: _ZTIN5eckit9ExceptionE" like this</p> <pre><code>Start 2: basic_python 2: Test command: /usr/local/Python/2.7.10/bin/python "coast.py" 2: Environment variables: 2: PYTHONPATH=/opt/src/ecmwf/Magics-2.29.4-Source/build/python 2: LD_LIBRARY_PATH=/opt/src/ecmwf/Magics-2.29.4-Source/build/lib 2: MAGPLUS_HOME=/opt/src/ecmwf/Magics-2.29.4-Source/test/.. 2: OMP_NUM_THREADS=1 2: Test timeout computed to be: 1500 2: Traceback (most recent call last): 2: File "coast.py", line 11, in &lt;module&gt; 2: from Magics.macro import * 2: File "/opt/src/ecmwf/Magics-2.29.4-Source/build/python/Magics/__init__.py", line 32, in &lt;module&gt; 2: _Magics = swig_import_helper() 2: File "/opt/src/ecmwf/Magics-2.29.4-Source/build/python/Magics/__init__.py", line 28, in swig_import_helper 2: _mod = imp.load_module('_Magics', fp, pathname, description) 2: ImportError: /usr/local/Magics/2.29.4/gnu/4.4.7/lib/libMagPlus.so: undefined symbol: _ZTIN5eckit9ExceptionE </code></pre> <p>There was no error while building shared libaray libMagPlus.so. The error just was raised at runtime when Python module loading it.</p> <p>Checked with nm, the undefined symbol '_ZTIN5eckit9ExceptionE' is from a static library libOdb.a, like this</p> <pre><code>nm libOdb.a | grep _ZTIN5eckit9ExceptionE U _ZTIN5eckit9ExceptionE U _ZTIN5eckit9ExceptionE U _ZTIN5eckit9ExceptionE U _ZTIN5eckit9ExceptionE U _ZTIN5eckit9ExceptionE U _ZTIN5eckit9ExceptionE 0000000000000000 V DW.ref._ZTIN5eckit9ExceptionE U _ZTIN5eckit9ExceptionE U _ZTIN5eckit9ExceptionE U _ZTIN5eckit9ExceptionE U _ZTIN5eckit9ExceptionE U _ZTIN5eckit9ExceptionE U _ZTIN5eckit9ExceptionE </code></pre> <p>But there was no any complaint about undefined symbol '_ZTIN5eckit9ExceptionE' for the excutables which linked against the static library libOdb.a directly at the both of complation time and runtime time. All C, Fortran codes also worked well with the static library libOdb.a, except the shared library libMagPlus.so. </p> <p>The library LibMagPlus.so was linked like this</p> <pre><code>/usr/bin/g++ -fPIC -pipe -O2 -g \ -Wl,--disable-new-dtags -shared \ -Wl,-soname,libMagPlus.so -o ../lib/libMagPlus.so \ ... ... \ -Wl,-Bstatic -L$ODB_API/lib -lOdb \ ... ... </code></pre> <p>The library libOdb.a was built like this</p> <pre><code>usr/bin/ar qc ../../lib/libOdb.a ... ... /usr/bin/ranlib ../../lib/libOdb.a </code></pre> <p>Searched the FAQ and Googled, little help with my problem. I knew little about C++, and have no idea how to get this fixed. </p> <p>[ In response to Jorge's inputs, updated these ]</p> <p>Exceptions.h</p> <pre><code>#ifndef eckit_Exceptions_h #define eckit_Exceptions_h #include &lt;errno.h&gt; #include "eckit/eckit.h" #include "eckit/eckit_version.h" #include "eckit/log/CodeLocation.h" #include "eckit/log/Log.h" #include "eckit/log/SavedStatus.h" #include "eckit/compat/StrStream.h" namespace eckit { //----------------------------------------------------------------------------- void handle_panic(const char*); void handle_panic(const char*, const CodeLocation&amp;); /// @brief General purpose exception /// Derive other exceptions from this class and implement then in the class that throws them. class Exception : public std::exception { public: // methods /// Constructor with message Exception(const std::string&amp; what, const CodeLocation&amp; location = CodeLocation() ); /// Destructor /// @throws nothing ~Exception() throw(); virtual const char *what() const throw() { return what_.c_str(); } virtual bool retryOnServer() const { return false; } virtual bool retryOnClient() const { return false; } virtual bool terminateApplication() const { return false; } static bool throwing(); static void exceptionStack(std::ostream&amp;,bool callStack = false); const std::string&amp; callStack() const { return callStack_; } protected: // methods void reason(const std::string&amp;); Exception(); virtual void print(std::ostream&amp;) const; private: // members std::string what_; ///&lt; description std::string callStack_; ///&lt; call stack SavedStatus save_; ///&lt; saved monitor status to recover after destruction Exception* next_; CodeLocation location_; ///&lt; where exception was first thrown friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; s,const Exception&amp; p) { p.print(s); return s; } }; </code></pre> <p>nm -Cl $ODB_API/lib/libOdb.a | grep -i "eckit::Exception"</p> <pre><code> U eckit::Exception::Exception(std::string const&amp;, eckit::CodeLocation const&amp;) /opt/src/OdbAPI-0.10.2-Source/eckit/src/eckit/exception/Exceptions.h:84 U eckit::Exception::~Exception() /opt/src/OdbAPI-0.10.2-Source/eckit/src/eckit/exception/Exceptions.h:108 0000000000000000 W eckit::Exception::retryOnClient() const /opt/src/OdbAPI-0.10.2-Source/eckit/src/eckit/exception/Exceptions.h:48 0000000000000000 W eckit::Exception::retryOnServer() const /opt/src/OdbAPI-0.10.2-Source/eckit/src/eckit/exception/Exceptions.h:47 0000000000000000 W eckit::Exception::terminateApplication() const /opt/src/OdbAPI-0.10.2-Source/eckit/src/eckit/exception/Exceptions.h:49 0000000000000000 W eckit::Exception::what() const /opt/src/OdbAPI-0.10.2-Source/eckit/src/eckit/exception/Exceptions.h:46 U eckit::Exception::print(std::ostream&amp;) const U typeinfo for eckit::Exception </code></pre> <p>I also tried to unpack all object files from libOdb.a and relink libMagPlus.so with all of them with option '-fvisibility=default -rdynamic', like this</p> <pre><code>ar x libOdb.a ( ./Odb ) /usr/bin/g++ -fvisibility=default -rdynamic -fPIC -pipe -O2 -g \ -Wl,--disable-new-dtags -shared \ -Wl,-soname,libMagPlus.so -o ../lib/libMagPlus.so \ ... ... \ ./Odb/*.o \ ... ... </code></pre> <p>But still got these undefined symbols</p> <pre><code>U eckit::Exception::~Exception() /opt/src/OdbAPI-0.10.2-Source/eckit/src/eckit/exception/Exceptions.h:108 U eckit::Exception::print(std::ostream&amp;) const U typeinfo for eckit::Exception </code></pre> <p><strong>Wondering if needs to touch Exceptions.h and how to touch it ?</strong></p> <p>Anybody can help ?</p> <p>Appreciating your time</p> <p>Regards</p>
<p>Take a look at <code>Exceptions.h</code> file. Note how all your undefined symbols belong to functions that are <strong>declared but not defined</strong>.</p> <pre><code>~Exception() throw(); // [...] virtual void print(std::ostream&amp;) const; </code></pre> <p><code>eckit::Exception::~Exception()</code> is your destructor (declared in <code>Exceptions.h:108</code> but not defined). The same applies to <code>eckit::Exception::print(std::ostream&amp;) const</code>.</p> <p>In the case of <code>typeinfo for eckit::Exception</code>, the problem here is that you have virtual functions that are not declared as <em>pure virtual</em> (in abstract classes), but are neither defined, so the type is not complete.</p> <p>If I'm not wrong, as <code>eckit::Exception</code> class is meant to be superclass for other derived classes, its destructor should be declared <code>virtual</code> too.</p> <p>Check where are those missing functions declared. They should be either in an object file skipped/missed by the archiver (if missing functions are defined in a <code>.cpp</code> file) or in a header file that you didn't include (if they are defined in a <code>.hpp</code> file).</p> <p>See also: <a href="http://stackoverflow.com/questions/307352/g-undefined-reference-to-typeinfo">g++ undefined reference to typeinfo</a></p>
How to where do i process my data with observable .map and .subscribe <p>I'm retriving some data from my API:</p> <pre><code>[ { "id": 1, "lat": 50.607084, "lng": 3.043099 }, { "id": 2, "lat": 50.607084, "lng": 3.043099 }, ] </code></pre> <p>I'd like to process the data only with reactive programing so that inside my request, google map markers get created.</p> <pre><code> this.http.get('http://api/getData') .map(res =&gt; { return res.json() }) .subscribe( data =&gt; { console.log(data); }); </code></pre> <p>when doing this i'm getting a lot of objects, i could not fin a way to log or isolate only the latitude (i get "unknown"). </p> <p>I'd like to be able to put a function inside the ".map" (observable ?) that will get all variable, and create markersOptions that i'll put in an array.</p> <pre><code>let markerOptions: GoogleMapsMarkerOptions = { position: latlng, title: 'id' }; </code></pre> <p>From wath i've seen on google, most of people prefer put the object in a private variable and i assume take care of it, in an other function. </p>
<p>What you need to do is mapping the array retrieved from the server to a list of GoogleMapsMarkerOptions. So, (I don't know the constructor of GoogleMapsMarkerOptions) something like:</p> <pre><code>this.http.get('http://api/getData') .map(res =&gt; { return res.json().map(x =&gt; { return new GoogleMapsMarkerOptions({ title: x.it, position: new GoogleMapsLatLng(x.lat, x.lng) }); }); }) .subscribe( data =&gt; { console.log(data); }); </code></pre> <p>The second map is a standard javascript method (not rxjs). If you need to support old browsers you can use lodash or underscore.</p>
How to add analytics code in React Native lifecycle <p>I have a <code>TabBarIOS</code> which contains five navigators. I need to track each view on screen for google analytics, but ReactNative doesn't provide a lifecycle for that.</p> <p>I'v tried to track in the <code>componentDidMount</code> of those views, but it will be only called once in its lifecycle for each view. Switching between tabs will not trigger <code>componentDidMount</code> again.</p> <p>Furthermore, when I <code>push()</code>/<code>pop()</code> a view into/from a navigator, I need a callback to find which component will be shown.</p> <p>Is there any callback method or delegate method which would be called when a component is going to show (like <code>-viewDidAppear:</code> in iOS)?</p>
<p>TabBarIOS.Item has a property named <a href="https://facebook.github.io/react-native/docs/tabbarios-item.html#onpress" rel="nofollow">onPress()</a> that gets called when the item is pressed. You can use this callback to update analytics.</p>
C# - Why is Enumerable<T> serializable for T that are not serializable? <p>So far I've been considering <code>typeof(T).IsSerializable</code> to be true if <code>T</code> has attribute <code>[Serializable]</code>. (And unrelated to the confusingly named <code>ISerializable</code>). <br> That first assumption is wrong; <code>IsSerializable</code> seems to be more complicated and I don't understand what it's meant be to be used for. </p> <p>Examples where <code>IsSerializable</code> is true but the type isn't serializable:</p> <pre><code>using NUnit.Framework; [TestFixture] internal class Tests { private class MyClass {} [Test] public void TestIsNotSerialisable() { // Passes Assert.That(typeof(MyClass).IsSerializable, Is.False); } [Test] public void TestIsNotSerialisableArray() { // Fails (is Serializable) Assert.That(typeof(MyClass[]).IsSerializable, Is.False); } [Test] public void TestIsNotSerialisableList() { // Fails (is Serializable) Assert.That(typeof(List&lt;MyClass&gt;).IsSerializable, Is.False); } } </code></pre> <p><a href="https://msdn.microsoft.com/en-us/library/system.type.isserializable(v=vs.110).aspx" rel="nofollow">MSDN for IsSerializable</a>. </p> <p>So why is <code>T[]</code> serializable even if <code>T</code> isn't?</p>
<p>The MSDN link you shared explains this in the <strong>Remarks</strong> section:</p> <blockquote> <p>If the current Type represents a constructed generic type, this property applies to the generic type definition from which the type was constructed. For example, if the current Type represents MyGenericType (MyGenericType(Of Integer) in Visual Basic), the value of this property is determined by MyGenericType.</p> </blockquote> <p>So <code>List&lt;T&gt;</code> is considered serializable even though you can construct generic types from it that are not serializable, and the <code>IsSerializable</code> property does not reflect that.</p>
Is it possible to embed a c++ or java compiler inside Unity 5 scene <p>I'm implementing a game which teaches programming just like robocode and other related applications but I want to implement this game in unity. the user should answer problems by writing his code in the text-area and then compile it, then I should receive his output if there is no error.<br> Seriously I've searched on google for 3 days and I can't get any answer, it is my graduation project so please I need serious help.</p>
<p>Not a Unity expert, but you could get away with calling the compiler as an external program - see <a href="http://answers.unity3d.com/questions/1108055/execute-external-program.html" rel="nofollow">this</a> example, where they go over how to call a program in a Windows environment.</p> <p>You'd have to make sure that the compiler is installed and accessible, but other than that things should work.</p> <p>As a general pattern, this is the way most other programs would access a compiler, rather than including it in their binary.</p>
Get text from private stash link <p>I have application where I getting code from stash raw file. Scrapping from public repositories is simple, it looks like this:</p> <pre><code> public getRawFile(rawLink: string) { return this.http.get(rawLink).map((res: Response) =&gt; res.text()); } </code></pre> <p>But now I would like to get code from stash raw file, but from private repository. If user have access(is logged into stash) than source code from raw file is loaded. </p> <p>If I trying same way, I getting respone:</p> <pre><code> XMLHttpRequest cannot load 'private_stash_file_link'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. EXCEPTION: Response with status: 0 for URL: null Uncaught Response with status: 0 for URL: null </code></pre> <p>How can I handle this, cookies, specific options for get request, is it even possible?</p> <p><strong>EDIT 1.</strong></p> <p>Tried: </p> <pre><code> public getRawFile(link: string) { let headers = new Headers(); headers.append('Access-Control-Allow-Headers', 'Content-Type'); headers.append('Access-Control-Allow-Methods', 'GET, OPTIONS'); headers.append('Access-Control-Allow-Origin', '*'); let options = new RequestOptions({headers: headers, withCredentials: true}); return this.http.get(link, options).map((res: Response) =&gt; res.text()); } </code></pre> <p>but same result for private repository..</p> <p><a href="https://plnkr.co/edit/ogDayyIOEbOLkI8XBzOX?p=preview" rel="nofollow">plunker</a></p>
<p>The server that you are making the request to has to implement CORS to grant JavaScript from your website access (Cross Origin Resource Sharing (CORS)). So if you have access to the place where you are scraping, then add the following HTTP headers at the response of the receiving end:</p> <pre><code>Access-Control-Allow-Headers: Content-Type Access-Control-Allow-Methods: GET, POST, OPTIONS Access-Control-Allow-Origin: *.example.com </code></pre> <p>Make sure to replace "*.example.com" with the domain name of the host that is sending the data/getting the data. Doing this should fix your problem.</p>
Cannot read property of undefined issue on callback <p>I have a very simple class that is wrapping a node.js serial port class. On object creation, a new logger is created. When stepping through, everything seems fine - when I call open, I can see that the logger is a valid logger object. However, when the error method is triggered by an error on opening the port, the logger is no longer defined - it seems there's some issue with callbacks and the created object, but I have no idea what? Thanks for the help!</p> <p>EDIT: I wrote the class in TypeScript, and I'm realizing this is probably a super annoying, classic JavaScript "this" issue...I apologize - I'm pretty new to js.</p> <pre><code>"use strict"; var SerialPort = require('serialport'); const logger = require('../logger'); class MySerialPort { constructor() { this.log = new logger(); } error(error) { console.log(error); try { this.log.log('Serial port error: ' + error); } catch (e) { console.log(e); } } open(commport) { this.port = new SerialPort(commport); this.port.on('data', this.dataRecieved); this.port.on('error', this.error); return true; } dataRecieved(data) { console.log(data.toString()); } } module.exports = MySerialPort; </code></pre>
<p>use an arrow function or bind this, either way should work</p> <p><code>this.port.on('error', (err) =&gt; {this.error(err)});</code></p> <p>or</p> <pre><code>var error=this.error.bind(this); this.port.on('error', error); </code></pre>
Twig loop through array <p>I have the following <code>json_decode</code> data which is something like this:</p> <pre><code>Array ( [0] =&gt; Array ( [id] =&gt; 218 [startTime] =&gt; 1478363400000 [EndTime] =&gt; 1478367000000 [c] =&gt; Array ( [id] =&gt; 1 [code] =&gt; A [name] =&gt; Name [postalCode] =&gt; 7TF [contact] =&gt; 1111 242 3144 [email] =&gt; [website] =&gt; / [fax] =&gt; [address] =&gt; Thisistheaddress [latitude] =&gt; 53.80729675111 [longitude] =&gt; -1.5190633535385 [status] =&gt; ONLINE ) [service] =&gt; Array ( [id] =&gt; 1 [code] =&gt; 100 [description] =&gt; GENERAL ) ) [1] =&gt; Array ( [id] =&gt; 237 [startTime] =&gt; 1478593800000 [EndTime] =&gt; 1478597400000 [c] =&gt; Array ( [id] =&gt; 1 [code] =&gt; A [name] =&gt; Name [postalCode] =&gt; 7TF [contact] =&gt; 1111 242 3144 [email] =&gt; [website] =&gt; / [fax] =&gt; [address] =&gt; Thisistheaddress [latitude] =&gt; 53.80729675111 [longitude] =&gt; -1.5190633535385 [status] =&gt; ONLINE ) [service] =&gt; Array ( [id] =&gt; 1 [code] =&gt; 100 [description] =&gt; GENERAL ) ) [2] =&gt; Array ( [id] =&gt; 199 [StartTime] =&gt; 1478187000000 [EndTime] =&gt; 1478190600000 [c] =&gt; Array ( [id] =&gt; 1 [code] =&gt; A [name] =&gt; Name [postalCode] =&gt; 7TF [contact] =&gt; 1111 242 3144 [email] =&gt; [website] =&gt; / [fax] =&gt; [address] =&gt; Thisistheaddress [latitude] =&gt; 53.80729675111 [longitude] =&gt; -1.5190633535385 [status] =&gt; ONLINE ) [service] =&gt; Array ( [id] =&gt; 1 [code] =&gt; 100 [description] =&gt; GENERAL ) ) ) </code></pre> <p>My question is how do i iterate this so i could get the [startTime] , [name] and [address] in twig. I have tried the following:</p> <pre><code> {% for key,a in TimeInfo|keys %} Key : {{ key }} {% endfor %} </code></pre> <p>The result above is just giving me a key, I also tried the following:</p> <pre><code> {% for a in TimeInfo %} {{ a.name }} {% endfor %} </code></pre> <p>The above result is an error. Appreciate the help :) </p>
<p>Please make sure that you use json_decode function before pass your TimeInfo array to twig template. You can iterate it as a simple multidimensional array. Small trick with startTime/StartTime will help you to avoid an error related to first capital letter in the StartTime element's key of your data array. </p> <pre><code>&lt;ul&gt; {% for array in TimeInfo %} &lt;li&gt; &lt;ul&gt; &lt;li&gt;Start Time: {{ attribute(array, 'startTime') ?: attribute(array, 'StartTime') }}&lt;/li&gt; &lt;li&gt;Name: {{ attribute(array, 'c').name }}&lt;/li&gt; &lt;li&gt;Address: {{ attribute(array, 'c').address }}&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre>
Make scope of lock smaller in threadsafe queue <p>I have a dll which has a high priority functionality that runs in a high priority thread. This dll needs to report progress. Basically a callback system is used. The issue is that the dll has no control over the amount of time the callback takes to complete. This means the high priority functionality is dependent on the implementation of the callback which is not acceptable.</p> <p>The idea is to have a class inbetween that buffers the progress notifications and calls the callback.</p> <p>I'm new to C++11 and it's threading functionality and trying to discover the possibilities. I have an implementation but I have an issue(at least one that I see now). When the thread awakens after the wait the mutex is reacquired and stays acquired until the next wait. This means the lock is acquired for as long as the lengthy operation continues. Adding progress will block here. Basically a lot of code for no gain. I thought of changing the code to this but I don't know if this is the correct implementation.</p> <pre><code> Progress progress = queue.front(); queue.pop(); lock.unlock(); // Do lengthy operation with progress lock.lock(); </code></pre> <p>I think I need to wait for the condition variable, but that should not be connected to the lock. I don't see how this can be done. Pass a dummy lock and use a different lock to protect the queue? How should this problem be tackled in C++11?</p> <p>header file</p> <pre><code>#include &lt;atomic&gt; #include &lt;condition_variable&gt; #include &lt;mutex&gt; #include &lt;thread&gt; #include &lt;queue&gt; #include "Error.h" #include "TypeDefinitions.h" struct Progress { StateDescription State; uint8 ProgressPercentage; }; class ProgressIsolator { public: ProgressIsolator(); virtual ~ProgressIsolator(); void ReportProgress(const Progress&amp; progress); void Finish(); private: std::atomic&lt;bool&gt; shutdown; std::condition_variable itemAvailable; std::mutex mutex; std::queue&lt;Progress&gt; queue; std::thread worker; void Work(); }; </code></pre> <p>cpp file</p> <pre><code>#include "ProgressIsolator.h" ProgressIsolator::ProgressIsolator() : shutdown(false), itemAvailable(), worker([this]{ Work(); }), progressCallback(progressCallback), completedCallback(completedCallback) { // TODO: only continue when worker thread is ready and listening? } ProgressIsolator::~ProgressIsolator() { Finish(); worker.join(); } void ProgressIsolator::ReportProgress(const Progress&amp; progress) { std::unique_lock&lt;std::mutex&gt; lock(mutex); queue.push(progress); itemAvailable.notify_one(); } void ProgressIsolator::Finish() { shutdown = true; itemAvailable.notify_one(); } void ProgressIsolator::Work() { std::unique_lock&lt;std::mutex&gt; lock(mutex); while (!shutdown) { itemAvailable.wait(lock); while (!queue.empty()) { Progress progress = queue.front(); queue.pop(); // Do lengthy operation with progress } } } </code></pre>
<pre><code>void ProgressIsolator::Work() { while (!shutdown) { Progress progress; { std::unique_lock&lt;std::mutex&gt; lock(mutex); itemAvailable.wait(lock, [this] { return !queue.empty(); }); progress = queue.front(); queue.pop(); } // Do lengthy operation with progress } } </code></pre>
IndexError: list index out of range in Python 3 <p>I am newbie to Python. I got the index error when I run the code. I have seen the relevant questions in Stackoverflow, but I still can't see what the bug is. I am very appreciated for any response. Thank you. Here is the code:</p> <pre><code> class Card: def __init__(self, suit = 0, rank = 2): self.suit = suit self.rank = rank suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] rank_names =[None,'Ace','2','3','4','5','6','7','9','10','Jack','Queen', 'King'] def __str__ (self): return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit]) def __lt__(self,other): t1 = self.suit, self.rank t2 = other.suit, other.rank return t1 &lt; t2 class Deck: def __init__(self): self.cards = [] for suit in range(4): for rank in range(1, 14): card = Card(suit, rank) self.cards.append(card) def __str__(self): res = [ ] for card in self.cards: res.append(str(card)) return '\n'.join(res) deck1 = Deck() print(deck1) </code></pre> <p>Then I got the following error:</p> <pre><code> Traceback (most recent call last): File "/Users/Enze/Python/untitled/Inheritance.py", line 35, in &lt;module&gt; print(deck1) File "/Users/Enze/Python/untitled/Inheritance.py", line 30, in __str__ res.append(str(card)) File "/Users/Enze/Python/untitled/Inheritance.py", line 11, in __str__ return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit]) IndexError: list index out of range </code></pre>
<p>You have <code>13</code> items inside your <code>rank_names</code> list so the index of last element is of value <code>12</code> (lists are enumerated starting with <code>0</code>) - inside loop</p> <pre><code>for suit in range(4): for rank in range(1, 14): card = Card(suit, rank) </code></pre> <p>the maximum index you try to get is <code>13</code> (<code>range</code> is generating numbers one-by-one in order excluding borders) and that's why you've got <code>index out of range</code> exception</p>
drop down code for store locator on magento <p>Please can anyone help with the code for a drop down for store locator in magento,this is a look alike of what i want to achieve:</p> <p><a href="http://www.watchrepublic.co.za/store-locator.html" rel="nofollow">http://www.watchrepublic.co.za/store-locator.html</a></p> <p>Thank you.</p>
<p>I have no experience with Magento, but after a bit of googling, I came across a <a href="https://www.magentocommerce.com/magento-connect/responsive-custom-menu.html" rel="nofollow">drop down menu extension</a>.</p>
How to use a dict to subset a DataFrame? <p>Say, I have given a DataFrame with most of the columns being categorical data.</p> <pre><code>&gt; data.head() age risk sex smoking 0 28 no male no 1 58 no female no 2 27 no male yes 3 26 no male no 4 29 yes female yes </code></pre> <p>And I would like to subset this data by a dict of key-value pairs for those categorical variables.</p> <pre><code>tmp = {'risk':'no', 'smoking':'yes', 'sex':'female'} </code></pre> <p>Hence, I would like to have the following subset.</p> <pre><code>data[ (data.risk == 'no') &amp; (data.smoking == 'yes') &amp; (data.sex == 'female')] </code></pre> <p>What I want to do is:</p> <pre><code>data[tmp] </code></pre> <p>What is the most python / pandas way of doing this?</p> <hr> <p>Minimal example:</p> <pre><code>import numpy as np import pandas as pd from pandas import Series, DataFrame x = Series(random.randint(0,2,50), dtype='category') x.cat.categories = ['no', 'yes'] y = Series(random.randint(0,2,50), dtype='category') y.cat.categories = ['no', 'yes'] z = Series(random.randint(0,2,50), dtype='category') z.cat.categories = ['male', 'female'] a = Series(random.randint(20,60,50), dtype='category') data = DataFrame({'risk':x, 'smoking':y, 'sex':z, 'age':a}) tmp = {'risk':'no', 'smoking':'yes', 'sex':'female'} </code></pre>
<p>You can create a look up data frame from the dictionary and then do an inner join with the <code>data</code> which will have the same effect as <code>query</code>:</p> <pre><code>from pandas import merge, DataFrame merge(DataFrame(tmp, index =[0]), data) </code></pre> <p><a href="https://i.stack.imgur.com/xW4kf.png" rel="nofollow"><img src="https://i.stack.imgur.com/xW4kf.png" alt="enter image description here"></a></p>
PhpStorm with Live Edit on Mozilla Firefox <p>Can I use Live Edit plugin on Mozilla Firefox and if I can how to do that?</p> <p>Thanks</p>
<p>You cannot -- <strong>LiveEdit plugin works with Chrome browser only</strong>.</p> <p><a href="https://www.jetbrains.com/help/phpstorm/2016.2/live-editing-of-html-css-and-javascript.html?search=live%20e" rel="nofollow">https://www.jetbrains.com/help/phpstorm/2016.2/live-editing-of-html-css-and-javascript.html?search=live%20e</a></p> <hr> <p>If it has to be Firefox .. then you should try some another solution, <strong>LiveReload</strong> perhaps.</p>
Is strip_tags necessary for phpmailer? <p>I'm using phpmailer with the following settings:</p> <pre><code>$mail-&gt;ContentType = 'text/plain'; $mail-&gt;IsHTML(false); ... $mail-&gt;Body = $_POST['comments']; $mail-&gt;Body = strip_tags($mail-&gt;Body); </code></pre> <p>I noticed strip_tags() cuts off the text if it hits a single greater than / less than sign (i.e if the user put in one of those characters legitimately).</p> <p>Given that I have content type = 'text/plain' and ishtml = false, is it even necessary to have strip_tags() in there?</p>
<p>No, it is not neccesary. If you set <code>$mail-&gt;isHTML(false)</code> and you write HTML in the email, it is sent like text plain so it doesnt interpret it like HTML.</p> <p>For example I've just done this:</p> <pre><code>$mail-&gt;ContentType = 'text/plain'; $mail-&gt;isHTML(false); $mail-&gt;Subject = 'Your password'; $mail-&gt;Body = '&lt;p&gt;Your password is 123&lt;/p&gt; &lt;a href="www.google.com"&gt; Go to google &lt;/a&gt;'; </code></pre> <p>And the mail looks like this:</p> <pre><code>&lt;p&gt;Your password is 123&lt;/p&gt; &lt;a href="wwww.google.com"&gt; Go to google&lt;/a&gt; </code></pre>
GROUP_CONCAT limiting to 100 values is not working <p>I am trying to extract a sum of modified history field limited by 100 and grouped by each account, but the query below extracts sum of all rows from CDR_Accounts with charged_quantity = 60 and does not limit to 100.</p> <p>table1 = table2 and these are the temporary tables. I have simplified the query and filtered all data in temporary tables.</p> <p>Nevertheless, the query still gives me the total sum of all 'history' fields, however I need the sum for only 100 of them.</p> <p>table1/table2 format:</p> <pre><code>+-----------+----------+------------+-------------+----------------------+ | i_account | id | account_id | CLD | history | +-----------+----------+------------+-------------+----------------------+ | 10272 | 46479968 | 0814781293 | 27815212963 | +1x60@1.32d100%=1.32 | | 6316 | 46480100 | 0813741427 | 27780233136 | +1x60@1.32d100%=1.32 | | 6316 | 46480107 | 0813741427 | 27780233136 | +1x60@1.32d100%=1.32 | | 13830 | 46480435 | 0814346396 | 27781356515 | +1x60@1.32d100%=1.32 | | 13830 | 46480436 | 0814346396 | 27781356515 | +1x60@1.32d100%=1.32 | +-----------+----------+------------+-------------+----------------------+ </code></pre> <p>Account</p> <pre><code>SELECT sum(SUBSTRING_INDEX(history,'=',-1)), cdr.i_account, cdr.account_id FROM table1 cdr WHERE cdr.id IN (SELECT SUBSTRING_INDEX(group_concat(s.id SEPARATOR ','), ',', 100) id FROM table2 s GROUP BY id ) GROUP BY i_account; </code></pre>
<p>I'm not clear about what your query does is. However limit applies to the final result which includes the grouping as well. if you need to limit the result of GROUP_CONCAT, first apply the limit and then apply the grouping</p>
image augmentation algorithms for preparing deep learning training set <p>To prepare large amounts of data sets for training deep learning-based image classification models, we usually have to rely on image augmentation methods. I would like to know what are the usual image augmentation algorithms, are there any considerations when choosing them? </p>
<p>The litterature on data augmentation is very very large and very dependent on your kind of applications. The first things that come to my mind are the galaxy competition's rotations and Jasper Snoeke's data augmentation. </p> <p>But really all papers have their own tricks to get good scores on special datasets for exemples stretching the image to a specific size before cropping it or whatever and this in a very specific order.</p> <p>More practically to train models on the likes of CIFAR or IMAGENET use random crops and random contrast, luminosity perturbations additionally to the obvious flips and noise addition. </p> <p>Look at the CIFAR-10 tutorial on TF website it is a good start. Plus TF now has <code>random_crop_and_resize()</code> which is quite useful.</p> <p><strong>EDIT:</strong> The papers I am referencing <a href="https://arxiv.org/pdf/1503.07077v1.pdf" rel="nofollow">here</a> and <a href="https://arxiv.org/pdf/1502.05700v2.pdf" rel="nofollow">there</a>.</p>
Disable the background of a uibutton <p>I have a circular custom menu with several buttons (with image and text). To not cut title, I had to unlarge button size, but the background of few buttons overlay partially the image or title of other button. That why I'd like to disable the background of buttons, or make image and/title only active.</p> <p>How can I do? Thanks</p>
<p>As others have mentioned, you could change the background color quite easily with the following:</p> <p><strong>Swift 3.0</strong></p> <pre><code>buttonName.backgroundColor = UIColor.clear </code></pre> <p><strong>Swift 2.2 and prior</strong></p> <pre><code>buttonName.backgroundColor = UIColor.clearColor() </code></pre> <p>Are your buttons overlapping because they're crowded? If so then from a design point of view I'd look at redesigning that aspect. Users may be misclicking if you have a number of overlapping crowded buttons.</p>
Missing return in a function expected to return 'UITableViewCell' with two tableView <p>I use a croll view, and there are a two(or many) tableView in one view like this</p> <p><a href="https://i.stack.imgur.com/jVO6y.png" rel="nofollow"><img src="https://i.stack.imgur.com/jVO6y.png" alt="layout"></a></p> <p>but at function:</p> <pre><code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { </code></pre> <p>It's a error</p> <blockquote> <p>missing return in a function expected to return 'UITableViewCell' <a href="https://i.stack.imgur.com/TLCJk.png" rel="nofollow"><img src="https://i.stack.imgur.com/TLCJk.png" alt="error"></a></p> </blockquote> <p>But I have did</p> <p><code>return cell</code></p> <p>How the error happened?</p> <pre><code>class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var scroll: UIScrollView! @IBOutlet var recipesImageView: UIImageView! @IBOutlet var tableView:UITableView! @IBOutlet var tableView2: UITableView! var recipes:Recipe! var noodles:Recipe! var snacks:Recipe! var category: Int = Int() @IBAction func segmented(sender: AnyObject) { switch sender.selectedSegmentIndex { case 0: scroll.setContentOffset(CGPoint(x:0, y:0), animated: true) case 1: scroll.setContentOffset(CGPoint(x:375, y:0), animated: true) case 2: scroll.setContentOffset(CGPoint(x:750, y:0), animated: true) case 3: scroll.setContentOffset(CGPoint(x:1125, y:0), animated: true) default: print() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. switch self.category { case 0: self.recipesImageView.image = UIImage(named: recipes.image) title = self.recipes.name case 1: self.recipesImageView.image = UIImage(named: noodles.image) title = self.noodles.name case 2: self.recipesImageView.image = UIImage(named: snacks.image) title = self.snacks.name case 3: self.recipesImageView.image = UIImage(named: noodles.image) title = self.noodles.name case 4: self.recipesImageView.image = UIImage(named: noodles.image) title = self.noodles.name default: self.recipesImageView.image = UIImage(named: recipes.image) title = self.recipes.name } self.tableView.backgroundColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.5) //刪除多餘的隔線 self.tableView.tableFooterView = UIView(frame: CGRectZero) self.tableView.separatorColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 1) //title = self.recipes.name tableView.estimatedRowHeight = 36.0; tableView.rowHeight = UITableViewAutomaticDimension; self.tableView.delegate = self self.tableView.dataSource = self self.tableView2.delegate = self self.tableView2.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { var cellNum:Int? if tableView == self.tableView { cellNum = 4 } else if tableView == self.tableView2 { cellNum = 1 } return cellNum! } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { if(tableView == self.tableView) { let cell: DetailTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! DetailTableViewCell //cell.backgroundColor = UIColor.clearColor() if self.category == 0 { switch indexPath.row { case 0: cell.fieldLabel.text = "名稱" cell.valueLabel.text = recipes.name cell.amountLabel.text = "" case 1: cell.fieldLabel.text = "類型" cell.valueLabel.text = recipes.type cell.amountLabel.text = "" case 2: cell.fieldLabel.text = "收藏" cell.valueLabel.text = (recipes.isFavor) ? "Yes" : "No" cell.amountLabel.text = "" case 3: cell.fieldLabel.text = "食材" cell.valueLabel.text = recipes.material cell.amountLabel.text = recipes.amount default: cell.fieldLabel.text = "" cell.valueLabel.text = "" cell.amountLabel.text = "" } } if self.category == 1 { switch indexPath.row { case 0: cell.fieldLabel.text = "名稱" cell.valueLabel.text = noodles.name cell.amountLabel.text = "" case 1: cell.fieldLabel.text = "類型" cell.valueLabel.text = noodles.type cell.amountLabel.text = "" case 2: cell.fieldLabel.text = "收藏" cell.valueLabel.text = (noodles.isFavor) ? "Yes" : "No" cell.amountLabel.text = "" case 3: cell.fieldLabel.text = "食材" cell.valueLabel.text = noodles.material cell.amountLabel.text = noodles.amount default: cell.fieldLabel.text = "" cell.valueLabel.text = "" cell.amountLabel.text = "" } } if self.category == 2 { switch indexPath.row { case 0: cell.fieldLabel.text = "名稱" cell.valueLabel.text = snacks.name cell.amountLabel.text = "" case 1: cell.fieldLabel.text = "類型" cell.valueLabel.text = snacks.type cell.amountLabel.text = "" case 2: cell.fieldLabel.text = "收藏" cell.valueLabel.text = (snacks.isFavor) ? "Yes" : "No" cell.amountLabel.text = "" case 3: cell.fieldLabel.text = "食材" cell.valueLabel.text = snacks.material cell.amountLabel.text = snacks.amount default: cell.fieldLabel.text = "" cell.valueLabel.text = "" cell.amountLabel.text = "" } } if self.category == 3 { switch indexPath.row { case 0: cell.fieldLabel.text = "名稱" cell.valueLabel.text = noodles.name cell.amountLabel.text = "" case 1: cell.fieldLabel.text = "類型" cell.valueLabel.text = noodles.type cell.amountLabel.text = "" case 2: cell.fieldLabel.text = "收藏" cell.valueLabel.text = (noodles.isFavor) ? "Yes" : "No" cell.amountLabel.text = "" case 3: cell.fieldLabel.text = "食材" cell.valueLabel.text = noodles.material cell.amountLabel.text = noodles.amount default: cell.fieldLabel.text = "" cell.valueLabel.text = "" cell.amountLabel.text = "" } } if self.category == 4 { switch indexPath.row { case 0: cell.fieldLabel.text = "名稱" cell.valueLabel.text = noodles.name cell.amountLabel.text = "" case 1: cell.fieldLabel.text = "類型" cell.valueLabel.text = noodles.type cell.amountLabel.text = "" case 2: cell.fieldLabel.text = "收藏" cell.valueLabel.text = (noodles.isFavor) ? "Yes" : "No" cell.amountLabel.text = "" case 3: cell.fieldLabel.text = "食材" cell.valueLabel.text = noodles.material cell.amountLabel.text = noodles.amount default: cell.fieldLabel.text = "" cell.valueLabel.text = "" cell.amountLabel.text = "" } } return cell } else if tableView == tableView2 { let cell: MaterialDetailTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell2") as! MaterialDetailTableViewCell //cell.backgroundColor = UIColor.clearColor() if self.category == 0 { switch indexPath.row { case 0: cell.materialLabel.text = recipes.material default: cell.materialLabel.text = "" } } if self.category == 1 { switch indexPath.row { case 0: cell.materialLabel.text = noodles.material default: cell.materialLabel.text = "" } } if self.category == 2 { switch indexPath.row { case 0: cell.materialLabel.text = snacks.material default: cell.materialLabel.text = "" } } if self.category == 3 { switch indexPath.row { case 0: cell.materialLabel.text = noodles.material default: cell.materialLabel.text = "" } } if self.category == 4 { switch indexPath.row { case 0: cell.materialLabel.text = noodles.material default: cell.materialLabel.text = "" } } return cell } //-----------------------this line appear error } //避免被前面一頁的隱藏導覽列所影響 override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.hidesBarsOnSwipe = false self.navigationController?.setNavigationBarHidden(false, animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ </code></pre> <p>}</p>
<p>You return nothing, when <code>tableView != self.tableView</code> and <code>tableView != tableView2</code>. That's why you see this error. If you are sure that this cannot be reached, try removing your <code>else if</code> condition</p>
Create vector selecting values from two different vectors <p>Currently, this code works to do what I want to do where dx$res is a vector selecting values from dx$val1 or dx$val2 depending on value of dx$x0.</p> <pre><code>x0&lt;-c(1,2,1,2,2,1) val1&lt;-c(8,6,4,5,3,2) val2&lt;-c(4,8,6,7,9,5) dx&lt;-data.frame(x0,val1,val2) dx$res&lt;-(dx$x0==1)*dx$val1+(dx$x0==2)*dx$val2 </code></pre> <p>I would like to know if there were more elegant methods to do this like using apply function.</p>
<p>One option is <code>model.matrix</code> with <code>rowSums</code>. It is also more general for 'n' number of distinct elements in the 'x0' column.</p> <pre><code>dx$res &lt;- rowSums(dx[-1]*model.matrix(~ factor(x0) - 1 , dx)) dx$res #[1] 8 8 4 7 9 2 </code></pre>
How do I compile this Fortran code with new 2017 ifort? <p>I have the following fortran code that compiles with pre 2017 ifort:</p> <pre><code>program parallel_m contains character(500) function PARALLEL_message(i_ss) character(50) :: Short_Description = " " integer :: i_s =0 integer :: n_threads = 0 ! PARALLEL_message=" " ! if (i_s&gt;0) then if (len_trim("test this ")==0) return endif ! if (i_s==0) then PARALLEL_message=trim("10")//"(CPU)" if (n_threads&gt;0) PARALLEL_message=trim(PARALLEL_message)//"-"//trim("200")//"(threads)" else PARALLEL_message=trim("a")//"(environment)-"//&amp; &amp; trim("a")//"(CPUs)-"//&amp; &amp; trim("a")//"(ROLEs)" endif ! end function end program parallel_m </code></pre> <p>Going through the preprocessor :</p> <pre><code>icc -ansi -E example.F &gt; test.f90 </code></pre> <p>Which produces:</p> <pre><code># 1 "mod.F" program parallel_m contains character(500) function PARALLEL_message(i_ss) character(50) :: Short_Description = " " integer :: i_s =0 integer :: n_threads = 0 ! PARALLEL_message=" " ! if (i_s&gt;0) then if (len_trim("test this ")==0) return endif ! if (i_s==0) then PARALLEL_message=trim("10") if (n_threads&gt;0) PARALLEL_message=trim(PARALLEL_message) else PARALLEL_message=trim("a") &amp; trim("a") &amp; trim("a") endif ! end function end program parallel_m </code></pre> <p>This unfortunately with intel 2017 does not compile, the same output compiles without complaint on 2016 and 2015 ifort releases. this is the error that I get:</p> <pre><code>mod.F(19): error #5082: Syntax error, found '&amp;' when expecting one of: &lt;LABEL&gt; &lt;END-OF-STATEMENT&gt; ; TYPE INTEGER REAL COMPLEX BYTE CHARACTER CLASS DOUBLE ... &amp; trim("a") ------------------------^ mod.F(20): error #5082: Syntax error, found '&amp;' when expecting one of: &lt;LABEL&gt; &lt;END-OF-STATEMENT&gt; ; TYPE INTEGER REAL COMPLEX BYTE CHARACTER CLASS DOUBLE ... &amp; trim("a") ------------------------^ compilation aborted for test.f90 (code 1) </code></pre>
<p>Your program is illegal Fortran after the preprocessing because the <code>//</code> is interpretted as a C comment.</p> <p>Simply do not use <code>icc</code> but <code>ifort</code>. <code>Ifort</code> is for Fortran, <code>icc</code> is for C. <code>Ifort</code> uses a different preprocessor <code>fpp</code> which does not discard <code>//</code>.</p>
Value not set correctly with JavaScript and Primefaces <p>im sending a variable with a JS to an inputtext. then when the value has been set i click on a p:commandButton to call a method that uses that value but the value that passes is blank... although the js sent the value to the input and i see it... it takes it as blank. if i input the value myself it does read it in the method... otherwhise it does not... any ideas? here's my code as much resumed as i can get it (it's kind of long):</p> <p>XHTML:</p> <pre><code>&lt;!-- Modal --&gt; &lt;div class="modal fade" id="myModalId" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header bg-warning"&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" id="myModalLabel"&gt;&lt;b&gt;#{msg.html32}&lt;/b&gt;&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;center style="font-size: 14px"&gt;#{msg.html31}&lt;/center&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;p:commandLink action="#{bd.setId(dotcalpro.id)}" styleClass="btn btn-md btn-info" value="#{msg.htmlborrar}" immediate="true" update="tbResult, growl" accesskey="r" onclick="modalIdhide()"/&gt; &lt;p:spacer height="5"/&gt; &lt;p:commandLink styleClass="btn btn-md btn-info" value="#{msg.html48}" immediate="true" update="tbResult, growl" onclick="modalIdhide()"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;p:column width="60"&gt; &lt;f:facet name="header"&gt;#{msg.dotcalprotbver}&lt;/f:facet&gt; &lt;center&gt; &lt;button type="button" class="btn btn-warning btn-xs" onclick="detalle('#{tb.zid}'); modalIdshow();" &gt; &lt;i class="fa fa-search fa-2x"&gt;&lt;/i&gt; &lt;/button&gt; &lt;/center&gt; &lt;/p:column&gt; </code></pre> <p>JS:</p> <pre><code>function detalle(vT0){ document.getElementById("formdotcalpro:id").value= rTrim(vT0); updateInput('formdotcalpro:id', '#F2F2F2') //alert(document.getElementById("formdotcalpro:id").value); var x = document.getElementById("formdotcalpro:id").value; alert("valor: " + x) } //Modal id show function modalIdshow(){ $("#myModalId").modal(); } //Modal id hide function modalIdhide(){ $("#myModalId").modal('hide'); } </code></pre> <p>Bean:</p> <pre><code>/** * Setea tipo de valor de la meta para busqueda * @param next */ public void setId(String id){ FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("id", id); System.out.println("valor : " + id); } </code></pre> <p>I say again just in case i have resumed the code as much as posible.</p>
<p>well i found some sort of solution with my sesion variable... it worked but not quite sure if it's the rigth aproach.</p> <p>just added this in my Bean class:</p> <pre><code>/** * Setea tipo de valor de la meta para busqueda * @param next */ public void setId(String id){ HttpServletRequest rq = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); String idval = rq.getParameter("formdotcalpro:id"); FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("id", idval); //System.out.println("valor : " + idval); } </code></pre> <p>I still welcome another point of view to this problem if you have the time.</p>
Paypal Donation Button in asp.net page <p>I've created a paypal donation button from paypal business account with all default setting. I copy paste the html into my asp.net page, and it looks fine. The problem is when I click on the button simply nothing happen. Is this because I'm still on localhost? Will it be work and go to paypal page when I upload the website?</p> <pre><code> &lt;form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top"&gt; &lt;input type="hidden" name="cmd" value="_s-xclick"&gt; &lt;input type="hidden" name="hosted_button_id" value="buttonId"&gt; &lt;input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"&gt; &lt;img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1"&gt; &lt;/form&gt; </code></pre>
<p>Your asp.net page probably already has a form tag on it and you may have placed the PayPal code inside that form, which won't work. Instead of using the form with the hidden fields that PayPal generated for you, you could just use a link with url parameters. Here's an example (make sure you replace YOUR_BUTTON_ID_HERE with your id):</p> <pre><code>&lt;a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amp;hosted_button_id=YOUR_BUTTON_ID_HERE"&gt; &lt;img src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" alt="PayPal - The safer, easier way to pay online!" /&gt; &lt;/a&gt; </code></pre>
Dstream output to Rabbitmq <p>I am using spark 2.0 (python). I am trying to send the output stream to Rabbitmq. Following is my implemetation, </p> <pre><code>def sendPartition(iter): connection = pika.BlockingConnection(pika.URLParameters('amqp://user:pass@ip:5672/')) channel = connection.channel() for record in iter: channel.basic_publish(exchange='ExchangePostingUpdate', routing_key='PostingUpdate', body=json.dumps(record) ) channel.close() data_stream.foreachRDD(lambda rdd: rdd.foreachPartition(lambda partition:sendPartition(partition,rabbitconnection))) </code></pre> <p>It is working fine. But as we see here it is estabilshing connection and closing it for every partition. Is there any better way to do this ?</p> <p>i tried to estabilsh a connection and pass to <code>sendPartition(iter,conn)</code> but i did not work. </p>
<p>What you have right now is probably close to the optimum in a general case. Python workers don't share state so you cannot reuse connections between partitions in the same batch.</p> <p>It should be possible to reuse connections for each worker between batches by creating a singleton wrapping a connection pool (there are well established patterns you can use like Borg pattern or using module as a singleton) but this will work only under certain assumptions:</p> <ul> <li><code>spark.python.worker.reuse</code> is set to true.</li> <li>Disabled dynamic allocation (<code>spark.dynamicAllocation.enabled</code>).</li> </ul> <p>If resources are created dynamically and / or not reused keeping persistent pool won't be helpful.</p>
Edit all conflicting files in a git merge/rebase (special character safe) <p>In the middle of a <code>git rebase</code>, I have a status such as:</p> <pre><code>$ git status --short M lib/tmuxinator.rb UU lib/tmuxinator/cli.rb UU lib/tmuxinator/config.rb A spec/fixtures/TMUXINATOR_CONFIG/TMUXINATOR_CONFIG.yml M tmuxinator.gemspec </code></pre> <p>How can I open the files with conflicts (denoted <code>U</code> above) in my text editor with a single command?</p> <p><strong>The solution must work with <code>\n</code> and special characters in the filenames.</strong></p>
<p>Many commands have a <code>-z</code>, <code>-0</code>, or <code>--null</code> option to produce/consume <code>NUL</code>-terminated output.</p> <p>Use the following: </p> <pre><code>git status -sz | sed -rnz 's/^(U.|.U) (.*)/\2/p' | xargs -0 $EDITOR </code></pre> <p>Or as a <code>gitconfig</code> alias:</p> <pre><code>[alias] resolve=!"git status -sz | sed -rnz 's/^(U.|.U) (.*)/\\2/p' | xargs -0 $EDITOR #" </code></pre>
Type 3 Function Procedure in post Script <p>I am a beginner for post script and just started working on post script. I want to create a post script procedure which I can use for shading effect for post script.This shading can have more then 2 colors so I need to define stitching function of type 3.</p> <p>I am thinking of defining a procedure for function2 and later I can use this procedure in defining the type 3 function.</p> <p>below is what I tried...</p> <pre><code>/Function2 { /b2 exch def /g2 exch def /r2 exch def /b exch def /g exch def /r exch def /FunctionType 2 /Domain [ 0 1 ] /C0 [ r g b ] /C1 [ r2 g2 b2 ] /N 1 } def /Function3 { /num exch def /FunctionType 3 /Domain [ 0 1 ] /Functions [1 1 num { pop Function2 } for ] /Bounds [ 1 1 num-1 { pop } for ] /Encode [ 1 1 num { pop 0 1 } for ] } def { /ShadingType 3 /ColorSpace /DeviceRGB /Coords [ 200 200 0 200 200 100 ] /Extend [ true true ] /Function Function3 } shfill </code></pre> <p>Issue I am facing is how to read bound variables from the stack. I am not sure this will work or not. please check and let me know the issues in that.</p>
<p>I'm not really sure what you are asking for here. Perhaps you could clarify the question. You don't 'read bound variables from the stack', stack objects are just that, objects on the stack.</p> <p>This:</p> <pre><code> **/Bounds [ 1 1 num-1 { pop } for ]** </code></pre> <p>looks incorrect to me 'num-1' will be immediately evaluated, and you don;t seem to have defined a name object '/num-1', so will throw an undefined error I think.</p> <p>Also, of course, the '**' constructs will similarly throw an error.</p> <p>You have defined the functions as 'procedures' (in PostScript terminology actually executable arrays), whereas PostScript functions are required to be dictionaries, so what you have here won't work. That is you have used '{' and '}' when you should use '&lt;&lt;' and '>>', in simplistic terms.</p> <p>Function dictionaries don't take arguments on the stack If you are truly just starting out in PostScript, functions and shadings are probably the worst possible place to start, since they are rather complex.</p> <p>Here is a working example shading using both a type 2 and a type 3 function, for your perusal:</p> <pre><code>%!PS-Adobe-3.0 gsave 0.480 setlinewidth 1 setlinecap 1 setlinejoin 0.302 0.302 0.302 setrgbcolor /stop_function &lt;&lt; /FunctionType 2 /Domain[0 1] /C0 [1 0 0] /C1 [0 1 0] /N 1 &gt;&gt; def /RepFunction &lt;&lt; /FunctionType 3 /Domain [ -81 1 ] /Functions [ 82 {stop_function} repeat ] /Bounds [ -80 1 0 {} for ] /Encode [ -81 1 0 { pop 0 1 } for ] &gt;&gt; def &lt;&lt; /PatternType 2 /Shading &lt;&lt; /ShadingType 3 /ColorSpace [/DeviceRGB] /Extend [false false] /Coords [-1300.8 -468 979.2 60 504 7.2] /Function &lt;&lt; /FunctionType 3 /Domain [0 1] /Bounds [] /Encode[-80 1] /Functions [RepFunction] &gt;&gt; &gt;&gt; &gt;&gt; matrix makepattern setpattern 12.000 528.000 moveto 84.000 528.000 lineto 84.000 456.000 lineto 12.000 456.000 lineto closepath gsave fill grestore 0.302 0.302 0.302 setrgbcolor stroke grestore showpage </code></pre>
Golang Pointer and Struct member function <h2>Invoke function</h2> <p>When I define a struct <code>Lock</code> and a function <code>Test</code> with the struct <code>Lock</code> as the function receiver</p> <pre><code>type Lock struct { } func (self Lock) Test() { fmt.Println("Test Func") } </code></pre> <p>I found that I can call this function with a <code>Lock</code> struct pointer </p> <pre><code>lock := &amp;Lock{} lock.Test() </code></pre> <p>The same, if I define a struct <code>Lock</code> and a function <code>Test</code> as the <code>Lock</code>'s pointer as the receiver, I can call this function through <code>Lock</code> struct instance.</p> <p>So whatever the receiver is the struct itself or the struct pointer, I can call this function through the both? What's the reason. As my comprehension, the struct and the struct pointer are totally two different type!</p> <h2>Interface</h2> <p>If a define a interface <code>Locker</code> like this</p> <pre><code>type Locker interface { Test() } </code></pre> <p>And define a struct <code>Lock</code> and a function <code>Test</code> with the struct <strong>instance</strong> as the receiver, I can't assign a struct pointer variable to a <code>Locker</code> interface var.</p> <p>On the contrary, If a define a struct <code>Lock</code> and a function <code>Test</code> with the struct <strong>pointer</strong> as the receiver, assign a struct instance variable to a <code>Locker</code> interface var can work!</p> <p>I'm so confused about the language design. Can anybody give me some advice?</p>
<p>Usually, Golang does things for you under the hood and this is typically one of those cases.</p> <p>When you define a function with a struct as receiver and you pass it a pointer to the struct, then Golang does the conversion for you: it passes a copy of the struct pointed to.</p> <p>When you define a function with a pointer as a receiver and you pass it a struct, Golang creates a pointer to this struct.</p> <p>However, when defining an interface, you're working on types: The <code>Locker</code> interface defines a type which implements the function <code>Test()</code>.</p> <p>And with interfaces, Golang won't help you: if your type doesn't implement a method, then it does not implement the interface. No hidden conversion here.</p> <p>Usually, it's better to be clear about what you want and how you want it and thus preventing Go from doing those weird conversions.</p>
Unable to find null value reference to remove nullpointer when registering a user to the database, registers but throws null pointer <p>I am trying to register a user (using java, Java swing). I am able to get it to be inserted into the database but its throwing null pointer. I checked the internet for null pointer to handle it and what it said was not initializing a variable and using it. And referring to a null object. But in my code i cant find it. Please help. </p> <pre><code>public class registerr extends javax.swing.JFrame { Connection conn; OracleResultSet rs = null; OraclePreparedStatement pst= null; public registerr() { initComponents(); connect(); } public void connect() { // connection with Oracle DB } </code></pre> <p>Clicking the register button, the value of texfield gets added to Database but then throws null pointer exception</p> <pre><code> private void regActionPerformed(java.awt.event.ActionEvent evt) { try{ String fname = FnameTF.getText().trim(); String lname = LnameTF.getText().trim(); String uname = UnameTF.getText().trim(); String pass1 = Pass1TF.getText().trim(); String pass2 = Pass2TF.getText().trim(); String sqli = "insert into login" + "(fname, lname,uname, pass)" + " values ('"+FnameTF.getText()+"','"+LnameTF.getText()+"','"+UnameTF.getText()+"','"+Pass1TF.getText()+"')"; pst = (OraclePreparedStatement) conn.prepareStatement(sqli); pst.executeUpdate(sqli); pst.close(); int count = 0; if(uname.equals("") || fname.equals("") || lname.equals("") || Pass1TF.getText().equals("") ||Pass2TF.getText().equals("")) { System.out.println("Please fill in all the fields"); } else if(pass1.equals(pass2)) { } else { System.out.println("Passwords do not match"); } while (rs.next()) { count++; } if(count == 1) { JOptionPane.showMessageDialog(null, "Please use new value for username"); System.out.println("Success"); } else { System.out.println("Successfully registered"); JOptionPane.showMessageDialog(null, "Successfully registered!"); } } catch(Exception ex) { ex.printStackTrace(System.out); } } </code></pre> <p>Here is the stack trace </p> <pre><code> run: Connected java.lang.NullPointerException at dbms.registerr.regActionPerformed(registerr.java:225) at dbms.registerr.access$000(registerr.java:18) at dbms.registerr$1.actionPerformed(registerr.java:87) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022) at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2348) at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:402) at javax.swing.JToggleButton$ToggleButtonModel.setPressed (JToggleButton.java:308) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased (BasicButtonListener.java:252) at java.awt.Component.processMouseEvent (Component.java:6533) at javax.swing.JComponent.processMouseEvent(JComponent.java:3324) at java.awt.Component.processEvent(Component.java:6298) at java.awt.Container.processEvent(Container.java:2236) at java.awt.Component.dispatchEventImpl(Component.java:4889) at java.awt.Container.dispatchEventImpl(Container.java:2294) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466) at java.awt.Container.dispatchEventImpl(Container.java:2280) at java.awt.Window.dispatchEventImpl(Window.java:2746) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl. doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain$JavaSecurityAccessImpl. doIntersectionPrivilege(ProtectionDomain.java:86) at java.awt.EventQueue$4.run(EventQueue.java:731) at java.awt.EventQueue$4.run(EventQueue.java:729) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl. doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at java.awt.EventDispatchThread.pumpOneEventForFilters (EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter (EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy (EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) BUILD SUCCESSFUL (total time: 25 seconds) </code></pre>
<p><code>rs</code> is null because it's not being set to anything else within the method.</p> <p>As you're using <code>executeUpdate</code>, then you can use its return value for count:</p> <pre><code>int count = pst.executeUpdate(sqli); </code></pre> <p>instead of trying to use <code>rs</code>.</p>
jQuery targeting selector by input type and form name <p>I want to target any input of text type belonging to a form of a specific name. Because the form will have numerous input fields, I don't want to target a particular input name, but rather, capture the blur (or focusout) event for any <code>input[type="text"]</code> occurring within the form wrap.</p> <p>My present code, which doesn't work:</p> <pre><code>$( document ).ready(function() { $('form[name="tax_form"] input[type="text"]').on("blur",function() { alert($(this).val()); }); }); </code></pre> <p>I answered my own question. Because the code sample is essentially correct, there is no need for multiple people to try to solve the unsolvable. The problem had something to do with where I placed the javascript code, and nothing to do with structure or syntax of the code, itself.</p>
<p>The way the event <code>"change"</code> works is what it sounds like you want. An event handler doesn't actually fire when the input is clicked or if text is keyed in, it fires when text is entered <strong><em>and</em></strong> then the input loses focus.</p> <p>In the following Snippet the same selector you are using is delegated to the <code>"change"</code> event. You'll notice that the <code>['tax_form']</code> has 4 text inputs yet the last one is the only one working. The reason is because if an input isn't assigned a <code>type</code> attribute, then by default <code>type</code> is <code>'text"</code>. So when using a selector based on an input's <code>type="text"</code>, you must keep that in mind. So if you are in full control of your HTML, make sure that each input has a <code>type</code> attribute with an explicit value, <strong><em>or</em></strong> use classes which is better IMO.</p> <h3>SNIPPET</h3> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $('form[name="tax_form"] input[type="text"]').on("change", function() { alert($(this).val()); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;form name='notIt'&gt; &lt;fieldset&gt; &lt;legend&gt;Not a Tax Form&lt;/legend&gt; &lt;input&gt; &lt;input type="text"&gt; &lt;input&gt; &lt;input type="text"&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;br/&gt; &lt;br/&gt; &lt;form name='stillNotIt'&gt; &lt;fieldset&gt; &lt;legend&gt;Still not a Tax Form&lt;/legend&gt; &lt;input type="text"&gt; &lt;input&gt; &lt;input type="text"&gt; &lt;input&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;br/&gt; &lt;br/&gt; &lt;form name='tax_form'&gt; &lt;fieldset&gt; &lt;legend&gt;Tax Form&lt;/legend&gt; &lt;input class='klass' value='TEXT INPUT BY DEFAULT'&gt; &lt;input value='TEXT INPUT BY DEFAULT'&gt; &lt;input name='text' value='TEXT INPUT BY DEFAULT'&gt; &lt;input type='number'&gt; &lt;input type='text' value='THIS ONE COUNTS'&gt; &lt;/fieldset&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
How to open NavigationDrawer with Fab? <p><strong>strong text</strong> I want while click on FAB button it Open Navigation Drawer.</p> <p>How to do?</p>
<p>You can take a look at this <a href="https://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html#openDrawer(android.view.View)" rel="nofollow">DrawerLayout</a></p> <pre><code>mDrawerLayout = (DrawerLayout) getView().findViewById(R.id.drawer_layout); FloatingActionButton myFab = (FloatingActionButton) myView.findViewById(R.id.myFAB); myFab.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //if you need open the slide: mDrawerLayout.openDrawer(Gravity.LEFT); //if you need close the slide mDrawerLayout.closeDrawer(Gravity.LEFT); } }); </code></pre>
Transform property extends webpage, also having center issues <p>Here's the codepen if it's easier. I'm also a beginner, just a heads up.</p> <p><a href="http://codepen.io/anon/pen/yaRpPL" rel="nofollow">http://codepen.io/anon/pen/yaRpPL</a></p> <p>My problem is that every time I hover over this circle, it extends the page size large enough that a scroll bar comes up when the circle reaches max size. I don't know how to explain, I just don't want that to happen...</p> <p>Also, I can't get the text in the center of that circle to appear <em>directly</em> in the center. I feel like I've tried every CSS property I could think of.</p> <p>Lastly, any tips on getting that circle to stay in the center for most common screen resolutions would be greatly appreciated. I have the margins set to percentages and it seems to be okay.</p> <p>HTML:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Echoes from Firelink&lt;/title&gt; &lt;link href="homepage.css" type="text/css" rel="stylesheet"&gt; &lt;link rel="shortcut icon" href="coiledsword.ico"&gt; &lt;/head&gt; &lt;header&gt; &lt;a href="homepage.htm" style="color:black"&gt;home | &lt;/a&gt; &lt;a href="homepage_easy.htm" style="color:black"&gt;lite version&lt;/a&gt; &lt;/header&gt;&lt;!--End header--&gt; &lt;body&gt; &lt;div id="background_container"&gt; &lt;div id="content_container"&gt; &lt;p&gt;From Software homepage&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS:</p> <pre><code>/* CSS page for the homepage. */ header { text-align: center; font-size: 10px; } #content_container { background-color: black; text-align:center; color: white; height: 200px; width: 200px; margin: 20% 45% 20% 45%; border-radius: 50%; transition: 2s; } #content_container:hover { transform: scale(1.4); } </code></pre>
<p>You need to change your margin, Do not use percentage values.</p> <p>If you need to center your text just the code below to the parent element. </p> <pre><code>display:flex; justify-content:center; align-items:center; </code></pre> <p>The css code: </p> <pre><code>header { text-align: center; font-size: 10px; } #content_container { display:flex; justify-content:center; align-items:center; background-color: black; text-align:center; color: white; height: 200px; width: 200px; border-radius: 50%; transition: 2s; } #content_container:hover { transform: scale(1.4); } </code></pre>
Timeseries Objects Duplicate Entries <p>I am working on a time series NoSQL database where I need to stamp values on an hourly basis. However, some times the values might stay the same. If the values, which are coming from a third party API, are the same, should I store them as duplicates or wait until the values are updated? In the first case, it results in many duplicates but I am not sure if it's the right approach? Any thoughts?</p>
<p>If values stays the same then it is not a duplicate entry as timestamp has changed.</p>
Getting GPS updates using fused location in background service For ex(15 mins)? <p>Am new for android development need to get gps location in background service without user interaction like for every 15 mins need to fetch the coordinates and send the results to server how can i achieve this. Then i tried fused location syncadapter combination it works am getting coordinates but i need to use that location class in dedicated android-service how can i achieve this need to make that service run for ever 15 mins fetch the coordinates and send that result to server let me post my Google api client class:</p> <pre><code>import android.content.Context; import android.location.Location; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.FusedLocationProviderApi; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import java.text.DateFormat; import java.util.Date; /** * Created by 4264 on 14-10-2016. */ public class Locationlistener implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,LocationListener { LocationRequest mLocationRequest; GoogleApiClient mGoogleApiClient; Location mCurrentLocation; String mLastUpdateTime; private Context context; private static final long INTERVAL = 1000 * 10; private static final long FASTEST_INTERVAL = 1000 * 5; public Locationlistener(Context c) { context=c; //show error dialog if GoolglePlayServices not available createLocationRequest(); mGoogleApiClient = new GoogleApiClient.Builder(context) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mGoogleApiClient.connect(); } protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(INTERVAL); mLocationRequest.setFastestInterval(FASTEST_INTERVAL); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } public String lat(){ String lat=null; if(mCurrentLocation==null){ Log.d("is null","null"); } else { lat=String.valueOf(mCurrentLocation.getLatitude()); } return lat; } protected void startLocationUpdates() { PendingResult&lt;Status&gt; pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this); Log.d("started", "Location update started ..............: "); } public void updateUI() { Log.d("updated", "UI update initiated ............."); if (null != mCurrentLocation) { String lat = String.valueOf(mCurrentLocation.getLatitude()); String lng = String.valueOf(mCurrentLocation.getLongitude()); Log.e("latw",lat); Log.e("Long",lng); } else { Log.d("", "location is null ..............."); } } @Override public void onConnected(Bundle bundle) { Log.d("connected", "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected()); startLocationUpdates(); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.d("failed", "Connection failed: " + connectionResult.toString()); } @Override public void onLocationChanged(Location location) { Log.d("locationchanged", "Firing onLocationChanged.............................................."); mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateUI(); } } </code></pre> <p>it works in syncadapter but i need to make this in service how can i achieve this and another doubt if user turn off the gps how can i get location is it possible with network location updates thanks in advance!!</p>
<p>I would suggest you to use AlarmManager to wake up device and receive location as soon as possible (interval 0) then continue to sleep at each 15 minutes. So this approach better than non-stop service.</p> <p>If user turns off the gps, you will be still getting (network provider) location updates but not accurate due to location settings aren't adequate. Also to solve this, you can use <a href="https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi" rel="nofollow">SettingsApi</a></p> <blockquote> <p>When making a request to location services, the device's system settings may be in a state that prevents an app from obtaining the location data that it needs. For example, GPS or Wi-Fi scanning may be switched off. </p> </blockquote>
dialog sapui5 oError.body display Rendering <p>Hi I have a dialog witch should display the content of an error in the console from a button.</p> <p>Inside a UPDATE CRUD I have a dialog witch should return me an error from the console if the operation is in a certain situation. This is my code from the error function.</p> <pre><code> function(oError){ var StringoError = JSON.parse(oError.response.body); /*alert("Error!\n"+oError.message);*/ alert(StringoError.error.message.value); </code></pre> <p>if I use the 2 alerts it works .. but now I have to style the user experience and put the content of Error.message and StringoError.error.message.value in a dialog/popover/popup.. so I implemented like this:</p> <pre><code> var dialog = new Dialog({ title: (oError.message), type: 'Message', state: 'Error', content: new Text({ text: JSON.parse(oError.response.body).error.message.value, }), beginButton: new sap.m.Button({ text: 'Close', press: function () { dialog.close(); } }), afterClose: function() { dialog.destroy(); } }); dialog.open(); }); </code></pre> <p>The problem is that I get to see the title but I can't see error.message.value and the console gives me back as error: </p> <blockquote> <p>The renderer for class sap.ui.core.Control is not defined or does not define a render function! Rendering of __control0 will be skipped!</p> </blockquote>
<p>Should it not be <code>sap.m.Text</code>? Or are you using the AMD Module format? But you are using <code>sap.m.Button</code> in the same code...</p> <pre class="lang-js prettyprint-override"><code>content: new sap.m.Text({ text: JSON.parse(oError.response.body).error.message.value, }), </code></pre>
Error in `[<-`(`*tmp*`, i, succ, value = 1) : subscript out of bounds <p>I have to simulate an image with a white crack on a black background. So I defined a function that adds to a matrix with all elements equal to zero some consecutive points equal to one. The function is the following: </p> <pre><code>crepa&lt;-function(matrice) { start&lt;-sample(1:ncol(matrice),1) matrice[1,start]&lt;-1 for (i in 2:nrow(matrice)) { alpha&lt;-sample(c(-1,0,1),1) succ&lt;-start+alpha if (succ==(ncol(matrice)+1)) succ==ncol(matrice) if (succ==0) succ==1 matrice[i,succ]&lt;-1 start&lt;-succ } matrice&lt;-as.matrix(matrice) } </code></pre> <p>To control whether the function works well, I applied it over and over again to the following matrix:</p> <pre><code> m&lt;-matrix(0,64,64) imma&lt;-crepa(m) par(mar=rep(0,4)) image(t(imma), axes = FALSE, col = grey(seq(0, 1, length = 256))) </code></pre> <p>In most cases the result is correct. However, in few cases I run into this Error:</p> <blockquote> <p>Error in <code>[&lt;-</code>(<code>*tmp*</code>, i, succ, value = 1) : subscript out of bounds</p> </blockquote>
<p>These two lines:</p> <pre><code> if (succ==(ncol(matrice)+1)) succ==ncol(matrice) if (succ==0) succ==1 </code></pre> <p>Should be:</p> <pre><code> if (succ==(ncol(matrice)+1)) succ=ncol(matrice) if (succ==0) succ=1 </code></pre> <p>In case you still can't see it, you've used the equality test <code>==</code> when you should use assignment <code>=</code> or <code>&lt;-</code>.</p> <p>The error message told me it had to be the element going off the matrix, so I started printing out the values of <code>succ</code> and then noticed it wasn't being reset within the right range, and only <em>then</em> did I spot the mistake. I probably looked at the code ten times without noticing. I also figured that kind of error was more likely with a small matrix, and so tested with a 6x6 matrix which meant I could be more likely to see it than with a 64x64!</p>
Calculated column based on other calculated column <p>I have code that will sum data for the hours column based on a description and then will sum hours based on the supervisor column. I would like to add a calculated column that will take the first sum and divide it by the second sum to give me a percentage. Here is my code with what I think is the right path for the percent column, but I can't get it to work. Any help is appreciated!</p> <pre><code>SELECT sap.Description, Sum(main.Hours) AS SumOfHours, main.supervisor1email AS SupervisorEmail, (SELECT SUM(sub.hours) FROM v_MES_TcActivities sub WHERE sub.costctr = '106330' AND sub.AttCode Not Like 'MEAL' AND sub.clockin Between dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate())) and dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate())) AND sub.supervisor1email = main.supervisor1email ) AS TotalHours, (SELECT Sum(subsub.hours) / TotalHours AS 'Percent' ) AS Percent FROM v_MES_TcActivities AS main LEFT JOIN t_SAP_AttCodes AS sap ON main.AttCode = sap.Code WHERE main.AttCode Not Like 'MEAL' AND main.CostCtr Like '106330' AND main.ClockIn Between dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate())) and dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate())) GROUP BY sap.Description, main.supervisor1email, Percent ORDER BY main.supervisor1email </code></pre> <p><a href="https://i.stack.imgur.com/Kk5Yx.png" rel="nofollow">Here is the before code</a></p> <p><a href="https://i.stack.imgur.com/hWKAK.png" rel="nofollow">Here is what I am looking to see</a></p>
<p>You can try this as well</p> <pre><code>SELECT Description, SumOfHours, SupervisorEmail, TotalHours, SumSubsubHr/TotalHours AS 'Percentage' FROM ( SELECT sap.Description, Sum(main.Hours) AS SumOfHours, main.supervisor1email AS SupervisorEmail, (SELECT SUM(sub.hours) FROM v_MES_TcActivities sub WHERE sub.costctr='106330' AND sub.AttCode Not Like 'MEAL' AND sub.clockin Between dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate())) and dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate())) AND sub.supervisor1email = main.supervisor1email ) AS TotalHours, Sum(sub.hours) AS 'SumSubsubHr' FROM v_MES_TcActivities AS main LEFT JOIN t_SAP_AttCodes AS sap ON main.AttCode = sap.Code WHERE main.AttCode Not Like 'MEAL' AND main.CostCtr Like '106330' AND main.ClockIn Between dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate())) and dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate())) GROUP BY sap.Description, main.supervisor1email )t </code></pre>
Android: Drag map while keeping marker at the center <p>I a, currently getting Current Location of device (lat,lng) in MapActivity. Now I want to let the user move the map, while keeping the marker at the center. This means that whenever the map is moved, current location will be updated. (Right?)</p> <p>I followed this <a href="http://stackoverflow.com/questions/19346206/android-how-to-move-a-map-under-a-marker?noredirect=1&amp;lq=1">android How to move a map under a marker</a> and <a href="http://stackoverflow.com/questions/21652902/how-to-attach-a-flexible-marker-on-map-something-like-uber-and-lyft">How to attach a flexible marker on map something like Uber and Lyft?</a> but couldn't get my concept clear. </p> <p>Activity_map.xml (Here I have added ImageView)</p> <pre><code>&lt;RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;fragment android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.MapFragment" /&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@drawable/gps" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>My MapActivity is as follows</p> <pre><code> public class MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener,GoogleMap.OnInfoWindowClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); // int x =_st.jsonArray.length(); if (android.os.Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) { checkLocationPermission(); } // 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); fragmentOnMap = (FragmentOnMap)getFragmentManager().findFragmentById(R.id.fragment_bottom); getFragmentManager().beginTransaction().hide(fragmentOnMap); } @Override public void onMapReady(GoogleMap googleMap) { //Get Last Known Location and convert into Current Longitute and Latitude final LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); final Location currentGeoLocation = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); double currentLat = currentGeoLocation.getLatitude(); double currentLon = currentGeoLocation.getLongitude(); LatLng currentLatLng = new LatLng(currentLat,currentLon); //Toast.makeText(this,"Cur Lat" +currentLat+"Lon"+currentLon,Toast.LENGTH_LONG).show(); // Get JSON String and Break it down into individual nodes //double x=_location.getLatitude(); //double y=_location.getLongitude(); json_string = getIntent().getExtras().getString("JSON_DTA"); LatLng latLng = null; try { int count = 0; //jsonObject = new JSONObject(json_string); jsonArray = new JSONArray(json_string); while (count &lt; jsonArray.length()) { JSONObject JO = jsonArray.getJSONObject(count); _id = JO.getInt("id"); _doctorname = JO.getString("doctorname"); _doclat = JO.getString("latitude"); _doclong = JO.getString("longitude"); count++; Double d = Double.parseDouble(_doclat); Double e = Double.parseDouble(_doclong); latLng = new LatLng(d, e); DecimalFormat df = new DecimalFormat("####0.0"); DistanceBetweenPoints distanceBetweenPoints = new DistanceBetweenPoints(); double distance = distanceBetweenPoints.CalculationByDistance(currentLatLng,latLng); double distanceThreshHold = 7 ; if(distance &lt; distanceThreshHold ) { mMap = googleMap; mMap.setOnInfoWindowClickListener(this); MarkerOptions _markeroptions = new MarkerOptions() .position(latLng) .title(_doctorname+": " + df.format(distance) + " KM" ) .icon(BitmapDescriptorFactory.fromResource(R.drawable.smallest_logo)); mMap.addMarker(_markeroptions); mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); } else { mMap = googleMap; } } } catch (JSONException e) { e.printStackTrace(); } //Initialize Google Play Services if (android.os.Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } } else { buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } @Override public void onConnected(@Nullable Bundle bundle) { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(1000); mLocationRequest.setFastestInterval(1000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } } @Override public void onConnectionSuspended(int i) { } @Override public void onLocationChanged(Location location) { mLastLocation = location; if (mCurrLocationMarker != null) { mCurrLocationMarker.remove(); } //Place current location marker LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title("Current Position"); markerOptions.draggable(true); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); mCurrLocationMarker = mMap.addMarker(markerOptions); // Toast.makeText(this, "Current" + latLng, Toast.LENGTH_LONG).show(); String tag = null; Log.d(tag, "lon: " + location.getLongitude() + " ----- lat: " + location.getLatitude()); //move map camera mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomTo(11)); //stop location updates if (mGoogleApiClient != null) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } public boolean checkLocationPermission(){ if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Asking user if explanation is needed if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an expanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } return false; } else { return true; } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission was granted. if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (mGoogleApiClient == null) { buildGoogleApiClient(); } mMap.setMyLocationEnabled(true); } } else { // Permission denied, Disable the functionality that depends on this permission. Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); } return; } // other 'case' lines to check for other permissions this app might request. //You can add here other case statements according to your requirement. } } </code></pre> <p>Your help will much appreciated. Thank you.</p>
<p>Having a map under an ImageView with your marker icon would be the best way to go here (just a framelayout with your map fragment under and your marker image centered on top should work). Then you can use an <code>OnCameraIdleListener</code> which would receive a callback when the map movement has ended. So just set an instance of <code>OnCameraIdleListener</code> to your map to listen for movement callbacks like so:</p> <pre><code>map.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() { @Override public void onCameraIdle() { //get latlng at the center by calling LatLng midLatLng = map.getCameraPosition().target; } }); </code></pre>