input
stringlengths
51
42.3k
output
stringlengths
18
55k
Implementing a concentrated distribution curve <p>I am working on a project right now and I need to map a variable amount of elements (say between 12 and 18 for this case) across 10 depth levels. Up until now, no worries here.</p> <p>The thing that bothers me is this: We are currently looking at implementing a concentration point to this distribution but I have no idea how to do it cleanly.</p> <p>In the above case, a total of 12-18 elements are distributed across 10 levels. But with the addition of the concentration, we need for the majority of the elements to be mapped around the depth of the concentration (let's say depth 4).</p> <p>I realize this means we are creating a bell curve but I cannot find for the life of me a way to implement it cleanly, with as little risk of leftovers as possible. I am after all running this a few hundred times at game load.</p> <p>EDIT: Here is an example of what is desired.</p> <p>Quantity: 18</p> <ul> <li>Level 1: 3</li> <li>Level 2: 2 </li> <li>Level 3: 2</li> <li>Level 4: 5</li> <li>Level 5: 3</li> <li>Level 6: 2</li> <li>Level 7: 1</li> <li>Level 8: 0</li> <li>Level 9: 0</li> <li>Level 10: 0</li> </ul>
<p>Well, one way to make it clear is to use discrete distribution with a peak, and Poisson might be a good choice</p> <p>Sample Poisson up to 9, if it is above 9 reject and resample. Otherwise shift it by 1 and return.</p> <p>Some pseudo-code based on <a href="http://numerics.mathdotnet.com/api/MathNet.Numerics.Distributions/Poisson.htm" rel="nofollow">MathDotNet</a></p> <pre><code>using MathNet.Numerics.Distributions; int Sample(Random rng, double lambda) { for( ;; ) { int r = Poisson.Sample(rng, lambda); if (r &lt; 10) return r+1; } return -1; } </code></pre> <p>Checking Mode of the <a href="https://en.wikipedia.org/wiki/Poisson_distribution" rel="nofollow">Poisson distribution</a>, it is clear that for peak at 4 you'll have to have <code>lambda</code> between 3 and 4. For <code>lambda=3</code>, you'll get two equal peaks in your sampling at 3 and 4, for <code>lambda=4</code> you'll get two peaks at 4 and 5 (remember shift by 1). Just play with it and try to set it to something in between which fits your requirements</p>
Generate unique download link for a PDF file <p>Hello everybody I'm new here please be friendly and don't get angry cause I'm a beginner.</p> <p>To introduce you:</p> <p>First I generated a <code>pdf</code> and save it after the user bought the file in a protected folder on my server. Than I save the path to this file with an id in my database. </p> <p>Second have a php file where I show the user contents/entrys from a database like a download link for the file.</p> <p>My link looks like this:</p> <pre><code>&lt;a href="http://my-website.de/download?link=&lt;?php echo $row["url_to_my_file"] ?&gt;" target="_blank"&gt;Download you file&lt;/a&gt; </code></pre> <p>When the user clicks on it he'll be redirected to my download.php where I get the url and send the user the download:</p> <pre><code>$my_file = file_get_contents($_GET['link']); $size = strlen($my_file); $file_name = 'My_file_name.pdf'; header('Content-Disposition: attachment; filename="' . $name . '"'); header('Content-Type: application/pdf'); header('Content-Length: ' . $size); echo $my_file; </code></pre> <p>It works all fine but I have a big problem. When the user right clicks on the link he can see the path where the file is and he can download the file just like his mind (and not mine) and also when I lock the site where he can download the file because he know the download link.</p> <p>No I get the idea to generate a <code>md5</code> string and save it in my database when the user clicks on <strong>Download</strong>. That's my approach:</p> <pre><code>//Generate unique download key $key = md5(uniqid(rand(), true)); //Insert into my database $sql = "INSERT INTO download_keys (md5_key, expired, download_link) VALUES ('$key', false, '$url')"; </code></pre> <p>Seacond give the user a new link: </p> <pre><code>&lt;a href="http://my-website.de/download?link='$key'" target="_blank"&gt;Download you file&lt;/a&gt; </code></pre> <p>But I cant do this in my file where I show the user the files and don't know how to deal with more than one file? </p> <p>This is my new download.php</p> <pre><code>$key = $_GET['key']; $sql = "SELECT download_link FROM download_keys WHERE '$key' = md5_key AND expired = 'false'"; //Check if sql is empty or not if (mysql_num_rows($sql)==0) { echo "No file found or key expired!"; } else { $link = $row["download_link"]; } $sql = "UPDATE download_link SET expired = 'true' WHERE '$key' = md5_key"; </code></pre> <p>At the end I change the expire value to true so when the user want to download the file with this link again it don't works.</p> <p><strong>Whats the right way to implement this unique file download function so that the user just see the key and not the path?</strong></p> <p>So all in all: I want to make a secret download link which the user can use only one. To download the file again he has do click the download button on the site even if he know the url </p> <p>Thank you for your help! I hope you understan my problem. Thanks.</p>
<p>Ahh, do you mean how to display the link as <code>"http://my-website.de/download?link=baksjcbasduo123231sdsad"</code> instead of <code>"http://my-website.de/download?link=baksjcbasduo123231sdsad.php"</code> ?</p> <p>If that's the case: First, You'll need to create an <code>.htaccess</code> file</p> <p>Then put this in your .htaccess file:</p> <pre><code>RewriteEngine On RewriteRule ^http://my-website.de/download/(.*)$ http://my-website.de/download?link=$1 [QSA,L] </code></pre>
Displaying youtube video from mysql database using php? <p>I want to display youtube video on a page, the following is my code in order to fetch youtube video URL from the database stored in mysql and then display it by iterating using while loop. However, the iframe does not display any video inside it.</p> <pre><code>&lt;?php if ($get_result != false) { while ($row = mysqli_fetch_array($get_result, MYSQLI_ASSOC)) { ?&gt; &lt;iframe width="560" height="315" src="&lt;?php echo $row["url"]; ?&gt;" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; &lt;?php } } ?&gt; </code></pre> <p>I have also tried using video tag inside while loop but it does not display the Youtube video inside the video player. Please help me to solve this issue.</p>
<p>You can use Youtube with embed, like this:</p> <pre><code>&lt;iframe width="560" height="315" src="https://www.youtube.com/embed/&lt;?php echo $row["url"]; ?&gt;?autoplay=1&amp;autohide=1&amp;controls=1&amp;showinfo=0&amp;modestbranding=1&amp;rel=0"&gt;&lt;/iframe&gt; </code></pre>
Laravel updating eloquent event: getting the data <p>I have been reading about eloquent events. There is an event for every interaction with a Model: creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored.</p> <p>I want to know the data from a Model when it has been updated and the data it has before. Is it possible? Because the documentation havent so much info about how to use these events.</p>
<p>You're looking for <a href="https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html#method_getDirty" rel="nofollow"><code>getDirty()</code></a> and <a href="https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html#method_getOriginal" rel="nofollow"><code>getOriginal()</code></a> methods.</p> <pre><code>User::updating(function ($user) { $dirty = $user-&gt;getDirty(); $original = $user-&gt;getOriginal(); }); </code></pre>
How to find the html element of a given text <p>Assume I have the following code to be parsed using JSoup</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-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;div id="myDiv" class="simple" &gt; &lt;p&gt; &lt;img class="alignleft" src="myimage.jpg" alt="myimage" /&gt; I just passed out of UC Berkeley &lt;/p&gt; &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p> <p>The question is, given just a keyword "Berkeley", is there a better way to find the element/XPath (or a list of it, if multiple occurrences of the keyword is present) in the html, which has this keyword as part of its text.</p> <p>I don't get to see the html before hand, and will be available only at runtime.</p> <p>My current implementation - Using Java-Jsoup, iterate through the children of body, and get "ownText" and text of each children, and then drill down into their children to narrow down the html element. I feel this is very slow.</p>
<p>Not elegant but simple way could look like :</p> <pre><code>import java.util.HashSet; import java.util.Set; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; public class JsoupTest { public static void main(String argv[]) { String html = "&lt;body&gt; \n" + " &lt;div id=\"myDiv\" class=\"simple\" &gt;\n" + " &lt;p&gt;\n" + " &lt;img class=\"alignleft\" src=\"myimage.jpg\" alt=\"myimage\" /&gt;\n" + " I just passed out of UC Berkeley\n" + " &lt;/p&gt;\n" + " &lt;ol&gt;\n" + " &lt;li&gt;Berkeley&lt;/li&gt;\n" + " &lt;li&gt;Berkeley&lt;/li&gt;\n" + " &lt;/ol&gt;\n" + " &lt;/div&gt; \n" + "&lt;/body&gt;"; Elements eles = Jsoup.parse(html).getAllElements(); // get all elements which apear in your html Set&lt;String&gt; set = new HashSet&lt;&gt;(); for(Element e : eles){ Tag t = e.tag(); set.add(t.getName()); // put the tag name in a set or list } set.remove("head"); set.remove("html"); set.remove("body"); set.remove("#root"); set.remove("img"); //remove some unimportant tags for(String s : set){ System.out.println(s); if(!Jsoup.parse(html).select(s+":contains(Berkeley)").isEmpty()){ // check if the tag contains your key word System.out.println(Jsoup.parse(html).select(s+":contains(Berkeley)").get(0).toString());} // print it out or do something else System.out.println("---------------------"); System.out.println(); } } } </code></pre>
Redirecting subdomain URL to specific URL <p>On my site, each group has a specific URL, eg: domain.com/my-group, domain.com/my-group2 and so on..</p> <p>What I would like is that the user uses my-group.domain.com, my-group2.domain.com to get to its group.</p> <p>How can I achieve that?</p>
<p>You can setup Apache to listen on both  my-group.domain.com and my-group2.domain.com using the Virtual Host configuration.</p> <p>Apache's documentation on this topic should be enough to get you started: <a href="https://httpd.apache.org/docs/current/vhosts/" rel="nofollow">https://httpd.apache.org/docs/current/vhosts/</a></p>
Custom Exception override message with JSON.NET <p>If you create a custom Exception that overrides the virtual property <code>Message</code> with something like this:</p> <pre><code>public class GrossException : Exception { public GrossException() : base("Eww, gross") { } } public class BarfException : GrossException { public override string Message { get; } = "BARF!!"; } </code></pre> <p>Then, when sending <code>BarfException</code> using JSON.NET through ASP.NET, the <code>Message</code> property will contain </p> <blockquote> <p>"Eww, gross"</p> </blockquote> <p>Instead of the overridden value. I believe this is related to the fact that Exception implements <code>ISerializable</code>, but since the <code>Message</code> property is virtual, should I not be allowed to override it like this and still have it work?</p> <p>Is there a proper way to implement Exception and be able to override the <code>Message</code> property and still have it work?</p>
<p>You are correct that this is happening because <code>Exception</code> implements <a href="https://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable(v=vs.110).aspx" rel="nofollow"><code>ISerializable</code></a> and Json.NET <a href="http://www.newtonsoft.com/json/help/html/serializationguide.htm#ISerializable" rel="nofollow">supports this interface</a>. Specifically, from the reference source, in the method <a href="https://referencesource.microsoft.com/#mscorlib/system/exception.cs,549" rel="nofollow"><code>Exception.GetObjectData(SerializationInfo info, StreamingContext context)</code></a>, the <code>Exception</code> type serializes the underlying <em>field</em>, not the property:</p> <pre><code> info.AddValue("Message", _message, typeof(String)); </code></pre> <p>Microsoft may have done this because the <code>Message</code> property has a default value if the underlying field is not set:</p> <pre><code> public virtual String Message { get { if (_message == null) { if (_className==null) { _className = GetClassName(); } return Environment.GetResourceString("Exception_WasThrown", _className); } else { return _message; } } } </code></pre> <p>By serializing the field, not the property, an exception with the default message will have its visible message automatically shown in the <code>CurrentUICulture</code> of the receiving system when deserialized.</p> <p>Thus, if you want the value of the message property to appear in the JSON, instead of the underlying field, you're going to need to override <a href="https://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.getobjectdata(v=vs.110).aspx" rel="nofollow"><code>GetObjectData()</code></a>. And, since <a href="https://msdn.microsoft.com/en-us/library/akebc4z9(v=vs.110).aspx" rel="nofollow"><code>AddValue()</code></a> throws an exception if you try to add a value with the same name as a pre-existing value, and <a href="https://msdn.microsoft.com/en-us/library/system.runtime.serialization.serializationinfo(v=vs.110).aspx" rel="nofollow"><code>SerializationInfo</code></a> has no <code>SetValue()</code> method to replace a current value, you're going to need to do something with a bit of code smell:</p> <pre><code>public class GrossException : Exception { public GrossException() : base("Eww, gross") { } protected GrossException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class BarfException : GrossException { public BarfException() : base() { } protected BarfException(SerializationInfo info, StreamingContext context) : base(info, context) { } public override string Message { get { return "BARF!!"; } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { var tempInfo = new SerializationInfo(GetType(), new FormatterConverter()); base.GetObjectData(tempInfo, context); foreach (SerializationEntry entry in tempInfo) { if (entry.Name != "Message") { info.AddValue(entry.Name, entry.Value, entry.ObjectType); } } info.AddValue("Message", Message); } } </code></pre> <p>As you can see, this solution violates the design of your inheritance hierarchy since the value of the underlying <code>_message</code> field is no longer the value <em>required</em> by the base class <code>GrossException</code>. But at least the JSON is pretty.</p> <p>A better solution would be to modify the <code>GrossException</code> type to have a protected constructor in which the message can be specified:</p> <pre><code>public class GrossException : Exception { public GrossException() : base("Eww, gross") { } protected GrossException(SerializationInfo info, StreamingContext context) : base(info, context) { } protected GrossException(string message) : base(message) { } } </code></pre> <p>Or, if you just want to <em>see</em> the overridden message in the JSON for debugging purposes (say, because you're logging exceptions), you could just add it to the serialization stream like so:</p> <pre><code>public class BarfException : GrossException { public BarfException() : base() { } protected BarfException(SerializationInfo info, StreamingContext context) : base(info, context) { } public override string Message { get { return "BARF!!"; } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("OverriddenMessage", Message); } } </code></pre> <p>Either solution avoids the code smell.</p>
Random images from file without duplicating any <p>Hello Working on a poker game. I have my cards randomly being called from a file, but I want there to be no duplicates. for example, no 2 five of clubs, or 2 jack of spades in the same hand. That's basically what I have been trying to do, and once I get that done, my game should be finished Here is some of the code</p> <pre><code>string[] CardDisplay = new string[5]; for (int i = 0; i &lt; 5; i++) { CardDisplay[i] = getRandomImage(); } PokerCard[0] = PokerCard1.ImageUrl = Path.Combine("~/GameStyles/VideoPoker/Images/Poker/", CardDisplay[0]); PokerCard[1] = PokerCard2.ImageUrl = Path.Combine("~/GameStyles/VideoPoker/Images/Poker/", CardDisplay[1]); PokerCard[2] = PokerCard3.ImageUrl = Path.Combine("~/GameStyles/VideoPoker/Images/Poker/", CardDisplay[2]); PokerCard[3] = PokerCard4.ImageUrl = Path.Combine("~/GameStyles/VideoPoker/Images/Poker/", CardDisplay[3]); PokerCard[4] = PokerCard5.ImageUrl = Path.Combine("~/GameStyles/VideoPoker/Images/Poker/", CardDisplay[4]); public string getRandomImage() { string[] fileNames = Directory.GetFiles(MapPath("~/GameStyles/VideoPoker/Images/Poker/")); int CurrentPick; CurrentPick = rand.Next(fileNames.Length); string CardToShow = fileNames[CurrentPick]; return Path.GetFileName(CardToShow); } </code></pre> <p>Here is a screenshot of what I have</p> <p><img src="https://i.stack.imgur.com/GkTT4.jpg" alt="enter image description here"></p>
<p>I recommend using LINQ to accomplish this:</p> <pre><code>string[] fileNames = Directory.GetFiles(MapPath("~/GameStyles/VideoPoker/Images/Poker/")); var randomCards = fileNames .OrderBy(i =&gt; Guid.NewGuid()) .Take(5) .Select(filePath =&gt; Path.Combine("~/GameStyles/VideoPoker/Images/Poker/", Path.GetFileName(filePath))) .ToArray(); PokerCard[0] = PokerCard1.ImageUrl = randomCards[0]; PokerCard[1] = PokerCard2.ImageUrl = randomCards[1]; PokerCard[2] = PokerCard3.ImageUrl = randomCards[2]; PokerCard[3] = PokerCard4.ImageUrl = randomCards[3]; PokerCard[4] = PokerCard5.ImageUrl = randomCards[4]; </code></pre> <p>This will simply reorder the array of fileNames, sort by a random Guid (Which will essentially randomize the array), and then take the first 5 elements.</p> <p>Here's a .NET fiddle showing how it will work: <a href="https://dotnetfiddle.net/c1996q" rel="nofollow">https://dotnetfiddle.net/c1996q</a></p>
How do I refactor this code to make it shorter? <pre><code>import math def roundup(x): return int(math.ceil(x / 10.0)) * 10 w=0 while w == 5: print("Would you like to *work out* a missing letter in a GTIN-8 code, or *check* a code?") response = input(":") if response == 'work out': print("Input a 7 digit GTIN-8 code and I'll work out the 8th") c1 = int(input("Enter FIRST number: ")) c2 = int(input("Enter SECOND number: ")) c3 = int(input("Enter THIRD number: ")) c4 = int(input("Enter FOURTH number: ")) c5 = int(input("Enter FIFTH number: ")) c6 = int(input("Enter SIXTH number: ")) c7 = int(input("Enter SEVENTH number: ")) y = (c1*3+c2+c3*3+c4+c5*3+c6+c7*3) ru2=roundup(y) GTIN8 = ru2-y print("Your GTIN8 Code would be: "+str(c1)+str(c2)+str(c3)+str(c4)+str(c5)+str(c6)+str(c7)+str(GTIN8)) print("Wanna work out another?") if response == 'check': print("Input a 8 digit GTIN-8 code and I'll check if it's correct") c1 = int(input("Enter FIRST number: ")) c2 = int(input("Enter SECOND number: ")) c3 = int(input("Enter THIRD number: ")) c4 = int(input("Enter FOURTH number: ")) c5 = int(input("Enter FIFTH number: ")) c6 = int(input("Enter SIXTH number: ")) c7 = int(input("Enter SEVENTH number: ")) c8 = int(input("Enter EIGTH number: ")) y = (c1*3+c2+c3*3+c4+c5*3+c6+c7*3) ru2=roundup(y) GTIN8 = ru2-y if GTIN8 != c8: print("Nope that product code is incorrect!") reply=input("Want to know the correct answer to your code? Type yes if so: ") if reply == 'yes': print("The correct answer would have been: "+str(GTIN8)) if GTIN8 == c8: print("That code is correct!") </code></pre> <p>The problem is that I have tried time and time again, to make this code smaller.</p> <p>Even by inputting 'response' as a string, to allow the user to type the code in one go.</p> <p>If you couldn't already tell, this is a code for a GTIN-8 product code and I know there are various other GTIN-8 codes out there but I just couldn't do it, let alone copy.</p>
<p>To get you started, here is one simple way of reducing the number of lines</p> <pre><code>c = [int(x) for x in input("Input a 8 digit GTIN-8 code and I'll check if it's correct").split("")] </code></pre> <p>Now you can access each character with <code>c[n]</code>.</p>
Jquery to append text in textbox from other textboxes in the same Mvc view <p>I have 3 textboxes on a form in my mvc view, FirstName, LastName, UserName. The UserName needs to be the FirstName + LastName. I tried the following Jquery which will add the letters of the FirstName field to UserName on the FirstName.KeyUp event, but when I add letters from the LastName field to the UserName it overwrites the FirstName letters (actually I only need the 1st letter of the lastName). What is the Jquery for this to "Append" letters and not overwrite? Is KeyUp a good event for this -- maybe LostFocus or something? Or should I use a function that returns a value with the return keyword? What is the Jquery for that approach?</p> <pre><code>@using (Html.BeginForm()) { &lt;fieldset&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.FirstName) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.FirstName) @Html.ValidationMessageFor(model =&gt; model.FirstName) &lt;/div&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.LastName) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.LastName) @Html.ValidationMessageFor(model =&gt; model.LastName) &lt;/div&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.UserName) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.UserName) @Html.ValidationMessageFor(model =&gt; model.UserName) &lt;/div&gt; &lt;/fieldset&gt; } &lt;script type="text/javascript"&gt; $(function () { $("#FirstName").keyup(function () { $("#UserName").val(this.value); }); $("#LastName").keyup(function () { $("#UserName").val(this.value); }); }); &lt;/script&gt; </code></pre>
<p>You can read both the input values(<em>FirstName and LastName</em>) and append it to get the final value and still overwrite the UserName input value.</p> <pre><code>$(function(){ $("#FirstName").keyup(function () { $("#UserName").val($(this).val()+ $("#LastName").val()); }); $("#LastName").keyup(function () { $("#UserName").val( $("#FirstName").val()+$(this).val()); }); }); </code></pre> <p>If you want to add only the first letter of last name, you can do this</p> <pre><code>$(function(){ $("#FirstName").keyup(function () { var lastName = $("#LastName").val(); if(lastName!=='') { lastName=lastName.charAt(0); } $("#UserName").val($(this).val()+ lastName); }); $("#LastName").keyup(function () { var lastName = $(this).val(); if(lastName!=='') { lastName=lastName.charAt(0); } $("#UserName").val( $("#FirstName").val()+lastName); }); }); </code></pre> <p><a href="http://jsbin.com/vupeximazi/edit?js,console,output" rel="nofollow">Here</a> is a working jsfiddle.</p>
Column Manipulations in Spark Scala <p>I am learning to work with Apache Spark(Scala) and still figuring out how things work out here</p> <p>I am trying to acheive a simple task of 1. Finding Max of column 2. Subtract each value of the column from this max and create a new column</p> <p>The code I am using is </p> <pre><code>import org.apache.spark.sql.functions._ val training = sqlContext.createDataFrame(Seq( (10), (13), (14), (21) )).toDF("Values") val training_max = training.withColumn("Val_Max",training.groupBy().agg(max("Values")) val training_max_sub = training_max.withColumn("Subs",training_max.groupBy().agg(col("Val_Max")-col("Values) )) </code></pre> <p>However I am getting a lot of errors. I am more or less fluent in R and had I been doing the same task my code would have been</p> <pre><code>library(dplyr) new_data &lt;- training %&gt;% mutate(Subs= max(Values) - Values) </code></pre> <p>Any help on this will be greatly appreciated</p>
<p>Here is a solution using window functions. You'll need a <code>HiveContext</code> to use them</p> <pre><code>import org.apache.spark.sql.hive.HiveContext import org.apache.spark.sql.functions._ import org.apache.spark.sql.expressions.Window val sqlContext = new HiveContext(sc) import sqlContext.implicits._ val training = sc.parallelize(Seq(10,13,14,21)).toDF("values") training.withColumn("subs", max($"values").over(Window.partitionBy()) - $"values").show </code></pre> <p>Which produces the expected output :</p> <pre><code>+------+----+ |values|subs| +------+----+ | 10| 11| | 13| 8| | 14| 7| | 21| 0| +------+----+ </code></pre>
how connect to multiple hosts/databases in laravel <p>I'm new in laravel and wondering how could I connect to multiple hosts and multiple databases in Laravel ? </p> <p>if yes how i could do that dynamically ?</p> <p>how to add new host connection dynamically ?</p> <p>how to add new database connection dynamically ?</p> <pre><code>Config::set("database.connections.mysql", [ "host" =&gt; "...", "database" =&gt; "...", "username" =&gt; "...", "password" =&gt; "... ]); </code></pre> <p>this is what i had found but i have no idea how to work further. </p>
<p>In your database.php, you can add multiple databases. </p> <pre><code>'mysql' =&gt; [ 'driver' =&gt; 'mysql', 'host' =&gt; '', 'port' =&gt; '', 'database' =&gt; '', 'username' =&gt; '', 'password' =&gt; '', 'charset' =&gt; 'utf8', 'collation' =&gt; 'utf8_unicode_ci', 'prefix' =&gt; '', 'strict' =&gt; false, ], 'mysql2' =&gt; [ 'driver' =&gt; 'mysql', 'host' =&gt; '', 'port' =&gt; '', 'database' =&gt; '', 'username' =&gt; '', 'password' =&gt; '', 'charset' =&gt; 'utf8', 'collation' =&gt; 'utf8_unicode_ci', 'prefix' =&gt; '', 'strict' =&gt; false, ], </code></pre> <p>In order to use the databases, you can use a variable to use a specific connection, such as:</p> <pre><code>$db1 = DB::connection('mysql'); $db2 = DB::connection('mysql2'); </code></pre> <p>Where mysql and mysql2 are the name you've defined your database by in your database.php</p> <p>To run any raw SQL query, use:</p> <pre><code>$user1 = $db1-&gt;table('user_login') -&gt;select('*') -&gt;get(); $user2 = $db2-&gt;table('user_login') -&gt;select('*') -&gt;get(); </code></pre>
cannot register aframe component in js file <p>I am trying to register an aframe component in a js file which is included from the base html file. The components are registered correctly when in the html inside script tags, but do not register when in the js file.</p> <p>example of code in html:</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-html lang-html prettyprint-override"><code>&lt;html lang="en-US"&gt; &lt;link rel="stylesheet" type="text/css" href="style.css" media="screen" /&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Gravity Puzzle&lt;/title&gt; &lt;meta name="description" content=""&gt; &lt;script src="dist/aframe-v0.3.0.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="app.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;a-scene id="scene"&gt; &lt;script&gt; AFRAME.registerComponent('mouse-click-listener', { init: function () { var el = this.el; window.addEventListener('click', function () { console.log("click"); el.emit('click', null, false); }); } }); &lt;/script&gt; &lt;a-sky id="sky" color="#AAAACC"&gt;&lt;/a-sky&gt; &lt;a-entity id="cameraRoot" mouse-click-listener position="2 0.5 2" rotation="0 225 0"&gt; &lt;a-entity id="myCamera" camera acceleration look-controls keyboard-controls&gt; &lt;/a-entity&gt; &lt;/a-entity&gt; &lt;/a-scene&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Example of code in the js file:</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>function initialise() { AFRAME.registerComponent('mouse-click-listener', { init: function () { console.log("registered"); var el = this.el; window.addEventListener('click', function () { console.log("click"); el.emit('click', null, false); }); } }); } window.onload = initialise;</code></pre> </div> </div> </p> <p>Note, the 'registered' text does not appear in the browser console. What am I missing?</p>
<p>Best to place the script tag after A-Frame before the scene. </p> <pre><code>&lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Gravity Puzzle&lt;/title&gt; &lt;meta name="description" content=""&gt; &lt;script src="dist/aframe-v0.3.0.js"&gt;&lt;/script&gt; &lt;script src="mycomponent.js&gt;&lt;/script&gt; &lt;/head&gt; </code></pre> <p>And don't need to wrap or wait for load:</p> <pre><code> AFRAME.registerComponent('mouse-click-listener', { init: function () { console.log("registered"); var el = this.el; window.addEventListener('click', function () { console.log("click"); el.emit('click', null, false); }); } }); } </code></pre>
Angular directive nesting bizarrely broken when upgrading from 1.4.9 to 1.5.0 <p>Apologies for the vague title; I have yet to figure out exactly <em>what</em> is breaking after the upgrade. Possibly the nesting of directives or template issues?</p> <p>(example images &amp; links to CodePens below)</p> <h2>Problem</h2> <p>I have a simple open source AngularJS library that generates a calendar. When using AngularJS 1.4.9 it works perfectly. But when I bump up to AngularJS 1.5.0 it breaks the layout in the most bizarre of ways.</p> <p>No errors are thrown and all calendar days <em>are</em> generated in the DOM, however, all the days are output into a single week and all weeks are output into a single month (not even the first week or month either.. arghhh!).</p> <h2>Research</h2> <p>I have read the <a href="https://docs.angularjs.org/guide/migration#migrating-from-1-4-to-1-5" rel="nofollow">migration guide for 1.4 > 1.5</a> but didn't see anything that sounded related. I also read through the <a href="https://github.com/angular/angular.js/blob/master/CHANGELOG.md#150-ennoblement-facilitation-2016-02-05" rel="nofollow">1.5 changelog</a> and the related rc changelogs; again nothing sounded related.</p> <p>When I check the actual arrays of months/weeks/etc that are generated in JS everything looks great. If I remove the nested directives and simply have all the markup in a single template, the DOM output is correct (this is not a true solution since this would break certain functionality of the library).</p> <p>Any ideas would be greatly appreciated.</p> <hr> <h2>Code &amp; Demos</h2> <p>See the exact same code with the different versions of AngularJS (check Settings > JavaScript to see the linked libraries):</p> <ul> <li>1.4.9 (working): <a href="https://codepen.io/benjamincharity/pen/BLYrqr?editors=1000" rel="nofollow">https://codepen.io/benjamincharity/pen/BLYrqr?editors=1000</a></li> <li>1.5.0 (broken): <a href="http://codepen.io/benjamincharity/pen/pEVVXV?editors=1000" rel="nofollow">http://codepen.io/benjamincharity/pen/pEVVXV?editors=1000</a></li> </ul> <p><strong>Again, the only difference is the version of AngularJS included.</strong></p> <p>The directive that is being used is simply:</p> <p><code> &lt;!-- This should generate a 30 day calendar starting with the current day --&gt; &lt;bc-calendar class="bc-calendar--days"&gt;&lt;/bc-calendar&gt; </code></p> <p><a href="https://i.stack.imgur.com/WddqN.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/WddqN.jpg" alt="enter image description here"></a></p>
<p>This isn't exactly 100% an answer, but that specific library relies heavily on the <code>replace</code> directive flag, which has since been deprecated <a href="https://github.com/angular/angular.js/commit/eec6394a342fb92fba5270eee11c83f1d895e9fb" rel="nofollow">see here</a>. I downloaded the source and removed the replace flag on each directive, then with a few modifications to the css was able to achieve this. <a href="https://i.stack.imgur.com/Rsc4L.png" rel="nofollow"><img src="https://i.stack.imgur.com/Rsc4L.png" alt="angular-json-calendar modification"></a></p> <p>The css changes were on <code>.bc-calendar--days, .bc--calendar--days</code> <code>width : 50px; display: inline-flex;</code>. </p>
Maven compilation of my Java 8 source code fails <p>On my mac, I am trying to compile some Java 8 source code I wrote. It compiles fine in Eclipse, but in Maven, the compilation is failing. </p> <p>I get multiple errors of the form:</p> <pre><code>[INFO] ------------------------------------------------------------- [ERROR] COMPILATION ERROR : [INFO] ------------------------------------------------------------- [ERROR] /Users/admin/eclipse/workspaces/default/Java8/src/main/java/language/utilities/MapDemo.java:[14,33] lambda expressions are not supported in -source 1.7 (use -source 8 or higher to enable lambda expressions) </code></pre> <p>Running mvn -v yields:</p> <pre><code>Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T16:41:47+00:00) Maven home: /Users/admin/apache-maven-3.3.9 Java version: 1.8.0_91, vendor: Oracle Corporation Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home/jre Default locale: en_IE, platform encoding: UTF-8 OS name: "mac os x", version: "10.12", arch: "x86_64", family: "mac" </code></pre> <p>Running the export command shows that the JAVA_HOME variable is set to:</p> <pre><code>JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home" </code></pre> <p>What is this '-source' property? Why do I need to set it if my Java version is Java 8?</p>
<p>Set</p> <pre><code>&lt;maven.compiler.source&gt;1.8&lt;/maven.compiler.source&gt; &lt;maven.compiler.target&gt;1.8&lt;/maven.compiler.target&gt; </code></pre> <p>in the <a href="https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html" rel="nofollow">properties of your pom</a>.</p> <p>You should not set this in the <code>settings.xml</code> because you force other people to change their <code>settings.xml</code> and use JDK8 in all of their other projects by default!</p>
Issues with delimiter ("\t | \n") Java <p>I am having issues using my delimiter in my scanner. I am currently using a scanner to read a text file and put tokens into a string. My tutor told me to use the delimiter (useDelimiter("\t|\n")). However each token that it is grabbing is ending in /r (due to a return in the text file). This is fine for printing purposes, however i need to get the string length. And instead of returning the number of actual characters, it is returning the number of characters including that /r. Is there a better delimiter I can use that will accomplish the same thing (without grabbing the /r)? code is as follows:</p> <pre><code> studentData.useDelimiter("\t|\n"); while (studentData.hasNext()) { token = studentData.next(); int tokenLength = token.length(); statCalc(tokenLength); } </code></pre> <p>I am well aware that I could simply remove the last character of the string token. However, for many reasons, I just want it to grab the token without the /r. Any and all help would be greatly appreciated.</p>
<p>Try this:</p> <pre class="lang-java prettyprint-override"><code>studentData.useDelimiter("\\t|\\R"); </code></pre> <p>The <code>\R</code> pattern matches any linebreak, see <a href="https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html" rel="nofollow">documentation</a>.</p> <p>I guess the remaining <code>\r</code> char is a partially consumed linebreak in Windows environment. With the aforementioned delimiter, the scanner will properly consume the line.</p>
Making a namepaced function asynchronous using setimeout <p>I have this function which is using namespace. I want to make it asynchronous. Assuming that this function is being called on click of some button ?</p> <pre><code>var ns = { somemfunc: function (data) { alert("hello"); } } </code></pre> <p>EDIT - Sorry for being unclear on this. I want to make the call to this function asynchronous by putting the settimeout function inside the somefunc function. Not sure how to do that.</p> <p>Thanks in advance</p>
<p>You can set this function to be called asynchronously by adding a <code>setTimeout</code> block within the definition of <code>somefunc</code>, note that I am using the term asynchronous loosely here as this function isn't really doing any asynchronous work. An async function would be a function that does some work that takes some time to execute, such as making a network request, aggregating its results and then reporting back to the caller to do some sort of DOM refresh or something, it normally reports back to the caller using a callback, or resolving/rejecting a promise, in the time that this long running code is running, the Event Queue is not blocked and can continue to process other actions if this was not the case then the app would be unresponsive until the long running task finished computing.</p> <p>What you want to achieve here is not truly async as you're simply scheduling the function to run on the Event Queue in 2 seconds.</p> <pre><code>var ns = { somemfunc: function (data) { setTimeout(function() { alert("hello"); }, 2000); } } ns.somemfunc(); </code></pre> <p>When <code>ns.somefunc()</code> is called, its now set to execute the function <code>somefunc</code> on the Event Queue in 2000ms (2 seconds). Remember Javascript is single threaded, tasks are scheduled to run on the event queue and will be processed contiguously. If you set the timeout to run the function after 2000ms but the jobs before it take 500ms to compute, then we actually wait 2500ms for the queue to serve that function.</p>
Docker container date/time totally different to host PC <p>When I run a docker container on my PC it has a totally different date/time to the host PC. See commands below. The time on the container recognizerDev is for the previous day, different hour, different minutes to the host. Any idea what is going on? </p> <pre><code>PS C:\Users\Bobby&gt; date 11 October 2016 19:51:38 PS C:\Users\Bobby&gt; docker exec recognizerDev date Mon Oct 10 21:43:54 UTC 2016 </code></pre> <p>When I try the same thing running on an AWS linux host the date/time is correct except for a 1 hour difference due to timezones.</p> <p>Note that the first command returns the correct time/date in UTC+1 (London) as per my PC. The second command says it is in UTC but this cannot be right as if so it would return the same result less 1 hour.</p>
<p>This is only a partial answer (because it does not necessarily resolve the problem), but may help with diagnosis.</p> <p>When you are running docker under Linux (as on your AWS host), you are just running processes on the host. That is, there isn't a substantial difference between <code>docker run fedora ls</code> vs running <code>ls</code>, except that the former has a slightly different view of system resources. The time reported in the container will always match the time reported on the host, modulo timezone settings.</p> <p>When you running docker anywhere else (e.g., under Windows or MacOS), there is an additional layer in play: docker spawns a Linux virtual machine (historically using VirtualBox, although I think they may <a href="https://blog.docker.com/2016/03/docker-for-mac-windows-beta/" rel="nofollow">take advantage of other options these days</a>) and then runs docker inside the virtual machine. </p> <p>Because this is effectively a different machine from your host, it is possible for the time to drift. There are various ways of solving this sort of problem, including running ntp inside the virtual machine or running special guest agents that take care of keeping time in sync with the host. I don't know enough about how Docker configures these systems to know how or if they handle this explicitly.</p> <p>If your docker vm has been running for a long period of time, simply restarting it may resolve the problem. Possibly <a href="https://docs.docker.com/machine/reference/restart/" rel="nofollow">docker machine restart</a> is what you need.</p>
Stopping CSRF checking for subdomains <p>For our Laravel 5.3 API, I want to remove the need for CSRF tokens since everything is handled with OAuth2 and JWT.</p> <p>Currently the API operates on the subdomain: <code>api.example.com</code></p> <p>I tried this but it still requests CSRF tokens:</p> <pre><code>class VerifyCsrfToken extends BaseVerifier { protected $except = [ 'api.*' ]; } </code></pre> <p>I'd also like to be able to disable the CSRF protection when I am doing random route tests on the main app which is on <code>app.example.dev</code>, but adding <code>'app.*'</code> to <code>$except</code> also doesn't work.</p> <p>Is it possible to do this?</p>
<p>You can overwrite the <code>shouldPassThrough</code> method in the <code>BaseVerifier</code> class, where-in it would support a subdomain in <code>$except</code> such as <code>api.yourdomain.com</code></p> <pre><code>/** * Determine if the request has a URI that should pass through CSRF verification. * * @param \Illuminate\Http\Request $request * @return bool */ protected function shouldPassThrough($request) { foreach ($this-&gt;except as $except) { if (Str::is($except, $request-&gt;url())) { // break out of CSRF check return true; } } return false; } </code></pre>
Alamofire: [Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-999 "cancelled" <p>The service I'm connecting to is using a self signed certificate. For dev purposes I do not want to validate that chain. </p> <p>Using swift 3 with Alamofire 4. Fixed the ATS accordingly:</p> <pre><code>&lt;key&gt;NSAppTransportSecurity&lt;/key&gt; &lt;dict&gt; &lt;key&gt;NSExceptionDomains&lt;/key&gt; &lt;dict&gt; &lt;key&gt;url.com&lt;/key&gt; &lt;dict&gt; &lt;key&gt;NSExceptionAllowsInsecureHTTPLoads&lt;/key&gt; &lt;true/&gt; &lt;key&gt;NSExceptionRequiresForwardSecrecy&lt;/key&gt; &lt;false/&gt; &lt;key&gt;NSIncludesSubdomains&lt;/key&gt; &lt;true/&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;/dict&gt; </code></pre> <p>Code to connect and disable evaluation. </p> <pre><code> let serverTrustPolicies: [String: ServerTrustPolicy] = [ "example.domain.com": .pinCertificates( certificates: ServerTrustPolicy.certificates(), validateCertificateChain: false, validateHost: true ), "sub.url.com": .disableEvaluation ] let sessionManager = Alamofire.SessionManager( serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) ) let headers = ["Authorization": "Basic /*...*/"] sessionManager.request("https://sub.url.com/path", headers: headers).responseJSON { response in print(response.request) // original URL request print(response.response) // HTTP URL response print(response.data) // server data print(response.result) // result of response serialization debugPrint(response) if let JSON = response.result.value { print("JSON: \(JSON)") } } </code></pre> <p>Error log from dumpPrint</p> <blockquote> <p>[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey=<a href="https://sub.url.com/path" rel="nofollow">https://sub.url.com/path</a>, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=<a href="https://sub.url.com/path" rel="nofollow">https://sub.url.com/path</a>}</p> </blockquote> <p>URL has been masked. </p>
<p>Please add this statement to the end of responseJson block:</p> <pre><code>manager.session.invalidateAndCancel() </code></pre> <p>It happens if the object of the manager is not retained till execution of the block completes, so this would ensure its retention.</p> <p>Cheers!</p>
AndroidManifest.xml with key com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME <p>I am getting this random exceptions on some devices. I wonder what I am doing wrong. Please let me know what more information I can provide for this issue. I am clueless what else I can provide to help make this question more useful. I am getting no hints from my app.</p> <pre><code>0 java.lang.RuntimeException: Unable to create service com.google.android.gms.cast.framework.media.MediaNotificationService: java.lang.IllegalStateException: The fully qualified name of the implementation of OptionsProvider must be provided as a metadata in the AndroidManifest.xml with key com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME. 1 at android.app.ActivityThread.handleCreateService(ActivityThread.java:2474) 2 at android.app.ActivityThread.access$1600(ActivityThread.java:130) 3 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) 4 at android.os.Handler.dispatchMessage(Handler.java:99) 5 at android.os.Looper.loop(Looper.java:137) 6 at android.app.ActivityThread.main(ActivityThread.java:4847) 7 at java.lang.reflect.Method.invokeNative(Native Method) 8 at java.lang.reflect.Method.invoke(Method.java:535) 9 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 10 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 11 at dalvik.system.NativeStart.main(Native Method) 12 Caused by: java.lang.IllegalStateException: The fully qualified name of the implementation of OptionsProvider must be provided as a metadata in the AndroidManifest.xml with key com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME. 13 at com.google.android.gms.cast.framework.CastContext.zzbd(Unknown Source) 14 at com.google.android.gms.cast.framework.CastContext.getSharedInstance(Unknown Source) 15 at com.google.android.gms.cast.framework.media.MediaNotificationService.onCreate(Unknown Source) 16 at android.app.ActivityThread.handleCreateService(ActivityThread.java:2458) 17 ... 10 more 18 java.lang.IllegalStateException: The fully qualified name of the implementation of OptionsProvider must be provided as a metadata in the AndroidManifest.xml with key com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME. 19 at com.google.android.gms.cast.framework.CastContext.zzbd(Unknown Source) 20 at com.google.android.gms.cast.framework.CastContext.getSharedInstance(Unknown Source) 21 at com.google.android.gms.cast.framework.media.MediaNotificationService.onCreate(Unknown Source) 22 at android.app.ActivityThread.handleCreateService(ActivityThread.java:2458) 23 at android.app.ActivityThread.access$1600(ActivityThread.java:130) 24 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) 25 at android.os.Handler.dispatchMessage(Handler.java:99) 26 at android.os.Looper.loop(Looper.java:137) 27 at android.app.ActivityThread.main(ActivityThread.java:4847) 28 at java.lang.reflect.Method.invokeNative(Native Method) 29 at java.lang.reflect.Method.invoke(Method.java:535) 30 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 31 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 32 at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>Edit - <strong>ManifestFile</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.mcruiseon.buseeta"&gt; &lt;!-- For Options menu call support --&gt; &lt;uses-permission android:name="android.permission.CALL_PHONE"/&gt; &lt;!-- To auto-complete the email text field in the login form with the user's emails --&gt; &lt;uses-permission android:name="android.permission.READ_PHONE_STATE"/&gt; &lt;uses-permission android:name="android.permission.INTERNET"/&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/&gt; &lt;uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /&gt; &lt;!-- To auto-complete the email text field in the login form with the user's emails --&gt; &lt;uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/&gt; &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/&gt; &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/&gt; &lt;!-- For the background service to run forever --&gt; &lt;uses-permission android:name="android.permission.WAKE_LOCK"/&gt; &lt;!-- For Current Location on Driver App --&gt; &lt;permission android:name="${manifestApplicationId}.permission.MAPS_RECEIVE" android:protectionLevel="signature"/&gt; &lt;uses-permission android:name="${manifestApplicationId}.permission.MAPS_RECEIVE"/&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/&gt; &lt;!-- For QR Code --&gt; &lt;uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/&gt; &lt;uses-permission android:name="android.permission.CAMERA"/&gt; &lt;uses-feature android:name="android.hardware.Camera"/&gt; &lt;uses-permission android:name="android.permission.GET_TASKS"/&gt; &lt;!-- Google Cloud Messaging --&gt; &lt;uses-permission android:name="${manifestApplicationId}.permission.C2D_MESSAGE" android:protectionLevel="signature"/&gt; &lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/&gt; &lt;uses-feature android:glEsVersion="0x00020000" android:required="true"/&gt; &lt;application android:name="com.mcruiseon.buseeta.InitializingApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:largeHeap="true" android:supportsRtl="true" android:theme="@style/AppTheme.NoActionBar"&gt; &lt;meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/&gt; &lt;meta-data android:name="com.google.android.geo.API_KEY" android:value="${mapsKey}"/&gt; &lt;activity -- MY ACTIVITIES -- &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre>
<p>Your app is attempting to connect to the MediaNotificationService somewhere, which relies on the Google Cast SDK. You need to create a class that extends OptionsProvider. Then, you need to register the class you created in your Manifest, like this:</p> <pre><code>&lt;application&gt; ... &lt;meta-data android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME" android:value="com.example.myapp.CastOptionsProvider" /&gt; &lt;/application&gt; </code></pre> <p>Information on this can be found here: <a href="https://developers.google.com/cast/docs/android_sender_integrate#initialize_the_cast_context" rel="nofollow">https://developers.google.com/cast/docs/android_sender_integrate#initialize_the_cast_context</a></p>
Monitor.Wait and Task.Delay on main thread <p>I want to do work on the main UI thread(dispatcher), populating data but paginatedly so that the dispatcher is not held long enough for UI to hang. I also want the work requests to be executed in order.</p> <p>My solution was to use a FIFO guaranteed locking mechanism that waits on a bool, then leaves the lock and continues on to do work and then run Task.Delay as appropriate before setting the bool back at the end.</p> <p>However, what I find is that when the logic runs Task.Delay, another requester in the queue correctly sees that the bool is set, and calls Monitor.Wait but the dispatcher doesn't resume from the other execution at Task.Delay nor does any other UI work get done. It appears effectively deadlocked.</p> <p>Is there a way to .Wait such that the thread itself is still available to do other work? Am I going about this all wrong?</p> <p>Here is a very simplified code snippet:</p> <pre><code>public class QueuedBufferLock { #region data private object innerLock; private volatile int ticket_EndOfQueue = 0; private volatile int ticket_NextToEnter = 1; #endregion #region constructor public QueuedBufferLock() { this.innerLock = new Object(); } #endregion #region public methods public void Enter() { int myTicket = Interlocked.Increment(ref this.ticket_EndOfQueue); Monitor.Enter(this.innerLock); while (true) { if (myTicket == this.ticket_NextToEnter) { return; } else { Monitor.Wait(this.innerLock); } } } public void Wait() { Monitor.Wait(this.innerLock); } public void Exit() { Interlocked.Increment(ref this.ticket_NextToEnter); Monitor.PulseAll(this.innerLock); Monitor.Exit(this.innerLock); } #endregion } </code></pre> <p>And the code running on the dispatcher:</p> <pre><code>this.updateObservableQueuedLock.Enter(); while (this.isUpdatingObservable) { this.updateObservableQueuedLock.Wait(); } this.isUpdatingObservable = true; this.updateObservableQueuedLock.Exit(); // do some work that periodically yields back control to keep things smooth //Thread.Sleep(200); // this successfully doesn't deadlock, but of course it stalls UI await Task.Delay(200); this.isUpdatingObservable = false; </code></pre>
<p>Found a solution!</p> <p><a href="https://github.com/StephenCleary/AsyncEx/wiki" rel="nofollow">AsyncEx</a> provides the AsyncLock and AsyncMonitor classes, which not only solve the problem of Monitor.Wait only handling requesters, it allows for yielding up control of the thread within the asynchronous lock itself! And even better, the default wait queue logic is FIFO guaranteed. This will satisfy all 3 requirements I had for throttling UI updates so that other UI work can be interspersed and keep UI responsive.</p>
Java Action Listener and JButtons <p>I have a gui class which has three different <code>JButtons</code> linked to one <code>ActionListener</code>. </p> <p>In the <code>ActionListener</code> class I want an interaction between these three <code>JButtons</code> in a way that allows the program to "remember" which button was clicked previously. </p> <p>For example: </p> <ol> <li>If button1 is clicked --> remember this, </li> <li>Then when button2 gets clicked next: do a action relative to button1 being clicked. </li> </ol> <p>In other words if button1 click, now inside the if clause check for button2 click. </p> <p>Right now <code>getActionCommand()</code> does not allow me to use nested if statements because it only checks the current button clicked and has no "memory".</p> <pre><code>public void actionPerformed(ActionEvent e){ if (Integer.parseInt(e.getActionCommand()) == 0){ System.out.println("This is Jug 0"); // wont be able to print the following if (Integer.parseInt(e.getActionCommand()) == 1){ System.out.println("This is Jug 1 AFTER jug 0"); //I will never be able to print this } } } </code></pre>
<p>From my understanding of what you are looking todo...</p> <p>So one way of achieving this is to create a instance variable that is a Boolean, so will be set true is the button has been previously clicked and then you could check inside your method if that flag has been set true. Drawback of that approach would be that the flag will always be true once it has been clicked once. You'll have to implement a way to reset this flag. </p> <pre><code>private boolean hasButtonOneBeenPressed = false; //set this to true when the button has been clicked public void actionPerformed(ActionEvent e){ if (Integer.parseInt(e.getActionCommand()) == 0 &amp;&amp; !hasButtonOneBeenPressed){ System.out.println("This is Jug 0"); // wont be able to print the following } else if(Integer.parseInt(e.getActionCommand()) == 1 &amp;&amp; hasButtonOneBeenPressed){ System.out.println("This is Jug 1 AFTER jug 0"); } else { //do something else } } </code></pre>
Prevent database commit on assert failure in php <p>For the sanity testing of my code I am putting asserts at various places in my code.</p> <p>I want it to be the case that whenever an assert is hit, the database transaction should not be completed (i.e. the data should not be committed to database, instead it should be rolled back).</p> <p>I could not find any clean way of achieving this. </p> <p>I am using the code igniter framework.</p> <p>Any idea how to achieve this?</p>
<p>The functionality should not be part of an assert. If it is the case then the functionality will be distorted in production mode when asserts are disabled.</p> <p>We can perform additional database operation on assert failure to record and track more details of the error, but should not abort/interfere with outside transactions. </p> <p>Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.</p> <p>Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.</p> <p><a href="http://php.net/manual/en/function.assert.php" rel="nofollow" title="More Details Here">More details</a></p>
Tool to parse Java thread dump output <p>The Dropwizard metrics library has a servlet to output a thread dump of the server: <a href="https://github.com/dropwizard/metrics/blob/3.2-development/metrics-servlets/src/main/java/com/codahale/metrics/servlets/ThreadDumpServlet.java" rel="nofollow">https://github.com/dropwizard/metrics/blob/3.2-development/metrics-servlets/src/main/java/com/codahale/metrics/servlets/ThreadDumpServlet.java</a></p> <p>Is there any existing tool that parses this output into a more structured format and maybe also generate a nice html output for it?</p>
<p>Give <a href="https://github.com/irockel/tda" rel="nofollow">TDA - Thread Dump Analyzer</a> a try.</p> <p>This will let you easily view locked monitors and waiting threads and provides overview of heap objects at a thread dump (if class histograms were logged).</p> <p>You could also try:</p> <ul> <li><a href="http://mchr3k.github.io/javathreaddumpanalyser/" rel="nofollow">Java Thread Dump Analyser</a></li> <li><a href="http://spotify.github.io/threaddump-analyzer/" rel="nofollow">threaddump-analyzer</a> by Spotify</li> </ul>
Docx4j.toPDF - hf.fo file <p>I'm creating a pdf like this:</p> <pre><code>WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath)); OutputStream os = new java.io.FileOutputStream(outputFilePath); Docx4J.toPDF(wordMLPackage, os); </code></pre> <p>It works fine. After the pdf created, a hf.fo file appears in the doot directory. Why? How can I change the path of this file?</p>
<pre><code>if (log.isDebugEnabled()) { foSettings.setFoDumpFile(new java.io.File(System.getProperty("user.dir") + "/hf.fo")); } </code></pre> <p>Turn off DEBUG level logging for org.docx4j.convert.out.fo.FOPAreaTreeHelper</p>
Compiling againts especific version of armhf g++ <p>I'm doing a crossbuild of a QT app from a Debian (Stretch) PC to a Debian (Jessie) BeagleBone Black, and when I executed this, I got the message </p> <pre><code>/home/bbuser/totemguard/totemguard: /usr/lib/arm-linux-gnueabihf/libstdc++.so.6: version `GLIBCXX_3.4.22' not found (required by /home/bbuser/totemguard/totemguard) </code></pre> <p>I saw that the armhf g++ version was 6.1 so I install the 4.9.2-10 (the same that I had on the BeagleBone Black) and recompiled my code, with similar result (different GLIBXX version):</p> <pre><code>/home/bbuser/totemguard/totemguard: /usr/lib/arm-linux-gnueabihf/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by /home/bbuser/totemguard/totemguard) </code></pre> <p>Reading the <a href="https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html" rel="nofollow">ABI Policy and Guidelines</a>, the G++ version for GLIBCXX_3.4.21 is 5.1.0:</p> <blockquote> <p>GCC 4.9.0: GLIBCXX_3.4.20, CXXABI_1.3.8 </p> <p>GCC 5.1.0: GLIBCXX_3.4.21, CXXABI_1.3.9</p> <p>GCC 6.1.0: GLIBCXX_3.4.22, CXXABI_1.3.10</p> </blockquote> <p>But I never had the 5.1 version installed on my host PC or BeagleBone Black board.</p> <p>Listing the /usr/lib/arm-linux-gnueabihf/ directory we can see that there are only the GCC 4.9.0 and GCC 6.1.0 libstdc++ version:</p> <pre><code>lrwxrwxrwx 1 root root 19 ago 3 15:53 libstdc++.so.6 -&gt; libstdc++.so.6.0.22 -rw-r--r-- 1 root root 658064 dic 27 2014 libstdc++.so.6.0.20 -rw-r--r-- 1 root root 1019632 ago 3 15:53 libstdc++.so.6.0.22 </code></pre> <p>This problem begin after a distro-upgrade from jessie to stretch, and I can't upgrade the beaglebone black gcc version.</p> <p>What can I do?</p> <p>EDIT 1: On a test board (BeagleBone Black) I added the stretch repository and did this:</p> <pre><code>bbuser@beaglebone:~/totemguard$ sudo apt-cache policy libstdc++6 libstdc++6: Installed: 4.9.2-10 Candidate: 6.1.1-11 Version table: 6.1.1-11 0 500 http://ftp.us.debian.org/debian/ stretch/main armhf Packages *** 4.9.2-10 0 500 http://ftp.us.debian.org/debian/ jessie/main armhf Packages 100 /var/lib/dpkg/status bbuser@beaglebone:~/totemguard$ sudo apt-get install libstdc++6 Reading package lists... Done Building dependency tree Reading state information... Done The following extra packages will be installed: gcc-6-base The following NEW packages will be installed: gcc-6-base The following packages will be upgraded: libstdc++6 1 upgraded, 1 newly installed, 0 to remove and 726 not upgraded. Need to get 517 kB of archives. ... </code></pre> <p>And the application ran fine (not 100% tested, but give no errors). Still this is a test board and I cant do the same on a production board.</p>
<p>solution 1) use -static (full libraries) or compile-in only libstdc++ as static to the binary</p> <p>solution 2) distribute the appropriate libstdc++ version with the binary (possibly using LD_PRELOAD)</p> <p>solution 3) use exactly the same g++ libstdc++ version for crosscompiling (at least matching)</p> <p>usually better is to use solution 1) - you will have no problems across distros upgrade</p>
Compare two strings and output result where both are equal <p>I have two strings, and I want to output one string where both give the same values. e.g.</p> <pre><code>var string1 = "ab?def#hij@lm"; var string2 = "abcd!f#hijkl]"; //expected output would be "abcdef#hijklm" </code></pre> <p>I have thought a way to do this would be to assign each character to an array, then compare each character individually but that seems inefficient, as I'm going to pass this through strings with tens of thousands of characters.</p> <p>Any help is appreciated, doesn't have to be code, just to guide me in the general direction. </p>
<p>You could use <code>replace</code> with its callback argument:</p> <pre><code>string1.replace(/[^a-z]/ig, (_, i) =&gt; string2[i]) </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var string1 = "ab?def#hij@lm"; var string2 = "abcd!f#hijkl]"; var res = string1.replace(/[^a-z]/ig, (_, i) =&gt; string2[i]); console.log(res);</code></pre> </div> </div> </p> <p>This will favour letters, but if both strings have different letters at the same position, the character in <code>string1</code> will get precedence. On the other hand, if both have a non-letter, the one from <code>string2</code> will be taken.</p>
How to use `const`ness in this example? <p>I have some code which implements graph algorithms; in particular, there are these snippets, which cause problems:</p> <pre><code>class Path{ private: const Graph* graph; public: Path(Graph* graph_) : graph(graph_) { ... } </code></pre> <p>(which is supposed to create <code>Path</code> object with a constant pointer to a graph)</p> <pre><code>class GradientDescent{ private: const Graph graph; public: Path currentPath; GradientDescent(const Graph&amp; graph_) : graph(graph_), currentPath(Path(&amp;graph_)) {} </code></pre> <p>(which is supposed to create a <code>GradientDescent</code> object that has a const <code>Graph</code> and a non-const <code>Path</code>)</p> <p>The problem is, as I am just trying to figure out how to use <code>const</code>s, I get this error:</p> <pre><code>error: no matching constructor for initialization of 'Path' GradientDescent(const Graph&amp; graph_) : graph(graph_), currentPath(Path(&amp;graph_)) {} longest_path.cpp:103:9: note: candidate constructor not viable: 1st argument ('const Graph *') would lose const qualifier Path(Graph* graph_) : graph(graph_) { </code></pre>
<p>The problem is that your <code>Path</code>'s constructor expects a pointer to non-<code>const</code> <code>Graph</code>.</p> <p>To get rid of this problem simply change your constructor declaration:</p> <pre><code>Path(const Graph* graph_) : graph(graph_) { ... } </code></pre>
Ceph pool deleted but files remain in list <p>I filled up my OSDs through Rados-gw, and the only thing I could do to get Ceph working again was delete the pool that was taking up all the room, and recreate it. Nevertheless, when I list the contents of all pools (using <code>boto</code>), it shows all the files that were there (the disk space is freed, so those files no longer exist in reality.)</p> <p>What's causing this inconsistency?</p>
<p>If you only deleted the buckets pool, typically <strong>.rgw.buckets</strong>, then that would explain why you still have the list of all the objects.</p> <p>The index pool takes care of the list of objects. You would also need to delete the <strong>.rgw.buckets.index</strong> pool as well. Make sure you stop your gateways before doing this as well.</p> <p>When you start the gateway back up and create a new bucket then the index pool will be recreated (if the rgw auth has wrx permission to the monitor).</p>
Generalizing map-values in Racket <p>Suppose I have the following function:</p> <pre><code>(define foo (lambda (n) (values n (* 2 n)))) </code></pre> <p>I want to call map <code>foo</code> over the list <code>'(1 2 3 4)</code>. Hence, I create a <code>map-values</code> function:</p> <pre><code>(define map-values (lambda (f xs) (match xs ['() (values '() '())] [(cons x xs) (let-values ([(a b) (f x)] [(as bs) (map-values f xs)]) (values (cons a as) (cons b bs)))] ))) </code></pre> <p>Now, I can do the following:</p> <pre><code>(map-values foo '(1 2 3 4)) =&gt; (values '(1 2 3 4) '(2 4 6 8)) </code></pre> <p>However, what if <code>foo</code> returns three values, or four, ... etc.? I'll need to create a new <code>map-values</code> function for each case. Is there a way to generalize <code>map-values</code> so that is can work with any <code>foo</code> that returns multiple values?</p>
<p>This does what you want:</p> <pre class="lang-scm prettyprint-override"><code>(define (map-values proc lst) (define (wrap e) (call-with-values (lambda () (proc e)) list)) (apply values (apply map list (map wrap lst)))) (define (foo n) (values n (* 2 n) (/ 1 n))) (map-values foo '(1 2 3 4)) ; ==&gt; (1 2 3 4) ; ==&gt; (2 4 6 8) ; ==&gt; (1 1/2 1/3 1/4) </code></pre> <p>This is compatible with the standard schemes as well. </p>
Grails with external log4j with name "${appname}.log", it not work <p>1.Grails version 2.5.1</p> <p>i used Grails external log4j like this in env:</p> <pre><code>grails.config.locations = ["file:${basedir}/grails-app/config/log4j.groovy"] </code></pre> <p>and log4j.groovy like this</p> <pre><code>log4j = { appenders { appender new org.apache.log4j.DailyRollingFileAppender(name:"dailyAppender", layout:pattern(conversionPattern: '%d{yyyy-MM-dd HH:mm:ss,SSS} %l %c{3} %m%n'),fileName:"D:\\error-logs\\b2-error.log",datePattern:"'.'yyyy-MM-dd") } console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n') error 'org.codehaus.groovy.grails.web.servlet', 'org.codehaus.groovy.grails.web.pages', 'org.codehaus.groovy.grails.web.sitemesh', 'org.codehaus.groovy.grails.web.mapping.filter', 'org.codehaus.groovy.grails.web.mapping', 'org.codehaus.groovy.grails.commons', 'org.codehaus.groovy.grails.plugins', 'org.codehaus.groovy.grails.orm.hibernate', 'org.springframework', 'org.hibernate', 'net.sf.ehcache.hibernate' debug "grails.plugin.mail", "gsuk.sms", 'grails.app.jobs', "gsuk.service" } </code></pre> <p>well,it error when the “=” in log4j.groovy</p> <p>i don`t know why and how to make it work </p> <p>by the way ,if i use it in config.groovy ,everything is ok ...</p>
<p>I have something similar in my environment and it's working just fine. The difference may be that I have a log4j section in both my internal and external Config.groovy files. In my <code>\grails-app\conf\Config.groovy</code> file I have:</p> <pre><code>grails.config.locations = ["file:path\to\external-config.groovy"] ... log4j.main = {...} </code></pre> <p>In my external-config.groovy I have:</p> <pre><code>log4j.external = {...} </code></pre> <p>This allows me to have both an base log4j definition used in my application at all times and then an external one I can append to the internal one. You just have to name them something differently, doesn't have to be <code>.main</code> or <code>.external</code>, it could be <code>.foo</code> and <code>.bar</code>.</p>
Reading protobuf messages via winpcap API <p>I'm using winpcap to capture network traffic, and I know for a fact that this traffic mainly consists of serialized Protocol Buffer exchanges. How can I detect those messages in the traffic if I know all the types of message that a system is likely to transmit?</p>
<p>This will be a bit difficult, because protocol buffers are not self-describing and when you read through a raw stream of bytes there is no easy way to determine when one message ends and another begins. However, with a bit of effort you may be able to recover some of the data if you have a good understanding of the wire format.</p> <p>The protocol buffer <a href="https://developers.google.com/protocol-buffers/docs/encoding" rel="nofollow">wire format</a> essentially consists of a series of key-value pairs. Each key represents a field number and wire type (together called a tag), and the value is the actual data associated with that field number. If you know the messages you're looking for, I would start by searching for the tags you expect to see based on the types and fields numbers in your message definitions. You will have to read the documentation at the link above to figure out how to calculate the tag and format it as a varint, and then search for those raw varint bytes. Once you have found what appears to be a tag, you will have to try to parse the message from there, making an educated guess about where the message ends.</p>
recursively iterate nested python dictionary <p>I have nested python dictionary like this.</p> <pre><code>d = {} d[a] = b d[c] = {1:2, 2:3} </code></pre> <p>I am trying to recursively convert the nested dictionary into an xml format since there can be more nested dictionary inside such as <code>d[e] = {1:{2:3}, 3:4}</code>. My desired XML format is like this</p> <pre><code>&lt;root&gt; &lt;a&gt;b&lt;/a&gt; &lt;c&gt; &lt;1&gt;2&lt;/1&gt; &lt;2&gt;3&lt;/3&gt; &lt;/c&gt; &lt;/root&gt; </code></pre> <p>I have so far this python code to handle nested xml using lxml library. But it doesn't give me the desired output. </p> <pre><code>def encode(node, Dict): if len(Dict) == 0: return node for kee, val in Dict.items(): subNode = etree.SubElement(node, kee) del msgDict[kee] if not isinstance(val, dict): subNode.text = str(val) else: return encode(subNode, val) </code></pre> <p>Any help is appreciated. Thank you. </p>
<p>The way you recall encode does not look correct. Maybe this helps. For simplicity I just append stuff to a list (called <code>l</code>). Instead, you should do your <code>etree.SubElement(...)</code>.</p> <pre><code>def encode(D, l=[]): for k, v in D.items(): if isinstance(v, dict): l2 = [k] encode(v, l2) l.append(l2) else: l.append([k, v]) </code></pre>
expected unqualified-id before '.' token arduino library <p>I am getting this error:</p> <blockquote> <p>In function 'void loop()': headers_stepper_test:12: error: expected unqualified-id before '.' token expected unqualified-id before '.' token</p> </blockquote> <p>in this code:</p> <pre><code>#include "StepperMotor.h" void setup() { // put your setup code here, to run once: StepperMotor(8,9); } void loop() { // put your main code here, to run repeatedly: void StepperMotor.moveDegrees(-180); delay(1000); } </code></pre> <p>The cpp library file:</p> <pre><code>#include "Arduino.h" StepperMotor::StepperMotor(int pin1, int pin2) { dirPin=pin1; pinMode(dirPin,OUTPUT); stepperPin=pin2; pinMode(stepperPin,OUTPUT); } void StepperMotor::stepDegrees(bool dir, int steps); { digitalWrite(dirPin,dir); delay(50); for(int i=0;i&lt;steps;i++){ digitalWrite(stepperPin, HIGH); delayMicroseconds(800); digitalWrite(stepperPin, LOW); delayMicroseconds(800); } void StepperMotor::moveDegrees(int degreeNumber); { if (degrees &gt; 0){ userAbs = (degreeNumber); stepNumber = (userAbs * 200/360); step(true,stepNumber); } if (degrees &lt; 0){ userAbs = (-1*degreesNumber); stepNumber = (userAbs * 200/360); step(false,stepNumber); } } </code></pre> <p>the .h header file:</p> <pre><code>#ifndef StepperMotor_h #define StepperMotor_h #include "Arduino.h" class StepperMotor { public: StepperMotor(int pin1, int pin2); void moveDegrees(int degreeNumber); private: void stepDegrees(bool dir, int steps); int dirPin; int stepPin; float userAbs; float stepNumber; }; #endif </code></pre> <p>When I am trying to implement my own library files. I am not sure if I need the "void" in this case but the same error comes up either way. What is causing this?</p>
<p>Lets recap your code:</p> <pre><code>void loop() { // put your main code here, to run repeatedly: void StepperMotor.moveDegrees(-180); delay(1000); } </code></pre> <p>First thing first: Don't put <code>void</code> in the call to <code>moveDegress()</code> there.</p> <p>Second: </p> <p>The method <code>moveDegrees</code> is not static, therefore, you need an instance of the class <code>StepperMotor</code> in order to call it:</p> <pre><code>// note: you can initialize the variable here // but I'll do it in setup StepperMotor stepperMotorInstance; // your variable void setup() { stepperMotorInstance = StepperMotor(8,9); // option 2: initialize variable in setup } void loop() { // put your main code here, to run repeatedly: stepperMotorInstance.moveDegrees(-180); delay(1000); } </code></pre> <p>Hope it helps</p>
C#: Can't seem to wrap my head around a compile error <p>I'm facing a compilation issue in "PromoteEmployee" within "public static void PromoteEmployee(List employeeList, IsPromotable IsEligibleToPromote)".</p> <p>Would appreciate if someone could give me a hint on how I should go about this.</p> <p>EDIT:</p> <p>The error is: "Inconsistent accessibility: parameter type 'Program.IsPromotable' is less accessible than method 'Program.Employee.PromoteEmployee(List, Program.IsPromotable)'</p> <pre><code>class Program { static void Main(string[] args) { List&lt;Employee&gt; empList = new List&lt;Employee&gt;(); empList.Add(new Employee() { ID = 101, Name = "Test1", Salary = 5000, Experience = 5 }); empList.Add(new Employee() { ID = 101, Name = "Test2", Salary = 2000, Experience = 1 }); empList.Add(new Employee() { ID = 101, Name = "Test3", Salary = 4000, Experience = 4 }); IsPromotable isPromotable = new IsPromotable(Promote); Employee.PromoteEmployee(empList, isPromotable); } public static bool Promote(Employee emp) { if (emp.Experience &gt;= 5) { return true; } else { return false; } } delegate bool IsPromotable(Employee empl); public class Employee { public int ID { get; set; } public string Name { get; set; } public int Salary { get; set; } public int Experience { get; set; } public static void PromoteEmployee(List&lt;Employee&gt; employeeList, IsPromotable IsEligibleToPromote) { foreach (Employee employee in employeeList) { if (IsEligibleToPromote(employee)) { Console.WriteLine(employee.Name + " promoted"); } } } } } </code></pre>
<p>The error I get compiling your program is:</p> <pre><code>(67:28) Inconsistent accessibility: parameter type 'Program.IsPromotable' is less accessible than method 'Program.Employee.PromoteEmployee(System.Collections.Generic.List&lt;Program.Employee&gt;, Program.IsPromotable)' </code></pre> <p>This error occurs because <code>PromoteEmployee</code> is <code>public</code>, but <code>IsPromotable</code> is private.</p> <blockquote> <p>If somebody from outside class Program wants to call <code>PromoteEmployee</code>, he can't do that, because he can't create an instance of <code>Program.IsPromotable</code>, because it's private to <code>Program</code>.</p> </blockquote> <p>-- <a href="http://stackoverflow.com/users/424129/ed-plunkett">http://stackoverflow.com/users/424129/ed-plunkett</a></p> <p>To fix it make <code>IsPromotable</code> <code>internal</code> or <code>public</code> so that others outside <code>Program</code> can create it.</p> <p>Alternatively you can make <code>PromoteEmployee</code> private.</p>
set weird sorting behavior (python) <p>I found out something weird and I was wondering if it was a known thing. This is my code: -Python 3.5.2-</p> <pre><code>numbers = [9,4,6,7,1] setlist = set() for item in numbers: setlist.add(item) print(setlist) numbers = [9,4,6,7,1,5] setlist = set() for item in numbers: setlist.add(item) print(setlist) </code></pre> <p>And this is my output (it never changes):</p> <p><code>{9, 4, 1, 6, 7} {1, 4, 5, 6, 7, 9} Process finished with exit code 0</code></p> <p>If you run it you will see that the first output isn't in order but the second one is. It seems to only gets in order for some reason if the set has more then 5 objects. Wiki.python.com also says that sets dont get sorted at al. This all is really weird to me so i hoped i could get some more explanation.</p>
<p>sets are unordered collections by design. If you want a collection of items that retain order, consider using a list, instead. Lists have <code>insert</code> and <code>append</code> methods available to you.</p> <pre><code>my_list = [] for item in some_iterable: my_list.append(item) </code></pre>
How to create Android Games <p><strong>How are professional Android Games made?</strong> </p> <p>I'm interested in starting a little project for a game on android.</p> <p>I have already developed an android app so I have got some experience with Android Studio, Java, and Android in general.</p> <p>I have looked online but I was not able to find a good enough answer to my questions:</p> <ul> <li><p>How do I create an Android game (or game in general)?</p></li> <li><p>Which tools are involved (feel free to suggest me some)?</p></li> <li><p>Which programming language(s) are involved?</p></li> <li><p>What Is the difference between a 2D and 3D game (excluding the mere visual one).</p></li> </ul> <p>I know it probably isn't a very specific question. But I was not able to find an answer elsewhere. </p>
<p>I would consider making regular Java games to practice before diving into Android games. Look <a href="http://zetcode.com/tutorials/javagamestutorial/" rel="nofollow">here</a> for a good start. There are plenty of others if you just search in google.</p> <p>This forum is not meant for getting answers and tutorials to questions like that. This is for specific code problems. Hopefully this is enough to get you started.</p>
Does anyone know details about PERM-AR-DO? <p>According to <a href="https://source.android.com/devices/tech/config/uicc.html" rel="nofollow">https://source.android.com/devices/tech/config/uicc.html</a>,</p> <blockquote> <p>AR-DO (E3) is extended to include PERM-AR-DO (DB), which is an 8-byte bit mask representing 64 separate permissions.</p> </blockquote> <p>Does anyone know the specification for PERM-AR-DO?</p> <p>GlobalPlatform Secure Element Access Control specifications version 1.0 and 1.1 do not contain it. For the access rule data object, AR-DO (0xE3), only tags 0xD0 and 0xD1 are defined.</p>
<p>The data object PERM-AR-DO (tag 0xDB), just as the other data objects defined on the <a href="https://source.android.com/devices/tech/config/uicc.html" rel="nofollow">UICC Carrier Privileges page</a> (DeviceAppID-REF-DO with SHA-256 and PKG-REF-DO), is a Google-specific extension to the GP Secure Element Access Control specification. Consequently, you won't find anything about these DOs in the GP specifications. </p> <p>The page that you linked actually provides an answer to your question in the FAQ section:</p> <blockquote> <p><strong>We assume we can grant access to all carrier-based permissions or have a finer-grained control. What will define the mapping between the bit mask and the actual permissions then? One permission per class? One permission per method specifically? Will 64 separate permissions be enough in the long run?</strong></p> <p><em>A: This is reserved for the future, and we welcome suggestions.</em></p> </blockquote> <p>So the answer is that the interpretation of the PERM-AR-DO is not yet defined. This is also reflected in the Android source code that parses the access rules (in <a href="https://android.googlesource.com/platform/frameworks/opt/telephony/+/android-7.0.0_r14/src/java/com/android/internal/telephony/uicc/UiccCarrierPrivilegeRules.java#591" rel="nofollow">UiccCarrierPrivilegeRules.java on lines 591-601</a>):</p> <pre><code> } else if (rule.startsWith(TAG_AR_DO)) { TLV arDo = new TLV(TAG_AR_DO); //E3 rule = arDo.parse(rule, false); // Skip unrelated rules. if (!arDo.value.startsWith(TAG_PERM_AR_DO)) { return null; } TLV <b>permDo</b> = new TLV(TAG_PERM_AR_DO); //DB <b>permDo</b>.parse(arDo.value, true); } else { </code></pre> <p>This code parses the AR-DO and extracts the PERM-AR-DO but then simply drops the extracted value (<code>permDo</code>).</p> <p>Similarly, the resulting <code>AccessRule</code> object contains a value <code>accessType</code> which is always set to 0:</p> <pre><code> long accessType = <b>0</b>; <i>[...]</i> AccessRule accessRule = new AccessRule(IccUtils.hexStringToBytes(certificateHash), packageName, <b>accessType</b>); </code></pre> <p>Moreover, inside the class <code>AccessRule</code> there is a comment besides the field <code>accessType</code> that indicates that the field is "<em>not currently used</em>":</p> <pre><code> public long accessType; // <b>This bit is not currently used, but reserved for future use.</b> </code></pre>
Search multi-dimesional array and return specific value <p>Hard to phrase my question, but here goes. I've got a string like so: "13,4,3|65,1,1|27,3,2". The first value of each sub group (ex. <strong>13</strong>,4,3) is an id from a row in a database table, and the other numbers are values I use to do other things. </p> <p>Thanks to "Always Sunny" on here, I'm able to convert it to a multi-dimensional array using this code:</p> <pre><code>$data = '13,4,3|65,1,1|27,3,2'; $return_2d_array = array_map ( function ($_) {return explode (',', $_);}, explode ('|', $data) ); </code></pre> <p>I'm able to return any value using </p> <pre><code>echo $return_2d_array[1][0]; </code></pre> <p>But what I need to be able to do now is search all the first values of the array and find a specific one and return one of the other value in i'ts group. For example, I need to find "27" as a first value, then output it's 2nd value in a variable (3).</p>
<p>You can loop through the dataset building an array that you can use to search:</p> <pre><code>$data = '13,4,3|65,1,1|27,3,2'; $data_explode = explode("|",$data); // make array with comma values foreach($data_explode as $data_set){ $data_set_explode = explode(",",$data_set); // make an array for the comma values $new_key = $data_set_explode[0]; // assign the key unset($data_set_explode[0]); // now unset the key so it's not a value.. $remaining_vals = array_values($data_set_explode); // use array_values to reset the keys $my_data[$new_key] = $remaining_vals; // the array! } if(isset($my_data[13])){ // if the array key exists echo $my_data[13][0]; // echo $my_data[13][1]; // woohoo! } </code></pre> <p>Here it is in action: <a href="http://sandbox.onlinephpfunctions.com/code/404ba5adfd63c39daae094f0b92e32ea0efbe85d" rel="nofollow">http://sandbox.onlinephpfunctions.com/code/404ba5adfd63c39daae094f0b92e32ea0efbe85d</a></p>
Unable to use sudo commands within Docker, "bash: sudo: command not found" is displayed <p>I have installed TensorFlow using the following command "docker run -it b.gcr.io/tensorflow/tensorflow:latest-devel" and I need to set up TensorFlow Serving on a windows machine. I followed the instructions given at "<a href="https://github.com/tensorflow/serving/blob/master/tensorflow_serving/g3doc/setup.md" rel="nofollow">https://github.com/tensorflow/serving/blob/master/tensorflow_serving/g3doc/setup.md</a>" and while running the below-mentioned sudo command while installing TensorFlow Serving dependencies:</p> <pre><code>sudo apt-get update &amp;&amp; sudo apt-get install -y \ build-essential \ curl \ git \ libfreetype6-dev \ libpng12-dev \ libzmq3-dev \ pkg-config \ python-dev \ python-numpy \ python-pip \ software-properties-common \ swig \ zip \ zlib1g-dev </code></pre> <p>The following error is displayed:</p> <pre><code>bash: sudo: command not found </code></pre>
<p>Docker images typically do not have <code>sudo</code>, you are already running as <code>root</code> by default. Try</p> <pre><code>apt-get update &amp;&amp; apt-get install -y \ build-essential \ curl \ git \ libfreetype6-dev \ libpng12-dev \ libzmq3-dev \ pkg-config \ python-dev \ python-numpy \ python-pip \ software-properties-common \ swig \ zip \ zlib1g-d </code></pre> <p>If you wish to not run as root, see the <a href="https://docs.docker.com/engine/reference/builder/#/user" rel="nofollow">Docker documentation on the User command</a>.</p>
Is MySQL Query framed properly? <p>I'm attempting to run the following Query on an AWS ec2 xlarge instance: </p> <pre><code>mysql&gt; CREATE TABLE 3 SELECT * FROM TABLE 2 WHERE ID IN (SELECT ID FROM TABLE1); </code></pre> <p>I attempted using ec2 as I thought perhaps it was my laptop making the query taking long as Table1 has 14000 rows and 6 columns and table 2 has around 1 million rows and 11 columns. However I get: </p> <p>Write failed: Broken pipe</p> <p>When using the aws instance, and DBMS timeout on my laptop. </p> <p>Should the Query be taking > than these timeout triggers? Anyway to word the query better?</p>
<p>Try split logically the query </p> <pre><code>CREATE TABLE3 SELECT * FROM TABLE2 WHERE ID IN (SELECT ID FROM TABLE1 where id between 1 and 10000); </code></pre> <p>and then </p> <pre><code>insert into table3 SELECT * FROM TABLE2 WHERE ID IN (SELECT ID FROM TABLE1 where id between 10001 and 20000); </code></pre>
How to SQL select duplicates by one field and differs by another <p>I have the table <code>person_log</code> with the following fields:</p> <ul> <li><code>id</code></li> <li><code>timestamp</code></li> <li><code>first_name</code></li> <li><code>last_name</code></li> <li><code>action</code></li> </ul> <p>with some example data</p> <pre><code>1;012545878;homer;simpson;eating 2;812345222;homer;simpson;watching tv 3;312322578;marge;simpson;cooking 4;114568568;bart;simpson;skating 5;015345345;bart;simpson;skating </code></pre> <p>Now I need to select all recordsets where <code>first_name</code> and <code>last_name</code> is the same and occurs at least two times, but <code>action</code> differs.</p> <p>Resulting in selecting <code>id</code>s 1 and 2.</p> <p>How can I do that? TIA?</p>
<p>Use a derived table to get the persons having atleast 2 distinct actions and join it to the original table to get the other columns in the result.</p> <pre><code>select p.* from person_log p join (select first_name,last_name from person_log group by first_name,last_name having count(*) &gt;=2 and count(distinct action) &gt;= 2) p1 on p1.first_name=p.first_name and p1.last_name=p.last_name </code></pre>
Rails/Devise: XHR returns 401 <p>I have a Rails app that uses Devise for authentication. I authenticate through the usual Rails views, and most of the app is done with the usual Rails ActionView pages. </p> <p>One page of my app includes a React app that requests data via XHR with the isomorphic-fetch library. I've been developing it in Safari, which works fine, but in Chrome or Firefox I get HTTP 401 messages when I try an XHR get. </p> <p>It appears that the difference is that on Safari I am getting a response header of 'Set-Cookie' that sets a session cookie, and in Chrome I'm not.</p> <p>Here's what I've tried: * Adding <code>X-CSRF-Token</code> to my AJAX fetch requests * Setting <code>config.http_authenticatable_on_xhr</code> to true and setting <code>config.navigational_format = [:html, :json]</code></p> <p>It's a new Rails 5 app. I have a similar Rails 4 app where the XHRs work fine. How do I make my XHRs work here?</p>
<p>I got this to work. I checked my previous app, which used jQuery for the AJAX calls. When I replaced <code>fetch</code> with <code>jquery-ujs</code>, it worked! I saw my problem was that it had not been sending the session cookie with the request. I researched how to do this with <code>isomorphic-fetch</code>, and found the <a href="https://github.github.io/fetch/#Headers" rel="nofollow">github/fetch</a> documentation. When I structure my request like this, it works:</p> <pre><code>fetch('/my_resource.json?param=someparam', { 'credentials': 'same-origin' }) </code></pre> <p>Gotta send the cookies.</p>
SQL Server count orders within dates per customer <p>I'm trying to get the following data:</p> <ul> <li>List all customers who have ordered twice or more in the last 12 months</li> <li>List all customers who have ordered just once in last 12 months</li> <li>List any customers who do not fit in the criteria above</li> </ul> <p>I'm using SQL Server 11.0.</p> <p>I have the following tables:</p> <p><strong>dbo.[Order]</strong>:</p> <pre><code>CustomerID OrderID </code></pre> <p><strong>dbo.Customer</strong>:</p> <pre><code>BusinessName Postcode </code></pre> <p><strong>dbo.AccountCallbacks</strong>:</p> <pre><code>UserId NotInterestedReasonID </code></pre> <p>I need a count of all orders from dbo.[Order] where the last record in dbo.AccountCallbacks had the UserID of '6EAE3206-519E-4DE7-B10B-6F2476D7D20F' and a null NotInterestedReasonID between each of the date ranges above and then for everything else.</p> <p>I'm not sure what other information to give, this is what I have come up with currently, but feel I'm going about it in a peculiar fashion!</p> <pre><code>SELECT Customer.CustomerID, BusinessName, Postcode, NumOrders FROM Customer INNER JOIN (SELECT CustomerID, COUNT(OrderID) AS NumOrders FROM dbo.[Order] WHERE UserId = '6EAE3206-519E-4DE7-B10B-6F2476D7D20F' AND NOT (PaymentDate IS NULL) AND OrderDate &lt;= DATEADD(MONTH, -12, GETDATE()) GROUP BY CustomerID) AS payingCustomers ON Customer.CustomerID = payingCustomers.CustomerID INNER JOIN (SELECT CustomerID, MAX(CallbackDate) AS LastCallbackDate FROM dbo.AccountCallBacks WHERE NotInterestedReasonID IS NULL GROUP BY CustomerID) AS otherCustomers ON Customer.CustomerID = otherCustomers.CustomerID ORDER BY NumOrders DESC </code></pre> <p>As you may have guessed, SQL isn't my strongest suit! I really hope I've given the needed info, if not, let me know.</p> <p>Example Data:</p> <p><strong>AccountCallbacks:</strong></p> <pre><code>CallbackID UserID CustomerID Created CallbackDate Enabled CallbackTimeID NotInterestedReasonID 16 695624B5-90E0-45C0-AFCF-07C7A275BE6E 504 2011-02-01 10:40:37.183 2015-10-08 1 3 1 17 695624B5-90E0-45C0-AFCF-07C7A275BE6E 505 2011-02-01 10:40:37.220 2011-11-01 0 3 NULL 18 2B37842F-33AF-4777-9FC7-3D4F648F5D8F 506 2011-02-01 10:40:37.263 2012-08-20 0 1 NULL 19 2B37842F-33AF-4777-9FC7-3D4F648F5D8F 508 2011-02-01 10:40:37.300 2012-07-20 0 1 NULL 20 2B37842F-33AF-4777-9FC7-3D4F648F5D8F 509 2011-02-01 10:40:37.340 2014-02-10 0 1 NULL </code></pre> <p><strong>Order:</strong></p> <pre><code>OrderID CustomerID UserID OrderDate PaymentTypeID PaymentStatusID PaymentDate TransactionRef PurchaseOrderNumber 44523 4199 695624B5-90E0-45C0-AFCF-07C7A275BE6E 2016-10-11 16:54:01.350 1 2 2016-10-11 16:57:13.000 011194 44522 3748 695624B5-90E0-45C0-AFCF-07C7A275BE6E 2016-10-11 16:13:00.290 1 2 2016-10-11 16:13:57.000 011486 44521 1812 2B37842F-33AF-4777-9FC7-3D4F648F5D8F 2016-10-11 16:08:16.923 1 2 2016-10-11 16:09:33.000 082663 </code></pre> <p><strong>Customer:</strong></p> <pre><code>CustomerID BusinessName Postcode 502 Company 1 BP3 6UK 503 Company Name BP3 6BK 504 Company ABC SS13 1LS </code></pre> <p>Expected output : (this would be a different set of data depending on which 'report' it is as stated above)</p> <pre><code>CustomerID BusinessName Postcode 799 Company2 LTD YO17 6YA 5586 Company3 Plc EH3 9DJ 5638 MR A ENG LTD EP4 1PL 6707 DUSTO Ltd NE22 7LB </code></pre>
<p>Try something like this:</p> <p><strong>List all customers who have ordered twice or more in the last 12 months</strong></p> <pre><code>SELECT COUNT(o.OrderID), o.CustomerID FROM Order o WHERE o.UserID = '6EAE3206-519E-4DE7-B10B-6F2476D7D20F' AND o.OrderDate &gt; DATEADD(MONTH, -12, GETDATE()) GROUP BY o.CustomerID HAVING COUNT(o.OrderID) &gt; 2 </code></pre> <p><strong>List all customers who have ordered just once in last 12 months</strong></p> <pre><code>SELECT COUNT(o.OrderID), o.CustomerID FROM Order o WHERE o.UserID = '6EAE3206-519E-4DE7-B10B-6F2476D7D20F' AND o.OrderDate &gt; DATEADD(MONTH, -12, GETDATE()) GROUP BY o.CustomerID HAVING COUNT(o.OrderID) = 1 </code></pre> <p>I'm a little confused on the problem. You want all of the customers who "don't fit in the criteria." What criteria?</p>
PHP output Excel-The file format and extension don't match <p>I have made a script that outputs a XLS file with data brought from my database. Problem is that when you view the file on OSX and Linux it looks as it is supposed to. </p> <p><strong>Behaviour on Windows</strong></p> <p>On Windows excel shows the following message.</p> <blockquote> <p>The file format and extension 'nameofthefile.xls' don't match. The file could be corrupted or unsafe. Unless you trust.....</p> </blockquote> <p>Have you ever faced this problem?</p> <pre class="lang-php prettyprint-override"><code>$sql = "MY SQL QUERY"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) &gt; 0) { $output .= '&lt;table class="table" border="1" &lt;tr&gt; &lt;th&gt;MY Table heads&lt;/th&gt; &lt;th&gt;MY Table heads&lt;/th&gt; &lt;/tr&gt;'; $count = 1; while ($row = mysqli_fetch_array($result)) { $data = strtotime($row['reg_date']); $format_date = date("d.M.Y", $data); $output .= ' &lt;tr&gt; &lt;td&gt;' . $count++ . '&lt;/td&gt; &lt;td&gt;' . $row["id"] . '&lt;/td&gt; &lt;td&gt;' . $row["firstname"] . '&lt;/td&gt; &lt;td&gt;' . $row["lastname"] . '&lt;/td&gt; &lt;td&gt;' . $format_date . '&lt;/td&gt; &lt;/tr&gt;'; } $output .= '&lt;/table&gt;'; header("Content-Type: application/xls"); header("Content-Disposition: attachement; filename=download.xls"); echo $output; } } </code></pre>
<p>I've had the same problem using Laravel with <a href="http://www.maatwebsite.nl/laravel-excel/docs" rel="nofollow">http://www.maatwebsite.nl/laravel-excel/docs</a> and i solve the problem by checking if there was a clean code, i had a apostrophe (') character somewhere in my code and when i detected it i just erased that character and the file was exported with success. Good luck!</p>
Can't see the extension I've installed in GeneXus 15 <p>I've installed the SmartDevicePlus (from DVelop) extension in my Genexus15 folder. The setup ends telling me it completed successfully. Yet, I can't find the SD+ menu in Tools. </p> <p>I've also tried to install the WorkWithPlus (from DVelop) extension from the Add-in manager but here is the message I got:<br> 1)File DVelopWorkWithPlus_9.1.15_Ev2_U4_higher_Setup.rar installed correctly.<br> 2)Failed to install file DVelopWorkWithPlus_9.1.15_Ev2_U4_higher_Setup.rar. </p>
<p>You should install the proper setups for Gx 15 for both WorkWithPlus and SmartDevicesPlus, you can download them from www.dvelop.com.uy/downloads.</p> <p>By using this setups you should use the products on Gx15. If you have other problems please write us to support@workwithplus.com or by Skype (supportwwp) so we can connect by Team Viewer and help you with the first steps.</p> <p>We can also schedule an online demo of the products so you can take further advantage of your tests with them!</p> <p>Sofía</p>
Assembly "movdqa" access violation <p>I am currently trying to write a function in assembly and i want to move 128 bits of a string located at the memory address stored in <code>rdx</code> into the <code>xmm1</code> register.</p> <p>If i use <code>movdqa xmm1, [rdx]</code>, i get a access violation exception while reading at position <code>0xFFFFFFFFFFFFFFFF</code>.</p> <p>If i try to use <code>movdqu xmm1, [rdx]</code> instead, i dont get the exception. The problem is if i use movdqu, the order of the bits is inverted.</p> <p>So i do not know why i get an exception when using <code>movdqa</code> but not when i am using <code>movdqu</code></p>
<p>Most of this has been said in the comments already, but let me summarise. There are three problems raised by your code/question:</p> <p>1) <code>MOVDQA</code> requires the addresses it deals with (<code>[rdx]</code> in your case) to be aligned to a 16-byte boundary and will trigger an access violation otherwise. This is what you are seeing. Alignment to a 16-byte (DQWORD) boundary means that, using your example, you should read from e.g. <code>0xFFFFFFFFFFFFFFF0</code> rather than <code>0xFFFFFFFFFFFFFFFF</code>, because the latter number is not divisible by 16.</p> <p>2) The address you use, <code>0xFFFFFFFFFFFFFFFF</code>, is almost certainly invalid.</p> <p>3) Provided you use <code>MOVDQA</code> to read from a valid 16-byte-aligned memory location, the results (in <code>xmm1</code> in your case) will be <strong>IDENTICAL</strong> to when you use <code>MOVDQU</code>. The only relevant difference between the two here is that <code>movdqU</code> allows you to read from <strong>U</strong>naligned (hence the U) memory whereas <code>movdqA</code> requires a (16-byte) <strong>A</strong>ligned memory location. (The latter case will often be faster, but I don't think you need to worry about that at this stage.)</p>
Prevent size of canvas chart js to equal window height and width <p>I am <a href="http://www.chartjs.org/docs/#doughnut-pie-chart-introduction" rel="nofollow">using chartjs</a> to display data and the chart (canvas) takes up 100% width and 100% height of the window.</p> <p>I want to reduce this to be <code>600px</code> by <code>600px</code>. To do this I tried using <code>Chart.defaults.global.legend.fullWidth = false;</code> however this didn't work.</p> <p>I have created a <a href="https://jsfiddle.net/ce7rgaz6/" rel="nofollow">jsfiddle her</a>e for your convenience.</p> <p>See code below:</p> <p><strong>HTML</strong></p> <pre><code>&lt;canvas id="myChart" width="400" height="400"&gt;&lt;/canvas&gt; </code></pre> <p><strong>JS</strong></p> <pre><code>var ctx = document.getElementById("myChart"); Chart.defaults.global.defaultFontColor = "#000"; Chart.defaults.global.legend.fullWidth = false; var myChart = new Chart(ctx, { type: 'pie', data: { labels: labels, datasets: [{ label: '# of Followers', data: followers, backgroundColor: [ 'rgba(255, 99, 132, 0.9)', 'rgba(54, 162, 235, 0.9)', 'rgba(255, 206, 86, 0.9)', 'rgba(75, 192, 192, 0.9)', 'rgba(153, 102, 255, 0.9)', 'rgba(255, 159, 64, 0.9)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 5 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); </code></pre>
<p>Add 'responsive: false' to the chart options </p> <pre><code>options: { responsive: false, scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } </code></pre>
reading through a .txt file <p>I'm just trying to get the hang of c++ and I'm having problems reading through the lines of a .txt file. For the project that I am working on, I'm trying to read though a text file that has some placeholder elements, and then I'm trying to create a new output file that will store txt inputed by the user in place of the place holder txt.</p> <p>Here's what the txt file looks like, and How it should look after I run my program:</p> <pre><code>_DATE _NAME _ADDRESS </code></pre> <p>it should look like this after my program runs</p> <pre><code>10/11/2016 John Doe 116 W Cherry St Apt 20 Hanover Park, IL </code></pre> <p>Here's my code:</p> <pre><code>#include &lt;iostream&gt; #include&lt;string&gt; #include &lt;fstream&gt; using namespace std; void get_address(string&amp; date, string&amp; name, string&amp; address1, string&amp; address2, string&amp; state, string&amp; town); ifstream inputFile; ofstream outputFile; int main() { string date, name, address1,address2, state, town, jobTitle; get_address(date, name, address1,address2,state,town); return 0; } void get_address(string&amp; date, string&amp; name, string&amp; address1, string&amp; address2, string&amp; state, string&amp; town) { inputFile.open("toAddress.txt"); outputFile.open("output.txt"); cout &lt;&lt; "Enter the date: "; cin &gt;&gt; date; cout &lt;&lt; "Enter your name"; cin &gt;&gt; name; cout &lt;&lt; "Enter the adress: "; cin &gt;&gt; address1; cout &lt;&lt; "Enter address line 2"; cin &gt;&gt; address2; cout &lt;&lt; "Enter state"; cin &gt;&gt; state; cout &lt;&lt; "Enter city or town"; cin &gt;&gt; town; string line=""; while (getline (inputFile, line)) { if (line.compare("_DATE")) { outputFile &lt;&lt; date&lt;&lt;endl; } else if (line.compare("_NAME")) { outputFile &lt;&lt; name&lt;&lt;endl; } else if (line.compare("_ADDRESS")) { outputFile &lt;&lt; address1 &lt;&lt; endl; if (address2 != "") { outputFile &lt;&lt; address2 &lt;&lt; endl; } outputFile &lt;&lt; town &lt;&lt; ", " &lt;&lt; state; } else outputFile &lt;&lt; endl; } outputFile.close(); inputFile.close(); } </code></pre> <p>The problem resides somewhere in the while loop, or in my if/else statements, because when I comment the if statements and my while loop out, I'm able to write to the output file no problem. But when I try to run the program with them in it, nothing gets written to the output file. Any help would be most appreciated.</p>
<p>You should use:</p> <p>if (line.compare ("_DATE")==0)</p> <p>to test for equality.</p> <p><a href="http://www.cplusplus.com/reference/string/string/compare/" rel="nofollow">http://www.cplusplus.com/reference/string/string/compare/</a></p>
Database server and public website communication <p>So, i'm getting slightly familiar with html, css and frameworks in general and i have a fair understanding of Java. However, i can only see how you can make inbuilt functions and computations with Javascript that you add to your html file. But i don't understand how it works with say a Java program on your computer that the website would fetch data and information from. Can anyone explain that? I couldn't find any good answers on the internet.</p> <p>Say i want to compute the value 2+3 with Java on a server and then fetch that value and display it on the website. How would i do that?</p>
<p>I achieve this functionality by sending an ajax request via javascript to a java servlet on the server here is an example that I use:</p> <p>Say you have a link:</p> <pre><code>&lt;a href="#" onclick = 'shipProduct(1)'&gt;Test&lt;/a&gt; </code></pre> <p>When this link is clicked it will look for the corresponding javscript function, which in my case is:</p> <pre><code> /** * * @param {type} action * @param {type} bundleId * @returns {undefined} */ function shipProduct(bundleId) { $.ajax ({ url: "/FlcErp-war/ShipmentServlet", //this is the name of the serverlet in your project type: "GET", // the type of your request data: _action + "=addToShipped&amp;bundleId=" + bundleId, success: function (content) { if (content.substring(0, 1) == '_') { alert(content); } else { //rebuild shipment tables to show updated //information about the item buildShipmentQueue(); } }, error: function (xhr, status, error) { alert(xhr.responseText); alert(status); alert(error); } }); } </code></pre> <p>What I did was have have an annotated java servlet to serve my request:</p> <p>your doPost and doGet will handle your post and get requests</p> <pre><code>/** * * @author samo */ @WebServlet("/ShipmentServlet") public class ShipmentServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String _addToShipped = "addToShipped"; private static final String _bundleId = "bundleId"; private static final String _shipmentId = "shipmentId"; private static final String _productId = "productId"; private static final String _updateQueue = "updateQueue"; private static final String _unship = "unship"; private static final String _setInSession = "setInSession"; private static final String _externalBundleId = "externalBundleId"; private static final String _plywood = "P"; private static final String _veneer = "V"; private static final String _lumber = "L"; private static final String _bundle = "Bundle"; private static final String _list = "List"; private boolean multipleActions; private String[] actions; /** * Processes requests for both HTTP &lt;code&gt;GET&lt;/code&gt; and &lt;code&gt;POST&lt;/code&gt; * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processBundleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NamingException, CloneNotSupportedException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { this.actions = null; //this is where we will get the actions to process //if there is more than one action the string will contain // a comma as a delimiter String action = request.getParameter("_action"); InitialContext ctx = new InitialContext(); LoadShipmentController lsc = (LoadShipmentController) ctx.lookup("loadShipmentController"); switch (action) { case _addToShipped: shipProduct(request, out); break; case _updateQueue: Shipment shipment = lsc.getCurrent(); String type = shipment.getShipmentType(); String shipmentQueue = ""; switch (type) { case _veneer: shipmentQueue = lsc.getVeneerShipmentQueue(); break; case _plywood: shipmentQueue = lsc.getShipmentQueue(); break; case _lumber: shipmentQueue = lsc.getShipmentQueue(); break; } out.println(shipmentQueue); break; case _unship: unshipProduct(request, out); break; case _setInSession: String bundleId = request.getParameter(_bundleId); lsc.setBundleId(bundleId); break; case _list: out.println(lsc.getBundleAndProductListString()); break; // setSessionVariable(_externalBundleId, bundleId); } } } public void shipProduct(HttpServletRequest request, PrintWriter out) throws NamingException, CloneNotSupportedException { Integer bundleId = Integer.valueOf(request.getParameter(_bundleId)); InitialContext ctx = new InitialContext(); ShipmentController shipmentController = (ShipmentController) ctx.lookup("shipmentController"); LoadShipmentController loadShipmentController = (LoadShipmentController) ctx.lookup("loadShipmentController"); // getting the product from the bundle, because that's all we care about Product product = shipmentController.loadBundle(bundleId).getProduct(); String type = product.getProductType(); //because the way we ships differs depending on the product type I need to //check first mainly for veneer shipments because their bundle count is not //predetermined boolean loaded = false; switch (type) { case _veneer: loaded = loadShipmentController.loadVeneerProduct(product, bundleId); break; case _plywood: loaded = loadShipmentController.loadPlywoodProduct(product, bundleId); break; case _lumber: loaded = loadShipmentController.loadLumberProduct(product, bundleId); break; } if(!loaded) { out.println("_" + loadShipmentController.getErrors()); } } public void unshipProduct(HttpServletRequest request, PrintWriter out) throws NamingException { Integer bundleId = Integer.valueOf(request.getParameter(_bundle)); InitialContext ctx = new InitialContext(); LoadShipmentController loadShipmentController = (LoadShipmentController) ctx.lookup("loadShipmentController"); boolean unship = loadShipmentController.unshipByBundleId(bundleId); if (!unship) { String error = loadShipmentController.getErrors(); out.println("Error:" + error); } } private void setSessionVariable(String name, String value) { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext externalContext = context.getExternalContext(); HttpSession session = (HttpSession) externalContext.getSession(false); session.setAttribute(name, value); } // &lt;editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."&gt; /** * Handles the HTTP &lt;code&gt;GET&lt;/code&gt; method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processBundleRequest(request, response); } catch (NamingException ex) { Logger.getLogger(ShipmentServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (CloneNotSupportedException ex) { Logger.getLogger(ShipmentServlet.class.getName()).log(Level.SEVERE, null, ex); } } /** * Handles the HTTP &lt;code&gt;POST&lt;/code&gt; method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } </code></pre>
SQL Server: Joining three tables while showing null matches <p>I have spent a couple of hours trying to figure out this particular join. I have these three SQL Server tables (assume all the requisite indexes and foreign keys):</p> <pre><code>create table [mykey] (keyname varchar(32) not null); go create table [myinstance] ( instancename varchar(48) not null); go create table [mypermissions] ( keyname varchar(32), instancename varchar(48), permission int not null); go insert into [mykey] (keyname) values ('test_key_1'), ('test_key_2'), ('test_key_3'); GO insert into [myinstance] (instancename) values ('sqlexpress'), ('std2008'), ('ent2012'); GO insert into mypermissions (keyname, instancename, permission) values ('test_key_1', 'sqlexpress', 1), ('test_key_1', 'std2008', 0), ('test_key_2', 'ent2012', 1), ('test_key_2', 'sqlexpress', 0) GO </code></pre> <p>I am trying to create a join that shows all the permissions for keynames while also showing where specific permissions are missing. I would like the output to look like this (order unimportant):</p> <pre><code>keyname instancename permission ---------- ------------ ---------- test_key_1 sqlexpress 1 test_key_1 std2008 0 test_key_1 ent2012 NULL test_key_2 ent2012 1 test_key_2 sqlexpress 0 test_key_2 std2008 NULL test_key_3 sqlexpress NULL test_key_3 std2008 NULL test_key_3 ent2012 NULL </code></pre> <p>but instead it looks like this:</p> <pre><code>keyname instancename permission ---------- ------------ ---------- test_key_1 sqlexpress 1 test_key_1 std2008 0 test_key_2 ent2012 1 test_key_2 sqlexpress 0 test_key_3 NULL NULL </code></pre> <p>I have spent a couple of hours with all sorts of joins with no luck. Maybe what I want to do is impossible. Here is the most recent one I tried:</p> <pre><code>select k.keyname, p.instancename, p.permission from mykey k full join mypermissions p on (k.keyname = p.keyname) full join myinstance i on p.instancename = i.instancename </code></pre> <p>Is what I am trying to do possible?</p>
<p>You need to use <a class='doc-link' href="http://stackoverflow.com/documentation/sql/261/join/8033/cross-join#t=201610112041488869063"><code>CROSS JOIN</code></a> to get all combinations of keyname and instancename before you join the third table. Look at this query</p> <pre><code>SELECT * FROM myinstance mi CROSS JOIN mykey mk </code></pre> <p>This will output</p> <pre><code>instancename keyname ------------ ---------- sqlexpress test_key_1 std2008 test_key_1 ent2012 test_key_1 sqlexpress test_key_2 std2008 test_key_2 ent2012 test_key_2 sqlexpress test_key_3 std2008 test_key_3 ent2012 test_key_3 </code></pre> <p>You can use <a class='doc-link' href="http://stackoverflow.com/documentation/sql/261/join/939/left-outer-join#t=201610112042431719805"><code>LEFT JOIN</code></a> to the third table and extract the columns required as shown in the below query:</p> <pre><code>SELECT mk.keyname, mi.instancename, mp.permission FROM myinstance mi CROSS JOIN mykey mk LEFT JOIN mypermissions mp ON mk.keyname = mp.keyname AND mi.instancename = mp.instancename ORDER BY mk.keyname, mi.instancename </code></pre>
Yii2 assets bundle max folder size limit <p>I want to theme integration in Yii2. I have a theme which have 24 MB assets folder.I'm using asset bundle.Other theme folders are created but asset folder is not created on backend/asset folder.</p>
<p>Google cache exceed over 618 MB and asset bundle is not working I clear google cache and fixed the problem <a href="https://i.stack.imgur.com/ZRuC2.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZRuC2.png" alt="enter image description here"></a></p>
How to recursively get records in Laravel? <p>I have entity called posts in my app. Posts can be children of other posts, so that parent post has hasMany('posts') and children have hasOne('post') the inclusion is infinite.</p> <p>Here is the schema: </p> <p><a href="https://i.stack.imgur.com/KjSz4.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/KjSz4.jpg" alt="enter image description here"></a></p> <p>How can I recursively get all children and children of children and etc. of the first Post that has 'post_id' set to null? </p> <p>Please don't comment about performance here, I do know that such a schema is bad, what I want to know is only how to correctly write the recursive function to retrieve the infinite nested posts. </p> <p>For instance lets say, I have the first post 1. <br> Post 2 and 3 are children of post 1. <br> Post 4 and 5 are children of post 2. <br> Post 6 and 7 are children of post 3. <br> Post 8,9,10 are children of post 5. <br> Post 11,12,13 are children of post 7. <br> Post 14 is children of post 10. <br> I want to write a recursive function that will get me posts 2-14. <a href="https://i.stack.imgur.com/DRklq.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/DRklq.jpg" alt="enter image description here"></a></p>
<p>Since you specifically asked us not to comment about performance you should just add a <code>with</code> attribute on the post model to include all children eagerly.</p> <pre><code>class Post extends Model { protected $with = [ 'posts' ]; public function posts() { return $this-&gt;hasMany(Post::class); } } </code></pre>
Javascript/ES2015, count the number of occurrences and store as objects within an array <p>I am extracting data from a JSON feed and am trying to count the number of times each name (name_class) occurs.</p> <p>I want to return an array of objects in the following format, where count refers to the number of times the name appears:</p> <pre><code>myArray = [{name:"John", count: 5}, {name: "Sarah", count: 2}, {name: "Oliver", count: 3}]; </code></pre> <p>So far I have the following, but this does not count the number of occurrences, it simply adds another object to the array;</p> <pre><code> let namestUi = { renderNames(names){ var counter2 = []; let namesFound = names.map((name) =&gt; { let {name_class} = name; if(counter2.name == name_class){ counter2.count++; } else { counter2.push({name: name_class, count: 1}); } }); console.log(counter2); return namesFound; } }; </code></pre> <p>This is building the array of objects but not counting the number of occurrences. </p>
<pre><code>function count(names){ // Count occurrences using a map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) let map = new Map(); for (let name of names) { map.set(name, (map.get(name) || 0) + 1); } // Transform to array of { name, count } let result = []; for (let [name, count] of map) { result.push({name: name, count: count}); } return result; } count(["a", "b", "c", "a", "b", "a"]) // [{"name":"a","count":3},{"name":"b","count":2},{"name":"c","count":1}] </code></pre>
Overflow hidden doesn't work despite having height set <p>I'm not able to make the overflow to be hidden: <a href="http://codepen.io/aiwatko/pen/zKjaLx" rel="nofollow">http://codepen.io/aiwatko/pen/zKjaLx</a></p> <pre><code>.loader-overlay { position:absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: white; margin: 0; padding: 0; overflow: hidden; } </code></pre> <p>I've browsed the previous threads: I gave the height to the element with the overflow: hidden, I set the other container (my content div) to position: relative, yet when I scroll during the initial animation, I can still see my content that is underneath. I'd appreciate any hints.</p>
<p>By setting your <code>.loader-overlay</code> height to be 100%, you are telling it to occupy 100% of its <em>parent</em>. Being that the parent in your case is <code>body</code>, which does not have a set height, it will not behave as you expect.</p> <p>What I would suggest is trying out CSS3 Viewport Height (vh). Something like this would set the div to the height of the viewport, which can change dynamically across devices:</p> <pre><code>height: 100vh; </code></pre> <p>This being said, your <code>content</code> isn't even in the div with overflow hidden, so it will add to your page's height regardless of what you do with <code>.loader-overlay</code>.</p>
UIPickerView selection row with click event, not scrolling <p>I created <code>UIPickerView</code> but I did not find a way to select row with click event.I can only select row with scrolling picker rows.</p> <p>Is there any way to select a row with click event?</p>
<p>Click event is not possible in <code>UIPickerView</code>.</p> <p>You can use <code>UITapGestureRecognizer</code> to get <code>CGPoint</code> and then calculate index of row clicked. But I will highly recommend not to do such things (Apple may reject the App) as <code>PickerView</code> is all about scrolling the list.</p>
Handling tel: links in voip app <p>Is there any method in iOS (CallKit? perhaps) where a VoIP app can register to handle tel: links? That way when a user selects a phone number (in safari for instance). They would be presented with two options to complete the call.</p>
<p>That capability does not exist in iOS today. If you are interested in that, I recommend filing a bug report to request it on Apple's <a href="http://bugreport.apple.com" rel="nofollow">Bug Report</a> website.</p>
Rails 5: rails s vs. bundle exec rails s <p>I'm starting a project on Rails 5 for the first time and I was curious why running 'rails s' when I was on Rails 4 worked fine, but now that I'm on Rails 5 I need to preface it with 'bundle exec' in order to run the command properly.</p> <p>Below is my Gemfile. Again, everything works normally if I preface all my rails commands with. I'm just curious if anyone else experiencing this or if someone can give me some insight as to why this is happening?</p> <pre><code> source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~&gt; 5.0.0', '&gt;= 5.0.0.1' # Use postgresql as the database for Active Record gem 'pg', '~&gt; 0.18' # Use Puma as the app server gem 'puma', '~&gt; 3.0' # Use SCSS for stylesheets gem 'sass-rails', '~&gt; 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '&gt;= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~&gt; 4.2' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~&gt; 5' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~&gt; 2.5' # Use Redis adapter to run Action Cable in production # gem 'redis', '~&gt; 3.0' # Use ActiveModel has_secure_password # gem 'bcrypt', '~&gt; 3.1.7' gem 'bootstrap', '~&gt; 4.0.0.alpha3' source 'https://rails-assets.org' do gem 'rails-assets-tether', '&gt;= 1.1.0' end gem "paperclip", "~&gt; 5.0.0" gem "browser" # Use Capistrano for deployment gem 'capistrano-rails', group: :development group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platform: :mri end group :development do # Access an IRB console on exception pages or by using &lt;%= console %&gt; anywhere in the code. gem 'web-console' gem 'listen', '~&gt; 3.0.5' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-watcher-listen', '~&gt; 2.0.0' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] </code></pre>
<p>It sounds like the <code>rails</code> command you have installed globally is rails 4 and it's the reason "it doesn't run properly" like you say. When you run <code>bundle exec</code> then it uses the <code>rails</code> commands from the current <code>Gemfile</code>, since you have <code>rails 5</code> in your Gemfile then it works properly.</p> <p>I'd recommend using either <a href="https://rvm.io/gemsets/basics" rel="nofollow">RVM</a> or <a href="https://github.com/rbenv/rbenv" rel="nofollow">rbenv</a>, I personally like RVM since it switches automatically to the gemset of the ruby version specified in my Gemfile.</p> <p>Example, when I <code>cd</code> into the directory of my project I get a message like: </p> <blockquote> <p>RVM used your Gemfile for selecting Ruby, it is all fine - Heroku does that too.</p> </blockquote>
What is the best way to maintain a C++ library which will be used by both managed and unmanaged code? <p>The C++(unmanaged) library in question is an evolving entity, and the way that it is currently handled is by providing a C++\CLI wrapper around it so that it can be used by C# code.</p> <p>The issue however is that whenever the base library changes, the wrapper need to be updated. This seems fragile and I'm looking for alternative approaches to solve this.</p>
<p>Create a C++Library.dll. As this library is being used by both managed and unmanaged clients, doing the following could be useful</p> <p>Create a static library C++StaticLibrary.lib Then wrap the C++StaticLibrary.lib in a C++DynamicLibrary.dll by exporting the required interfaces. </p> <p>Refer C++DynamicLibrary.dll from your c++/cli (adapter) dll. This way you could avoid building your adapter if you have only the implementation change in the library. If, however there is a change in the library interface the updation of the adapter is unavoidable.</p>
Avoid react-native navigator scene overlapping <p>I have a <code>ScrollView</code> with a list of items. When I click on one item I navigate to a new scene (slide in from the right). However, during the transition period the two scenes overlap; they are fine after the animation/transition is done. </p> <p>Here's an example: </p> <p><a href="https://i.stack.imgur.com/TXhPR.png" rel="nofollow"><img src="https://i.stack.imgur.com/TXhPR.png" alt="enter image description here"></a> </p> <p>and heres the related code: </p> <pre><code>render() { return ( &lt;Navigator initialRoute={routes.frontpage()} renderScene={(route, navigator) =&gt; { if(route.index === 1) { return ( &lt;TouchableHighlight onPress={() =&gt; navigator.pop()}&gt; &lt;View style={{flex: 1}}&gt; &lt;Text style={styles.header}&gt; other &lt;/Text&gt; &lt;Text&gt; {route.post.title} &lt;/Text&gt; &lt;/View&gt; &lt;/TouchableHighlight&gt; ) } return ( &lt;View style={{flex: 1}}&gt; &lt;Text style={styles.header}&gt; Frontpage &lt;/Text&gt; &lt;ScrollView&gt; { this.props.posts.map(post =&gt; ( &lt;TouchableHighlight key={post.created} onPress={() =&gt; { if (route.index === 0) { return navigator.push(routes.post(post)) } navigator.pop(); }}&gt; &lt;View&gt; &lt;PostSummary title={post.title} upvotes={post.ups} author={post.author} subreddit={post.subreddit} created={post.created_utc} /&gt; &lt;/View&gt; &lt;/TouchableHighlight&gt; )) } &lt;/ScrollView&gt; &lt;/View&gt; ) }} /&gt; ) } </code></pre> <p>Any ideas on how to solve this?</p>
<p>Navigator uses animations during transitions between two scenes. In your case it uses fade during the transition. How about using a different animation. Navigator has <a href="https://facebook.github.io/react-native/docs/navigator.html#scene-transitions" rel="nofollow">Scene Transitions</a> feature that you may try to change the animation.</p>
SQL MAX Date Does Not Decipher Seconds <p>I have a table which contains the following data:</p> <pre><code>ID | ObjectID | ActionDate ======================================= 12345 | 422107 | 2016-10-05 11:24:23.790 12346 | 422107 | 2016-10-05 11:24:28.797 </code></pre> <p>I want to return the ID and max date, but the MAX function does not seem to be calculating down to seconds value (SS). Am I missing something, or is this a limitation with the MAX function? Here is the code I am using:</p> <pre><code>SELECT TMOA.ObjectID AS [ObjID] , TMOA.ID AS [ObjActionID] , MAX(TMOA.ActionDate) AS [PrepDate] FROM TM_Procedure AS TMPRD left join TM_ObjectAction AS TMOA ON TMPRD.ID = TMOA.ObjectID GROUP BY TMOA.ObjectID , TMPRD.ID , TMOA.ID </code></pre>
<p>One option is to use the window function Row_Number()</p> <pre><code>Select * From ( Select * ,RowNr=Row_Number() over (Partition By ObjectID Order by ActionDate Desc From YourTable ) A Where RowNr=1 </code></pre>
How to pass data from one page to another page in python tkinter? <p>my program is this.. import tkinter as tk from tkinter import *</p> <pre><code>TITLE_FONT = ("Helvetica", 18, "bold") class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) self.title(" Allocation") width, height = self.winfo_screenwidth(), self.winfo_screenheight() self.geometry('%dx%d+0+0' % (width,height)) self.state('zoomed') self.wm_iconbitmap('icon.ico') container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, PageOne, PageTwo): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, c): frame = self.frames[c] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) logo = tk.PhotoImage(file="backesh.ppm") BGlabel = tk.Label(self,image=logo) BGlabel.image = logo BGlabel.place(x=0,y=0,width=592,height=450) label = tk.Label(self, text="This is the start page", font=TITLE_FONT) label.place(x=0,y=0,width=592,height=44) frame1 = Frame(self) Label(frame1, bd=5,bg="black",text=" Enter text : ",font=("Helvetica", 14),fg="light green",width=21).pack(side=LEFT) emp=Entry(frame1, bd =5,font=("Times New Roman", 14),width=25) emp.pack(side=LEFT) frame1.place(x=400,y=160) button1 = tk.Button(self, text="Go to Page One", command=lambda: controller.show_frame(PageOne)) button2 = tk.Button(self, text="Go to Page two", command=lambda: controller.show_frame(PageTwo)) button3 = tk.Button(self, text="Exit", command=self.quit) button1.place(x=100,y=406,width=200,height=44) button2.place(x=300,y=406,width=200,height=44) button3.place(x=500,y=406,width=80,height=44) class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) logo = tk.PhotoImage(file="backesh.ppm") BGlabel = tk.Label(self,image=logo) BGlabel.image = logo BGlabel.place(x=0,y=0,width=592,height=450) label = tk.Label(self, text="This is page one", font=TITLE_FONT) label.place(x=0,y=0,width=592,height=44) button1 = tk.Button(self, text="Go to Start Page", command=lambda: controller.show_frame(StartPage)) #button2 = tk.Button(self, text="Go to Page two", # command=lambda: controller.show_frame(PageTwo)) button3 = tk.Button(self, text="Exit", command=self.quit) button1.place(x=100,y=406,width=200,height=44) button3.place(x=300,y=406,width=200,height=44) class PageTwo(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) logo = tk.PhotoImage(file="backesh.ppm") BGlabel = tk.Label(self,image=logo) BGlabel.image = logo BGlabel.place(x=0,y=0,width=592,height=450) label = tk.Label(self, text="This is page two", font=TITLE_FONT) label.place(x=0,y=0,width=592,height=44) button1 = tk.Button(self, text="Go to Start Page", command=lambda: controller.show_frame(StartPage)) #button2 = tk.Button(self, text="Go to Page two", # command=lambda: controller.show_frame(PageTwo)) button3 = tk.Button(self, text="Exit", command=self.quit) button1.place(x=100,y=406,width=200,height=44) button3.place(x=300,y=406,width=200,height=44) if __name__ == "__main__": app = SampleApp() app.mainloop() </code></pre> <p>i want to take entry text data from StartPage and display it as label in PageOne. How to do it? I am new to this. Please type the code. Thanks in advance.</p>
<p>Firstly, correct the code of the class <strong>PageOne</strong> and <strong>StartPage</strong> and add <em>self.controller = controller</em> to the __init__ function:</p> <pre><code>class PageOne(tk.Frame): def __init__(self, parent, controller): #your code self.controler = controller </code></pre> <p>Add self before entry field in StartPage and before label in PageOne:</p> <pre><code>#entry in StartPage self.emp=tk.Entry(frame1, bd =5,font=("Times New Roman", 14),width=25) self.emp.pack(side=tk.LEFT) #label in PageOne self.label = tk.Label(self, text="This is page one", font=TITLE_FONT) self.label.place(x=0,y=0,width=592,height=44) </code></pre> <p>Then add a function go_to_page_one to StartPage class:</p> <pre><code>def go_to_page_one(self): self.controller.SomeVar = self.emp.get() #save text from entry to some var self.controller.frames[PageOne].correct_label() #call correct_label function self.controller.show_frame(PageOne) #show page one </code></pre> <p>On button1 in StartPage class change command to lambda: self.go_to_page_one():</p> <pre><code>button1 = tk.Button(self, text="Go to Page One", command=lambda: self.go_to_page_one()) </code></pre> <p>At last add a function correct label to the class PageOne:</p> <pre><code>def correct_label(self): self.label.config(text=self.controller.SomeVar) #correct the label </code></pre>
Typical coin change program in python that asks for specific amounts of each coin <p>Given a number "x" and a sorted array of coins "coinset", write a function that returns the amounts for each coin in the coinset that sums up to X or indicate an error if there is no way to make change for that x with the given coinset. For example, with x=7 and a coinset of [1,5,10,25]a valid answer would be {1: 7} or {1: 2, 5: 1}. With x = 3 and a coinset of [2,4] it should indicate an error.</p> <p>I know of this code for coin change</p> <pre><code>def change(n, coins_available, coins_so_far): # n is target result = [] if sum(coins_so_far) == n: yield coins_so_far elif sum(coins_so_far) &gt; n: pass elif coins_available == []: pass else: # multiple occurences of the same coin for c in change(n, coins_available[:], coins_so_far+[coins_available[0]]): yield c for c in change(n, coins_available[1:], coins_so_far): yield c n = 5 coins = [1,5,10,25] solutions = [s for s in change(n, coins, [])] for s in solutions: print(s) </code></pre> <p>But what if you can only use two parameters (n and coins_available). How could one possibly condense this. This is the only coin change code I've seen that actually shows the amounts for each coin. </p>
<p>As a concept, change <strong>coins_so_far</strong> to <strong>coins_this_call</strong>.</p> <p>Your recursion steps change to something of this ilk; although it's not complete, I hope you see the idea.</p> <pre><code>for c in change(n-sum(coins_this_call), coins_available[:]): yield coins_this_call.append(c) </code></pre> <p>You locally keep the count of coins at the current denomination -- don't pass the whole load through the recursions. When you recur, instead of passing the original amount as well as the coins already used, simply pass the <em>remaining</em> problem. When that returns with solutions, append the current level's solution, returning the augmented list to whatever called <em>this</em> instance.</p> <p>Is that enough hint to get you moving?</p>
How to reuse variables from previous request in the Paw rest client? <p>I need to reuse value which is generated for my previous request.</p> <p>For example, at first request, I make a POST to the URL /api/products/{UUID} and get HTTP response with code 201 (Created) with an empty body.</p> <p>And at second request I want to get that product by request GET /api/products/{UUID}, where UUID should be from the first request.</p> <p>So, the question is how to store that UUID between requests and reuse it?</p>
<p>The problem is in your first requests answer. Just dont return "[...] an empty body."</p> <p>If you are talking about a REST design, you will return the UUID in the first request and the client will use it in his second call: GET /api/products/{UUID}</p> <p>The basic idea behind REST is, that the server doesn't store any informations about previous requests and is "stateless".</p> <p>I would also adjust your first query. In general the server should generate the UUID and return it (maybe you have reasons to break that, then please excuse me). Your server has (at least sometimes) a better random generator and you can avoid conflicts. So you would usually design it like this:</p> <pre><code>CLIENT: POST /api/products/ -&gt; Server returns: 201 {product_id: UUID(1234...)} Client: GET /api/products/{UUID} -&gt; Server returns: 200 {product_detail1: ..., product_detail2: ...} </code></pre> <p>If your client "loses" the informations and you want him to be later able to get his products, you would usually implement an API endpoint like this:</p> <pre><code>Client: GET /api/products/ -&gt; Server returns: 200 [{id:UUID(1234...), title:...}, {id:UUID(5678...),, title:...}] </code></pre>
Making a dropdown in Bootstrap Select <p>Im trying to show my options in a group but I want it would be something like a dropdown menu, for example we have </p> <ul> <li>option 1</li> <li>option 2 </li> <li>option 3</li> </ul> <p>when user clicked on option 2 a dropdown menu opens and it contains </p> <ul> <li>sub_option 1</li> <li>sub_option 2</li> <li>sub_option 3</li> </ul> <p>is there any way I could do this with bootstrap select? if not , can you suggest me a way to do that ?!</p> <p>tnx every body</p>
<p>Here you go:</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>$(document).ready(function() { $('#Rank').bind('change', function() { var elements = $('div.container').children().hide(); // hide all the elements var value = $(this).val(); if (value.length) { // if somethings' selected elements.filter('.' + value).show(); // show the ones we want } }).trigger('change'); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"&gt;&lt;/script&gt; &lt;select size="1" id="Rank" title="" name="Rank"&gt; &lt;option value=""&gt;-Select Your Rank-&lt;/option&gt; &lt;option value="airman"&gt;Airman&lt;/option&gt; &lt;option value="senior-airman"&gt;Senior Airman&lt;/option&gt; &lt;/select&gt; &lt;div class="container"&gt; &lt;div class="airman"&gt; Line of text for Airman &lt;/div&gt; &lt;div class="senior-airman"&gt; Line of text for Senior Airman &lt;/div&gt; &lt;/div&gt; &lt;div class="container"&gt; &lt;div class="airman"&gt; &lt;select&gt; &lt;option&gt;Airman Stuff&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="senior-airman"&gt; &lt;select&gt; &lt;option&gt;Senior Airman Stuff&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
React router configuration for an SPA with fixed layout <p>This is my first post here, hope I'm covering everything and did a search for various topics, watched some vids, read the react router docs before getting stuck. :-(</p> <p>I'm working on a single page app, which has the following components:</p> <ul> <li><p>Layout - parent component, has two children:</p> <ul> <li>Maps - child component</li> <li>Events - child component, has one child component: <ul> <li>EventDetails</li> </ul></li> </ul></li> </ul> <p>Trying to configure react router to keep the Layout component on the page at all times, and render Maps and Events. Inside Events, when clicking on a link with an event_id (got the link working), it should display into EventDetails. I can't figure out how to get the EventDetails component to display into Events, with the Layout still displaying.</p> <p>I'm pretty sure I've got my routes mis-configured, or don't really understand IndexRoute completely....thanks in advance for looking.</p> <p>An image and some code below of my router config.</p> <p>An imgur link of a layout diagram: <a href="http://i.imgur.com/lOtpWqE.png" rel="nofollow">http://i.imgur.com/lOtpWqE.png</a></p> <p>And a link to the </p> <p>React router config:</p> <pre><code>&lt;Router history={hashHistory}&gt; &lt;Route path="/" component={Layout} &gt; &lt;Route path="/events/:event_id" component={EventDetail} /&gt; &lt;/Route&gt; </code></pre> <p></p>
<p>React-router controls what should be visible by injecting component into <code>children</code> prop. </p> <p>Let's imagine you have the following routes:</p> <pre><code>&lt;Route path="/" component={Layout} &gt; &lt;Route path="/maps" component={Maps} /&gt; &lt;Route path="/events/" component={Events}&gt; &lt;Route path="/events/:event_id" component={EventDetail}&gt; &lt;/Route&gt; &lt;/Route&gt; </code></pre> <p>With these routes react-router will automatically pass the Maps component as <code>children</code> prop in the Layout component when you are on <code>/maps</code> path or the Event component when you are on <code>/event</code>. The same thing happens for nested components/routes. Your job is to use <code>{this.props.children}</code> in render method of Root component and children components which want to display other nested components.</p> <p>To sum up your Layout component render method should look like this:</p> <pre><code>render() { &lt;div&gt; &lt;div&gt; [LAYOUT] This part doesn't change between routes &lt;/div&gt; &lt;div&gt; {this.props.children} // here I render nested component like events or maps &lt;/div&gt; &lt;/div&gt; } </code></pre> <p>Then your Event component</p> <pre><code> render() { &lt;div&gt; &lt;div&gt; [EVENT] This part doesn't change between nested event routes &lt;/div&gt; &lt;div&gt; {this.props.children} // here I render nested component inside event route like EventDetails &lt;/div&gt; &lt;/div&gt; } </code></pre> <p>Here you have collection of lessons for react-router: <a href="https://github.com/reactjs/react-router-tutorial/tree/master/lessons" rel="nofollow">https://github.com/reactjs/react-router-tutorial/tree/master/lessons</a> (Lesson 7 is your case).</p> <p><code>IndexRoute</code> is a Route component with <code>path="/"</code></p>
Can I use a menu or buttons to switch react components on a single page app? <p>This is somewhat of a continuation of <a href="http://stackoverflow.com/questions/39984426/using-nested-routes-with-react-route/39984817#39984817">this thread</a>, since I found a better way to word my question.</p> <p>All I want to do, is press a button on the side menu, which will switch a react component on another part of the screen. Currently I have my application with nested routes, but I have no idea how to update the components from the nested menu.</p> <p>Here is a drawing of what I am trying to do:</p> <p><a href="https://i.stack.imgur.com/DXRxy.png" rel="nofollow"><img src="https://i.stack.imgur.com/DXRxy.png" alt="enter image description here"></a> Basically at each option I click, I would like a different component to render on the <code>&lt;HelpPanel/&gt;</code> section or at least completely different information (I have different diagram, images, etc that need to be displayed).</p> <p>Initially I am trying to do it through nested Routes, but reached a point in which I am stuck and have no idea how I can update my <code>&lt;HelpPanel/&gt;</code> component according to what item the user clicks. Here is the current relevant code:</p> <pre><code>//app.js ReactDOM.render( &lt;Router history={hashHistory}&gt; &lt;Route path="/" component={App} handler={App}&gt; &lt;IndexRoute component={Index}/&gt; &lt;Route path="about" component={About}&gt; &lt;/Route&gt; &lt;Route path="help" component={Help}&gt; &lt;Route path="help/:helpOption" component={HelpPanel}/&gt; &lt;/Route&gt; &lt;/Route&gt; &lt;/Router&gt;, destination ); </code></pre> <p>//help.js</p> <p>export class HelpPanel extends Component{</p> <pre><code>render(){ return ( &lt;div&gt;{this.props.params.helpOption}&lt;/div&gt; ); } </code></pre> <p>}</p> <p>export class Help extends Component{</p> <p>render(){</p> <pre><code> return ( &lt;Grid&gt; &lt;Title/&gt; &lt;Row className="show-grid"&gt; &lt;Col lg={2} md={4} sm={4}&gt; &lt;HelpMenu/&gt; &lt;/Col&gt; &lt;Col lg={8} md={8} sm={8}&gt; {this.props.children || "Please select topic from the menu for more information"} &lt;/Col&gt; &lt;/Row&gt; &lt;/Grid&gt; ); </code></pre> <p>} }</p>
<p>i have build solution for this task. not perfect but it works.<br> check it out <a href="http://codepen.io/dagman/pen/gwzBjX" rel="nofollow">http://codepen.io/dagman/pen/gwzBjX</a>.<br> so when you click on <code>option2</code> <code>&lt;HelpPanel2 /&gt;</code> substitutes <code>&lt;HelpPanel1 /&gt;</code> and so on. Afaik react-router is about loading component when the prescribed url pathes is matched. </p> <pre><code> class HelpPage extends React.Component { constructor(props) { super(props); this.state = { panelIndex: 0 }; } getBtnId = (e) =&gt; { if(e.target &amp;&amp; e.target.nodeName == "BUTTON") { console.log(e.target); this.setState({ panelIndex: Number(e.target.id) }); } }; render() { return ( &lt;div className="container"&gt; &lt;HelpMenu getBtnId={this.getBtnId} /&gt; &lt;HelpPanels panelIndex={this.state.panelIndex} /&gt; &lt;/div&gt; ) } } const HelpMenu = ({ getBtnId }) =&gt; { return ( &lt;div className="btnGroup" onClick={getBtnId} &gt; &lt;button id="0"&gt;Option 1&lt;/button&gt; &lt;button id="1"&gt;Option 2&lt;/button&gt; &lt;button id="2"&gt;Option 3&lt;/button&gt; &lt;button id="3"&gt;Option 4&lt;/button&gt; &lt;/div&gt; ); }; class HelpPanels extends React.Component { render() { const panels = [ &lt;HelpPanel1 /&gt;, &lt;HelpPanel2 /&gt;, &lt;HelpPanel3 /&gt;, &lt;HelpPanel4 /&gt; ]; const correctPanel = panels[this.props.panelIndex]; return ( &lt;div className="panel-box"&gt; {correctPanel} &lt;/div&gt; ); } } const HelpPanel1 = () =&gt; ( &lt;h1&gt;Panel for Option 1&lt;/h1&gt; ); const HelpPanel2 = () =&gt; ( &lt;h1&gt;Panel for Option 2&lt;/h1&gt; ); const HelpPanel3 = () =&gt; ( &lt;h1&gt;Panel for Option 3&lt;/h1&gt; ); const HelpPanel4 = () =&gt; ( &lt;h1&gt;Panel for Option 4&lt;/h1&gt; ); ReactDOM.render( &lt;HelpPage /&gt;, document.getElementById('root') ); </code></pre>
Google Map: Remove all Circles <p>I'm looking for a javascript function that will clear all drawings from my map; something like <code>map.removeMarkers()</code> or <code>map.removeOverlays()</code>, but for shapes - specifically circles.</p> <p>I've seen some answers about how to do this on Android, but I'm looking for a web solution. I'm using <a href="https://hpneo.github.io/gmaps/" rel="nofollow">gmaps.js</a> to draw my circles:</p> <pre><code>// create circle loop for( i = 0; i &lt; data.mapArray.length; i++ ) { circle = map.drawCircle({ lat: data.mapArray[i].lat, lng: data.mapArray[i].lng, radius: parseInt(data.mapArray[i].radius), strokeColor: '#'+data.mapArray[i].color, strokeWeight: 8, fillOpacity: 0, click: (function (e) { return function () { $('#'+modalType).modal({ remote: modalURL+e }); }; })(data.mapArray[i].id) }); } // end loop </code></pre> <p>I'm guessing that within this loop I need to add the circles to an array, and then call a function to clear all of them, but I'm not sure how to execute that.</p>
<p>One easy solution is to store the objects in an array</p> <pre><code>&lt;input type="button" value="Clear all" onclick="removeAllcircles()"/&gt; &lt;script&gt; var circles = []; // create circle loop for( i = 0; i &lt; data.mapArray.length; i++ ) { var circle = map.drawCircle({ lat: data.mapArray[i].lat, lng: data.mapArray[i].lng, radius: parseInt(data.mapArray[i].radius), strokeColor: '#'+data.mapArray[i].color, strokeWeight: 8, fillOpacity: 0, click: (function (e) { return function () { $('#'+modalType).modal({ remote: modalURL+e }); }; })(data.mapArray[i].id) }); // push the circle object to the array circles.push(circle); } // end loop // remove All circles function removeAllcircles() { for(var i in circles) { circles[i].setMap(null); } circles = []; // this is if you really want to remove them, so you reset the variable. } &lt;/script&gt; </code></pre> <p>EDIT</p> <p>Once you have that array, you can use it to toggle on/of, or target some specific circle, like circkles[17] ...</p> <pre><code>&lt;input type="button" value="Toggle on" onclick="toggleOn()"/&gt; &lt;input type="button" value="Toggle off" onclick="toggleOff()"/&gt; &lt;script&gt; // Toggle off function toggleOff() { for(var i in circles) { circles[i].setMap(null); } } // Toggle on function toggleOn() { for(var i in circles) { circles[i].setMap(map); } } &lt;/script&gt; </code></pre>
ng-bind-html vs bind-html-compile? <p>I want to know the difference between ng-bind-html and bind-html-compile directives. For example I gave </p> <pre><code>&lt;p style='color:red'&gt;test&lt;p&gt; </code></pre> <p>to ng-bind-html, this strips out the style where as bind-html-compile does not. May I know when each directive should be used. Thanks.</p>
<p><strong>bind-html-compile</strong> is not a standard Angular directive, it comes with the module <a href="https://github.com/incuna/angular-bind-html-compile" rel="nofollow">https://github.com/incuna/angular-bind-html-compile</a> and it is used to compile binded data.To make it simple, it is equivalent to write html in your source code: it will be re-evaluated and if other directories are found, they will work as expected.</p> <p><strong>ng-bind-html</strong> is a standard directive (bundled with Angular itself) and just output html strings <strong>without compiling it</strong>.</p> <p>for example, if you controller has a variable with plain html, like in:</p> <pre><code>$scope.dataToDisplay = '&lt;h1&gt;&lt;strong&gt;Title&lt;/strong&gt;&lt;/h1&gt;'; </code></pre> <p>Then you can go with <code>ng-bind-html</code>.</p> <p>If you need to inject variables that contain html with other directives, such as:</p> <pre><code>$scope.dataToDisplay = '&lt;h1 ng-show="showIfOtherVariable"&gt;&lt;strong&gt;Title&lt;/strong&gt;&lt;/h1&gt;'; </code></pre> <p>then you need to aforementioned module.</p>
Reading from S3 Throws NoSuchMethodError, specifically, SSLConnectionSocketFactory <p>I am trying to read ORC file from S3, using <code>spark-shell</code>, following the guide below:</p> <p><a href="http://stackoverflow.com/questions/30792494/read-orc-files-directly-from-spark-shell">Read ORC files directly from Spark shell</a></p> <p>I have defined the path to be <code>s3a://...</code></p> <p>Unfortunately, this causes the following exception to be thrown: </p> <pre><code>java.lang.NoSuchMethodError: org.apache.http.conn.ssl.SSLConnectionSocketFactory.&lt;init&gt;(Ljavax/net/ssl/SSLContext;Ljavax/net/ssl/HostnameVerifier;)V at com.amazonaws.http.conn.ssl.SdkTLSSocketFactory.&lt;init&gt;(SdkTLSSocketFactory.java:56) ... </code></pre> <p>I have imported the jar file in spark-shell through the following command in an attempt to rectify the missing method, but to no avail.</p> <p><code>spark-shell --jars /home/admin/Downloads/httpclient4.5.2.jar, /home/admin/Downloads/httpclient-4.5.2.jar, /home/admin/Downloads/hadoop-common-2.6.0.jar, /home/admin/Downloads/hadoop-aws-2.6.0.jar, /home/admin/Downloads/aws-java-sdk-1.11.41.jar</code></p> <p>I am suspecting that spark has its own copy of <code>SSLConnectionSocketFactory</code>, as I was able to import <code>SSLConnectionSocketFactory</code> even while excluding the <code>--jars</code> option. </p> <p>Other than creating a maven project, (which is another headache, as I am having problems with it), is there anyway I can resolve this error where Spark claims that SSLConnectionSocketFactory could not be initialised?</p>
<p>I have noticed that some Spark versions are not compatible with some AWS versions. For example, with Spark 1.6 and hadoop 2.6 I had to use AWS 1.10.77 ( I was having the same problem).</p>
js-data multiple models in a single route <p>I'm using 3.0.0-rc.4 of js-data and I'm in need of loading multiple models from a single call to the backend API. I'm still building the backend as well and would prefer to be able to retrieve all the data from the different tables at one time instead of making multiple calls to different end points.</p>
<p>You can. Say the route your web app is trying to load is /posts/123, and you need to load Post #123 and its Comments, which reside in two different tables. In your client-side app you can do something like</p> <pre><code>store.find('post', 123) </code></pre> <p>or even</p> <pre><code>store.find('post', 123, { params: { with: 'comment' } }) </code></pre> <p>which will make a GET request to something like <code>/post/123</code> and <code>/post/123?with=comment</code> respectively.</p> <p>Your backend can respond with the Post record with its Comments embedded, and as long as you've told JSData about the relationship between posts and comments they each will be cached into the right part of the in-memory store. For example:</p> <pre><code>store.defineMapper('post', { relations: { hasMany: { comment: { localField: 'comments', foreignKey: 'post_id' } } } }); store.defineMapper('comment', { relations: { belongsTo: { post: { localField: 'post', foreignKey: 'post_id' } } } }); </code></pre> <p>You do:</p> <pre><code>store.find('post', 123) </code></pre> <p>Your backend responds with:</p> <pre><code>{ "id": 123, // ... } </code></pre> <p>You do:</p> <pre><code>store.find('post', 123, { params: { with: 'comment' } }) </code></pre> <p>Your backend responds with:</p> <pre><code>{ "id": 123, // ..., comments: [ { "id": 14323, "post_id": 123, // ... }, // ... ] } </code></pre> <p>If you're using Node.js + JSData on the backend, than check out <a href="https://github.com/js-data/js-data-express" rel="nofollow">https://github.com/js-data/js-data-express</a> which can parse the querystring correctlly and generate all of the Express routes for all of your Mappers. Using js-data-express your backend will be able to respond to the requests exactly as I indicated in my examples above.</p> <p>Once you've loaded data into the in-memory store, your View component can pull the data it needs to display out of the in-memory store:</p> <p>Get Post #123 out of the in-memory store:</p> <pre><code>store.get('post', 123) </code></pre> <p>Get the Comments for Post #123 out of the in-memory store:</p> <pre><code>store.getAll('comment', 123, { index: 'post_id' }) </code></pre> <p>If you're using the <code>DataStore</code> component, then the Post's Comments should also be available on the Post record itself, e.g. <code>post.comments</code>.</p>
Checking for Active Network connection and exiting the app if not active in ionic using ngCordova <p>i am developing a conference app that is data driven and constantly will be updated from the web server. i am storing data on the local storage for persistence, but when the app is installed and launched for the first time i want to pop up a "No Internet Connection" message and close the app when they click any button on the pop up. but when there is internet load the app. i have done this in my app.run function but it does not work.</p> <pre><code>var app = angular.module('starter', ['ionic', 'ionic-material', 'ngCordova']); app.run(function ($ionicPlatform, $ionicPopup, $timeout) { $ionicPlatform.ready(function () { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova &amp;&amp; window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { StatusBar.styleDefault(); } //checking for internet connection on startup if (window.Connection) { if (navigator.connection.type === Connection.NONE) { document.addEventListener("offline", function () { $ionicPopup.confirm({ title: "Internet Disconected", content: "Sorry, No internet connection now, please try again" }).then(function (result) { if (!result) { $ionicPlatform.exitApp(); } }); }, false); } } }); }); </code></pre> <p>the app pops up the message, but on click of any of the buttons(ok and cancel), the app just stays on white screen. it does not exit the app. i don't know what am doing wrong. please i need advice and code samples to correct my error. </p>
<p>A few aspects to keep in mind:</p> <ul> <li><p>your implementation of exitApp() is reported not to work in iOS devices</p></li> <li><p>kill an app is a big no for usability, you'd better present the interface with the latest chached data or if any data is cached a "no network connection" message integrated into the app layout (checkout Spotify for an example)</p></li> </ul> <p>In any case, your purpose could be reached with <code>ngCordova.plugins.network</code> module, bundled in <a href="http://ngcordova.com/" rel="nofollow">http://ngcordova.com/</a> </p> <p>This an example of service that returns current network status:</p> <pre><code>angular.module('app.common.connectivity', [ 'ngCordova.plugins.network' ]) .service('ConnectivityService', function($cordovaNetwork) { this.isOnline = $cordovaNetwork.isOnline() || false; }); </code></pre> <p>You can add this module and inject the service where needed, like in:</p> <pre><code>var app = angular.module('starter', ['ionic', 'ionic-material', 'app.common.connectivity']); app.run(function ($ionicPlatform, $ionicPopup, $timeout, ConnectivityService) { $ionicPlatform.ready(function () { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova &amp;&amp; window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { StatusBar.styleDefault(); } //checking for internet connection on startup if( !ConnectivityService.isOnline &amp;&amp; !window.localStorage.appLaunched ) { $ionicPopup.confirm({ title: "Internet Disconected", content: "Sorry, No internet connection now, please try again" }) .then(function(result) { $ionicPlatform.exitApp(); }); } // Apparently we're online so remember we already have been here if ( !localStorage.appLaunched ) localStorage.appLaunched = true; }); }); </code></pre>
Why do I get garbled output when I decode some HTML entities but not others? <p>In Perl, I am trying to decode strings which contain numeric HTML entities using <a href="https://metacpan.org/pod/HTML::Entities" rel="nofollow">HTML::Entities</a>. Some entities work, while "newer" entities don't. For example:</p> <pre><code>decode_entities('&amp;#174;'); # returns ® as expected decode_entities('&amp;#8486;'); # returns Ω instead of Ω decode_entities('&amp;#9733;'); # returns ★ instead of ★ </code></pre> <p>Is there a way to decode these "newer" HTML entities in Perl? In PHP, the <code>html_entity_decode</code> function seems to decode all of these entities without any problem.</p>
<p>The decoding works fine. It's how you're outputting them that's wrong. For example, you may have sent the strings to a terminal without encoding them for that terminal first. This is achieved through the <code>open</code> pragma in the following program:</p> <pre><code>$ perl -e' use open ":std", ":encoding(UTF-8)"; use HTML::Entities qw( decode_entities ); CORE::say decode_entities($_) for "&amp;#174;", "&amp;#8486;", "&amp;#9733;"; ' ® Ω ★ </code></pre>
How to check, whether exception was raisen in the current scope? <p>I use the following code to call an arbitrary callable <code>f()</code> with appropriate number of parameters:</p> <pre><code>try: res = f(arg1) except TypeError: res = f(arg1, arg2) </code></pre> <p>If <code>f()</code> is a two parameter function, calling it with just one parameter raises <code>TypeError</code>, so the function can be called properly in the <code>except</code> branch.</p> <p>The problem is when <code>f()</code> is one-parameter function and the exception is raisen in the body of <code>f()</code> (possibly because of a bad call to some function), for example:</p> <pre><code>def f(arg): map(arg) # raises TypeError </code></pre> <p>The control flow goes to the <code>except</code> branch because of the internal error of <code>f()</code>. Of course calling <code>f()</code> with two arguments raises a new <code>TypeError</code>. Then instead of traceback to the original error I get traceback to the call of <code>f()</code> with two parameters, which is much less helpful when debugging.</p> <p>How can my code recognize exceptions raised not in the current scope to reraise them?</p> <p>I want to write the code like this:</p> <pre><code>try: res = f(arg1) except TypeError: if exceptionRaisedNotInTheTryBlockScope(): # &lt;-- subject of the question raise res = f(arg1, arg2) </code></pre> <p>I know I can use a walkarround by adding <code>exc_info = sys.exc_info()</code> in the <code>except</code> block.</p> <p>One of assumptions is I have no control over <code>f()</code> since it is given by user of my module. Also its <code>__name__</code> attribute may be other than <code>'f'</code>. Internal exception may be raised by bad recurrent call to <code>f()</code>. The walkarround is unsuitable since it complicates debugging by the author of <code>f()</code>.</p>
<p>You can capture the exception object and examine it.</p> <pre><code>try: res = f(arg1) except TypeError as e: if "f() missing 1 required positional argument" in e.args[0]: res = f(arg1, arg2) else: raise </code></pre> <p>Frankly, though, not going the extra length to classify the exception should work fine as you should be getting both the original traceback and the secondary traceback if the error originated inside f() -- debugging should not be a problem.</p> <p>Also, if you have control over f() you can make second argument optional and not have to second-guess it:</p> <pre><code>def f(a, b=None): pass </code></pre> <p>Now you can call it either way.</p> <p>How about this:</p> <pre><code>import inspect if len(inspect.getargspec(f).args) == 1: res = f(arg1) else: res = f(arg1, arg2) </code></pre>
Getting the value outside the foreach php loop <p>Here is the code used to get the ids of a images in a gallery</p> <pre><code>&lt;?php $images = get_field('photogallery');?&gt; &lt;?php foreach( $images as $image ): ?&gt; &lt;?php echo $image['ID']; ?&gt; &lt;?php echo ','; ?&gt; &lt;?php endforeach; ?&gt; </code></pre> <p>I get the output</p> <pre><code> 1102 , 3380 , 3348 , 3354 , 3355 , </code></pre> <p>I would like to get this outside the loop because the result must be used in other shortcode also I see there is a whitespace after every number.</p> <p>the result must be </p> <pre><code> 1102,3380,3348,3354,3355 </code></pre> <p>Please help me.. thanks</p>
<p>You don't need to put <code>&lt;?php ... ?&gt;</code> everytime everywhere for each statement. Keep in mind that each time you close with <code>?&gt;</code> all characters are sent to the client until the next opening <code>&lt;?php</code>, that's why you obtain spaces around each comma:</p> <pre><code>&lt;?php foreach( $images as $image ): ?&gt;# #####&lt;?php echo $image['ID']; ?&gt;# #####&lt;?php echo ','; ?&gt;# &lt;?php endforeach; ?&gt; </code></pre> <p><em>(I changed white-spaces to <code>#</code>, this way you can see characters sent to the client (the browser))</em>.</p> <p>You can use <code>array_map</code> to "filter" only ID items and <code>implode</code> to join them , then you only need to store the result in a variable (<code>$result</code> here).</p> <pre><code>&lt;?php $images = get_field('photogallery'); $result = implode(',', array_map(function ($i) { return $i['ID']; }, $images)); echo $result; ?&gt; </code></pre> <p>Now you can use <code>$result</code> later everywhere you want.</p>
PHP: MySQL update always returns 0 <p>I'm trying to update some records in my database but the result always seems to be 0, although the query's syntax is correct.</p> <p>This is my code:</p> <pre><code>$results = mysqli_query($con, "SELECT * FROM scores LIMIT 10"); while ($row = mysqli_fetch_array($results)) { $id = $row['id']; $score1 = $row['score1']; $score2 = $row['score2']; if ($score1 &gt; $score2) { $query = "UPDATE scores SET final = '1' WHERE id = '{$id}'"; } elseif ($score1 &lt; $score2) { $query = "UPDATE scores SET final = '2' WHERE id = '{$id}'"; } else { $query = "UPDATE scores SET final = '0' WHERE id = '{$id}'"; } $result = mysqli_query($con, $query); } </code></pre> <p>I tried echoing the results of the "if structure" and they are correct as well. There must be something wrong with the execution.</p> <p>Here are my db records: <a href="https://i.stack.imgur.com/8fiiQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/8fiiQ.png" alt="enter image description here"></a></p>
<p>try $query = "UPDATE scores SET final = '1' WHERE id = '$id'";</p>
How to permit hash with * key => values? <p>I want to create an object with strong params that can accept dynamic hash keys.</p> <p>This is my code,</p> <pre><code>Quiz.create(quiz_params) def quiz_params params.require(:quiz).permit(:user_id, :percent, :grade, questions: {}) end </code></pre> <p>data that gets passed in would look something like this.</p> <pre><code>// the keys that get passed into question is always different quiz: { user_id: 1, percent: 80, grade: "B", questions: { "12": "24", "1": "12", "4": "3", "5": "22" } } </code></pre> <p>Currently however, when I try to create a Quiz, the questions hash turns out empty.</p>
<p>Until now I have only seen this:</p> <pre><code>def quiz_params questions_params = (params[:quiz] || {})[:questions].keys params.require(:quiz).permit(:user_id, :percent, :grade, questions: questions_params) end </code></pre>
Randarray not definied <p>I'm trying to create a two dimensional Array - but in the JS console it keeps saying my "Randarray" function isn't defined. I can't seem to figure out why it's undefined, maybe I just need another pair of eyes to look over it.</p> <p>Any help is appreciated!</p> <p><h1> Part 2 </h1></p> <pre><code>&lt;button id="array" onclick="Randarray()"&gt; Array &lt;/button&gt; &lt;script&gt; function Randarray() { randarray = new Array(5) randarray [0] = new Array(3) randarray [0][0] = "Toyota" randarray [0][1] = "1998" randarray [0][2] = "Black" randarray [1] = new Array(3) randarray [1][0] = "Ferrari" randarray [1][1] = "2006" randarray [1][2] = "Red" randarray [2] = new Array(3) randarray [2][0] = "Ferrari" randarray [2][1] = "2006" randarray [2][2] = "Red" randarray [3] = new Array(3) randarray [3][0] = "Jeep" randarray [3][1] = "2006" randarray [3][2] = "Silver" randarray [4] = new Array(3) randarray [4][0] = "Mercedes" randarray [4][1] = "2016" randarray [4][2] = "White" randarray [5] = new Array(3) randarray [5][0] = "BMW" randarray [5][1] = "2017" randarray [5][2] = "Black" function getArray(row,col){ document.arrayForm.myResult.value=randarray[row][col]; } document.getElementById('array').addEventListener('click', Randarray); &lt;/script&gt; </code></pre>
<p>You forgot to close the <code>Randarray</code> function before the <code>getArray</code> function. Do this:</p> <pre><code>} // Missing. function getArray(row,col) </code></pre> <p>Also, don't use event listener as well as <code>onclick</code> inline function.</p> <pre class="lang-html prettyprint-override"><code>&lt;button id="array" onclick="Randarray()"&gt;Array&lt;/button&gt; &lt;script&gt; function Randarray() { randarray = new Array(5) randarray[0] = new Array(3) randarray[0][0] = "Toyota" randarray[0][1] = "1998" randarray[0][2] = "Black" randarray[1] = new Array(3) randarray[1][0] = "Ferrari" randarray[1][1] = "2006" randarray[1][2] = "Red" randarray[2] = new Array(3) randarray[2][0] = "Ferrari" randarray[2][1] = "2006" randarray[2][2] = "Red" randarray[3] = new Array(3) randarray[3][0] = "Jeep" randarray[3][1] = "2006" randarray[3][2] = "Silver" randarray[4] = new Array(3) randarray[4][0] = "Mercedes" randarray[4][1] = "2016" randarray[4][2] = "White" randarray[5] = new Array(3) randarray[5][0] = "BMW" randarray[5][1] = "2017" randarray[5][2] = "Black" } function getArray(row, col) { document.arrayForm.myResult.value = randarray[row][col]; } document.getElementById('array').addEventListener('click', Randarray); &lt;/script&gt; </code></pre>
React with Redux - unable to bind action to parent <p>I am new to the Redux pattern i'm having some trouble linking an action in a separate JS file to it's parent component. Here is the component:</p> <pre><code>import React, {Component} from 'react'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import playSample from './sampleActions/clickToPlay'; class SamplesInnerLrg extends Component { render() { return &lt;div&gt; { this.props.samples.map((sample) =&gt; { return ( &lt;div key={sample.id} className="sample-comp-lge"&gt; &lt;div className="sample-comp-lge-header"&gt; &lt;span className="sample-comp-lge-Name"&gt;{sample.sampleName}&lt;/span&gt; &lt;span className="sample-comp-lge-id"&gt;{sample.sampleFamily}&lt;/span&gt; &lt;/div&gt; &lt;div className="sample-comp-lge-audio" ref={sample.id} onClick={() =&gt; this.bind.playSample(sample)}&gt; &lt;audio preload="auto" id="myAudio"&gt; &lt;source src={sample.soundSource} type="audio/wav" /&gt; &lt;/audio&gt; &lt;/div&gt; &lt;div className="sample-comp-lge-owner"&gt;{sample.uploader}&lt;/div&gt; &lt;/div&gt; ) }) } &lt;/div&gt; } } function mapStateToProps(state) { return { samples:state.samples }; } function matchDispatchToProps(dispatch) { return bindActionCreators({playSample:playSample},dispatch) } export default connect(mapStateToProps,matchDispatchToProps)(SamplesInnerLrg); </code></pre> <p>Specifically I am trying to have an onClick action on this line that will call a function in an imported file (clickToPlay.js):</p> <pre><code>&lt;div className="sample-comp-lge-audio" ref={sample.id} onClick={() =&gt; this.bind.playSample(sample)}&gt; </code></pre> <p>The clickToPlay file looks like so:</p> <pre><code>import $ from 'jquery'; export const playSample = (sample) =&gt; { console.log(sample); return { type:"Play_Sample_clicked", payload:sample } }; </code></pre> <p>the error i'm getting on click is Cannot read property 'playSample' of undefined. I'm guessing I have bound the action to the component correcly but I can't tell why?</p> <p>EDIT:</p> <p>Here is my index.js file as requested:</p> <pre><code>import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import {Provider} from 'react-redux'; import { createStore,compose } from 'redux'; import allReducers from './reducers'; const store = createStore(allReducers,compose( window.devToolsExtension ? window.devToolsExtension() : f =&gt; f )); ReactDOM.render( &lt;Provider store={store}&gt; &lt;App /&gt; &lt;/Provider&gt; , document.getElementById('root') ); </code></pre>
<p>You aren't exporting 'playSample' as the default export, you have two ways to reslove this:</p> <p>You can do:</p> <p><code>import { playSample } from './sampleActions/clickToPlay';</code></p> <p>or </p> <p>you can change <code>export const playSample</code> to <code>const playSample</code> Then add <code>export default playSample</code> at the end of your file.</p> <p>Another note I want to mention about this line: </p> <pre><code>return bindActionCreators({playSample:playSample},dispatch) </code></pre> <p>I don't see why you are doing <code>{playSample:playSample}</code> just change it to <code>playSample</code>. ES6 allows you to eliminate key if it's the same as value, this is called <strong>object literal property value shorthand</strong>.</p>
Disallow certain urls from googlebots <p>I have the following urls:</p> <pre><code>http://www.website.com/somethingawesome/?render=xml http://www.website.com/somethingawesome/?render=json </code></pre> <p>What I want is to disallow google from indexing when the url has <code>?render=xml</code> or <code>?render=json</code> inside it. <strong>This can be variable to any url.</strong></p> <p>My thoughts are :</p> <pre><code>Disallow: /?render=xml Disallow: /?render=json </code></pre> <p>Will this work though? Should I be concerned about the url portion too? How can I make this work?</p>
<p>You will need the wildcard first:</p> <pre><code>Disallow: /*?render=xml Disallow: /*?render=json </code></pre>
Sending push notification to specific user in Parse <p>I am trying to create a flow in Cloud Code where I need to send a push notification not to the user that just signed up, but to his partner.</p> <p>In my app, two Users can be connected as partners. My User table has a <code>partnerUser</code> column that points to his partner. So, the flow goes like this:</p> <p>1) Mark first signs ups in the app and adds his friend's John e-mail address as his partner 1.1) afterSave function is called but does nothing because Mark does not have a partner yet 2) John receives an email with invite code and signs up using that code. This connects them both in Parse 2.1) afterSave is called based on John's save(). The first thing I do is query the User table to find John's partner - in this case Mark. Then, with Mark's object at hand, I push a notification to Mark. </p> <p>My logs don't show any error, but the notification is not reaching Mark. Not sure if I am stuffing up with the query itself.</p> <p>I change the PFInstallation table to have a <code>Pointer</code> to the User. And I also have a column in the User table with the InstallationId. With this relationship, I was hoping I could send the individual push notification to a certain user. This is what I do in the cloud code:</p> <pre><code>Parse.Cloud.afterSave(Parse.User, function(request) { console.log(displayTime() + " - AfterSave Triggered for user " + request.object.get("firstName")); //Making sure the partners have been connected if (typeof request.object.get("partnerUser") !== 'undefined' || request.object.get("partnerUser") !== null) { var topicName = request.object.get("topicName"); //Searching for the partner (in this case the partner registered first) query = new Parse.Query(Parse.User); query.equalTo("objectId", request.object.get("partnerUser").id); query.doesNotExist("topicName"); //we just want a partner that has not been connected yet query.first({ success: function(userRetrieved) { console.log(displayTime() + ' - Partner Retrieved - name :' + userRetrieved.get("firstName")); //We need to send a push notification to the user that first signed up (in this case "userRetrieved") //because that user is not connected to the topic that joins both users console.log(displayTime() + " - Installation Id is: " + request.object.get("installationId")); //var partnerTopicName = request.object.get("partnerUser").id; var pushQuery = new Parse.Query(Parse.Installation); pushQuery.equalTo('user', userRetrieved); pushQuery.equalTo('installationId', request.object.get("installationId")); Parse.Push.send({ where: pushQuery, // Set our Installation query data: { "aps": { "content-available": 1, "sound": "default", "title": "Name Me", "alert": "", "type": "connect_push_notification_channel", "topic": topicName } } }, { useMasterKey: true, success: function() { console.log(displayTime() + " - Push done with installationId " + request.object.get("installationId")); }, error: function(err) { console.error(displayTime() + " - Push error " + err); } }); </code></pre> <p>Looking at my logs I can see:</p> <p>[11/10/2016 21:06:32.870 PM] - AfterSave Triggered for user Felipe</p> <pre><code>[11/10/2016 21:06:32.873 PM] - finished for: Felipe [11/10/2016 21:06:33.24 PM] - Partner Retrieved - name :Gemma [11/10/2016 21:06:33.24 PM] - Installation Id is: 2f4b6127-49d5-4586-84eb-595fbb1e3d6a [11/10/2016 21:06:33.25 PM] - Object UpdateAt equals to Object CreatedAt [11/10/2016 21:06:33.173 PM] - Push done with installationId 2f4b6127-49d5-4586-84eb-595fbb1e3d6a [11/10/2016 21:06:33.313 PM] - AfterSave Triggered for user Gemma [11/10/2016 21:06:33.313 PM] - finished for: Gemma [11/10/2016 21:06:33.319 PM] - saved </code></pre> <p>I know that push notifications work because I have another flow, from a Cloud Function, that pushes the notification to both users and they both get it. But the query is based on a Topic and not an Installation.</p> <p>Any tips or advices?</p> <p>Thanks</p>
<p>I finally found what the problem was. It was this line:</p> <pre><code>pushQuery.equalTo('installationId', request.object.get("installationId")); </code></pre> <p>this is actually taking the installationId from the second user, and not the first one, as it should have been. I changed the line to:</p> <pre><code>pushQuery.equalTo('installationId', userRetrieved.get("installationId")); </code></pre> <p>and now it works</p>
Swift 3 comparing array indexes <p>If i have two arrays &amp; i want to compare their indexes, for ex:</p> <pre><code>let var a1 = ["1", "2", "3"] let var a2 = ["3", "2", "3"] </code></pre> <p>And i wanted to print something to say which index wasn't the same, such as:</p> <pre><code>if a1[0] != a2[0] &amp;&amp; a1[1] == a2[1] &amp;&amp; a1[2] == a2[2]{ print("Index 0 is not the same.") </code></pre> <p>Would i have to write 7 more of those statements to show all 8 possibilities of all correct/all wrong/index 1&amp;1 wrong, etc?</p> <p>Thank you!</p>
<p>You can get all indexes like this:</p> <pre><code>let diffIndex = zip(a1, a2).enumerated().filter {$1.0 != $1.1}.map {$0.offset} </code></pre> <p>Explanation:</p> <ul> <li><code>zip</code> produces a sequence of pairs</li> <li><code>enumerated()</code> adds an index to the sequence</li> <li><code>filter</code> keeps only pairs with different values</li> <li><code>map</code> harvests the index, and builds the sequence of results.</li> </ul> <p>Running this on</p> <pre><code>let a1 = ["1", "2", "3", "4"] let a2 = ["3", "2", "3", "5"] </code></pre> <p>This produces a sequence <code>[0, 3]</code></p>
Typescript version conflict in Visual Studio Code <p>I have an Angular2 project created with the angular-cli project templates in <em>Visual Studio Code</em>. Also, I installed the latest version of Typescript (2.0.3) via npm as well as via the Microsoft link (<a href="https://www.microsoft.com/en-us/download/details.aspx?id=48593" rel="nofollow">https://www.microsoft.com/en-us/download/details.aspx?id=48593</a>) because I also use <em>Visual Studio 2015</em>. However, for some reason the I still get an error message when I start my Angular2 project. Note that even with a standard command prompt running tsc -v will still return 1.0.0.0.</p> <ul> <li>How does tsc -v determine the version of typescript?</li> <li>How do I get rid of this message in my Angular project and ensure it will be using the latest version of Typescript?</li> </ul> <p>What am I missing here? Appreciate your help.</p> <p><a href="https://i.stack.imgur.com/GKVky.png" rel="nofollow"><img src="https://i.stack.imgur.com/GKVky.png" alt="enter image description here"></a></p>
<p>Did you install TypeScript via NPM? If this is the case, try uninstalling it via <code>npm uninstall -g typescript</code>. Now reinstall it via <code>npm install -g typescript</code> and check if the problem is solved.</p>
Extracting first column that meets certain criteria for each row <p>I will try to explain what I am doing the best I can it is kind of confusing but I'll give it a shot. Essentially I start with 2 data frames. Each one containing a unique row per person and two items per user as columns. My goal is to turn this into 1 data frame with one unique row per user and the first item from each of the two data frames upon the condition that the items do not repeat. For example if for customer 1 in the first data frame his items are "a" and "d" and in the second data frame his items are "a" and "c", I would want the final data frame to be "a" and "c" for this customer. I have written an apply that does this however when I perform this on roughly 160,000 rows it takes quite a bit of time. I was hoping someone would be able to come up with a more efficient solution to my problem.</p> <pre><code>d1 &lt;- data.frame(id = c("1", "2", "3"), stringsAsFactors = F) r1 &lt;- data.frame(i1 = c("a", "b", "c"), i2 = c("d", "e", "f"), stringsAsFactors = F) rownames(r1) = d1$id r2 &lt;- data.frame(i1 = c("a", "c", "f"), i2 = c("c", "t", "l"), stringsAsFactors = F) rownames(r2) = d1$id dFinal &lt;- data.frame(id = d1$id, r1 = "", r2 = "", stringsAsFactors = F) dFinal$r1 = apply(dFinal, 1, function(x){r1[rownames(r1) == x["id"], "i1"]}) dFinal$r2 = apply(dFinal, 1, function(x){r2[rownames(r2) == x["id"], which(!r2[rownames(r2) == x["id"],c("i1","i2")] %in% x["r1"])[1]]}) </code></pre>
<p>Would the following do what you're looking for:</p> <pre><code># Keep only first column of first data.frame df &lt;- cbind(d1,r1,r2)[,-3] names(df) &lt;- c("id","r1_final","r2_i1","r2_i2") df$r2_final &lt;- df$r2_i1 # Keep only second column of second data.frame # if the value in the first column is found in first data.frame df[df$r1_final == df$r2_i1,"r2_final"] &lt;- df[df$r1_final == df$r2_i1,"r2_i2"] df_final &lt;- df[,c("id","r1_final","r2_final")] print(df_final) id r1_final r2_final 1 1 a c 2 2 b c 3 3 c f </code></pre> <p><strong>Edit:</strong> OP asked for a solution if there were four data.frames instead of 2 like in the example, here is some code that I haven't tested but it should work with two additional columns</p> <pre><code>df$r2_final &lt;- df$r2_i1 df$r3_final &lt;- df$r3_i1 df$r4_final &lt;- df$r4_i1 df[df$r1_final == df$r2_i1,"r2_final"] &lt;- df[df$r1_final == df$r2_i1,"r2_i2"] df[df$r3_i1 %in% c(df$r1_final,df$r2_final),"r3_final"] &lt;- df[df$r3_i1 %in% c(df$r1_final,df$r2_final),"r3_i2"] df[df$r4_i1 %in% c(df$r1_final,df$r2_final,df$r3_final),"r4_final"] &lt;- df[df$r4_i1 %in% c(df$r1_final,df$r2_final,df$r3_final),"r4_i2"] df_final &lt;- df[,c("id","r1_final","r2_final","r3_final","r4_final")] </code></pre>
Identify first occurence of event based on multiple criterias <p>I have a dataset in PowerPivot and need to find a way to flag ONLY the first occurrence of a customer sub event</p> <p>Context: Each event (COLUMN A) can have X number of sub events (COLUMN B), I already have a flag that identifies a customer event based on multiple criteria's (COLUMN D)... What I need is a way to flag <strong>only the first occurrence</strong> of a customer sub event within each event, I've added a <em>fake</em> COLUMN E to illustrate how the flagging should work. </p> <p><a href="https://i.stack.imgur.com/eATvb.png" rel="nofollow"><img src="https://i.stack.imgur.com/eATvb.png" alt="enter image description here"></a></p> <p>UPDATE Additional situation - Having duplicated customer sub_events but only need to flag the first sub_event... should look like this:</p> <p><img src="https://i.stack.imgur.com/Sdxh1.png" alt="enter image description here"></p>
<p>Create a calculated column in your model using the following expression:</p> <pre><code>= IF ( [Customer_Event] = 1 &amp;&amp; [Sub_Event] = CALCULATE ( FIRSTNONBLANK ( 'Table'[Sub_Event], 0 ), FILTER ( 'Table', 'Table'[Event] = EARLIER ( 'Table'[Event] ) &amp;&amp; [Customer_Event] = 1 ) ), 1, 0 ) </code></pre> <p>If <code>Sub_Event</code> column is a number replace <code>FIRSTNONBLANK ( 'Table'[Sub_Event], 0 )</code> by <code>MIN('Table'[Sub_Event])</code></p> <p>Also if your machine regional settings use <code>;</code> (semicolon) as list separator replace every <code>,</code> (comma) in my expression by a semicolon in order to match your settings.</p> <p><strong>UPDATE:</strong> Repeated values in <code>Sub_Event</code> column.</p> <p>I think we can use <code>CaseRow#</code> column to get the first occurence of <code>Sub_Event</code> value:</p> <pre><code>= IF ( [Customer_Event] = 1 &amp;&amp; [Sub_Event] = CALCULATE ( FIRSTNONBLANK ( 'Table'[Sub_Event], 0 ), FILTER ( 'Table', 'Table'[Event] = EARLIER ( 'Table'[Event] ) &amp;&amp; [Customer_Event] = 1 ) ) &amp;&amp; [CaseRow#] = CALCULATE ( MIN ( 'Table'[CaseRow#] ), FILTER ( 'Table', 'Table'[Event] = EARLIER ( 'Table'[Event] ) &amp;&amp; [Customer_Event] = 1 ) ), 1, 0 ) </code></pre> <p>It is not tested but should work.</p> <p>Let me know if this helps.</p>
What does "E2E use case" mean? <p>I know what is "use case", but I haven't any idea about "E2E" in this context.</p> <p>What does "E2E use case" mean ? All references are welcome.</p>
<p>It should be "End to End" Use Case.</p>
Displaying two different heatmaps in one file <p>I am new to Heatmaps and R as well. I have two different Heatmaps as image, how can I display them in single file one above the other. It's a cancer data. I want to show data of two stages of cancer. Column names are same in both datasets but row names differ. Want some easy to understand solution, as I don't have programming skill in R.</p> <p>Thank you in advance.</p>
<p>Have you tried facet from ggplot2?</p> <p>(Using the cookbook-r example it would be like this)</p> <pre><code>library(reshape2) library(ggplot2) sp &lt;- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1) sp </code></pre> <p>Gives you the single plot: </p> <p><a href="https://i.stack.imgur.com/onwLA.png" rel="nofollow"><img src="https://i.stack.imgur.com/onwLA.png" alt="enter image description here"></a></p> <p>If you use:</p> <pre><code> sp + facet_grid(sex ~.) </code></pre> <p>You get two different plots based on sex differences like this: </p> <p><a href="https://i.stack.imgur.com/vVxvy.png" rel="nofollow"><img src="https://i.stack.imgur.com/vVxvy.png" alt="enter image description here"></a></p>
Fill input field when an item has changed in a drop down menu (html,javascript) <p>Im trying to get acquainted with javascript and how to use it with html. What i want to do is very simple, when a value has changed in a dropdownmenu id like to fill an input field with a string.</p> <p>This is the HTML:</p> <pre><code>&lt;div&gt; &lt;input type="text" id="field_id" placeholder="Using..." style="width: 400px"&gt; &lt;select style="width: 180px" onchange="Test()"&gt; &lt;option value="" disabled selected&gt;Select&lt;/option&gt; {% for stuff in stuffs%} &lt;option value="{{stuff}}"&gt;{{stuff}}&lt;/option&gt; {% endfor %} &lt;/select&gt; &lt;/div&gt; </code></pre> <p>And the javascript in the same document:</p> <pre><code>&lt;script&gt; function Test() { document.getElementById(field_id).text = "asdsads"; } &lt;/script&gt; </code></pre> <p>Why wont the input field be filled with the string "asdsads"?</p>
<p>You should give the parameter to <code>getElementById</code> as String:</p> <pre><code>document.getElementById("field_id").value = "asdsads"; </code></pre> <p>Watch for the quotation marks around <code>field_id</code>.</p> <p>In your code the <code>field_id</code> is an (undefined) variable. You should see an error / warning in the Javascript console of your browser.</p> <p>And second: to set the value of an input field you need to set the <code>value</code> attribute, not the <code>text</code> attribute.</p> <p>Here is a working fiddle with your example: <a href="https://jsfiddle.net/oapzL020/" rel="nofollow">https://jsfiddle.net/oapzL020/</a></p>
Using a data_frame as an argument into a mutate and group_by routine <p>I have this data_frame (db) here with lots of columns:</p> <pre><code>A B C D ... ZZ 1 .23 .21 ... .23 2 .45 .12 ... .23 1 .47 ... .53 2 .49 ... .27 </code></pre> <p>I want to employ group_by and mutate with a function which gets a complete data_frame and returns a vector.</p> <pre><code>function1 &lt;- function(data_frame) { ... return(vector) } db %&gt;% group_by(A) %&gt;% mutate(results = function1(.)) </code></pre> <p>This is not working. It returns the results of using the function with the whole data_frame, not with the groups. </p> <p>I know I could solve it using for, but I'm looking for a dplyr solution. The function necessarily gets a data_frame, I'm not passing columns separately as arguments.</p>
<h2><code>dplyr</code></h2> <p>My trick has been to use <code>bind_cols</code>. By itself it won't honor any groups, so you need to nest it within a <code>do</code> block, such as:</p> <pre><code>library(dplyr) mtcars %&gt;% group_by(cyl) %&gt;% do(bind_cols(., { # "insert complex stuff here" data_frame(results = apply(., 1, mean)) })) # Source: local data frame [32 x 12] # Groups: cyl [3] # mpg cyl disp hp drat wt qsec vs am gear carb results # &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; # 1 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 23.59818 # 2 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 24.63455 # 3 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 27.23364 # # ... with 29 more rows </code></pre> <p>On benefit of this approach is that the code in the block can return <strong><em>one or more</em></strong> columns without further complication.</p> <p>So, using your code, it would look something like:</p> <pre><code>db %&gt;% group_by(A) %&gt;% do(bind_cols(., data_frame(results = function(.)))) </code></pre> <h2><code>tidyr</code></h2> <p>Another option is to use <a href="https://github.com/hadley/tidyr" rel="nofollow"><code>tidy</code></a> (RStudio blog <a href="https://blog.rstudio.org/2016/02/02/tidyr-0-4-0/" rel="nofollow">here</a>, though a little out of date it is still useful).</p> <pre><code>library(tidyr) # nest, unnest library(purrr) # map mtcars %&gt;% group_by(cyl) %&gt;% nest() %&gt;% mutate(results = map(data, ~ apply(., 1, mean))) %&gt;% unnest() </code></pre> <p>Your code might be something like (untested):</p> <pre><code>db %&gt;% group_by(A) %&gt;% nest() %&gt;% mutate(results = purrr::map(data, ~ function1(.))) %&gt;% unnest() </code></pre>
HTTP Response 503, however site works <p>At this moment I'm working with the Facebook API; I Need to fill in a Privacy Policy, so I did. However, after some research I discovered that the HTTP Response code will always be 503, But I can't find out why. The page is there, and when visiting it in a Browser it works, with no problem at all. Running a check, shows me that the page returns a 503 to facebook and any other request (For example. <a href="https://httpstatus.io/" rel="nofollow">https://httpstatus.io/</a>).</p> <p>I use cloudflare, nothing more. Why am I getting a 503 Response, but the page is just working fine?</p>
<p>It is possible to have 503 only when robot is visiting the page. Try to simulate Facebook User Agent from your browser or rest client.</p> <p>You can check Facebook user agents on developers facebook page: <a href="https://developers.facebook.com/docs/sharing/webmasters/crawler" rel="nofollow">https://developers.facebook.com/docs/sharing/webmasters/crawler</a></p> <p>Cloudflare could be the cause of your problem, because it blocks bad robots (Facebook should be good robot). Try to disable it and see if it works. If this is the problem, you need to contact Cloudflare support.</p>
What is the Difference between using Cloud or VPS server? <p>What is the Difference between using Cloud or VPS server?</p> <p>I want to know what method get more performance, have more speed and bandwich</p>
<p>Check out these links they should answer your question(s);</p> <p><a href="http://www.rackspace.co.uk/cloud-computing/vps" rel="nofollow">http://www.rackspace.co.uk/cloud-computing/vps</a></p> <p>or</p> <p><a href="https://www.greenhousedata.com/blog/whats-the-difference-between-vps-and-cloud-servers" rel="nofollow">https://www.greenhousedata.com/blog/whats-the-difference-between-vps-and-cloud-servers</a></p>
Update Pandas Cells based on Column Values and Other Columns <p>I am looking to update many columns based on the values in one column; this is easy with a loop but takes far too long for my application when there are many columns and many rows. What is the most elegant way to get the desired counts for each letter?</p> <p>Desired Output:</p> <pre><code> Things count_A count_B count_C count_D ['A','B','C'] 1 1 1 0 ['A','A','A'] 3 0 0 0 ['B','A'] 1 1 0 0 ['D','D'] 0 0 0 2 </code></pre>
<p>The most elegant is definitely the CountVectorizer from sklearn. </p> <p>I'll show you how it works first, then I'll do everything in one line, so you can see how elegant it is. </p> <h3>First, we'll do it step by step:</h3> <p>let's create some data</p> <pre><code>raw = ['ABC', 'AAA', 'BA', 'DD'] things = [list(s) for s in raw] </code></pre> <p>Then read in some packages and initialize count vectorizer</p> <pre><code>from sklearn.feature_extraction.text import CountVectorizer import pandas as pd cv = CountVectorizer(tokenizer=lambda doc: doc, lowercase=False) </code></pre> <p>Next we generate a matrix of counts</p> <pre><code>matrix = cv.fit_transform(things) names = ["count_"+n for n in cv.get_feature_names()] </code></pre> <p>And save as a data frame</p> <pre><code>df = pd.DataFrame(data=matrix.toarray(), columns=names, index=raw) </code></pre> <p>Generating a data frame like this: </p> <pre><code> count_A count_B count_C count_D ABC 1 1 1 0 AAA 3 0 0 0 BA 1 1 0 0 DD 0 0 0 2 </code></pre> <h3>Elegant version:</h3> <p>Everything above in one line</p> <pre><code>df = pd.DataFrame(data=cv.fit_transform(things).toarray(), columns=["count_"+n for n in cv.get_feature_names()], index=raw) </code></pre> <h3>Timing:</h3> <p>You mentioned that you're working with a rather large dataset, so I used the %%timeit function to give a time estimate. </p> <p>Previous response by @piRSquared (which otherwise looks very good!) </p> <pre><code>pd.concat([s, s.apply(lambda x: pd.Series(x).value_counts()).fillna(0)], axis=1) </code></pre> <p><code>100 loops, best of 3: 3.27 ms per loop</code></p> <p>My answer:</p> <pre><code>pd.DataFrame(data=cv.fit_transform(things).toarray(), columns=["count_"+n for n in cv.get_feature_names()], index=raw) </code></pre> <p><code>1000 loops, best of 3: 1.08 ms per loop</code></p> <p>According to my testing, <em>CountVectorizer</em> is about 3x faster. </p>
Removing last added Marker with number on .title <p>I immediately want to point out that I know such methods as setVisible () and remove (), but I do not know how to use them in this particular case. Well, in my application I add markers on the map in different places, which are numbered .titles and would like to make a button that will remove the last added marker. Each successive marker in my application has a feature .title (String.valueOf (f)), where f is the numbers that represent another marker from 0. I might add that the markers are assigned to each collected location saved in the ArrayList.<br> How will look button, which when pressed will remove the last marker from the map? Only last.</p>
<p>hold pointers to them then you will be able to remove them, here is sample:</p> <pre><code>// Somewhere above: private Marker mMyLocationMarker; // Add marker with options mMyLocationMarker = mGoogleMap.addMarker(options); // And to remove: mMyLocationMarker.remove(); </code></pre> <p>need more markers? - hold pointers in <code>List</code>, etc..</p>
Read many files from Kafka <p>I am reading 1 log file in Kafka, and creating a topic. This is succesful. To read this file, I am editing the file <em>config/connect-file-source.properties</em> to this purpose, and according to Step 7 of Kafka Quickstart (<a href="http://kafka.apache.org/quickstart#quickstart_kafkaconnect" rel="nofollow">http://kafka.apache.org/quickstart#quickstart_kafkaconnect</a>).</p> <p>But, now, I would like to read a lot of files. In the file <em>config/connect-file-source.properties</em> I have edited the variable <em>file</em> with a pattern, for instance: <em>file=/etc/logs/archive</em>.log* Because I want to read all the files of the directory logs, with the pattern <strong>archive*.log</strong>. But, this line doesn't work.</p> <p>What is the best form to implement the reading of files with a pattern, using the file <em>config/connect-file-source.properties</em> ?</p> <p>Thanks in advance</p> <p>Kind Regards</p> <p>Dario R</p>
<p>In <code>config/connect-file-source.properties</code>, </p> <p>source class is <code>FileStreamSource</code> and it uses task class as <a href="https://github.com/apache/kafka/blob/41e676d29587042994a72baa5000a8861a075c8c/connect/file/src/main/java/org/apache/kafka/connect/file/FileStreamSourceTask.java#L79" rel="nofollow"><code>FileStreamSourceTask</code></a>.</p> <p>It reads a file using <code>FileInputStream</code>, so it cannot open multiple files at once. (by passing a directory name or regex pattern..)</p> <p>You should implement your own <code>Source</code> &amp; <code>SourceTask</code> class.</p>
Python equivalent of SQL: SELECT w/ MAX() and GROUP BY <p>I have data like this:</p> <pre><code>df = pd.DataFrame( { 'ID': [1,1,2,3,3,3,4], 'SOME_NUM': [8,10,2,4,0,5,1] } ); df ID SOME_NUM 0 1 8 1 1 10 2 2 2 3 3 4 4 3 0 5 3 5 6 4 1 </code></pre> <p>And I want to group by the ID column while retaining the maximum value of SOME_NUM as a separate column. This would be easy in SQL:</p> <pre><code>SELECT ID, MAX(SOME_NUM) FROM DF GROUP BY ID; </code></pre> <p>But I'm having trouble finding the equivalent Python code. Seems like this should be easy. Anyone have a solution?</p> <p>Desired result:</p> <pre><code> new_df ID SOME_NUM 0 1 10 1 2 2 2 3 5 6 4 1 </code></pre>
<p>Seeing as how you are using Pandas... use the groupby functionality baked in</p> <pre><code>df.groupby("ID").max() </code></pre>
Remote build doesn't install dependencies using python 3.2 standard runtime <p>i'm uploading a worker to iron worker running Python 3.2 with in the standard environment, using my own http client directly (not the ruby or go cli) according to the REST API. However, despite having a .worker file along with my python script in a zip file and despite successfully uploading my worker, dependencies are not installed prior to the worker execution, so I get an error like that : </p> <pre><code>Traceback (most recent call last): File "/mnt/task/pakt.py", line 3, in &lt;module&gt; import requests ImportError: No module named requests </code></pre> <p>requests module is declared in my worker file that way :</p> <pre><code>pip "requests" </code></pre> <p>How can I fix this ? thanks .</p>
<p>You should use the new Docker based workflow, then you can be sure you have the correct dependencies, and that everything is working, before uploading. </p> <p><a href="https://github.com/iron-io/dockerworker/tree/master/python" rel="nofollow">https://github.com/iron-io/dockerworker/tree/master/python</a></p>
How to use browser.js to solve es6 class issue in IE 11 <p>I am using javascript classes and ran into the SCRIPT1002 issue in IE 11, where IE is unable to interpret the 'class' keyword that is available in es6. I have been reading that using babel is a way to work around this unfortunate issue. However, I am having issues understanding how to properly do this. below is my code. What do I need to add to allow IE 11 to properly interpret a js class?</p> <p>header including babel.js (browser.js is being loaded properly)</p> <pre><code>&lt;!-- babel --&gt; &lt;script type="text/babel" src="&lt;?php echo $GLOBALS["COMMON_ROOT"]; ?&gt;/scripts/babel-5.8.29/browser.js"&gt;&lt;/script&gt; </code></pre> <p>class in javascript file casuing the SCRIPT 1002 error</p> <pre><code>class assessmentAnswer { constructor(answerID, questionID, answerText, imagePath) { this._answerID = answerID; this._questionID = questionID; this._answerText = answerText; this._imagePath = imagePath; } getAnswerID(){ return this._answerID; } getQuestionID(){ return this._questionID; } getAnswerText(){ return this._answerText; } getImagePath(){ return this._imagePath; } getAll(){ return this.getAnswerID()+","+this.getQuestionID()+","+this.getAnswerText()+","+this.getImagePath(); } } </code></pre> <p>This code runs fine in Firefox.</p>
<p>Don't even try to run babel in ie. It will be awfully slow. Use a compiler toolchain (babel) to create an offline build process, and serve the compiled files. It's true that all modern browsers understand the class keyword, but until you have to support at least one browser that doesn't, you will have to compile. The babel compiler is a complex javascript program, I am sure you don't want to include additional hundreds of kilobytes of js code in your web application. Offline compilation is the way to go.</p> <p>You may wonder why is even babel capable of doing it in the browser: well it was created to support some developer workflows, but nowadays it is mostly unnecessary as browsers implement most of the es6 spec and some esnext specs like async/await too.</p> <p>This so thread should help you to get started: <a href="http://stackoverflow.com/questions/31593694/do-i-need-require-js-when-i-use-babel">Do I need require js when I use babel?</a></p>
How to create one generic RewriteRule for these cases? <p>I have a lot of rules with the same structure as below. Is there any way to have only one that will satisfy all of these cases?</p> <pre><code>RewriteRule ^ecology/?$ /content.php?slug=ecology [NC,L] RewriteRule ^vraveia/?$ /content.php?slug=vraveia [NC,L] RewriteRule ^bonus/?$ /content.php?slug=bonus [NC,L] </code></pre> <p>I tried</p> <pre><code>RewriteRule ^(.+)/?$ /content.php?slug=$1 [NC,L] </code></pre> <p>without luck</p>
<p>Use:</p> <pre><code>RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)/?$ /content.php?slug=$1 [NC,L] </code></pre> <p>This way, you avoid rewriting an existing file or directory</p> <p>With -f you test for files, and with -d for directories. <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond" rel="nofollow">http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond</a></p>
Converting to non-scalar type <p>I have 2 structs of the same size, layout and alignment, but of different types. I would like to copy one onto the other.</p> <pre><code>struct one s1; struct two s2; ... s1 = (struct one)s2; // error: conversion to non-scalar type requested s1 = *((struct one*)&amp;s2); // fine? </code></pre> <p>Is the 2nd method safe &amp; portable?</p> <p>Bonus: What was the thinking of the language designers here, are they making sure I take off the safety before I shoot myself in the foot?</p>
<p>The second method is undefined behaviour due to violating the strict aliasing rule. Even though <code>struct one</code> and <code>struct two</code> have the same layout, it is not permitted to use an lvalue of type <code>struct one</code> to access an object of type <code>struct two</code> or vice versa. </p> <p>In general, accessing an object via an expression of a different type is only allowed for using a character type to access another object; or via a union.</p> <p>An alternative would be:</p> <pre><code>memcpy(&amp;s1, &amp;s2, sizeof s1); </code></pre>