input
stringlengths
51
42.3k
output
stringlengths
18
55k
Need to create animation on clicking any option in MCQ <p>i need to create a MCQ question with 4 options. On clicking any option i need proper correct mark with some color animation over it. how to do this animation part in appcelerator Titanium. Share link to achieve it. </p>
<p>Animations are handled by the view object in Appcelerator. So, for example, if you put your answers in a label object, inside a view, then you can apply a animation. See the documentation and examples here: <a href="http://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.Animation" rel="nofollow">http://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.Animation</a></p>
Creating a jobject in C doesn't work <p>I want to transfer an <code>jobjectArray</code> from C to Java using JNI.<br> Currently, I get the following error:</p> <pre><code>SharedTable.c: In function ‘JAVA_model_JNIResultSet_getSpieler’: SharedTable.c:116:5: warning: passing argument 4 of ‘(*env)-&gt;SetObjectArrayElement’ from incompatible pointer type [enabled by default] ret, i, ptr); </code></pre> <p>I know that I should return a jObject but I don't know how to create it.<br> My struct looks like that:</p> <pre><code>typedef struct _Spieler { char vorname[50]; char nachname[50]; int trikotnummer; struct _Spieler *next; } Spieler; </code></pre> <p>and my code looks like that:</p> <pre><code>Spieler *ptr = head; jobjectArray ret; int i; jclass class = (*env)-&gt;FindClass(env, "model/Spieler"); ret= (*env)-&gt;NewObjectArray(env, count, class, NULL); for(i = 0; i &lt; count; i++) { (*env)-&gt;SetObjectArrayElement(env, ret, i, ptr); ptr = ptr-&gt;next; } return ret; </code></pre>
<p>As <strong>@talex</strong> correctly commented, you cannot fill a Java array with C structures. You should probably declare a Java class that is equivalent to the Spieler structure, and in your loop create each element of the array using a constructor of this Java class.</p> <p>Something like,</p> <pre><code>public class Spieler { private String vorname; private String nachname; private int trikotnummer; public Spieler(String vorname, String nachname, int trikotnummer) { this.vorname = vorname; this.nachname = nachname; this.trikotnummer = trikotnummer; } }; </code></pre> <p>Instead of using constructor, JNI allows you get field IDs of the fields of the Java class, and set them separately (even if they are private).</p>
How to apply each item of the list as the corresponding argument for a function in Scheme <p>I have a list (1 2 3) that I need to apply to the function (f a b c). </p> <p>The first part of the problem was merging two lists to create the list above, now I need to plug in those numbers as arguments. I am not sure how to do this. I was thinking about using apply or map, but I am not confident in how those work or if they would be the right method.</p> <p>Thank you. </p>
<p>You are looking for the procedure <code>apply</code>:</p> <pre class="lang-scm prettyprint-override"><code>(+ 1 2 3) ; ==&gt; 6 (let ((lst '(1 2 3))) (apply + lst)) ; ==&gt; 6 </code></pre> <p>Apply can also take additional arguments before the list.. eg. </p> <pre class="lang-scm prettyprint-override"><code>(let ((lst '(1 2 3))) (apply + 2 lst)) ; ==&gt; 8, same as (+ 2 1 2 3) </code></pre> <p>Also know that <code>+</code> in Scheme is just a variable. It could have been bound in your <code>let</code> as well:</p> <pre class="lang-scm prettyprint-override"><code>(let ((lst '(1 2 3)) (+ (lambda args (apply * args)))) (apply + 2 lst)) ; ==&gt; 12, same as (* 2 1 2 3) </code></pre> <p>So imagine you want to do multiple operations on the same set of data.. eg. what is the result of applying x,y,an z to this list:</p> <pre class="lang-scm prettyprint-override"><code>(let ((lst '(4 3 2)) (procs (list + - * /))) (map (lambda (proc) (apply proc lst)) procs)) ; ==&gt; (9 -1 24 2/3), same as (list (apply + lst) (apply - lst) ...) </code></pre>
How to select data with overdue dates? Mysql <p>I wanted to select data which has an overdue dates. For example, Deadline is 9-9-2016 and the date today is 10-10-2016. Clearly 9-9-2016 is already overdue. Thanks.</p>
<p>Have a look at the <a href="https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html" rel="nofollow">date and time functions</a> in MySql. Depending on the type of your column, you may want to use something like <code>CURRENT_DATE()</code> or <code>CURRENT_TIME()</code>:</p> <pre><code>select * from mytable where mydate &lt; CURRENT_DATE() </code></pre>
Form Method Spoofing in CodeIgniter <p>So I wanna use HTTP DELETE on my route when deleting the data.</p> <p>Is it possible to use method spoofing in CodeIgniter?</p> <p>Maybe like Laravel does by using hidden input "_method" ?</p> <pre><code>&lt;input type="hidden" name="_method" value="DELETE"&gt; </code></pre> <p>Is there any suggestion how to do this in CodeIgniter?</p> <p>Cheers.</p>
<p>You can try the <a href="https://github.com/chriskacerguis/codeigniter-restserver" rel="nofollow">codeigniter restserver</a>. It is full implementation and has DELETE method. Best would be send submit with ajax and remove element from the DOM after delete. Or try to plug angular to your app ;)</p>
What's the difference between void and cv void? <p>I have come across <strong>the type "cv void"</strong> in the latest draft of the C++ standard (<em>N4606</em>) :</p> <blockquote> <h3>8.3.3 [dcl.mptr], paragraph 3</h3> <p>A pointer to member shall not point to a static member of a class (9.2.3), a member with reference type, <strong>or “cv void”</strong>.</p> </blockquote> <p>With a little bit of research, I found <strong>"cv void" is a real type</strong>, but I have no idea what's the difference <strong>compared to the type void</strong>. Can you explain it <strong>with an example</strong> (maybe with a code) ?</p> <hr> <p><strong>EDIT</strong> :</p> <ul> <li>I sort of expected cv would stand for cv-qualified. My question here is, why do we need to "cv-qualify" the type void?</li> <li>The reason I said <strong>"cv void is a real type"</strong> is that, the standard actually defined it: <blockquote> <h3>3.9.1 [basic.fundamental], paragraph 9</h3> <p>A type cv void is an incomplete type that cannot be completed; such a type has an empty set of values...</p> </blockquote></li> </ul>
<p>"cv void" is not a real type. "cv" here is a shorthand for "possibly cv-qualified", which means "may have a <code>const</code> or a <code>volatile</code> on it".</p> <p>The passage means that a pointer-to-member may not point to an object of the following types: <code>void</code>, <code>const void</code>, <code>volatile void</code> and <code>const volatile void</code>. It's fairly obvious, since such objects cannot exist in the first place, but I guess it's nice to be clear.</p>
Borrow checker doesn't realize that `clear` drops reference to local variable <p>The following code reads space-delimited records from stdin, and writes comma-delimited records to stdout. Even with optimized builds it's rather slow (about twice as slow as using, say, awk).</p> <pre><code>use std::io::BufRead; fn main() { let stdin = std::io::stdin(); for line in stdin.lock().lines().map(|x| x.unwrap()) { let fields: Vec&lt;_&gt; = line.split(' ').collect(); println!("{}", fields.join(",")); } } </code></pre> <p>One obvious improvement would be to use <code>itertools</code> to join without allocating a vector (the <code>collect</code> call causes an allocation). However, I tried a different approach:</p> <pre><code>fn main() { let stdin = std::io::stdin(); let mut cache = Vec::&lt;&amp;str&gt;::new(); for line in stdin.lock().lines().map(|x| x.unwrap()) { cache.extend(line.split(' ')); println!("{}", cache.join(",")); cache.clear(); } } </code></pre> <p>This version tries to reuse the same vector over and over. Unfortunately, the compiler complains:</p> <pre class="lang-none prettyprint-override"><code>error: `line` does not live long enough --&gt; src/main.rs:7:22 | 7 | cache.extend(line.split(' ')); | ^^^^ | note: reference must be valid for the block suffix following statement 1 at 5:39... --&gt; src/main.rs:5:40 | 5 | let mut cache = Vec::&lt;&amp;str&gt;::new(); | ^ note: ...but borrowed value is only valid for the for at 6:4 --&gt; src/main.rs:6:5 | 6 | for line in stdin.lock().lines().map(|x| x.unwrap()) { | ^ error: aborting due to previous error </code></pre> <p>Which of course makes sense: the <code>line</code> variable is only alive in the body of the <code>for</code> loop, whereas <code>cache</code> keeps a pointer into it across iterations. But that error still looks spurious to me: since the cache is <code>clear</code>ed after each iteration, no reference to <code>line</code> can be kept, right?</p> <p>How can I tell the borrow checker about this?</p>
<p>The only way to do this is to use <a href="https://doc.rust-lang.org/stable/std/mem/fn.transmute.html"><code>transmute</code></a> to change the <code>Vec&lt;&amp;'a str&gt;</code> into a <code>Vec&lt;&amp;'b str&gt;</code>. <code>transmute</code> is unsafe and Rust will not raise an error if you forget the call to <code>clear</code> here. You might want to extend the <code>unsafe</code> block up to after the call to <code>clear</code> to make it clear (no pun intended) where the code returns to "safe land".</p> <pre><code>use std::io::BufRead; use std::mem; fn main() { let stdin = std::io::stdin(); let mut cache = Vec::&lt;&amp;str&gt;::new(); for line in stdin.lock().lines().map(|x| x.unwrap()) { let cache: &amp;mut Vec&lt;&amp;str&gt; = unsafe { mem::transmute(&amp;mut cache) }; cache.extend(line.split(' ')); println!("{}", cache.join(",")); cache.clear(); } } </code></pre>
Ruby remove new line character between html tags. <p>I would like to remove all the new line characters between </p> <pre><code>&lt;div class="some class"&gt; arbitrary amount of text here with possible new line characters &lt;/div&gt; </code></pre> <p>Is this possible in ruby?</p>
<p>Yes, you can easily do this using the Nokogiri gem. For example:</p> <pre><code>require "rubygems" require "nokogiri" html = %q! &lt;div class="some class"&gt; arbitrary amount of text here with possible new line characters &lt;/div&gt; ! doc = Nokogiri::HTML::DocumentFragment.parse(html) div = doc.at('div') div.inner_html = div.inner_html.gsub(/[\n\r]/, " ").strip puts html puts '-' * 60 puts doc.to_s </code></pre> <p>When run will output this:</p> <pre><code>&lt;div class="some class"&gt; arbitrary amount of text here with possible new line characters &lt;/div&gt; ------------------------------------------------------------ &lt;div class="some class"&gt;arbitrary amount of text here with possible new line characters&lt;/div&gt; </code></pre>
Add Image dynamically in runtime - Unity 5 <p>In my unity based Android game I wish to add the image dynamically based on the number of questions in each level. The image is shown for reference. Each correct answer will be marked in green and the wrong one in red. I am new to unity and trying hard to find steps to achieve this. </p> <p>Any help with an example for this requirement will be a great help.</p> <p><a href="http://i.stack.imgur.com/e13Gj.png" rel="nofollow"><img src="http://i.stack.imgur.com/e13Gj.png" alt="enter image description here"></a></p>
<p>I once wrote a script for dynamically creating buttons based on each level. What I did was creating the first button on the scene and adding the other buttons based on the first one. Below is the shell of my code:</p> <pre><code>// tutorialButton and levelButtons are public variables which can be set from Inspector RectTransform rect = tutorialButton.GetComponent&lt;RectTransform&gt; (); for (int i = 1; i &lt; levelSize; i++) { // Instantiate the button dynamically GameObject newButton = GameObject.Instantiate (tutorialButton); // Set the parent of the new button (In my case, the parent of tutorialButton) newButton.transform.SetParent (levelButtons.transform); //Set the scale to be the same as the tutorialButton newButton.transform.localScale = tutorialButton.transform.localScale; //Set the position to the right of the tutorialButton Vector3 position = tutorialButton.transform.localPosition; position.x += rect.rect.width*i; newButton.transform.localPosition = position; } </code></pre> <p>I am not exactly sure if this is the right approach as it may or may not give unexpected results depending on different screen sizes and your canvas, but hopefully it gives you an idea about dynamically creating objects.</p>
What is a simple way to secure api requests between uwp and asp core <p>I have a uwp application and an ASP Core server application. I want to perform Get and Post requests to the ASP server and I want to perform authorization on the server side.</p> <p>According to the team, they don't want you to use Basic authentication nor seems there be a way to perform digest Authentication. I don't want my client app to show the user any ui: it should be able to perform a secure request by itself.</p> <p>So: what is the most easy and secure protocol to use to perform api requests from UWP to an ASP Core server?</p>
<blockquote> <p>what is the most easy and secure protocol to use to perform api requests from UWP to an ASP Core server?</p> </blockquote> <p>I'd like to say this is a open question and I will give some suggestions and hope it can help you. Basic authentication and digest authentication you mentioned are defined in <a href="http://www.ietf.org/rfc/rfc2617.txt" rel="nofollow">rfc2617</a>. Since you don't want to use them, besides HTTP Basic/Digest you may have other choices like OAuth, HMAC and Azure API Management.</p> <ol> <li>Since you don't want the user to input username and password, to request an access token for authentication may meet your requirements. So I recommend you to use OAuth authentication which is popular. More details about OAuth2.0 please reference <a href="https://oauth.net/2/" rel="nofollow">this</a>. But it requires OAuth server, it may not be a easiest way.</li> <li><p>Another way you can apply HMAC authentication to secure Web Api. HMAC authentication uses a secret key for each consumer. For more details about HMAC authentication please reference <a href="http://%20http://stackoverflow.com/questions/11775594/how-to-secure-an-asp-net-web-api" rel="nofollow">this thread</a>. For more details about HMAC in uwp please reference <a href="https://msdn.microsoft.com/en-us/windows/uwp/security/macs-hashes-and-signatures" rel="nofollow">MACs, hashes, and signatures</a>. </p></li> <li><p>You can also use third party tools from Azure. <a href="https://azure.microsoft.com/en-us/services/api-management/" rel="nofollow">Azure API management</a> can help secure and optimize your APIs. Details please reference the <a href="https://msdn.microsoft.com/en-us/windows/uwp/security/intro-to-secure-windows-app-development#33-publishing-and-securing-access-to-rest-apis" rel="nofollow">Publishing and securing access to REST APIs</a> in uwp.</p></li> </ol>
Is it possible to disable the focus ring animation in Cocoa for a single app? <p>On macOS, you can disable the focus ring animation system-wide with this command:</p> <p><code>defaults write -globalDomain NSUseAnimatedFocusRing -bool NO</code></p> <p>Is there a way to do it in Cocoa for just your own app? I don't want to disable the focus ring altogether. I just want to disable (or modify) the jarring animation.</p>
<p>I ended up just using the <code>NSUseAnimatedFocusRing</code> constant in my own app instead of setting it globally.</p> <pre><code>func applicationDidFinishLaunching(_ aNotification: Notification) { // Disable focus ring animation. UserDefaults.standard.set(false, forKey: "NSUseAnimatedFocusRing") // etc... } </code></pre>
Removing punctuation/symbols from a list with Python except periods, commas <p>In Python, I need to remove almost all punctuation from a list but save periods and commas. Should I create a function to do this or a variable? Basically I want to delete all symbols except letters (I've already converted uppercase letters to lowercase) and periods and commas (and maybe apostrophes). </p> <pre><code>#Clean tokens up (remove symbols except ',' and '.') def depunctuate() clean_tokens = [] for i in lc_tokens: if (i not in [a-z.,]) ... </code></pre>
<p>You can build a set of unwanted punctuation from <a href="https://docs.python.org/2/library/string.html#string.punctuation" rel="nofollow"><code>string.punctuation</code></a> - which provides a string containing punctuation, and then use a <em>list comprehension</em> to filter out the letters contained in the set:</p> <pre><code>import string to_delete = set(string.punctuation) - {'.', ','} # remove comma and fullstop clean_tokens = [x for x in lc_tokens if x not in to_delete] </code></pre>
My program will not print, closes immediately after entering a number (C) <pre><code>#include &lt;stdio.h&gt; int main() { int input, i, sum = 0; printf("Please enter a number between 1 and 5: "); scanf_s("%d", &amp;input); for (i = 0; i &lt; 5; i++) { sum += input + i; } printf("Sum = %d\n", sum); return 0; } </code></pre> <p>When I open it up, it asks the question but as soon as I enter a number it closes without printing what the sum is.</p>
<p>Use ctrl+F5 to run the program.</p>
Falcon parsing json error <p>I'm trying out Falcon for a small api project. Unfortunate i'm stuck on the json parsing stuff and code from the documentation examples does not work.</p> <p>I have tried so many things i've found on Stack and Google but no changes. I've tried the following codes that results in the errors below</p> <pre><code>import json import falcon class JSON_Middleware(object): def process_request(self, req, resp): raw_json = json.loads(req.stream.read().decode('UTF-8')) """Exception: AttributeError: 'str' object has no attribute 'read'""" raw_json = json.loads(req.stream.read(), 'UTF-8') """Exception: TypeError: the JSON object must be str, not 'bytes'""" raw_json = json.loads(req.stream, 'UTF-8') """TypeError: the JSON object must be str, not 'Body'""" </code></pre> <p>I'm on the way of giving up, but if somebody can tell me why this is happening and how to parse JSON in Falcon i would be extremely thankful.</p> <p>Thanks</p> <p>Environment: OSX Sierra Python 3.5.2 Falcon and other is the latest version from Pip</p>
<p>your code should work if other pieces of code are in place . a quick test(filename app.py):</p> <pre><code>import falcon import json class JSON_Middleware(object): def process_request(self, req, resp): raw_json = json.loads(req.stream.read()) print raw_json class Test: def on_post(self,req,resp): pass app = application = falcon.API(middleware=JSON_Middleware()) t = Test() app.add_route('/test',t) </code></pre> <p>run with: <code>gunicorn app</code><br> <code>$ curl -XPOST 'localhost:8000' -d '{"Hello":"wold"}'</code></p>
How does placement new know which layout to create? <pre><code>#include &lt;iostream&gt; #include &lt;typeinfo&gt; struct A { int a; }; struct B : virtual A { int b; }; struct C : virtual A { int c; }; struct D : B,C { int d; }; int main() { D complete; B contiguous; B &amp; separate = complete; B * p[2] = {&amp;separate, &amp;contiguous}; // two possible layouts for B: std::cout&lt;&lt; (int)((char*)(void*) &amp;p[0]-&gt;a -(char*)(void*)&amp;p[0]-&gt;b)&lt;&lt;" "&lt;&lt; sizeof(*p[0])&lt;&lt; "\n"; std::cout&lt;&lt; (int)((char*)(void*) &amp;p[1]-&gt;a -(char*)(void*)&amp;p[1]-&gt;b)&lt;&lt;" "&lt;&lt; sizeof(*p[1])&lt;&lt; "\n"; alignas(B) char buff[sizeof(B)]; void * storage = static_cast&lt;void*&gt;(buff); // new expression skips allocation function: auto pointer= new (storage) B; // Which layout to create? std::cout &lt;&lt; typeid(pointer).name()&lt;&lt;"\n"; pointer-&gt;~B(); // Destructor knows layout through typed pointer. } // sample output (Debian 8, amd64): // 24 16 // 4 16 // P1B </code></pre> <p>Is there a section in the <em>C++14 standard</em> that reqires 'new' to create a particular layout? Is there guarantee that the layout created by new fits into a buffer of size sizeof(B) and with offset zero?</p> <hr> <p>edit: Could you please use grep-friendly terminology or provide references? I added a reference to the standard to the question.</p> <p>Take into consideration the sample output above: What does the number 24 tell you? What is the size of the buffer?</p> <p>There might be a statement in the standard that a most derived object is always a straightforward, contiguous copy of the object representation, but I haven't found this one.</p> <p>The thing we know about new is that it shall be used with a complete object type. [expr.new]</p> <p>There is an example for a new-expression with the placement option in [class.dtor] §12.4 (14). However, the example might work simply because the class therein is standard-layout.</p>
<blockquote> <p><em>Where is the guarantee that the layout created by new fits into a buffer of size sizeof(B) and with offset zero</em></p> </blockquote> <p>From the the type being named in <code>new</code> as its argument being <code>B</code>. A <code>B</code> is being made, not an <code>D</code>. The type <code>B</code> "knows nothing" about <code>D</code>. The declaration of <code>D</code> has no influence on <code>B</code>; the <code>B</code> declaration can be put into translation units in which <code>D</code> doesn't appear, yet everywhere in the program there will be agreement about the size of <code>B</code> and is layout, regardless of whether <code>D</code> is also known in those places or not.</p> <p>A C++ object of type <code>T</code> has a size <code>sizeof T</code>. This means that it fits into <code>sizeof T</code> bytes; it cannot be the case that <code>(sizeof T) + k</code> bytes are required for its representation, where <code>k &gt; 0</code>.</p>
How to create customize report in c#.net windows application and eliminate white space of hidden columns <p>I am developing C# windows application and I want to report From sqlserver database.so I added Dataset to my project And I added report.rdlc to my project.the point is that I want to select the field programmatically after that show that fiels in the report for user.it means that I want to customize the report and I know it wiill create white space between columns .how can I remove this white spaces so I want to know how to do this in c#</p> <p>code :</p> <pre><code> ReportDataSet ds = new ReportDataSet(); DataTable dt = new DataTable(); PersianCalendar p = new PersianCalendar(); SqlDataAdapter sqlda = new SqlDataAdapter("SelectPersonelWithID", new SqlConnection(DBsetting.Connstring)); sqlda.SelectCommand.CommandType = CommandType.StoredProcedure; sqlda.SelectCommand.Parameters.AddWithValue("@ID", comboBox1.SelectedValue); dt.Clear(); ds.Clear(); sqlda.Fill(ds, ds.Tables[2].TableName); sqlda.Fill(dt); this.reportViewer1.RefreshReport(); if (dt.Rows.Count &gt; 0) { ReportDataSource rds = new ReportDataSource("DataTable3", ds.Tables[2]); ReportParameter rpt1 = new ReportParameter("ReportParameter1", dt.Rows[0]["name"].ToString()); ReportParameter rpt2 = new ReportParameter("ReportParameter2", p.GetYear(DateTime.Now) + " / " + p.GetMonth(DateTime.Now) + " / " + p.GetDayOfMonth(DateTime.Now)); this.reportViewer1.LocalReport.SetParameters(rpt1); this.reportViewer1.LocalReport.SetParameters(rpt2); this.reportViewer1.LocalReport.DataSources.Clear(); this.reportViewer1.LocalReport.DataSources.Add(rds); this.reportViewer1.LocalReport.Refresh(); this.reportViewer1.RefreshReport(); } </code></pre> <p><a href="http://i.stack.imgur.com/RljFD.jpg" rel="nofollow">I Want Report Like The Picture</a></p>
<p>You need to create boolean value parameter for each of the columns that user selects for display in RDLC report. Pass all these parameters to RDLC report. Set the Visibility > Hidden property of each columns with respective parameter.</p> <p>For example, 'Age' column is to be excluded and say @AgeVisible is the boolean parameter with value <em>false</em>. Then, select the 'Age' column (<em>not the textbox but the column</em>) and set the property Visibility > Hidden to expression <code>=Iif(@AgeVisible, False, True)</code></p> <p>Following picture might help you what I am saying.<a href="http://i.stack.imgur.com/zksfW.png" rel="nofollow"><img src="http://i.stack.imgur.com/zksfW.png" alt="See the Picture for help"></a></p> <p><strong>To make visible columns expand and fill the space of excluded (hidden) columns so that report width is maintained, more work needs to be done.</strong></p> <p>The rdlc file is an xml document. It defines column widths as following xml (<em>This is specific to RDLC file created using Visual Studio 2005, it may differ for other version</em>). Below xml suggests that there are 6 columns in the table.</p> <pre><code> &lt;TableColumns&gt; &lt;TableColumn&gt; &lt;Width&gt;0.5in&lt;/Width&gt; &lt;/TableColumn&gt; &lt;TableColumn&gt; &lt;Width&gt;1.125in&lt;/Width&gt; &lt;/TableColumn&gt; &lt;TableColumn&gt; &lt;Width&gt;1in&lt;/Width&gt; &lt;/TableColumn&gt; &lt;TableColumn&gt; &lt;Width&gt;1in&lt;/Width&gt; &lt;/TableColumn&gt; &lt;TableColumn&gt; &lt;Width&gt;0.5in&lt;/Width&gt; &lt;/TableColumn&gt; &lt;TableColumn&gt; &lt;Width&gt;1.375in&lt;/Width&gt; &lt;/TableColumn&gt; &lt;/TableColumns&gt; </code></pre> <p>Basically logic is simple, just increase the width of visible columns. But its implementation requires few lines of code.</p> <ol> <li><p>Calculate the sum of width of hidden columns and then re-calculate width of visible columns</p> <pre><code> float[] resizedwidth; // code for recalculation goes here </code></pre></li> <li><p>Read entire report xml into string variable 'rptxml'</p> <pre><code> String rptxml = System.IO.File.ReadAllText(@"D:\SO\WinFormQ\WinFormQ\Report1.rdlc"); </code></pre></li> <li><p>Replace above xml segment with modified xml segment</p> <pre><code> int start = rptxml.IndexOf("&lt;TableColumns&gt;"); int end = rptxml.IndexOf("&lt;/TableColumns&gt;") + "&lt;/TableColumns&gt;".Length; String resizedcolumns = String.format( "&lt;TableColumns&gt;" + "&lt;TableColumn&gt;&lt;Width&gt;{0}in&lt;/Width&gt;&lt;/TableColumn&gt;" + "&lt;TableColumn&gt;&lt;Width&gt;{1}in&lt;/Width&gt;&lt;/TableColumn&gt;" + "&lt;TableColumn&gt;&lt;Width&gt;{2}in&lt;/Width&gt;&lt;/TableColumn&gt;" + "&lt;TableColumn&gt;&lt;Width&gt;{3}in&lt;/Width&gt;&lt;/TableColumn&gt;" + "&lt;TableColumn&gt;&lt;Width&gt;{4}in&lt;/Width&gt;&lt;/TableColumn&gt;" + "&lt;TableColumn&gt;&lt;Width&gt;{5}in&lt;/Width&gt;&lt;/TableColumn&gt;" + "&lt;/TableColumns&gt;" , resizedwidth[0], resizedwidth[1], resizedwidth[2], resizedwidth[3], resizedwidth[4], resizedwidth[5] ); rptxml = rptxml.Substring(0, start) + resizedcolumns + rptxml.Substring(end); </code></pre></li> <li><p>Create TextReader from string variable 'rptxml' </p> <pre><code> TextReader tr = new StringReader(rptxml); </code></pre></li> <li><p>Use LoadReportDefinition() method to load the modified report definition</p> <pre><code> reportViewer1.LocalReport.LoadReportDefinition(tr); </code></pre></li> </ol> <p>Continue with specifying DataSources and ReportParameters etc. and finally display the report. <em>NOTE:</em> Don't forget to close TextReader <code>tr.Close()</code>.</p>
setState(...): Can only update a mounted or mounting component. where is the culprit? <p>I got this warning.</p> <p>Warning: setState(...): Can only update a mounted or mounting component.</p> <p>How do I know which setState is throwing it? I put a log in front of all setState and none is being print. There should be a better method? I suspect it's coming from a callback or listener somewhere.</p> <p>Thanks a lot!</p>
<p>Have you tried this?</p> <pre><code>console.log(this.state.WHATYOUNEED) </code></pre>
Format command invocation string with multiple options <p>I have a function <code>ping</code> that needs to pass a string of a format<br> <code>ping mpls ipv4 &lt;ip here&gt; &lt;param name&gt; &lt;valiue&gt; &lt;param name&gt; &lt;valiue&gt; ...</code><br> to a testbed device's method.</p> <pre><code>def ping(device, ip_address, **kwargs): options = ['destination', 'dsmap', 'exp', 'fec-type', 'flags', 'force-explicit', 'interval', 'output', 'pad', 'repeat', 'reply', 'session', 'size', 'source', 'sweep', 'timeout', 'ttl', 'verbose'] for key, value in kwargs.items(): if key in options: cmd ="ping mpls ipv4 {0} {1} {2}".format(ip_address, key, value) output = device.execute(cmd) return output </code></pre> <p>Example usage:</p> <pre><code>ping(device, ip, size='100', interval='10', sweep='100 1500 100') </code></pre> <p><code>device</code> is a testbed device and <code>ip</code> is a string containing an IPv4 IP.</p> <p>The problem is that it calls the <code>device.execute</code> once for every keyword argument I specify and only returns the last return value. How can this be fixed?</p>
<p>Does this help?</p> <pre><code>valid_options = ('{} {}'.format(key, value) for key, value in kwargs.items() if key in options) cmd_options = ' '.join(valid_options) cmd = 'ping mpls ipv4 {} {}'.foramt(ip_address, cmd_options) </code></pre> <p>BTW I recommend you to learn about <a href="//anandology.com/python-practice-book/iterators.html#generator-expressions" rel="nofollow">generator expressions</a> and <a href="//docs.python.org/3/library/itertools.html" rel="nofollow">itertools</a>. They wold save you from the "pyramid of doom" antipattern (lots of netted loops and conditions) clearly visible in your <code>test_001</code> function.</p>
Can we use addOptional and addParameter together? <p>inputParser provides addOptional and addParameter. The doc (<a href="https://www.mathworks.com/help/matlab/ref/inputparser-class.html" rel="nofollow">https://www.mathworks.com/help/matlab/ref/inputparser-class.html</a>) says</p> <blockquote> <p>You can define your scheme by calling <code>addRequired</code>, <code>addOptional</code>, and <code>addParameter</code> in any order, but when you call your function that uses the input parser, you should pass in required inputs first, followed by any optional positional inputs, and, finally, any name-value pairs.</p> </blockquote> <p>But I cannot make this work, and got the following error. </p> <pre><code>K&gt;&gt; a = inputParser; K&gt;&gt; addOptional(a, 'o', 'x'); K&gt;&gt; addParameter(a, 'p', 1); K&gt;&gt; parse(a, 'w', 'p', 2) </code></pre> <p>The argument <code>'w'</code> is a string and does not match any parameter names. It failed validation for the argument <code>'o'</code>.</p> <p>If we define the default value as number.</p> <pre><code>a = inputParser; addOptional(a, 'o', 42); addParameter(a, 'p', 1); parse(a, 'p', 2); parse(a, 3, 'p', 2); parse(a, 3); </code></pre> <p>it works.</p> <p>Did I miss anything?</p>
<p>I do not recommended the use of <code>inputParser</code> with optional arguments that are allowed to be character arrays, because <code>parse()</code> cannot distinguish if the user passes a parameter name (which is always of type <code>char</code>) or the optional input argument. Thus, it is a logical consequence of this behaviour why you cannot pass a <code>char</code> as an optional input argument.</p> <p>However, if you specify a validation function for the optional input arguments that may be <code>char</code>, you can make it work. From the <a href="https://mathworks.com/help/matlab/ref/inputparser.addoptional.html#bs8nb4r-3" rel="nofollow"><code>addOptional</code></a> documentation under section ‘Tips’:</p> <blockquote> <p>For optional string inputs, specify a validation function. Without a validation function, the input parser interprets valid string inputs as invalid parameter names and throws an error.</p> </blockquote> <p>This is the error your example generated.</p> <h1>Fixing your example</h1> <p><code>'o'</code> is the optional input argument. If you know how to validate the values <code>'o'</code> needs to accept, provide a validation function that returns <code>true</code> for those valid inputs. For example, if you know <code>'o'</code> will always be a <code>char</code> array, try the following (line by line).</p> <pre><code>a = inputParser; addOptional(a, 'o', 'default', @ischar); addParameter(a, 'p', 1); parse(a, 'x'); % OK parse(a, 'Hello, World!', 'p', 2); % OK parse(a, 'p', 'p', 'p') % OK, although quite cryptic parse(a, 3); % Throws an error, as expected, because 3 is not a char parse(a, 'p', 4) % Throws a somewhat unexpected error, because we meant to set parameter 'p' to value 4 </code></pre> <p>The last line seems counter-intuitive, but it's not! We'd expect the parser to detect the parameter <code>'p'</code> instead of implicitly assuming it is the character we provide for optional argument <code>'o'</code>, which we wanted to omit. It is the expected behaviour, though, as I will explain now.</p> <h1>Why <code>char</code> optionals give <code>inputParser</code> a hard time</h1> <p>The demonstrated bahviour is expected because both the optional and parameter arguments are not required, i.e., optional. If you'd have two optional input arguments, <code>'o1'</code> and <code>'o2'</code>, their order matters to the input parser (which is why the MATLAB documentation calls them ‘optional <em>positional</em> arguments’). You could never pass a value for <code>'o2'</code> before a value for <code>'o1'</code>. This implies <code>'o2'</code> can only be used if <code>'o1'</code> is also specified. In other words, <code>'o1'</code> impedes the use of any other optional arguments.</p> <p>The same is true for parameters, which should always come after other optional input arguments (as you already quoted). As such, they behave like optionals if any optional input arguments are allowed to be <code>char</code>. The result is MATLAB's <code>inputParser</code> not knowing if a <code>char</code> input is an optional input argument or a parameter. MATLAB's developers have decided to require explicit ordering of optional inputs, so MATLAB can be sure what optional arguments are passed to <code>parse()</code>.</p> <h1>Suggested action if optional inputs may be <code>char</code></h1> <p>Because using optional input arguments requires MATLAB to assume some input arguments referring to an optional input argument, others referring to parameters, this may result in errors, behaviour or results unexpected by the end-user if not all optional arguments are specified.</p> <p>Input argument schemes are better if written explicitly to prevent this unexpected implicit behaviour. I suggest that if optional input arguments are required that accept <code>char</code> input, you always make them parameters, i.e., name-value pair arguments using <code>addParameter</code>. Using optional input arguments that accept <code>char</code> input only works if not using any parameters, or by explicitly stating (e.g. in the help) that parameter input argument can be used if and only if all optional input arguments are given as well.</p>
Action bar only shows one item next to search view <p>I want to have a search view and two buttons in the Action Bar. So I created menu/options_menu.xml:</p> <pre><code>&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:id="@+id/action_search" android:title="Search" android:icon="@drawable/ic_menu_search" android:showAsAction="always" android:actionViewClass="android.widget.SearchView" /&gt; &lt;item android:title="Route" android:id="@+id/action_route" android:icon="@drawable/route" android:showAsAction="always" /&gt; &lt;item android:title="Cancel" android:id="@+id/action_cancel" android:icon="@drawable/cancel" android:showAsAction="always" /&gt; &lt;/menu&gt; </code></pre> <p>I am inflating it in code:</p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false); return true; } </code></pre> <p>This is what I get:</p> <p><a href="http://i.stack.imgur.com/hTvFs.png" rel="nofollow"><img src="http://i.stack.imgur.com/hTvFs.png" alt="enter image description here"></a></p> <p>As you can see, only the first item ("route") is shown. I can make second item ("cancel") visible if I let iconify the search widget:</p> <pre><code> //searchView.setIconifiedByDefault(false); </code></pre> <p><a href="http://i.stack.imgur.com/p4Rxk.png" rel="nofollow"><img src="http://i.stack.imgur.com/p4Rxk.png" alt="enter image description here"></a></p> <p>However, I want to have search widget expanded and both items visible. Is it possible?</p> <p><strong>Update</strong></p> <p>I managed to make them visible by setting <code>android:orderInCategory="1"</code> for "Route" and "Cancel" and <code>android:orderInCategory="2"</code> for the search widget:</p> <p><a href="http://i.stack.imgur.com/IRQTk.png" rel="nofollow"><img src="http://i.stack.imgur.com/IRQTk.png" alt="enter image description here"></a></p> <p>This is almost what I wanted. The issue is that I want search widget to go first (leftmost), and then these two items. Is it possible?</p> <p><strong>Update 2</strong></p> <p>I tried "recommended" way. I set for <code>SearchView</code>:</p> <pre><code>android:showAsAction="always|collapseActionView" </code></pre> <p>After I click on search icon, I get expanded view:</p> <p><a href="https://i.stack.imgur.com/TlthU.png" rel="nofollow"><img src="https://i.stack.imgur.com/TlthU.png" alt="enter image description here"></a></p> <p>Two problems:</p> <ol> <li>(Minor) Navigation UI occupies a room on the left thus reducing space available for <code>SearchView</code>.</li> <li>(Major) Android icon appears as a part of navigation UI. Can I get rid of it? </li> </ol>
<p>Created one demo, check it :</p> <p><strong>menu.xml :</strong></p> <pre><code>&lt;menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"&gt; &lt;item android:id="@+id/action_search" android:title="Search" android:icon="@android:drawable/ic_search_category_default" app:actionLayout="@layout/searchview" app:showAsAction="always|collapseActionView"/&gt; &lt;item android:title="Route" android:id="@+id/action_route" android:icon="@mipmap/ic_launcher" app:showAsAction="always" /&gt; &lt;item android:title="Cancel" android:id="@+id/action_cancel" android:icon="@mipmap/ic_launcher" app:showAsAction="always" /&gt; &lt;/menu&gt; </code></pre> <p><strong>searchview.xml :</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;SearchView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; </code></pre> <p><strong>Java :</strong></p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); if(searchItem!=null) { searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false); } return true; } </code></pre> <p><strong>Edited Java Based on Requirement (Always open searchview) :</strong></p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); MenuItem searchItem = menu.findItem(R.id.action_search); searchItem.expandActionView(); final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); if(searchItem!=null) { searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false); // This listener use for handle back press if you want to go back without collapsing searchview MenuItemCompat.setOnActionExpandListener(searchItem,new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem item) { return true; } @Override public boolean onMenuItemActionCollapse(MenuItem item) { onBackPressed(); return false; } }); } return true; } </code></pre> <p><strong>Screenshots :</strong></p> <p><a href="https://i.stack.imgur.com/eInKIl.png" rel="nofollow"><img src="https://i.stack.imgur.com/eInKIl.png" alt="Without click"></a> <a href="https://i.stack.imgur.com/rqvc6l.png" rel="nofollow"><img src="https://i.stack.imgur.com/rqvc6l.png" alt="With click"></a></p>
display data from selected option from vue component <p>How can I display the data from selected option, like in the example from docs <a href="http://vuejs.org/guide/forms.html#Select" rel="nofollow">vuejs.org</a> but with component?</p> <pre><code>&lt;div id="app"&gt; &lt;selection&gt;&lt;/selection&gt; &lt;div v-if="post"&gt; selected post: {{post.title}} &lt;/div&gt; &lt;div v-else&gt; no posts &lt;/div&gt; &lt;/div&gt; </code></pre> <p>main.js</p> <pre><code>Vue.component('selection', { template: "&lt;select v-model='post'&gt;&lt;option v-for='post in posts' v-bind:value='post.val'&gt;{{post.title}}&lt;option&gt;&lt;/select&gt;", data: function() { return { posts: [{ title: "lorem ipsum 1", val: '1' }, { title: "lorem ipsum 2", val: '2' }, { title: "lorem ipsum 3", val: '3' } ], post: null } }, }) new Vue({ el: "#app", data: { post: null } }).$mount('#app') </code></pre> <p><a href="https://jsfiddle.net/cthe6qva/" rel="nofollow">fiddle</a></p>
<p>You can make your <a href="http://vuejs.org/guide/components.html#Form-Input-Components-using-Custom-Events" rel="nofollow">component work with the v-model directive</a> by implementing two features:</p> <ul> <li>accept a <code>value</code> prop</li> <li>emit an <code>input</code>event with the new value</li> </ul> <p>First off, change your template to bind your <code>select</code> tag to the entire <code>post</code> object (not just the val property):</p> <pre><code>template: "&lt;select v-model='post'&gt;&lt;option v-for='post in posts' v-bind:value='post'&gt;{{post.title}}&lt;option&gt;&lt;/select&gt;" </code></pre> <p>Declare your component to have a 'value' property:</p> <pre><code>props: ['value'] </code></pre> <p>Now <code>watch</code> the component's <code>post</code> property and emit an <code>input</code> event with the selected post:</p> <pre><code> watch: { post: function() { this.$emit('input', this.post); } } </code></pre> <p>Then you simply use the <code>v-model</code> directive on your custom component:</p> <pre><code>&lt;selection v-model="post"&gt;&lt;/selection&gt; </code></pre> <p>Here is a <a href="https://jsfiddle.net/psteele/auL8ouds/" rel="nofollow">complete jsFiddle</a> showing this in action.</p>
On Copying Garbage <p>A couple of days ago I had a small discussion here about the copying of, let's call it <em>garbage</em> because that's what is actually is, from one array to another and if that is acceptable in standard C (ISO/IEC 9899-2011) or not.</p> <p>Wrapped in some example-code for clarity:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define ARRAY_SIZE 10 /* ? = any byte with ('?' != '?' || '?' == '?'), that is: '?' may or may not be equal to '?'. tl;dr: just random garbage 'x' = a one byte large (not necessary ASCII-encoded) known and defined character. tl;dr: neither random nor garbage */ int main(){ // array = [?,?,?,?,?,?,?,?,?,?] char array[ARRAY_SIZE]; // copy = [?,?,?,?,?,?,?,?,?,?] char copy[ARRAY_SIZE]; int i; // fill a part of "array" with a NUL terminated string // "part" is not necessary half+1 of it, the only condition is: #part &lt; ARRAY_SIZE // such that we have at least one byte of garbage for(i = 0;i &lt; ARRAY_SIZE/2;i++){ // casting "i" is a bit "holier than the pope", admitted array[i] = (char)i + '0'; } array[i] = '\0'; // array = ['0','1','2','3','4','\0',?,?,?,?] // "use" the array "array" printf("array = %s\n",array); // copy all of the elements of "array" to "copy" including // the garbage at the end for(i = 0;i &lt; ARRAY_SIZE;i++){ copy[i] = array[i]; } // copy = ['0','1','2','3','4','\0',?,?,?,?] // "use" the array "copy" printf("copy = %s\n",copy); // no further use of either "array" or "copy". // obvious at the end of main() but meant generally, of course exit(EXIT_SUCCESS); } </code></pre> <p>The paragraph in the standard that defines those kid of arrays is in the list of derived types:</p> <blockquote> <p><strong>6.2.5 Types</strong></p> <p><em>20</em> Any number of derived types can be constructed from the object and function types, as follows:</p> <ul> <li>An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type. The element type shall be complete whenever the array type is specified. Array types are characterized by their element type and by the number of elements in the array. An array type is said to be derived from its element type, and if its element type is <em>T</em>, the array type is sometimes called "array of <em>T</em>". The construction of an array type from an element type is called "array type derivation".</li> </ul> </blockquote> <p>My question is: does "nonempty set" just mean that the <code>n</code> (where <code>n</code> stands in for an integer literal; it has nothing to do with VLAs) in the declaration <code>T a[n]</code> must be greater than zero?</p> <p>For those of you who need a practical reason: in the realtime area a well defined number of operations is preferred over an unknown amount. It is also slower a large part of the times (assuming a random distribution of the input) because of the necessary measurement and this overhead matters a lot in the embeded area. Every saved nano-amperehour counts when the battery needs to keep enough juice to run it for a couple of years.</p>
<p>Yes, it means ARRAY_SIZE must be greater than zero. At this level you should probably leave the optimization to the compiler. But if the ARRAY_SIZE is a defined constant, you can optimize by an array which its elements are the same size as your CPU registers. your array size should be an integer multiple of the size of your registers. for more optimization you should dig into assembler outputs.</p>
Why would I use getters and setters or properties while I can do all the logic inside the constructor? <p>Why would I use getters and setters or properties while I can do all the logic inside a constructor?</p> <pre><code>class Example{ private int ID; private string name; //constructor public Example (string name, int id){ if (name == "" || name == null) { throw new Exception("name cannot be null or empty");}else{this.name = name;} if (id &lt; 0) { throw new Exception("ID cannot be negative"); } else { this.ID = id; } } } </code></pre>
<p>You cant get that variables since they are private. For the question, if you do not want to get/set values, you don't need them. But the advantages of properties are calculations for all the time.</p> <p>For example:</p> <pre><code>get { return myString == null ? string.Empty : myString } set { !string.IsNullOrEmpty(value) ? value : "" } </code></pre>
Tool to create Hand Held Units and Mobiles (Android, iOS, Winphones and WinCE) and that should/ can support legacy unmanaged library (DLL) <p>We are exploring to create an application that should work on Desktop (Windows 7/8.1/10) as well as on Hand Held Units and Mobiles (Android, iOS, Winphones and WinCE).</p> <p>We have a legacy unmanaged library (DLL) implemented in Delphi programming language for desktop which communicates to the external(embedded) devices.</p> <ol> <li>Can we use Xamarin in this case to create such an application?</li> <li>Is there any way to reuse the legacy unmanaged library (DLL) on other platforms?</li> <li>If we want to reuse the code, Can we create a C# based portable library that can be used on Desktop, Hand Held Units and mobiles?</li> <li>Does Xamarin has in-built APIs, libraries to support communication to external devices on Serial Port, USB, Wi-Fi and Bluetooth?</li> </ol>
<ol> <li>yes, but not Windows CE</li> <li>No</li> <li>Yes, but not Windows CE</li> <li>Xamarin provides C# bindings for the native platform APIs. If you can do it natively on the platform, you should be able to do it via Xamarin.</li> </ol>
Add margin on both sides of free space(background) in Html - css page <p>I am trying to add margin on both sides of free space in Html. and fill background in the middle remaining part only.</p> <p>But this id doesn't work when i put it in body tag.</p> <pre><code>#bodyid{ display: block; margin-left: 100px; margin-right: 100px; background-color: #E3EAEA; } </code></pre> <p>above given colors are random. Result should be like this.</p> <p><img src="http://i.stack.imgur.com/Z4S1s.png" alt="capture[![this should be the result">]<a href="http://i.stack.imgur.com/Z4S1s.png" rel="nofollow">1</a></p> <p>Thanks for helping.</p>
<p>Just make body white and add a container <code>div</code>. Like here: <a href="https://jsfiddle.net/p1mz721k/" rel="nofollow">https://jsfiddle.net/p1mz721k/</a></p>
Traversing through a linked list in C, get caught in Loop <p>I keep getting caught in a loop but i dont know how to fix it. We have to traverse through the list. It prints but it doesn't move on to the next test function. I don't think the code is recognizing the end of the list and isn't exiting the while loop.</p> <pre><code>void traverse_int(struct s_node* head) { struct s_node* next_node; int* x; next_node=head; while(next_node != NULL) { if (next_node-&gt;elem == NULL) { my_str("NULL"); } else { x=(int*) next_node-&gt;elem; my_int(*x); } my_str(" "); next_node=next_node-&gt;next; } my_char('\n'); } </code></pre> <p>this is the test case that i am using: </p> <pre><code> a = 17; b = 10; c = 16; d = 95; add_elem(&amp;a, &amp;head); add_elem(&amp;b, &amp;head); add_elem(&amp;c, &amp;head);= add_elem(&amp;d, &amp;head); traverse_int(head); my_str("\nshould print 95 16 10 17\n"); </code></pre> <p>It does not print my_str it just gets caught and prints: 95 16 10 17 </p> <p>it should print:</p> <p>95 16 10 17</p> <p>should print 95 16 10 17</p> <p>Please help!!</p>
<p>I'm old but with link lists like your stack thing here I see you need to assign a NULL value to the tail of your linked list first and then every time a node is added then add a NULL to the new tail. You did not assign a NULL value to your end node so you have an endless loop.</p>
Override func Error! Method does not override any method from its superclass <pre><code>override func touchesBegan(touches: Set&lt;NSObject&gt;, withEvent event: UIEvent) { } override func supportedInterfaceOrientations() -&gt; Int { } </code></pre> <p>Here I have an error. It says </p> <blockquote> <p>Method does not override any method from its superclass. </p> </blockquote> <p>This comes multiple times, I can't fix it.</p> <p>Do you know something about it?</p>
<p>The error is coming because your method signature is different than the actual ones. You should use the exact method signature for overriding (Either you should use auto-complete feature provided in Xcode or refer the documentation)</p> <p><a href="https://developer.apple.com/reference/uikit/uiresponder/1621142-touchesbegan" rel="nofollow">Touches Began</a>:</p> <pre><code>override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { } </code></pre> <p>In Swift 3 <a href="https://developer.apple.com/reference/uikit/uiviewcontroller/1621435-supportedinterfaceorientations" rel="nofollow">supportedInterfaceOrientations</a> is no longer a method, it's a computed property, so it's signature becomes:</p> <pre><code>override var supportedInterfaceOrientations : UIInterfaceOrientationMask { } </code></pre>
looking for android pattern unlock <p>I forgot my android pattern, for which i don't want to do factory reset n loose my data, pics n other stuffs. </p> <p>Unfortunately, my mobile data or wifi is also not enabled, which could help me to login with my google account and i have reset it.</p> <p>My study shows me that, i need to remove gesture.key file, for which through android sdk i already tried below command:</p> <p><strong>adb shell rm /data/system/gesture.key</strong></p> <p>but i got permission denied as result. </p> <p>second, i tried to enable wifi or data network, but again no result since android which i am using is rooted. Because of permission denied , i couldnt able to perform anything. </p> <p>Please suggest if you know how to get it resolve without data loss.Appreciate your responses.</p>
<p>you cant remove pattern files without root permission,just need root permission or install custom recovery. if USB debug enabled you can root. use this links for root <a href="http://forum.xda-developers.com/zenfone-5/general/root-asus-zenfone-5-kitkat-4-4-2-100-t2947092" rel="nofollow">(root-asus-zenfone-5-kitkat-4-4-2)</a> and <a href="http://redirect.viglink.com/?format=go&amp;jsonp=vglnk_147604792795814&amp;key=f0a7f91912ae2b52e0700f73990eb321&amp;libId=iu34pt3601000n4o000DAc0ts96u3&amp;loc=http%3A%2F%2Fforum.xda-developers.com%2Fandroid%2Fgeneral%2Fasus-zenfone-5-lollipop-root-t3135056&amp;v=1&amp;out=https%3A%2F%2Fdrive.google.com%2Ffile%2Fd%2F0B9OM9nJbQarYZVRKM09sa21jOW8%2Fview&amp;ref=https%3A%2F%2Fwww.google.com%2F&amp;title=Asus%20Zenfone%205%20Ultimate%20Guide%3AROOT%2CROM%2CTWEAK%E2%80%A6%20%7C%20Android%20Development%20and%20Hacking&amp;txt=https%3A%2F%2Fdrive.google.com%2Ffile%2Fd%2F0B9O...9sa21jOW8%2Fview" rel="nofollow">root-asus-zenfone-5-lollipop-5.0</a></p>
Angular 2 ng module imports <p>What is the significance of imports metadata of ngmodule decorator, when we are importing files at top. Difference between both the inputs.</p>
<p>These imports are entirely different concepts. </p> <p>The imports at the top of the file are TypeScript imports to make classes, interfaces and variables known to the current file and are not related to Angular2.</p> <p>The <code>@NgModule()</code> imports are to make <code>exports: []</code> of the imported <code>@NgModule()</code>s known to the importing <code>@NgModule()</code> so that they applied to components of the importing module if selectors match. </p> <p>Also <code>providers: []</code> of an imported module are added to the root scope of the injector (only when the module is not lazy loaded). </p>
Apache permission error on WAMP <p>I may be missing the obvious posting, but everything I've seen seems to apply to an older version of Apache with a different httpd.conf file.</p> <p>I have the good old "You don't have permission to access / on this server" message.</p> <p>With an older version of Apache that I used to use, the "order deny,allow" followed by "allow from all" worked. Not with this new one.</p> <p>Here's what I think the applicable section is that I need to change. I haven't seen this exact wording in other posts:</p> <pre><code>&lt;Directory /&gt; AllowOverride none Require all denied &lt;/Directory&gt; </code></pre> <p>Thanks</p>
<p>Okay, I found it...</p> <ol> <li><p>Change httpd.conf to have "require all granted"</p></li> <li><p>Change httpd-vhosts line "Require local" to "Require all granted"</p></li> </ol> <p>It was the second file that I needed to change. (and no others, at least for me)</p>
PHP isn't able to read file <p>I'm stuck trying to open a file with fopen in php.</p> <pre><code> $db_ausgaenge = "statuseing.php"; $dout = fopen($db_ausgaenge, "x+"); print $dout; print(shell_exec('whoami')); print(shell_exec('pwd')); print(shell_exec('id')); fwrite($dout, $out); fclose($dout); Warning: fopen(statuseing.php): failed to open stream: File exists in /var/www/html/zufallsgenerator.php on line 33 </code></pre> <p>I checked following items:</p> <ul> <li>chmod for statuseing.php 0777</li> <li>owner is www-data with groud www-data</li> <li>script is running as user www-data </li> <li>groups are uid=33(www-data) gid=33(www-data) groups=33(www-data) </li> <li>pwd is /var/www/html as expected</li> <li>the path the scripts want's to open is correct </li> <li><p>checked openbase dir in php.ini showed in phpinfo(), added /var/www/html, but php doesn't care about it. </p> <p>open_basedir = /var/www/html/</p></li> </ul> <p>After daemon-reload and restarting apache2 via systemctl nothing changed, phpinfo() didn't show the path given in the config. restarting the system via init 6 didn't took effect, too. </p>
<p>Look at the mode you are using.</p> <p>x+ means that if the file already exists an error will be thrown.</p> <p>To find the correct mode depending on your scenario check out <a href="http://php.net/manual/en/function.fopen.php" rel="nofollow">http://php.net/manual/en/function.fopen.php</a></p>
Python screenshot over internet by email <p>How to make this better ? <a href="https://github.com/Seiff/python-screenshot-over-internet" rel="nofollow">https://github.com/Seiff/python-screenshot-over-internet</a> how to make the poplib connection read emails on runtime instead of running every 5mins to check ?</p>
<p>Reading through the documentation, there doesnt seem to be a current fix for real time. What is possible is reducing the batch time in the .bat file (Currently at 300 s ).</p> <pre><code> :loop start directory\screenshotwithemail.py timeout /t 300 #Change this value goto loop </code></pre> <p>This might make it computationally expensive, but make it close to real time.</p> <p><a href="https://github.com/Seiff/python-screenshot-over-internet" rel="nofollow">Reference</a></p>
Creating # pages like Twitter with Firebase <p>I have a question to the Firebase community.</p> <p>How to structure the data for # pages like Twitter? (e.g:#funnyVideos so that any one can see that link and add some stuff into it) in Firebase?</p>
<p>It sounds like you're trying to store hash tags. </p> <p>But that enough is not enough to determine your data model. </p> <p>In Firebase (as in most NoSQL databases) you model your data for the way you app consumes it. So you'll have to determine what screens there are in your app and what information they show.</p> <p>For example, if you want to show the hash tags per page, you'd store a list of hash tags per page:</p> <pre><code>hashtagsPerPage pageId1 hashTag1: true hashTag2: true pageId2 hashTag1: true hashTag3: true </code></pre> <p>If you also want a list of pages for a given hash tag, you'd <strong>also</strong> store:</p> <pre><code>pagesPerHashtag hashTag1 pageId1: true pageId2: true hashTag2 pageId1: true hashTag3 pageId2: true </code></pre> <p>And of course you'd then have the list of pages itself:</p> <pre><code>pages pageId1 title: "Creating # pages like Twitter with Firebase" url: "http://stackoverflow.com/questions/39947270/creating-pages-like-twitter-with-firebase" pageId2 title: "Structure Your Database" url: "https://firebase.google.com/docs/database/web/structure-data" </code></pre> <p>I highly recommend that you read both the <a href="https://firebase.google.com/docs/database/web/structure-data#fanout" rel="nofollow">Firebase documentation on data structuring</a> (the first two lists are the structure documented in the section "create data that scales").</p> <p>In addition there's this great primer on <a href="https://highlyscalable.wordpress.com/2012/03/01/nosql-data-modeling-techniques/" rel="nofollow">NoSQL data modeling</a>.</p>
How to generate 3 names without the same name repeated <pre><code>window.onload = start; function start () { var name = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"] var random = Math.floor(Math.random()*8) var random2 = Math.floor(Math.random()*8) var random3 = Math.floor(Math.random()*8) var name2 = [] name2.push(name[random]) name2.push(name[random2]) name2.push(name[random3]) for(i=0; i&lt;3; i++) { document.getElementById("par").innerHTML += name2[i] + "&lt;br/&gt;" ; } } </code></pre> <p>So far with this code i can generate 3 random names from the name array. But i want the 3 names not to be repeated, and I don't know how to make that happen. </p>
<p>Replace the assignment for random2 and random 3 with:</p> <pre><code>var random = Math.floor(Math.random()*8); var random2, random3; do { random2 = Math.floor(Math.random()*8); } while (random2==random); do { random3 = Math.floor(Math.random()*8); } while (random3==random || random3==random2); </code></pre> <p>Try it out here: <a href="https://jsfiddle.net/o04tf9ct/" rel="nofollow">https://jsfiddle.net/o04tf9ct/</a></p>
mod_rewrite pass variable and <p>What I would need to do is to pass 1 variable as variable, and the rest as a rest of URL intact, so I can get them by $_GET in php later. The below does not work:</p> <pre><code>RewriteRule ^store/([a-zA-Z0-9\_\-]+).html?(.*)/?$ store.php?var1=$1&amp;$2 [L] </code></pre> <p>Possible Links could be: </p> <pre><code>store/products.html store/products.html?sort=asc&amp;price=down store/products.html?price=down&amp;here_we_can_have_a_lot_of_different_params_in_whatever_order </code></pre> <p>Basically, just take this $var1 and the rest forward to URL? How can I do that?</p> <p>P.S. I think I found a solution:</p> <pre><code>RewriteRule ^store/([a-zA-Z0-9\_\-]+).html?(.*)/?$ store.php?var1=$1&amp;%{QUERY_STRING} [L] </code></pre>
<p>The problem is your premise as to how a <code>RewriteRule</code> works. A <code>RewriteRule</code> <em>only</em> matches against the URI path (in apache terms the Request URI) and not against the query string. This means the <code>(.*)/?$</code> at the end of your regex only works because it can reduce to just '$' (or the end of the string) and the <code>?</code> before it just means the regexp will match <code>.htm</code> as well as <code>.html</code></p> <p>The <em>simpler</em> version of your rule is as follows:</p> <pre><code>RewriteRule ^store/([a-zA-Z0-9\_\-]+).html store.php?var1=$1 [L,QSA] </code></pre> <p>The QSA stands for <code>Query String Append</code>, which simply adds back any existing query string to the rewritten URL.</p>
How to break this loop? <p>I have this code to average 100 pictures and save them into 10 JPEG files</p> <pre><code>int main(int argc, char** argv) { VideoCapture cap("C:/Pics/test_%d.jpeg"); while (cap.isOpened()) { Mat img; cap.read(img); // process(img); if (img.empty()) break; for (int i = 0; i &lt; 10; i++) { Mat avgImg(480, 640, CV_32FC3, Scalar()); for (int avgnumb = 10 * i; avgnumb &lt; (10 * i) +10; ++avgnumb) { cv::accumulate(img, avgImg); } avgImg = avgImg / 10; avgImg.convertTo(avgImg, CV_8UC3); char filename[100]; sprintf(filename, "C:/AvgPics/test_%d.jpeg", i); imwrite(filename, avgImg); } } return 0; } </code></pre> <p>However, even after finishing saving the 9th file, it doesn't break and continue to overwrite the saved file again and again. Can anyone help me in this? Thanks a lot.</p>
<p>I'm an idiot. Just remove the <code>while</code></p>
AutoValidateAntiForgeryToken vs. ValidateAntiForgeryToken <p>I was trying to secure a post method against side scripting just now through providing an anti forgery token but noticed, in .Net Core there is another attribute named as <code>AutoAntiForgeryToken</code>. The XML comments, and the online search did not provide much info on this new attribute. </p> <p>Any help and description of what the new attribute is, will be much appreciated. </p>
<p>From <code>AutoValidateAntiforgeryTokenAttribute</code> documentation:</p> <blockquote> <p>An attribute that causes validation of antiforgery tokens for all unsafe HTTP methods. An antiforgery token is required for HTTP methods other than GET, HEAD, OPTIONS, and TRACE. It can be applied at as a global filter to trigger validation of antiforgery tokens by default for an application.</p> </blockquote> <p><code>AutoValidateAntiforgeryTokenAttribute</code> allows to apply Anti-forgery token validation globally to all unsafe methods e.g. <code>POST, PUT, PATCH and DELETE</code>. Thus you don't need to add <code>[ValidateAntiForgeryToken]</code> attribute to each and every action that requires it.</p> <p>To use it add the following code to your <code>ConfigureServices</code> method of <code>Startup</code> class</p> <pre><code>services.AddMvc(options =&gt; { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); }); </code></pre> <p>If you need to ignore Anti forgery validation you can add <code>[IgnoreAntiforgeryToken]</code> attribute to the action.</p>
Strategies for abstracting db id from domain class <p>I am writing a simple CRUD application in Java and Spring4 with spring-data, and I want to see if I can keep the domain as pure/clean as possible, and I'm after some ideas/thoughts as to how I can go about achieving this.<br> I've structured the project with a parent pom and some child modules as follows:</p> <pre><code>parent pom |- domain | |- persistence | |- api | |- impl | |- service | |- api | |- impl | |- rest </code></pre> <p>In the persistence api module I have interfaces with methods for persisting/retrieving my domain classes. eg:</p> <pre><code>public interface GiftPersistence() { Gift saveOrUpdateGift(Gift gift); /* other methods ... */ } </code></pre> <p>Importantly, these methods are <strong>not</strong> repository methods. The methods in this module are those that are called by the service module implementations.</p> <p>The persistence impl module has an implementation of the interface that is specific to the database that I'm using (it's mongo today, but could be oracle or ms-sql, or anything else). This is where I have my repository interface that is specific to the database vendor.</p> <p>In the domain module I have my domain classes, but I don't want to model in anything that is database centric. eg:</p> <pre><code>public final class Gift { private String description; private boolean claimed; private String claimedBy; /* getters &amp; setters etc ... */ } </code></pre> <p>The reasons I don't want to model database specific things are:</p> <ul> <li>Persistence is not a concern of the domain</li> <li>Different database vendors might use different id strategies/datatypes, and I don't want to couple my domain code to any database vendor</li> <li>I might want to import the domain module into another project's pom, and that project might not do anything with a database</li> </ul> <p>I've been involved in a project in the past that did something similar (to be honest, that's where I've got the idea from!), but I don't have access to that project any more so can't use it to crib ideas.<br> Having said that I vaguely remember it did something with jackson mixins (though that might have been a similar idea/concept, but closer to the web concern than the db concern).<br> The other approach I've thought about is using aspects, but not really sure how/where I'd go about that.</p> <p>So, any ideas or thoughts as to how I might achieve the goal of keeping my domain clean of database concerns would be very much appreciated.</p> <p><strong>Edited with new idea I just found</strong><br> This is an interesting idea - <a href="https://github.com/CK35/example-ddd-with-spring-data-jpa" rel="nofollow">https://github.com/CK35/example-ddd-with-spring-data-jpa</a><br> The idea is that the domain module models the domain classes as interfaces, and the concrete implementations are (in my case) in the persistence-impl module. This way they can be annotated with domain concerns, including additional properties such as id.<br> This feels like a nice option as it means the domain is clean (albeit not a concrete implementation), and we can have different implementations of the persistence-api module, where the implementations of the domain classes have generic jpa annotations, or mongo annotations, or oracle ... </p> <p>Any other ideas?</p>
<p>If you want you can use an interface, although you'll probably find that you only ever have one implementation of this interface, defeating the whole purpose of the interface. Annotations themselves are pretty much interfaces. So an annotated class will be much the same.</p> <p>I'm not sure why you think having an ID field will mean that the class will be database dependent. The whole design intent of spring is to not make it interface with any persistence technology you want, and so you can use hibernate or whatever for persistence. If you do use hibernate you could configure your persistence classes in xml, so you won't see any persistence stuff in your domain object... except the ID of course, though I don't see this as a problem, if it is a massive problem well you could extend from a base class which has a private id field but you might not like that.</p> <p>When you do annotate a domain object with persistence concerns, won't have any problems with other client code which doesn't want to know about persistence. They will only be able to see it if they are using reflection or something crazy to read annotations.</p> <p>IMHO making all services, daos, entites, and all this stuff into interfaces, and then have only one implementation is overkill although I know some people will disagree. But I believe this is still a code smell none-the-less, because at then end of the day you have an interface with only 1 implementation. Say you are going to have more than one implementation later it will literally take you 10 seconds to change this back into an interface with 1 implementation with refactoring in eclipse. Simply copy your implementation code some where, extract the interface, change the current class to be the extracted interface, and put your copy code back in your project with something like <code>InterfaceImp extends Foo</code> on the top. Done. No need to overdo it at the start with maintaining some ghost interface.</p>
React/Redux - Dispatch not updating view <p>First small react/redux project to learn both react and redux.</p> <p>The onClick event on the button element fires as I can see the value in the console (in the reducer file). However, the view is not updating.</p> <p>Yes, I have looked online, and I have been stuck on this issue for a full day.</p> <p>What am I doing wrong?</p> <p>Thanks in advance.</p> <p>PanelContainer.js file:</p> <pre><code> class PanelContainer extends React.Component { constructor(){ super(); this.state = { color: new Color() } } render(){ return ( &lt;div class="container"&gt; &lt;Row&gt; &lt;Cell cols={`col-sm-12 col-md-3 col-lg-3`}&gt; &lt;Panel&gt; &lt;PanelBody color={this.state.color.generateColor(new Gray())}&gt; &lt;Title title={this.props.follower.count} /&gt; &lt;p&gt;{this.props.follower.description}&lt;/p&gt; &lt;p&gt;&lt;button class="btn btn-primary" onClick={() =&gt; this.props.getFollower()}&gt;Update&lt;/button&gt;&lt;/p&gt; &lt;/PanelBody&gt; &lt;/Panel&gt; &lt;/Cell&gt; &lt;/Row&gt; &lt;/div&gt; ); } } const mapStateToProps = (state) =&gt; { return { follower: state.followerReducer }; }; const mapDispatchToProps = (dispatch) =&gt; { return { getFollower: () =&gt; { dispatch(getFollower()); }, changeFollower: () =&gt; { dispatch(changeFollower()); } } } export default connect(mapStateToProps, mapDispatchToProps)(PanelContainer); </code></pre> <p>FolloweReducer.js file:</p> <pre><code>export default (state = { follower: { count: 0, description: "Default description" } }, action) =&gt; { switch(action.type){ case "GET_FOLLOWER": state = { ...state, follower: action.payload }; console.log("GET FOLLOWER", state); break; case "CHANGE_FOLLOWER": state = { ...state, follower: action.payload }; console.log("CHANGE FOLLOWER", state); break; default: break; } return state; }; </code></pre> <p>FollowerAction.js file:</p> <pre><code>export function getFollower() { return { type: "GET_FOLLOWER", payload: { count: 20, description: "New followers added this month" } } } export function changeFollower(){ return { type: "CHANGE_FOLLOWER", payload: { count: 50, description: "Changed Followers!!!" } } } </code></pre> <p>Store.js file:</p> <pre><code>const store = createStore(combineReducers({ followerReducer: followerReducer })); export default store; </code></pre> <p>App.js file:</p> <pre><code>import React from "react"; import ReactDom from "react-dom"; import {Provider} from "react-redux"; import PanelContainer from "./panel/PanelContainer"; import store from "./shared/Store"; let app = document.getElementById("app"); ReactDom.render( &lt;Provider store={store}&gt; &lt;PanelContainer /&gt; &lt;/Provider&gt;, app ); </code></pre>
<p>I believe the reason you don't see any updates in your rendered view is because you're wrongly mapping your state with the props you pass to the component. You state->props mapping function should be:</p> <pre><code>const mapStateToProps = (state) =&gt; { return { follower: state.followerReducer.follower }; }; </code></pre> <p><code>state.followerReducer</code> is the whole state object managed by your reducer. It's clear from this line</p> <pre><code>state = { ...state, follower: action.payload }; </code></pre> <p>and from your initial state definition that you store the data you update in <code>state.followerReducer.follower</code></p> <p>With your <code>mapStateToProps</code> function you have, <code>{this.props.follower.count}</code> in the render method will be the whole reducer object (which is <code>{follower: {...}}</code>.</p>
Custom eCommerce Pop-Up? <p>I am developing a site for a client and I need the ability to add a pop up on the home page that allows the user to enter their email/payment info and then click a button to purchase a ticket for an event. I've looked into WooCommerce and WP-eCommerce but I can't find a way to do this.</p> <p>Does anyone know a way that I can integrate this into a custom site built on top of Wordpress. </p> <p>--I know how to make a form pop up when clicking a button, I just need to know some way to integrate a payment gateway into a custom form. </p> <p>--It needs to be able to take credit card info, if It can work just with credit cards (not any other payment form) that fine. I just need something that works</p>
<p>The WooCommerce + <a href="https://wordpress.org/plugins/paypal-for-woocommerce/" rel="nofollow">PayPal for WooCommerce</a> combination is "something that works" but you would have to customize the part where it happens within a pop-up.</p> <p>This can be done with custom template files and hooks into WordPress / WooCommerce to build that out how you need it.</p>
How to find the difference between two dates c++ <p>I'm a student and I was wondering if anybody can help me debug one of my functions. For this program the user is suppose to input two dates in the format mm/dd/yy between the years of 1972-2071 and the program is suppose to output the difference between those two dates. All of my functions work except for the function that calculates the amount of days from 1/1/72. This is the way our professor would like us to do it with no extra features. Just a beginner version with a lot of if else statements and for loops. </p> <pre><code>int ChangeToNumber(int m, int d, int y) { int total=0; if(y&lt;=71) //if the year is between 2000-2071 { y+=28; for(int i=0; i&lt;y; i++) { if(!LeapYear(y)) { total+=365; } else { total+=366; } } } else //if the year is between 1972-1999 { for(int i=72; i&lt;y; i++) { if(!LeapYear(y)) { total+=365; } else { total+=366; } } } for(int i=1; i&lt;m; i++) { total+=DaysInMonth(m, y); } total += d; return total; } </code></pre>
<p>You can use <code>std::difftime</code> to help you in some percents.</p> <p>no extra features: </p> <p><a href="http://en.cppreference.com/w/cpp/chrono/c/difftime" rel="nofollow">http://en.cppreference.com/w/cpp/chrono/c/difftime</a></p> <pre><code>#include &lt;iostream&gt; #include &lt;ctime&gt; int main() { struct std::tm a = {0,0,0,24,5,104}; /* June 24, 2004 */ struct std::tm b = {0,0,0,5,6,104}; /* July 5, 2004 */ std::time_t x = std::mktime(&amp;a); std::time_t y = std::mktime(&amp;b); if ( x != (std::time_t)(-1) &amp;&amp; y != (std::time_t)(-1) ) { double difference = std::difftime(y, x) / (60 * 60 * 24); std::cout &lt;&lt; std::ctime(&amp;x); std::cout &lt;&lt; std::ctime(&amp;y); std::cout &lt;&lt; "difference = " &lt;&lt; difference &lt;&lt; " days" &lt;&lt; std::endl; } return 0; } </code></pre> <p>extra features:</p> <pre><code>#include "boost/date_time/gregorian/gregorian_types.hpp" using namespace boost::gregorian; date date1(2012, Apr, 2); date date2(2003, Feb, 2); long difference = (date1 - date2).days(); </code></pre>
Android ListView Item Add and Remove <p>When i Add Item to listview , listview doesn't show my added item. when i add the Item to adapter i want to seem it in listview... But it doesn't work. Where is my fail ? There is any example about Listview (Add/Remove/Edit) Example too ? </p> <p><strong>Adapter Code</strong></p> <pre><code> android.content.Context Context; LayoutInflater inflater; ArrayList&lt;Item&gt; Items=new ArrayList&lt;&gt;(); public MyAdapter(Context Context) { this.Context=Context; } @Override public int getCount() { return Items.size(); } @Override public Object getItem(int position) { return Items.get(position); } @Override public long getItemId(int position) { return 0; } public void AddItem(Item item) { Items.add(item); MyAdapter.this.notifyDataSetChanged(); } @Override public View getView(final int position, View convertView, ViewGroup parent) { ImageButton BtnSil; inflater=(LayoutInflater) Context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view=inflater.inflate(R.layout.fragment_lstview,parent,false); BtnRemove=(ImageButton)view.findViewById(R.id.Remove); BtnRemove.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Urunler.remove(position); MyAdapter.this.notifyDataSetChanged(); } }); return view; } </code></pre> <p><strong>Item Add Code</strong></p> <pre><code>adapter.AddItem(SecilenUrun); </code></pre>
<p>It should update. While rebuilding the view is a giant waste and an error, it should work. The most suspect thing is the getItemId(int position) returning 0. If the view is treating the ids as static that will often result in no-update and no values on screen have changed. Typically the default is return position, or some proper hashed value of item.</p> <p>But, certainly that should update. Though all the entries would look identical though Urunler would have the remove called for that position. Which wouldn't look significantly different other than the number of items.</p>
The class file for a new Thread and the class file for main are the same <p>I have a program called Main.java, shown as below. After compilation of this program, there will be two .class file: Main.class and Main$1.class. My problem is the two .class files are exactly the same. </p> <p>Anyone knows what is wrong? </p> <p>I wan to instrument some codes in the run() method of the new thread, but I cannot find the instructions of codes in the run() method of a new thread. </p> <pre><code>public class Main{ public static void main(String...args){ Thread t=new Thread(){ @Override public void run(){ System.out.println("xxxx"); } }; t.start(); } } </code></pre>
<p>My money would be on you not comparing the two class files correctly. I'd bet that you're writing something like this in your bash-like prompt:</p> <pre><code>md5sum Main.class Main$1.class </code></pre> <p>(or some checksumming tool other than <code>md5sum</code>)</p> <p>This is actually substituting the variable called <code>1</code> in the string - unless you've got that variable defined, that variable is empty, so that is expanding to:</p> <pre><code>md5sum Main.class Main.class </code></pre> <p>which will show as the same file contents.</p> <p>Try single-quoting the second string:</p> <pre><code>md5sum Main.class 'Main$1.class' </code></pre>
The coordinates or dimensions of the range are invalid in JSon <p>I am working on google scripts which can call REST API and get the data in google spreadsheets. But different Json objects work and which I am using now does not work...</p> <p>At first it was giving me an error as The coordinates or dimensions of the range are invalid. So looked to on at <a href="http://stackoverflow.com/questions/35844018/the-coordinates-or-dimensions-of-the-range-are-invalid-google-apps-script-an">&quot;The coordinates or dimensions of the range are invalid&quot; - Google Apps Script and JSON Data</a></p> <p>And now the result is <strong>undefined</strong>.. </p> <p>Really appreciate if someone can help </p> <pre><code>function pullJSON(k) { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheets = ss.getSheets(); var sheet = ss.getActiveSheet(); var url = "********"; // Paste your JSON URL here var headers = { "Content-Type": "application/json", }; var options = { "method": "GET", "headers": headers }; var response = UrlFetchApp.fetch(url, options); // get feed var dataAll = JSON.parse(response.getContentText()); // var dataSet = dataAll; Logger.log(dataAll.length); Logger.log(k); Logger.log(url); var rows = [], data; for (var k = 0; k &lt; Object.keys(dataSet).length; k++) { data = [Object.keys(dataSet)[k]]; Logger.log(data); rows.push([data.total1]);} //your JSON entities here dataRange = sheet.getRange( 1, 1,rows.length,1); // 3 Denotes total number of entites dataRange.setValues(rows); } </code></pre>
<p>What you are doing at the moment is calling <code>Object.keys()</code> on <code>dataSet</code>.<br> This returns an array of strings, e.g. <code>["status", "data"]</code>. </p> <p>Then you retrieve each of these keys separately and assign them as a one element array to data, so data looks like <code>["status"]</code>, and <code>["data"]</code>.<br> Since <code>["total1]"</code> is an array of a string it doesn't have the <code>"total1"</code> attribute, just an element with the value equal to the name.</p> <p>To get the actual total 1 value from each object within data you can</p> <pre><code>dataSet.data.forEach(function(x) { rows.push([x.total1]); }); </code></pre> <p>instead of the for loop.</p>
How can I ensure consistency between multiple model object instances <p><strong>BACKGROUND</strong></p> <p>This is a problem I keep coming back to as I'm developing an Android application. Let's say my app lets users "follow" TV shows. My <code>TVShow</code> model class is as follows:</p> <pre><code>public class TVShow { String title; String[] show_cast; boolean currently_airing = true; boolean following = false; long nextEpisodeTime; String genre; } </code></pre> <p>I have an SQL database that stores hundreds of TV shows. This is useful because I can leverage detailed queries to select shows based on specific information. The problem I get is when I have multiple instances of <code>TVShow</code> that represent the same show. </p> <p><strong>EXAMPLE</strong></p> <p>Let's say I have the TV show "The Walking Dead" in my database and I create a <code>TVShow</code> object from an SQL query. This object instance will be called <code>TVShow#1</code>. I decide to "follow" this show, so I set <code>TVShow#1.following = true</code>. Somewhere else in my app I query a list of shows that are currently airing, which "The Walking Dead" is part of. A new instance of <code>TVShow</code> will be created called <code>TVShow#2</code> for that list. The problem here is that I have two <code>TVShow</code> objects, <code>TVShow#1</code> and <code>TVShow#2</code> that represent "The Walking Dead", but they have differing values for <code>following</code>. This will cause problems throughout the logic of my application because there isn't a consistency between all <code>TVShow</code> instances that represent the same TV show. </p> <p><strong>MY BAD WORKAROUND</strong></p> <p>Expand this to a bunch of object instances and much more complicated fields and logic, and that is the situation I am currently in. I have mitigated this by loading all SQL data into memory (usually <code>ArrayList</code> or <code>HashMap</code>) when the app is launched, and only querying these Java objects instead of the SQL database. This solution is inefficient and inconvenient, where SQL queries could really help. I hope my examples were not too confusing. If I can clarify or provide more information, I'd be happy to. Please let me know if there is something better I can do to ensure consistency between multiple instances of the same model object.</p>
<p>It sounds like the "following" property should be the property of a user rather than a TV show.</p> <p>Your database should record the association between users and which shows they are following. So, if a user decides to follow a show, you save a persistent association in the database between that user and that show, and then the next time you query the database the state will be consistent.</p>
Determine cause of execute failure per row from BatchUpdateException <p>I have a java program that reads thousands of rows of data from a text file into a database. It uses statement batching to insert a couple thousand rows at a time.</p> <p>If rows any rows fail to update, I continue attempting the rest until the end of the list. After, I go back and check which rows failed, then print the info from those rows to a log file to check later.</p> <p>I'm wondering if there's a way to skip printing the failed row if it failed because of a duplicate entry. I'm fine with duplicates failing, but if the insert failed for some other reason I need the row to be output to my log file.</p> <p>The way I currently do this is:</p> <pre><code>int[] updateCounts; try { // Do my batch updates by iterating through a vector of data } catch (BatchUpdateException buE) { updateCounts = buE.getUpdateCounts(); } for (int c = 0; c &lt; updateCounts.length; ++c) { if (updateCounts[c] == Statement.EXECUTE_FAILED) { // Print data from the original data vector at index c } } </code></pre> <p>Instead of printing every row where updateCounts is EXECUTE_FAILED, I only want to print the ones that AREN'T because of a unique key.</p> <p>Between Google, StackOverflow, and the documentation for BatchUpdateException, I'm guessing there's no way to do this. But it'd be nice if there is and I just couldn't find it.</p>
<p>There may be two reasons;</p> <ol> <li>There may be a syntax mistake in the SQL Query.</li> <li>There may be duplicate entries for the primary key.</li> </ol> <p>As you are reading the data from a text file, I suggest you to use the <code>Load Data Local InFile</code> Query in SQL. This would resolve both of the above issues and all your genuine entries would be uploaded into the database.</p> <p>If this doesn't help, kindly add the queries to your question and the stacktrace would be helpful to answer. Please upvote so that I can directly comment on your question.</p>
AJAX response cache <p>i'm developing a mobile app using cordova . The app consists on sending AJAX requests to a php script on a distant server and then the php extracts the required data from a database and responds with these data in JSON format so the app can parse these data and show them on the app . The problem here is that I have to send the AJAX calls again every time i open the app or browse between the different pages of the app .</p> <p>here is the function that requests the data : </p> <pre><code>$.ajax({ crossDomain: true, type: "GET", async: false, url: "www.website.com/get-data.php?offset=8&amp;&amp;categorie=all , dataType: "json", cache: true, success: function (data) { //function to call if success callback } </code></pre> <p>});</p> <p>Is there any solution to cache the data or save them some how to prevent unecessary use of the internet connection and the waste of time waiting for the server's response ?</p> <p>thanks for answering .</p>
<p>You are not exactly describing the kind of data you want to save (is it only strings? is it an array? an object?) or showing any code, so I can only <a href="http://javascript.tutorialhorizon.com/2015/09/08/getting-started-with-localstorage-vs-sessionstorage-in-html5/" rel="nofollow">point</a> you to a direction. Take a look at this tutorial for a very quick start and you can learn a few things about sessionStorage and localStorage which might help you with your program. If either of these suggestions fits your needs you can do your own deeper research.</p> <p>(I am sorry I don't write this in a comment, I just don't have enough reputation) </p>
Designing a for loop with specifically named items <p>I often run into this situation when writing code for a GUI and would like to know would be a best-practice way of solving this. The situation is this:</p> <p>I have a number of identical items on my GUI which have different variable names, i.e. I have 10 'identical' buttons which are named Button1, Button2, Button3, etc...</p> <p>The buttons' displayed text is updated in the code and I want to check when they are updated if they meet a certain condition and then change the text color based on that condition. So for button1 I would write:</p> <pre><code>if (Button1.text == "true"){ Button1.textcolor = blue} else if (Button1.text == "false"){ Button1.textcolor = red} </code></pre> <p>Now it seems redundant to have to write this code again for each of the 10 buttons, replacing Button1's variable name with Button2's and so on up until Button10. Is there a way to change the "Button1" part of the code in a loop and keep everything else the same? So a pseudo-code example of what I'm looking for would be:</p> <pre><code>for (all buttons in (button1-button10)){ if (thisbutton.text == "true"){ thisbutton.textcolor = blue} else if (thisbutton.text == "false"){ thisbutton.textcolor = red}} </code></pre> <p>I don't know how to best approach this scenario and would appreciate input and guidance on this.</p> <p>Thanks</p>
<p>Whenever you have a set of similar objects don´t create a variable for every instance of those objects, instead put them into one single collection. Then you can easily loop this list and manipulate the objects within it:</p> <pre><code>var buttons = new List&lt;Button&gt;(); // put the buttons into the list using buttons.Add for (var b in buttons) { if (b.text == "true") { b.textcolor = blue } else { b.textcolor = red } } </code></pre> <p>You can also use a <code>GridView</code> to put all those buttons into a ragular grid.</p>
Optimizan ORDER BY & LIMIT queries in MySQL <p>I trying to optimize query like this:</p> <pre><code>SELECT sql_no_cache t.topic_id FROM blog AS b, topic AS t WHERE t.topic_publish = 1 AND t.topic_type &lt;&gt; 'topic' AND t.topic_lang = 'en' AND t.blog_id = b.blog_id ORDER BY t.topic_date_add DESC LIMIT 50; </code></pre> <p>Schema:</p> <pre><code>CREATE TABLE `topic` ( `topic_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `blog_id` int(11) unsigned NOT NULL, `user_id` int(11) unsigned NOT NULL, `topic_type` enum('topic_catalog','topic','link','question','photoset') NOT NULL DEFAULT 'topic', `topic_lang` varchar(16) NOT NULL DEFAULT 'russian', `topic_title` varchar(200) NOT NULL, `topic_date_add` datetime NOT NULL, `topic_date_edit` datetime DEFAULT NULL, `topic_publish` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`topic_id`), UNIQUE KEY `topic_date_add` (`topic_type`,`topic_lang`,`topic_publish`,`blog_id`,`topic_id`,`topic_date_add`), KEY `blog_id` (`blog_id`), KEY `user_id` (`user_id`), KEY `topic_date_add` (`topic_date_add`,`topic_type`), ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 </code></pre> <p>Table <code>topic</code> contains about 1M records and works very good (about 0.0016s) without <code>ORDER BY</code>.</p> <p>With <code>ORDER BY t.topic_date_add DESC</code> query is executing much longer (about 2.8083 on the same machine)</p> <p><code>Explain</code> on query with <code>order</code> looks like:</p> <pre><code>+----+-------------+-------+--------+----------------------+----------------+---------+--------------------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+----------------------+----------------+---------+--------------------+------+-------------+ | 1 | SIMPLE | t | index | blog_id,topic_rating | topic_date_add | 9 | NULL | 50 | Using where | | 1 | SIMPLE | b | eq_ref | PRIMARY,blog_type | PRIMARY | 4 | sku_prod.t.blog_id | 1 | Using where | +----+-------------+-------+--------+----------------------+----------------+---------+--------------------+------+-------------+ </code></pre> <p>I am a newbie in query optimization and can't understand why query with ordering executing so long. From <code>Explain</code> looks like performed only 50 rows.</p> <p>So would be happy to hear any ideas about optimization of this query. if needed I can add any missing information.</p>
<p>First, learn to use proper, explicit <code>JOIN</code> syntax:</p> <pre><code>SELECT sql_no_cache t.topic_id FROM blog b JOIN topic t ON t.blog_id = b.blog_id WHERE t.topic_publish = 1 t.topic_type &lt;&gt; 'topic' t.topic_lang = 'en' ORDER BY t.topic_date_add DESC LIMIT 50; </code></pre> <p>For this query, the optimal index would be <code>topic(topic_lang, topic_publish, topic_type, blog_id, topic_date_add, topic_id)</code>. The last two keys won't be used for ordering but their inclusion makes the index a covering index.</p> <p>Assuming that <code>blog_id</code> always matches something in <code>blog</code>, then why not just use:</p> <pre><code>SELECT sql_no_cache t.topic_id FROM topic t WHERE t.topic_publish = 1 t.topic_type &lt;&gt; 'topic' t.topic_lang = 'en' ORDER BY t.topic_date_add DESC LIMIT 50; </code></pre> <p>The same index works for this.</p>
R code to generate unique ID with prefix? <p>I have a table called "pipel" that contains more than 10,000 rows. I would like to add an ID column to assign a unique ID for each row. The unique ID must be 30 digits long and starts with "AKM_CC_Test_". I used the code below as a starting point but not sure how to format it to add the prefix and make it 30 digits long.</p> <pre><code>id &lt;- rownames(pipel) pipel &lt;- cbind(id=id, pipel) </code></pre> <p>For example first row ID will need to look like this AKM_CC_Test_000000000000000001</p>
<p>You could use <code>sprintf()</code>. This creates a 30 character string beginning with <code>"AKM_CC_Test_"</code> and ending in a sequence of <code>1:nrow(pipel)</code> with leading zeros.</p> <pre><code>x &lt;- "AKM_CC_Test_" sprintf("%s%0*d", x, 30 - nchar(x), 1:nrow(pipel)) </code></pre> <ul> <li><code>%s</code> inserts <code>x</code> into the string</li> <li><code>%0*d</code> adds <code>1:nrow(pipel)</code> with <code>*</code> leading zeros, after <code>x</code>. The <code>*</code> is used to insert <code>30 - nchar(x)</code> into the format (I did it programatically; you could just insert 18 there if you want)</li> </ul> <p>An example on a simple length 5 (<code>1:5</code>) vector would be </p> <pre><code>x &lt;- "AKM_CC_Test_" sprintf("%s%0*d", x, 30 - nchar(x), 1:5) # [1] "AKM_CC_Test_000000000000000001" "AKM_CC_Test_000000000000000002" # [3] "AKM_CC_Test_000000000000000003" "AKM_CC_Test_000000000000000004" # [5] "AKM_CC_Test_000000000000000005" </code></pre>
TypeError remains: Str object is not callable <p>I'm trying to make a python program that converts a 24-hour notation to a 12-hour notation, but the linux shell keeps saying: 'Str' object is not callable. I'm looking for hours now but can't find the solution? Do you people see it?</p> <p>def time(time, hours, minutes):</p> <pre><code> """ Changes time from 24-hour notation to 12-hour notation and adds postfix""" if int(hours) &gt; 12: x = ("{0:&lt;20}, is the same time as{1:&gt;20}{2:&gt;20}".format(time, hours -12 + ":" + minutes, "PM")) return x if int(hours) &lt; 12 and int(minutes) != 00 : x = ("{0:&lt;20}, is the same time as{1:&gt;20}{2:&gt;20}".format(time, time, "AM")) return x if int(hours) == 00 and int(minutes) == 00: x = ("{0:&lt;20}, is the same time as{1:&gt;20}{2:&gt;20}".format(time, hours +12 + ":" + minutes, "AM")) return x if int(hours) == 12 and int(minutes) == 00: x = ("{0:&lt;20}, is the same time as{1:&gt;20}{2:&gt;20}".format(time, time , "PM")) return x </code></pre> <p>def main():</p> <pre><code> print("{0:^30}".format("24h times converted to 12h times")) for time in sys.stdin: hours, minutes = time.split(':') y = time(time,hours, minutes) print (y) </code></pre> <p>if <strong>name</strong> == "<strong>main</strong>": main()</p>
<p>In the main loop you are using same name for the Function and the String i.e "time". This is causing ambiguity. Give them a different name and it will work fine. Use Like this.</p> <pre><code>for timeString in sys.stdin: hours, minutes = timeString.split(':') y = time(timeString,hours, minutes) print (y) </code></pre> <p>Hope this helps.</p>
cant configure dataSource and delegate <p>So i upgraded Xcode and the GitHub project code to swift 3.0 (my project is in Obj C and some of the pods i use from GitHub are in Swift). I got a bunch of errors and now i am stuck on these ones. For some reason my dataSource and delegate for the floatingActionButton (<a href="https://github.com/yoavlt/LiquidFloatingActionButton" rel="nofollow">git here</a>) now doesn't work. I tried to set the <code>dataSource</code> and <code>delegate</code> programmatically and on storyboard but it didn't work.</p> <p>Errors:</p> <blockquote> <p>Property 'dataSource' not found on object of type 'LiquidFloatingActionButton *'</p> <p>Property 'delegate' not found on object of type 'LiquidFloatingActionButton *'</p> </blockquote> <p>I believe if i figure out the <code>dataSource</code> and <code>delegate</code> issue then it'll fix the colour error below.</p> <p>Screenshot: <a href="http://i.stack.imgur.com/dJkCY.png" rel="nofollow"><img src="http://i.stack.imgur.com/dJkCY.png" alt="enter image description here"></a></p> <p>.h:</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; #import "ProductContentViewController.h" #import "LiquidFloatingActionButton-swift.h" @interface SetScreenViewController : UIViewController &lt;UIPageViewControllerDataSource, LiquidFloatingActionButtonDelegate, LiquidFloatingActionButtonDataSource&gt; ... @end </code></pre> <p>.m:</p> <pre><code> #import "LiquidFloatingActionButton-Swift.h" LiquidFloatingActionButton *floatingActionButton; NSMutableArray *liquidCells; bool *closeFloatingButtons; NSString *videoToWatchURL; - (void)addLiquidButton{ //Grabs the coordinates bottom right of the screen float X_Co = self.view.frame.size.width - 50; float Y_Co = self.view.frame.size.height - 50; //i subtract 10 so the button will be placed a little bit out X_Co = X_Co - 10; Y_Co = Y_Co - 10; //I create each cell and set the image for each button liquidCells = [[NSMutableArray alloc] init]; [liquidCells addObject:[[LiquidFloatingCell alloc]initWithIcon:[UIImage imageNamed:@".png"]]]; [liquidCells addObject:[[LiquidFloatingCell alloc]initWithIcon:[UIImage imageNamed:@".png"]]]; [liquidCells addObject:[[LiquidFloatingCell alloc]initWithIcon:[UIImage imageNamed:@".png"]]]; [liquidCells addObject:[[LiquidFloatingCell alloc]initWithIcon:[UIImage imageNamed:@".png"]]]; [liquidCells addObject:[[LiquidFloatingCell alloc]initWithIcon:[UIImage imageNamed:@".png"]]]; [liquidCells addObject:[[LiquidFloatingCell alloc]initWithIcon:[UIImage imageNamed:@".png"]]]; //Sets the floating button at the loaction provided floatingActionButton = [[LiquidFloatingActionButton alloc] initWithFrame:CGRectMake(X_Co, Y_Co, 50, 50)]; floatingActionButton.dataSource = self;//Error here floatingActionButton.delegate = self;//and here. //I set the color of the floating button floatingActionButton.color = [self colorWithHexString:@"01b8eb"]; //Enables the user interaction fuction to true so itll open or close floatingActionButton.userInteractionEnabled = YES; //Adds the flaoting button to the view [self.view addSubview:floatingActionButton]; } -(NSInteger)numberOfCells:(LiquidFloatingActionButton *)liquidFloatingActionButton{ return liquidCells.count; } -(LiquidFloatingCell *)cellForIndex:(NSInteger)index{ return [liquidCells objectAtIndex:index]; } </code></pre> <p>PodFile:</p> <pre><code># Uncomment this line to define a global platform for your project # platform :ios, '9.0' target 'Whats New' do # Uncomment this line if you're using Swift or would like to use dynamic frameworks # use_frameworks! # Pods for Whats New target 'Whats NewTests' do inherit! :search_paths # Pods for testing end target 'Whats NewUITests' do inherit! :search_paths # Pods for testing end pod 'CRToast', '~&gt; 0.0.7' pod "LiquidFloatingActionButton" pod 'DGActivityIndicatorView' pod 'M13ProgressSuite' pod 'SDWebImage', '~&gt;3.8' pod 'FSCalendar' use_frameworks! post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_settings['SWIFT_VERSION'] = '3.0' end end end end </code></pre>
<p>I think the problem is that your Objective-C code does not know the „<code>open var</code>“s <code>dataSource</code> and <code>delegate</code> of the <code>LiquidFloatingButton</code> Swift code.<br> To make them known, a Obj-c header file is required that exposes these Swift infos to your Obj-C code. This is described in detail in the Apple docs „<a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html" rel="nofollow">Swift and Objective-C in the Same Project</a>“, in your case particularly in the section „<em>Importing External Frameworks</em>“. It says:<br> <em>You can import a framework into any Objective-C .m file within a different target using the following syntax:</em> </p> <pre><code>@import FrameworkName; </code></pre>
Sub functions ml <p>So I'm trying to do an assignment for an ml course, the issue is that the function requires a set type: <code>int * int -&gt; int</code> for example, and the way that I see to solve the problem is to use another function (say for iteration) to solve the problem.</p> <p>I believe that lisp has some kind of way of having a function be in scope for only one other function.</p> <p>I think that this could be done:</p> <pre><code>fun a (x, y) = let fun b (i,j) = ...; in ...; </code></pre> <p>[Not sure of exact syntax for this but I remember reading something like this only it was for temporary variables (which could be functions?]</p> <p>but please correct me if this is wrong.</p>
<p>In ML, functions are first class citizens (i.e. values). You can bind them via <code>let</code> just like any other value. </p> <p>Therefore, your idea is correct. It is especially a good design for functions passed as "iterators" (i.e. to map/fold/iter). Your question is too vague however for any further advise.</p>
Batch file find a string <p>How can i get a word from a file and set it to a variabile for ex:</p> <p>The text file contains bunch of text and i want to find only one word with the 4 or 5 random characters behind it</p> <p>Fatbardh: 79%</p> <p>Now i want to get that Fatbardh word but the 79% could be random number it can be any number, i want to get that random number and set it to an variable</p> <p>can someone help me the text file is pretty long with a lot of words as well not only containing one word i dont know how to do it</p>
<p>Since you know the string token in the line you're searching for, you can use <code>FOR /F</code> to process the output of the <code>FINDSTR</code> command.</p> <pre><code>@echo off for /f "tokens=2 delims=: " %%a in ('findstr /i "Fatbardh" "YourFile.txt"') do set percent=%%a echo %percent% </code></pre> <p>If you don't want the % symbol in the variable, include it in the delimiters.</p> <pre><code>@echo off for /f "tokens=2 delims=:%% " %%a in ('findstr /i "Fatbardh" "YourFile.txt"') do set percent=%%a echo %percent% </code></pre>
grouping mongo documents using elements of array field <p>I have below 3 documents. Each represents a contact for a user :</p> <pre><code>{ "_id" : ObjectId("57f9f9f3b91d070315273d0d"), "profileId" : "test", "displayName" : "duplicateTest", "email" : [ { "emailId" : "a@a.com" }, { "emailId" : "b@b.com" }, { "emailId" : "c@c.com" } ] } { "_id" : ObjectId("57f9fab2b91d070315273d11"), "profileId" : "test", "displayName" : "duplicateTest2", "email" : [ { "emailId" : "a@a.com" } ] } { "_id" : ObjectId("57f9fcefb91d070315273d15"), "profileId" : "test", "displayName" : "duplicateTest2", "email" : [ { "emailId" : "b@b.com" } ] } </code></pre> <p>I need to aggregate/group them by array elements so that I can identify the duplicate contact ( based on email id). Since there is a common email id between doc (1 &amp; 2) and doc( 1 &amp; 3) these 3 represent one contact and should be merged into one as one contact.</p> <p>I tried doing this using $unwind and $group in java as below:</p> <pre><code>List&lt;DBObject&gt; aggList = new ArrayList&lt;DBObject&gt;(); BasicDBObject dbo = new BasicDBObject("$match", new BasicDBObject("profileId", "0fb72dcf-292b-4343-a0e7-1d613a803b1e")); aggList.add(dbo); BasicDBObject dboUnwind = new BasicDBObject("$unwind", "$email"); aggList.add(dboUnwind); BasicDBObject dboGroup = new BasicDBObject("$group", new BasicDBObject().append("_id", new BasicDBObject("name", "$email.emailId")) .append("uniqueIds", new BasicDBObject("$addToSet", "$_id")) .append("count", new BasicDBObject("$sum", 1))); aggList.add(dboGroup); BasicDBObject dboCount = new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$gte", 2))); aggList.add(dboCount); BasicDBObject dboSort = new BasicDBObject("$sort", new BasicDBObject("count",-1)); aggList.add(dboSort); BasicDBObject dboLimit = new BasicDBObject("$limit", 10); aggList.add(dboLimit); AggregationOutput output = collection.aggregate(aggList); System.out.println(output.results()); </code></pre> <p>This groups docs by email id (and rightly so) but doesn't serves the purpose.</p> <p>Any help would be highly appreciated.</p> <p>I need to implement the feature where user can be prompted about the possible duplicate contacts in his repository. I need aggregation result to be something like:</p> <pre><code>[ { "_id":{ "name":[ { "emailId" : "a@a.com" }, { "emailId" : "b@b.com" }, { "emailId" : "c@c.com" } ] }, "uniqueIds":[ { "$oid":"57f9fcefb91d070315273d15" }, { "$oid":"57f9fcefb91d070315273d11" }, { "$oid":"57f9fcefb91d070315273d15" } ], "count":3 }, </code></pre> <p>So basically, I need _id for all possible duplicate contacts (there could be another group of duplicates with _ids list as above) so that I can prompt it to user and user can merge them at his will. Hope its more clear now. Thanks!</p>
<p>Well your question differs a bit from the result you are seeking. Your inital question pointed me to the following aggregation:</p> <pre><code>db.table.aggregate( [ { $unwind: "$email" }, { $group: { _id : "$email.emailId", duplicates : { $addToSet : "$_id"} } } ] ); </code></pre> <p>This results in:</p> <pre><code>{ "_id" : "c@c.com", "duplicates" : [ ObjectId("57f9f9f3b91d070315273d0d") ] } { "_id" : "b@b.com", "duplicates" : [ ObjectId("57f9fcefb91d070315273d15"), ObjectId("57f9f9f3b91d070315273d0d") ] } { "_id" : "a@a.com", "duplicates" : [ ObjectId("57f9fab2b91d070315273d11"), ObjectId("57f9f9f3b91d070315273d0d") ] } </code></pre> <p>Grouped by EMail.</p> <p>But the sample output you added to your question made this aggregation:</p> <pre><code>db.table.aggregate( [ { $unwind: "$email" }, { $group: { _id : "$profileId", emails : { $addToSet : "$email.emailId"}, duplicates : { $addToSet : "$_id"} } } ] ); </code></pre> <p>Which results in:</p> <pre><code>{ "_id" : "test", "emails" : [ "c@c.com", "b@b.com", "a@a.com" ], "duplicates" : [ ObjectId("57f9fcefb91d070315273d15"), ObjectId("57f9fab2b91d070315273d11"), ObjectId("57f9f9f3b91d070315273d0d") ] } </code></pre>
Is there a better way than `const` to store large blocks of text? <p>I am making a single page web app with React. One of my pages has a large block of text like so:</p> <pre><code>const ContentText = &lt;p&gt;......huge block of text.......&lt;/p&gt; </code></pre> <p>It looks very ugly in my editor and I was wondering if there was a best practice for storing large blocks of text to render on a page.</p>
<p>I would create a module with your text and import it. That way you shouldn't care at all what it looks like in your editor because you're not really touching that file unless you're specifically trying to edit your huge block of text.</p> <pre><code>export default ` ....huge block of text.... ` </code></pre> <p>Then where you actually use it:</p> <pre><code>import hugeText from './text/hugeText' .... render() { return &lt;p&gt;{hugeText}&lt;/p&gt; } </code></pre> <p>Editors like atom and sublime also have "soft wrap" mode so you don't have a ton of horizontal scrolling.</p>
How to store temporary data in an Azure multi-instance (scale set) virtual machine? <p>We developed a server service that (in a few words) supports the communications between two devices. We want to make advantage of the scalability given by an Azure Scale Set (multi instance VM) but we are not sure how to share memory between each instance.</p> <p>Our service basically stores temporary data in the local virtual machine and these data are read, modified and sent to the devices connected to this server.</p> <p>If these data are stored locally in one of the instances the other instances cannot access and do not have the same information. Is it correct?</p> <p>If one of the devices start making some request to the server the instance that is going to process the request will not always be the same so the data at the end is spread between instances.</p> <p>So the question might be, how to share memory between Azure instances?</p> <p>Thanks</p>
<p>You could use <a href="https://azure.microsoft.com/en-us/documentation/articles/service-fabric-overview/" rel="nofollow">Service Fabric</a> and take advantage of <strong><a href="https://azure.microsoft.com/en-us/documentation/articles/service-fabric-reliable-services-reliable-collections/" rel="nofollow">Reliable Collections</a></strong> to have your state automagically replicated across all instances.</p> <p>From <a href="https://azure.microsoft.com/en-us/documentation/articles/service-fabric-reliable-services-reliable-collections/" rel="nofollow">https://azure.microsoft.com/en-us/documentation/articles/service-fabric-reliable-services-reliable-collections/</a>:</p> <blockquote> <p>The classes in the <code>Microsoft.ServiceFabric.Data.Collections</code> namespace provide a set of out-of-the-box collections that automatically make your state highly available. Developers need to program only to the Reliable Collection APIs and let Reliable Collections manage the replicated and local state.</p> <p><strong>The key difference between Reliable Collections and other high-availability technologies (such as Redis, Azure Table service, and Azure Queue service) is that the state is kept locally in the service instance while also being made highly available.</strong></p> <p>Reliable Collections can be thought of as the natural evolution of the <code>System.Collections</code> classes: a new set of collections that are designed for the cloud and multi-computer applications without increasing complexity for the developer. As such, Reliable Collections are:</p> <ul> <li>Replicated: State changes are replicated for high availability.</li> <li>Persisted: Data is persisted to disk for durability against large-scale outages (for example, a datacenter power outage).</li> <li>Asynchronous: APIs are asynchronous to ensure that threads are not blocked when incurring IO.</li> <li>Transactional: APIs utilize the abstraction of transactions so you can manage multiple Reliable Collections within a service easily.</li> </ul> </blockquote> <p><strong>Working with Reliable Collections</strong> -<br> <a href="https://azure.microsoft.com/en-us/documentation/articles/service-fabric-work-with-reliable-collections/" rel="nofollow">https://azure.microsoft.com/en-us/documentation/articles/service-fabric-work-with-reliable-collections/</a></p>
R tcltk: error when trying to display a png file depending on the OS <p>This is an issue I am encountering for different pieces of codes I am writing in R. Basically, I would like to generate a window that displays a picture (a .png file). Following for instance guidances from <a href="http://www.sciviews.org/recipes/tcltk/TclTk-image-display" rel="nofollow">this</a> or <a href="http://stackoverflow.com/questions/17581954/is-there-a-way-to-convert-image-with-r-jpeg-to-gif-for-example">this</a>, I come up with this kind of code:</p> <pre><code>library(tcltk) tmpFile &lt;- tempfile(fileext = ".png") download.file("https://www.r-project.org/logo/Rlogo.png", tmpFile) tcl("image","create","photo", "imageLogo", file=tmpFile) win1 &lt;- tktoplevel() tkpack(ttklabel(win1, image="imageLogo", compound="image")) </code></pre> <p>This works fine under Mac OS, but not on Linux nor on Windows, where I am displayed such an error message:</p> <blockquote> <p>[tcl] couldn't recognize data in image file</p> </blockquote> <p>I can find some workarounds when I want to display graphs, using for instance packages <code>tkrplot</code> or <code>igraph</code>. Nonetheless, I would be really eager to understand why I got such errors when running my scripts on Linux or Windows, whereas it works just fine on Mac OS.</p> <p>Apologies in case this issue is obvious, but I haven't found anything about potential differences with the <code>tcltk</code> package depending on the OS.</p>
<p>Tk's native support for PNG was added in 8.6. Prior to that, you need to have the <a href="https://sourceforge.net/projects/tkimg/" rel="nofollow">tkimg extension</a> loaded <em>into Tk</em> to add the image format handler required. If your installation of Tcl/Tk that R is using is set up right, you can probably make it work with:</p> <pre><code>tclRequire("Img") </code></pre> <p>once you've initialised things sufficiently. Yes, the name used internally is “<code>Img</code>” for historical reasons, but that's just impossible to search for! (This is the key thing <a href="https://stat.ethz.ch/pipermail/r-help/2005-August/077811.html" rel="nofollow">in this mailing list message from way back</a>.)</p> <p>However, upgrading the versions of Tcl and Tk to 8.6 is likely to be a better move.</p>
Lumen return information about deleted record, always gets ModelNotFoundException <p>I'm trying to use Pusher with Lumen to push events to clients to get data refresh. I've created very simple Event:</p> <pre><code>class CarEvent extends Event implements ShouldBroadcast{ use SerializesModels; public $car; private $type; public function __construct( Car $car, $type ) { $this-&gt;car = $car; $this-&gt;type = $type; } public function broadcastOn() { return ['car']; } public function broadcastAs() { return $this-&gt;type; } } </code></pre> <p>And I'm successfully fireing it in my controller using <code>Event::fire(new CarEvent($car,"add"));</code><br> Inside Pusher console I get below event: <a href="http://i.stack.imgur.com/R2hpp.png" rel="nofollow"><img src="http://i.stack.imgur.com/R2hpp.png" alt="enter image description here"></a></p> <p>My problem begins when I try to send event when record is deleted, below is my code:</p> <pre><code>public function deleteCar($id){ $car = $this-&gt;cars-&gt;findOrFail($id); $car-&gt;delete(); $oldCar = new Car; $oldCar-&gt;id=$id; Event::fire(new CarEvent($oldCar,"delete")); return Response::deleted(); } </code></pre> <p>This always gives <code>ModelNotFoundException</code> because model with given Id not exists anymore, which is true.</p> <p>My question is how I can fire event that will tell that car with specific id is deleted. I don't want to create another class that will extend Event and will be used only for delete, I'd like to use my existing CarEvent class.</p> <p>I need to pass simple object with just Id property like so: <a href="http://i.stack.imgur.com/Skav4.png" rel="nofollow"><img src="http://i.stack.imgur.com/Skav4.png" alt="enter image description here"></a></p> <p>Can I create Car object and set it <code>Id</code> property and somehow disable getting rest if data from database when model is serialized?</p>
<p>The problem doesn't come up when serializing but rather when unserializing. You see, your Event uses the <code>SerializesModels</code> trait. This trait has the following method:</p> <pre><code>protected function getRestoredPropertyValue($value) { if (! $value instanceof ModelIdentifier) { return $value; } return is_array($value-&gt;id) ? $this-&gt;restoreCollection($value) : (new $value-&gt;class)-&gt;newQuery()-&gt;useWritePdo()-&gt;findOrFail($value-&gt;id); } </code></pre> <p>This trait serializes models as a <code>ModelIdentifier</code>, which just holds the class name and the id. When unserializing, the model is fetched fresh from the database using that information. In your delete case, the <code>findOrFail</code> makes it, well, fail.</p> <p>I guess you can think of a solution that suits your needs now. This one, for instance, I guess should work for different models; if you know you just want this for Car models you can make a more straightforward one.</p> <pre><code>protected function getRestoredPropertyValue($value) { if ($this-&gt;type == 'delete' &amp;&amp; $value instanceof ModelIdentifier) { $model = (new $value-&gt;class); $pk = $model-&gt;getQueueableId(); $model-&gt;$pk = $value-&gt;id; return $model; } return parent::getRestoredPropertyValue($value); } </code></pre> <hr> <p><strong>Update</strong> Probably it's cleaner to have separate Events as you suggest. All constructors should receive a Car model, and for the delete case you create a simple object with the attributes you need. </p> <pre><code>abstract class CarEvent extends Event implements ShouldBroadcast { use SerializesModels; public $car; protected $type; public function __construct(Car $car) { $this-&gt;car = $car; } public function broadcastOn() { return ['car']; } public function broadcastAs() { return $this-&gt;type; } } </code></pre> <hr> <pre><code>class AddCarEvent extends CarEvent { protected $type = 'add'; } </code></pre> <hr> <pre><code>class DeleteCarEvent extends CarEvent { protected $type = 'delete'; public function __construct(Car $car) { $this-&gt;car = (object) ['id' =&gt; $car-&gt;id]; } } </code></pre>
Number range animation with maxscript <p>i'm new to maxscript and i'm trying to animate (show) numbers from number 0 to number 220 with maxscript. My problem is that i want to make <strong>integer</strong> range but with this code, it's making float number. help me !</p> <pre><code>b=box name: "ControlBox" wirecolor:blue height:1 t=text name: "ControlledText" wirecolor:red t.baseobject.renderable=true theCtrl = float_script() theCtrl.addNode "TheText" t theCtrl.addNode "TheBox" b theCtrl.SetExpression "TheText.text = TheBox.height as string\n0" t.kerning.controller=theCtrl animate on at time 100 b.height=220 max tool zoomextents all playAnimation() </code></pre>
<p>Change <code>TheBox.height</code> to <code>int(TheBox.height)</code> in your expression. There are also <code>ceil</code> and <code>floor</code> functions if you want to round to the next lower/higher number before truncating.</p>
Using HTTP in Angular 2: @angular/http/bundles/http.umd.js/src not found <p>I try to use HTTP module in angular 2. Here are the parts of code I added, hoping it'd be enough (not including usage of it):</p> <p><strong>systemjs.config.js</strong> (mapping)</p> <p>'<code>@angular/http': 'npm:@angular/http/bundles/http.umd.js'</code></p> <p><strong>app.module.ts</strong></p> <pre><code>import { Http } from '@angular/http'; (...) @NgModule({imports: [(...), Http] </code></pre> <p><strong>package.json</strong></p> <pre><code>"dependencies": { (...), "@angular/http": "2.0.0"} </code></pre> <p>Errors I get:</p> <pre><code>zone.js:1274 GET http://localhost:3000/node_modules/@angular/http/bundles/http.umd.js/src 404 (Not Found)scheduleTask @ zone.js:1274ZoneDelegate.scheduleTask @ zone.js:216Zone.scheduleMacroTask @ zone.js:153(anonymous function) @ zone.js:1304send @ VM700:3fetchTextFromURL @ system.src.js:1051(anonymous function) @ system.src.js:1781ZoneAwarePromise @ zone.js:478(anonymous function) @ system.src.js:1780(anonymous function) @ system.src.js:2809(anonymous function) @ system.src.js:3387(anonymous function) @ system.src.js:3701(anonymous function) @ system.src.js:4093(anonymous function) @ system.src.js:4556(anonymous function) @ system.src.js:4825(anonymous function) @ system.src.js:407ZoneDelegate.invoke @ zone.js:203Zone.run @ zone.js:96(anonymous function) @ zone.js:462ZoneDelegate.invokeTask @ zone.js:236Zone.runTask @ zone.js:136drainMicroTaskQueue @ zone.js:368ZoneTask.invoke @ zone.js:308 (index):31 Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:3000/node_modules/@angular/http/bundles/http.umd.js/src(…) </code></pre> <p>I checked and file http.umd.js is available at <em>@angular/http/bundles/http.umd.js</em>. Why is angular checking @angular/http/bundles/http.umd.js/<strong>src</strong>?</p>
<p>You are using <strong><code>Http</code></strong> wrong way in Angular2, It should be,</p> <pre><code>import { HttpModule } from '@angular/http'; @NgModule({ imports: [BrowserModule,HttpModule], ... }) </code></pre> <p>Now in <strong>component</strong> <code>eg. AppComponent</code></p> <pre><code>import { Http } from '@angular/http'; </code></pre>
Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables when trying to secure query <p>I wanted to secure my php code from sql injections using the bind_param functions and I came across this error. I checked the amount of ?'s and bind_params but they are both equal, so I have no idea what I have done wrong.</p> <p>I think this is the part the error comes from:</p> <pre><code>$conn = mysqli_connect($servername, $username, $password, $database); $searchText = $_POST['search']; echo "You searched for: " . htmlspecialchars($searchText, ENT_QUOTES, 'UTF-8'); $query = $conn-&gt;prepare("SELECT * FROM recources WHERE recource_title LIKE '%?%' OR recource_topic LIKE '%?%' OR recource_author LIKE '%?%' OR recource_description LIKE '%?%';"); $query-&gt;bind_param('s', $searchText, $searchText, $searchText, $searchText); $query-&gt;execute(); </code></pre> <p>Edit: I tried using <code>$query-&gt;bind_param('ssss'</code> instead of 1 s, but I still get this error.</p>
<p>You need to unquote your placeholders and concatenate the wildcards in the binding. Your error is because you have no placeholders in your query.</p> <p>Once you correct the placeholders you'll need to correct the binding call. The first parameter is what each variable being bound is so:</p> <pre><code>bind_param('s' </code></pre> <p>should really be</p> <pre><code>bind_param('ssss' </code></pre> <p>(because you have 4 variables) A Full example:</p> <pre><code>$query = $conn-&gt;prepare("SELECT * FROM recources WHERE recource_title LIKE ? OR recource_topic LIKE ? OR recource_author LIKE ? OR recource_description LIKE ?;"); $wild_var = '%' . $searchText . '%'; $query-&gt;bind_param('ssss', $wild_var, $wild_var, $wild_var, $wild_var); $query-&gt;execute(); </code></pre>
python nested if statements not working <p>I'm trying to make a game using pygame, and I've set up a couple of functions that I've tested and they work fine. However, in the code below, when I add a print statement to show if my code works, it prints on the first one but not the second. Any help?</p> <pre><code>for square in row: tile_x = row.index(square) # print statement works here if self.x_pos - tile_x &gt;= -4 and self.x_pos - tile_x &lt;= 4: tile_x = 4 - (self.x_pos - tile_x) tile_y = 4 - (self.y_pos - tile_y) if square == 'G': display('Grass',tile_x,tile_y) # print statement doesn't work here elif square == 'T': display('Tree',tile_x,tile_y) elif square == 'B': display('Bush',tile_x,tile_y) elif square == 'R': display('Rock',tile_x,tile_y) elif square == 'S': display('Stone',tile_x,tile_y) # display function has been tested, and it works fine </code></pre>
<p>I have just thought of something</p> <p>I am using <code>row.index(square)</code>, which is finding the <strong>first</strong> 'g' square and using the tile_x of <strong>that</strong> first square. This means it thinks the square I'm looking for is not in the correct range to show on the map, so the first if statement returns False and it doesn't show up or print out.</p>
My WebJob is missing dependency <p>I've created a webjob with a simple C# Console application. I make use of the Azure blobs and a database connection - locally everything works like a charm.</p> <p>In Azure portal I've made a simple app where I added my exe and force it to run. From the logs i get:</p> <pre><code>[10/09/2016 20:38:52 &gt; ed5cb9: ERR ] Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.WindowsAzure.Storage, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. </code></pre> <p>Don't mind the 6.0.0.0 version, I've tried 7.0.0.0 and the latest 7.2.1, the result does not differ.</p>
<blockquote> <p>Could not load file or assembly 'Microsoft.WindowsAzure.Storage, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.</p> </blockquote> <p>According to the error you provided, I recommend that you could try to make sure the specific assembly is deployed to Azure. You could use Kudu Console and check your assembly in the following path:</p> <p><code>d:\home\site\wwwroot\app_data\jobs\[triggered|continuous]\{job name}</code></p> <p>Additionally, if you deploy your WebJob via the Azure Portal, you could directly upload a zip file that contains the WebJob's files. For more details about Web Jobs, you could follow this <a href="https://github.com/projectkudu/kudu/wiki/Web-jobs" rel="nofollow">tutorial</a>.</p>
Where to find a dataset for Cross-Site Scripting (XSS)? <p>I'm working on a project related to XSS and currently I need a dataset that I can run through WEKA for example, to test some classification algorithms. I've been searching for it on Google but no luck.</p> <p>Please help me if you can, I would be very grateful.</p> <p>Thank you</p>
<p>You can have a look at this: <a href="https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet" rel="nofollow">XSS Cheat Sheet</a></p>
Unenroll Moodle users in a category using SQL <p>I need to <strong>unenroll</strong> all the <strong>users</strong> at once <strong>from all the courses</strong> in a specific <strong>category</strong> (chosen by name or shortname) in my <strong>moodle</strong> site. I think that a SQL statement is the way to do this.</p> <p>Courses aren't empty so delete all the courses is no option.</p> <p>Thank you</p>
<p>I have not tested the following solution, but it should produce the desired effect:</p> <pre><code>require($CFG-&gt;libdir . '/coursecatlib.php'); require($CFG-&gt;libdir . '/enrollib.php'); $categoryid = 0; // Replace with the desired category ID. $category = coursecat::get($categoryid); foreach ($category-&gt;get_courses() as $course) { // Simulates the deletion of the course, a better solution is to copy // the logic from `enrol_course_delete` here directly. enrol_course_delete($course); } </code></pre> <p>The above script can take a while so you should probably execute this from the command line.</p> <p>You can loop over the sub-categories using:</p> <pre><code>$categories = $category-&gt;get_children(); foreach ($categories as $category) { } </code></pre> <p>To obtain the ID of a category by shortname, use the following:</p> <pre><code>$name = "My category"; $categoryid = $DB-&gt;get_field('course_categories', 'id', array('name' =&gt; $name), MUST_EXIST); </code></pre> <p>Note that categories can have identical names, you should use the category <code>idnumber</code> instead.</p>
MYSQL select category that contains at least two elements from another table <p>Ecommerce: say I have two tables, one Categories, another Items.</p> <pre><code>Categories ------- category_id category_name Items ----- item_id item_name category_id </code></pre> <p>I need to select &amp; list on my page all those Categories that contains at least <strong>two</strong> items.</p> <p>I also need to know how many Categories overall i have, so i can paginate... Also, I need to show the number of items under each category if possible with mysql.</p> <p>so i tried</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS *, (SELECT * FROM items i WHERE i.category_id = c.category_id) as tot FROM categories c RIGHT JOIN items i ON i.category_id = c.category_id HAVING tot &gt; 1 LIMIT 10 </code></pre> <p>but doesn't work... any help is appreciated</p>
<p>What you are looking for is a simple aggregation where you group by category and count items.</p> <pre><code>select c.category_id, c.category_name, count(*) as items from categories c join items i on i.category_id = c.category_id group by c.category_id having count(*) &gt;= 2 order by c.category_id limit @skip, @show; </code></pre> <p>If you want to know how many categories match your condition:</p> <pre><code>select count(*) from categories c where ( select count(*) from items i where i.category_id = c.category_id ) &gt;= 2; </code></pre>
Retrieve all the classes annotated with a specific annotation(s) <p>I have defined a simple annotation in scala like this</p> <pre><code>case class MyAnnotation(value: String) extends StaticAnnotation </code></pre> <p>and then some classes that use this annotation</p> <pre><code>@MyAnnotation("en_US") class TestAnnotation </code></pre> <p>Now, I would like to get at runtime <strong>all</strong> the classes annotated with such annotation, but the documentation about <a href="http://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html" rel="nofollow">mirrors</a> and <a href="http://docs.scala-lang.org/overviews/reflection/annotations-names-scopes" rel="nofollow">annotations</a> in scala-reflect is not clear at all :-/</p> <p>Can anybody shed some lights on how to perform such runtime search?</p> <p>Thanks!</p>
<p>Over <a href="http://stackoverflow.com/questions/28214579/scala-reflection-finding-and-instantiating-all-classes-with-a-given-annotation">here</a> most likely the same question was asked and it was recommended to use <a href="https://github.com/ronmamo/reflections" rel="nofollow">reflections library</a>. <a href="http://www.47deg.com/blog/scala-macros-annotate-your-case-classes" rel="nofollow">Here</a> there is a sample of processing annotation with macro. </p> <p>Hope these links will be useful for you.</p>
Invalid length for a Base-64 char array or string on PDF blob data from Dynamics CRM <p>I am working on some code to read out the BODY field from a Dynamics CRM Email attachment and decode the Base64 string back to a file to write to the file system.</p> <p>This process seems to work fine on image files like .PNG etc, Excel .xls etc, but when i try and convert a PDF file to a byte array in C# i get the error:</p> <p>Invalid length for a Base-64 char array or string on the Convert.FromBase64String() line.</p> <pre><code>var binaryData = File.ReadAllText(@"E:\test\stream.txt"); byte[] byteArray = Convert.FromBase64String(binaryData); File.WriteAllBytes(@"E:\test\file.pdf", byteArray); </code></pre> <p>I've tried storing the binarydata in a file and reading it in as well as just defining a C# string with the content. As i say, it works on other file types but just not PDF. </p> <p>I found another reference to the same issue, <a href="https://social.microsoft.com/Forums/en-US/7a28e106-3715-42b9-a743-9e5207a02540/problem-while-decoding-the-body-field-of-activitymimeattachment-entity?forum=crm" rel="nofollow">https://social.microsoft.com/Forums/en-US/7a28e106-3715-42b9-a743-9e5207a02540/problem-while-decoding-the-body-field-of-activitymimeattachment-entity?forum=crm</a></p> <p>But the solution was just to loop through a byte array and write each byte individually, it still ends up in a corrupt PDF file that wont open in Acrobat.</p> <p>Ultimately, i will read the binaryData in from a database field or through the CRM API, but i just wanted to test the theory first and I seem to be good on all attachment types except PDF...</p>
<p>This is just a guess of mine, I have no idea if this works.</p> <p>Sometimes the character encoding is wrong because text files may have a BOM (<a href="https://en.wikipedia.org/wiki/Byte_order_mark" rel="nofollow">Byte Order Mark</a>) and just arbitrary binary data can interfere with it. You can force the encoding to ASCII by reading the data in as a binary <code>byte[]</code> and then converting it into ASCII as shown here:</p> <pre><code>byte[] data; data = File.ReadAllBytes(@"E:\test\stream.txt"); string base64 = System.Text.Encoding.ASCII.GetString(data); data = Convert.FromBase64String(base64); File.WriteAllBytes(@"E:\test\file.pdf", data); </code></pre> <p>Let's see if this solves anything.</p>
How to run firebird as an application? <p>I have downloaded ZIP file and unpacked it.</p> <p>Now, it is said, that FB can run as an application. How to run it this way?</p> <p>Running <code>firebird.exe</code> does nothing.</p> <p>I don't want to install it as a service. </p>
<p>Ok, it is </p> <pre><code>firebird -a </code></pre> <p>It is not listed here: <a href="http://firebirdsql.org/manual/firebird-commandline-utilities.html" rel="nofollow">http://firebirdsql.org/manual/firebird-commandline-utilities.html</a></p>
alternative to multiple data selector <p>I'm using <a href="https://github.com/no81no/jplist" rel="nofollow">jplist</a> plugin and following contributor's recommendations to toggle sorting.</p> <p>But having issue with multiple data-attribute selector.</p> <p>To trigger I need to select the element by multiple attribute like data-path, data-order and I don't know why : I can't trigger using a selector with multiple attributes. The console doesn't show any error. This just doesn't work </p> <pre><code>$('#toggle-order1').click(function() { // current sort button selected in sort group 1 -- return data-path var sortpath1 = $('#sortgroup1 .jplist-selected').attr('data-path'); // current sort button selected in sort group 1 -- return data-order var sortorder1 = $('#sortgroup1 .jplist-selected').attr('data-order'); if (sortorder1 == 'asc') { // *** This doesn't click any button $('button[data-path="' + sortpath1 + '"] [data-order="desc"]').trigger('click'); // *** This work but click all buttons that have data-path equals to sortpath1 $('button[data-path="' + sortpath1 + '"]').trigger('click'); } else if (sortorder1 == 'desc') { // *** This doesn't click any button $('button[data-path="' + sortpath1 + '"] [data-order="asc"]').trigger('click'); // *** This work but click all buttons that have data-path equals to sortpath1 $('button[data-path="' + sortpath1 + '"]').trigger('click'); } }); </code></pre> <p>The html buttons :</p> <pre><code>&lt;div id="sortgroup1" class="jplist-box" data-control-type="sort-buttons-group" data-control-name="sort-buttons-group-1" data-control-action="sort" data-mode="single"&gt; &lt;button id="set-asc-1" name="set" class="jplist-drop-down" data-path=".set" data-group="group1" data-type="text" data-order="asc" data-selected="false"&gt; Sort by Set AZ &lt;/button&gt; &lt;button id="set-desc-1" name="set" class="jplist-drop-down" data-path=".set" data-group="group1" data-type="text" data-order="desc" data-selected="false"&gt; Sort by Set ZA &lt;/button&gt; &lt;button id="price-asc-1" name="price" class="jplist-drop-down" data-path=".price" data-group="group1" data-type="number" data-order="asc" data-selected="false"&gt; Sort by Price ASC &lt;/button&gt; &lt;button id="price-desc-1" name="price" class="jplist-drop-down" data-path=".price" data-group="group1" data-type="number" data-order="desc" data-selected="false"&gt; Sort by Price DESC &lt;/button&gt; &lt;/div&gt; </code></pre> <p>The html toggle</p> <pre><code>&lt;button id="toggle-order1"&gt;&lt;i class="fa"&gt;&lt;/i&gt;&lt;/button&gt; </code></pre> <p>All suggestions are welcome.</p>
<p>You have to remove the space between the attributes, so this</p> <pre><code>$('button[data-path="' + sortpath1 + '"] [data-order="desc"]') </code></pre> <p>becomes this</p> <pre><code>$('button[data-path="' + sortpath1 + '"][data-order="desc"]') // ^^ look ma, no space </code></pre> <p>otherwise you're looking for descendant elements, just as you would with</p> <pre><code>$('div span') </code></pre>
HTML5 Canvas and JS Framerate slowly drops to 0 <p>I am trying to setup an html 5 canvas for a game and my fps starts out fine but then it slowly falls to 0 fps and lags the browser window out. I feel like I am missing something very important.</p> <p>JS I am using to manage the refresh and drawing:</p> <pre><code>var stop = false; var frameCount = 0; var $results = $("#stats"); var fps, fpsInterval, startTime, now, then, elapsed; var $canvas = $("#gameWorld")[0]; var context = $canvas.getContext("2d"); startAnimating(30); function startAnimating(fps) { fpsInterval = 1000 / fps; then = Date.now(); startTime = then; console.log(startTime); animate(); } function animate() { // stop if (stop) { return; } // request another frame requestAnimationFrame(animate); // calc elapsed time since last loop now = Date.now(); elapsed = now - then; // if enough time has elapsed, draw the next frame if (elapsed &gt; fpsInterval) { then = now - (elapsed % fpsInterval); // draw stuff here draw(); // Statistics var sinceStart = now - startTime; var currentFps = Math.round(1000 / (sinceStart / ++frameCount) * 100) / 100; $results.text("FPS: " + Math.round(currentFps)); } } function draw() { context.clearRect(0, 0, width, height); drawBackground(); } // Draw grid background function drawBackground() { context.strokeStyle = '#e6ebf4'; context.lineWidth = 1; var size = 50; for(var i=0; i &lt; width + size; i+=size) { context.moveTo(i,0); context.lineTo(i,height); context.stroke(); } for(var j=0; j &lt; height + size; j+=size) { context.moveTo(0,j); context.lineTo(width,j); context.stroke(); } } // resize the canvas to fill browser window dynamically window.addEventListener('resize', resizeCanvas, false); function resizeCanvas() { width = $canvas.width = window.innerWidth; height = $canvas.height = window.innerHeight; } resizeCanvas(); </code></pre> <p>Here is the Fiddle: <a href="https://jsfiddle.net/gf7kt8k8/" rel="nofollow">https://jsfiddle.net/gf7kt8k8/</a></p>
<p>The reason is, you are not clearing your paths. Use </p> <pre><code>context.beginPath(); </code></pre> <p>at the begin of <code>draw()</code>. This question was asked before <a href="http://stackoverflow.com/questions/9558895/html5-canvas-slows-down-with-each-stroke-and-clear#9559703">here</a></p>
Updating MongoDB document with a wildcard in field name <p>Have a fairly deeply nested document, part of the nesting includes an object that's a hash of ObjectIDs and a corresponding object. I need to update all the documents in the collection by updating just one value in the nested object. So I'm aware that if I had a structure like:</p> <pre><code>{ "name" : "Bob", "address" : { "street" : "123 Baker St" } } </code></pre> <p>I could update all "street" values with the following shell command: </p> <pre><code>db.mycollection.update({}, {$set : {"address.street" : "124 Baker St"}}, {multi: true}); </code></pre> <p>But in my case, the structure isn't so straightforward, it's got those UUIDs in there, and I want to update all. The structure is more like this:</p> <pre><code>{ "name": "Bob", "addresses" : { "0934029572035702834234092834" : { "street" : "123 Baker St" }, "0904958304959879873876862378" : { "street" : "123 Baker St" } } } </code></pre> <p>OK&lt; not a great example b/c in the real world you wouldn't want to change those addresses to be the same, but suppose for a moment that I do. How do I get all of the documents to change all "street" values in the nested "addresses" object without having to do it OID by OID? </p>
<p>I suppose you know the UUID's :P It's not a array but nested document structure which comes to a update command like:</p> <pre><code>db.mycollection.update({}, {$set : {"addresses.0934029572035702834234092834.street" : "124 Baker St"}}, {multi: true}); </code></pre>
Plot multiple surfaces <p>I'm trying and plot multiple surfaces on the same chart with Plotly package but I just can't get it done. A few days ago I could do this with no problem using the same code, but now it seems that after an update on Plotly it's not possible anymore. Here is an example of what I'm trying to do:</p> <pre><code>#Volcano surface plot_ly(z = volcano, type = 'surface') %&gt;% #First rectangle add_trace(x = c(10, 60), y = c(10, 50), z = matrix(160, nrow = 2, ncol = 2), type = 'surface', showscale = FALSE) %&gt;% #Second rectangle add_trace(x = c(10, 60), y = c(10, 50), z = matrix(180, nrow = 2, ncol = 2), type = 'surface', showscale = FALSE) </code></pre> <p>When I run the code above, I get the following output:</p> <pre><code>Error in p$x$data[[idx]]$marker : $ operator is invalid for atomic vectors </code></pre> <p>If I assign the Plotly object to some variable instead of using the '%>%' operator, like this:</p> <pre><code>#Volcano surface p &lt;- plot_ly(z = volcano, type = 'surface') #First rectangle p &lt;- add_trace(p, x = c(10, 60), y = c(10, 50), z = matrix(160, nrow = 2, ncol = 2), type = 'surface', showscale = FALSE) #Second rectangle p &lt;- add_trace(p, x = c(10, 60), y = c(10, 50), z = matrix(180, nrow = 2, ncol = 2), type = 'surface', showscale = FALSE) #Plot object p </code></pre> <p>... then I get the same output as before.</p> <p>If I plot the volcano and just one of the rectangles, it works just fine. Furthermore, I've tried to plot different surfaces than the rectangles and, still, I get the same error.</p> <p>Here is some information that might help:</p> <pre><code>&gt; sessionInfo() R version 3.3.1 (2016-06-21) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 16.04.1 LTS locale: [1] LC_CTYPE=pt_BR.UTF-8 LC_NUMERIC=C LC_TIME=pt_BR.UTF-8 LC_COLLATE=en_US.UTF-8 [5] LC_MONETARY=pt_BR.UTF-8 LC_MESSAGES=en_US.UTF-8 LC_PAPER=pt_BR.UTF-8 LC_NAME=C [9] LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=pt_BR.UTF-8 LC_IDENTIFICATION=C attached base packages: [1] parallel stats graphics grDevices utils datasets methods base other attached packages: [1] plotly_4.5.2 ggplot2_2.1.0 shiny_0.14.1 doMC_1.3.4 [5] iterators_1.0.8 quantstrat_0.9.1739 foreach_1.4.3 blotter_0.9.1741 [9] PerformanceAnalytics_1.4.4000 FinancialInstrument_1.2.0 quantmod_0.4-6 TTR_0.23-1 [13] xts_0.9-7 zoo_1.7-13 loaded via a namespace (and not attached): [1] Rcpp_0.12.7 compiler_3.3.1 plyr_1.8.4 base64enc_0.1-3 tools_3.3.1 digest_0.6.10 viridisLite_0.1.3 [8] jsonlite_1.1 tibble_1.2 gtable_0.2.0 lattice_0.20-34 DBI_0.5-1 yaml_2.1.13 dplyr_0.5.0 [15] httr_1.2.1 htmlwidgets_0.7 grid_3.3.1 R6_2.1.3 purrr_0.2.2 tidyr_0.6.0 magrittr_1.5 [22] scales_0.4.0 codetools_0.2-14 htmltools_0.3.5 assertthat_0.1 mime_0.5 xtable_1.8-2 colorspace_1.2-6 [29] httpuv_1.3.3 lazyeval_0.2.0 munsell_0.4.3 </code></pre> <p>Any thoughts about that issue?</p>
<p>Solved. Re-wrote code to:</p> <pre><code>#Create Plotly object plot_ly(showscale = FALSE) %&gt;% #Volcano surface add_surface(z = volcano) %&gt;% #First rectangle add_surface(x = c(10, 60), y = c(10, 50), z = matrix(160, nrow = 2, ncol = 2)) %&gt;% #Second rectangle add_surface(x = c(10, 60), y = c(10, 50), z = matrix(180, nrow = 2, ncol = 2)) </code></pre> <p>Works like a charm. Did it based on <a href="https://plot.ly/r/3d-surface-plots/" rel="nofollow">this</a> multiple surfaces plot example.</p>
Funcitonal Opposite of Subtract by Key <p>I have two RDDs of the form RDD1[K, V1] and RDD2[K, V2]. I was hoping to remove values in RDD2 which are not in RDD1. (Essentially an inner join on each of the RDD's keys, but I don't want to copy over RDD1's values.)</p> <p>I understand that there's a method <code>subtractByKey</code> which performs the opposite of this. (Keeps those that are distinct.)</p>
<p>You cannot avoid having some type of value here so applying <code>join</code> and mapping values seems to be the way to go. You can use:</p> <pre><code>rdd2.join(rdd1.mapValues(_ =&gt; None)).mapValues(_._1) </code></pre> <p>which replaces values with dummies (usually you can skip that because there is not much to gain here unless values are largish):</p> <pre><code>_.mapValues(_ =&gt; None) </code></pre> <p>joins, and drops placeholders:</p> <pre><code>_.mapValues(_._1) </code></pre>
Is there any callback function for Upload Image addon for CKEditor? <p>I am using CKeditor in my project and I have a requirement where I need to upload images too.</p> <p>I have downloaded <a href="http://ckeditor.com/addon/uploadimage" rel="nofollow">http://ckeditor.com/addon/uploadimage</a> Addon and it works fine. It perfectly sends data to server too.</p> <p>I just needed to add </p> <pre><code>CKEDITOR.config.filebrowserBrowseUrl = '/browser/browse.php'; CKEDITOR.config.filebrowserUploadUrl = '/uploader/upload.php'; </code></pre> <p>to make it work.</p> <p>But issue is, I want to to send additional parameters to server as well, so I know which product/item is being edited.</p> <p>Sending just image to server makes no sense to me, CKEditor has no information on it. Can someone please help me to send additional parameter to <code>UploadUrl</code>?</p>
<p>you can set <code>CKEDITOR.config.filebrowserUploadUrl</code> dynamically when you call <code>CKEDITOR.replace()</code>; this gives the ability to set different <code>UploadUrl</code> in different page. </p> <p>In your case I think you just need append different query string to <code>uploadUrl</code></p> <p>like:</p> <pre><code>CKEDITOR.replace( textarea_name, {filebrowserImageUploadUrl : '/uploader/upload.php?productId=123', filebrowserBrowseUrl : '/uploader/upload.php'} ) </code></pre> <p>In serverside upload.php you can receive <code>productId</code> when upload process is done, pass the <code>productId</code> to a callback function;</p>
Add tab to anchor text with regex <p>I have something like this ;</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;a href="#" class="example"&gt; Link 1 &lt;/a&gt; &lt;a href="#" class="example"&gt; Link 2 &lt;/a&gt; &lt;a href="#" class="example"&gt; Link 3 &lt;/a&gt;</code></pre> </div> </div> </p> <p>I want add tab before anchor text. Like this;</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;a href="#" class="example"&gt; Link 1 &lt;/a&gt; &lt;a href="#" class="example"&gt; Link 2 &lt;/a&gt; &lt;a href="#" class="example"&gt; Link 3 &lt;/a&gt;</code></pre> </div> </div> </p> <p>How can I do this with regex?</p>
<h2>Edit, following the question extension</h2> <p>From his comments, it now appears that the OP targets a more general use, adding <code>\t</code>s to <em>indent all lines</em> between the opening and closing tag.<br> Then its time to remember that <strong>regex is not a good way to parse HTML</strong>, as frequently observed here.</p> <p>But in this yet not too wide context we can propose a solution.<br> Unless somebody finds a better solution, I don't see a way to do it without 2 nested steps:</p> <pre><code>$updated_text = preg_replace_callback( '/(&lt;a[^&gt;]*&gt;)\s*(.*?)\s*(&lt;\/a&gt;)/s', function($matches) { return $matches[1] . "\n" . preg_replace('/([^\n]+)/', "\t$1", $matches[2]) . "\n" . $matches[3]; }, $text ); </code></pre> <p>Note that, in addition to be a poor way of doing it, it's much time consuming due to the <code>.*?</code> (not greedy) quantifier. </p> <hr> <h2>Initial answer</h2> <p>Thanks to the @bobblebubble suggestion I just understood what means "I want add tab" (I previously thought only to browser's tabs :).</p> <p>But I find its solution a bit too general: it'll add tab to <em>any line</em> which is not a tag!<br> I'd prefer to closely look for only <code>&lt;a&gt;</code> tags, and only when presented like in the OP's example:</p> <pre><code>$updated_text = preg_replace('/(&lt;a[^&gt;]*&gt;)\s*([^&lt;]*)\s*&lt;\/a&gt;/', '$1\n\t$2&lt;/a&gt;', $text); </code></pre> <p>Here is it working: <a href="https://regex101.com/r/qo2N22/1" rel="nofollow">https://regex101.com/r/qo2N22/1</a>.</p>
Adding same extensions to multiple controls in winforms <p>I want to add some extensions like move, resize,... to <code>PictureBox</code>, <code>Label</code>, <code>Panel</code> like this:</p> <pre><code>public class LiveControl: PictureBox { private Point cur = new Point(0, 0); public LiveControl() { ResizeRedraw = true; MouseDown += (s, e) =&gt; { cur = new Point(e.X, e.Y); }; MouseMove += (s, e) =&gt; { if (e.Button == MouseButtons.Left) { Control x = (Control)s; x.SuspendLayout(); x.Location = new Point(x.Left + e.X - cur.X, x.Top + e.Y - cur.Y); x.ResumeLayout(); } }; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); var rc = new Rectangle(this.ClientSize.Width - grab, this.ClientSize.Height - grab, grab, grab); ControlPaint.DrawSizeGrip(e.Graphics, this.BackColor, rc); } protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == 0x84) { var pos = this.PointToClient(new Point(m.LParam.ToInt32() &amp; 0xffff, m.LParam.ToInt32() &gt;&gt; 16)); if (pos.X &gt;= this.ClientSize.Width - grab &amp;&amp; pos.Y &gt;= this.ClientSize.Height - grab) m.Result = new IntPtr(17); } } private const int grab = 16; } </code></pre> <p>Is there anyway that I write it like a class and inherit it for all of them, or should I write 3 separate classes like the one I have written for the <code>PictureBox</code>?</p>
<p>You can encapsulate the logic in a helper class deriving from <a href="https://msdn.microsoft.com/en-us/library/system.windows.forms.nativewindow(v=vs.110).aspx" rel="nofollow"><code>NativeWindow</code></a> class. This way you can do the job without creating a derived class for each control which you want to move/resize.</p> <p>You can pass the control which you want to extend to the constructor of helper class and assign your control handle to the native window. Then overriding <code>WndProc</code> of native window will handle messages of the control. </p> <p>Also other stuffs like handling event of the control is simply possible by keeping a reference to the control which you passed in constructor and assigning event handlers.</p> <p>After creating such native window helper class the usage would be:</p> <pre><code>var h1 = new LiveControlHelper(this.pictureBox1); var h2 = new LiveControlHelper(this.button1); </code></pre> <p>Or you can use the helper for all controls of a container in a loop.</p> <p><strong>Example</strong></p> <p>In below example, I refactored the code which you posted. This way you can use the code for all controls without need to inheritance.</p> <pre><code>using System; using System.Drawing; using System.Windows.Forms; </code></pre> <pre><code>public class LiveControlHelper : NativeWindow { private Control control; private Point cur = new Point(0, 0); private const int grab = 16; public LiveControlHelper(Control c) { control = c; this.AssignHandle(c.Handle); control.MouseDown += (s, e) =&gt; { cur = new Point(e.X, e.Y); }; control.MouseMove += (s, e) =&gt; { if (e.Button == MouseButtons.Left) { Control x = (Control)s; x.SuspendLayout(); x.Location = new Point(x.Left + e.X - cur.X, x.Top + e.Y - cur.Y); x.ResumeLayout(); } }; control.Paint += (s, e) =&gt; { var rc = new Rectangle(control.ClientSize.Width - grab, control.ClientSize.Height - grab, grab, grab); ControlPaint.DrawSizeGrip(e.Graphics, control.BackColor, rc); }; control.Resize += (s, e) =&gt; { control.Invalidate(); }; } protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == 0x84) { var pos = control.PointToClient(new Point(m.LParam.ToInt32() &amp; 0xffff, m.LParam.ToInt32() &gt;&gt; 16)); if (pos.X &gt;= control.ClientSize.Width - grab &amp;&amp; pos.Y &gt;= control.ClientSize.Height - grab) m.Result = new IntPtr(17); } } } </code></pre> <p><strong>Note</strong></p> <p><strong>1-</strong> To be able to revert the control to its normal state (non-resizable non-movable) it's better to assign event handlers using methods and not using lambda. You need to revome event handlers to revert the control to its normal state. Also to do so, you need to call <code>DestroyHanlde</code> method of helper class.</p> <p><strong>2-</strong> I just refactored the posted code to make it reusable for controls without need to implement a derived version of all controls. But you can enhance the code by:</p> <ul> <li><p>Enable moving the control and resizing it using surface, edges and corners of control by setting <code>m.Result</code> to suitable values.</p></li> <li><p>Draw grab borders/handlers on control.</p></li> </ul> <p><strong>3-</strong> If you need to call <code>SetStyle</code> on control, you can simply use an extension method from <a href="http://stackoverflow.com/a/36773585/3110834">this post</a> and call it this way:</p> <pre><code>control.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true); </code></pre>
Pushing Laravel 5.2 app to Heroku, all files in public/ are missing <p>I have a Laravel application deployed on Heroku. However, all files that are in 'public' folder of my application are not loaded.</p> <p>That is, no css and / or js are loaded pages after deployment. Only HTML is loaded.</p> <p>This is the structure of my 'public' folder:</p> <p><img src="http://i.stack.imgur.com/X6Uqn.png" alt="This is the structure of my &#39;public&#39; folder"></p> <p>I'm loading the css that way:</p> <pre><code>&lt;link href="{{ URL::asset('css/bootstrap.min.css') }}" rel="stylesheet"&gt; </code></pre> <p>And JS that way:</p> <pre><code>{!! Html::script('js/parsley.min.js') !!} </code></pre> <p><strong>EDIT</strong></p> <p>I've figured out what was wrong.</p> <p>Instead of loading the css the way I was doing, I should do this:</p> <pre><code> &lt;link href="{{ asset('css/parsley.css') }}" rel="stylesheet"&gt; </code></pre> <p>And for Js:</p> <pre><code>&lt;script type="text/javascript" src="{{ asset('js/parsley.min.js') }}&gt;&lt;/script&gt; </code></pre>
<p>It's very strange.</p> <p>Are you sure that the files exist in the public folder?</p> <p>Laravel 5.2 does not include html helpers function out the box, do you update your composer? </p> <p>You can remove helper function and try without it, just use... </p> <p>for css </p> <pre><code> &lt;link href="/css/bootstrap.min.css" rel="stylesheet"&gt; </code></pre> <p>and js</p> <pre><code> &lt;script src="/js/parsley.min.js"&gt;&lt;/script&gt; </code></pre> <p>if everything is ok, the problem is in your helper functions.</p>
PHP explode in array <p>I was wondering is it possible to convert the following array:</p> <pre><code>Array ( "2016-03-03 19:17:59", "2016-03-03 19:20:54", "2016-05-03 19:12:37" ) </code></pre> <p>Into this:</p> <pre><code>Array ( "2016-03-03", "2016-03-03", "2016-05-03" ) </code></pre> <p>Without creating any loops?</p>
<p>There's no explicit loops, if you can use <a href="http://php.net/manual/en/function.array-map.php"><code>array_map</code></a>, although internally it loops:</p> <pre><code>function format_date($val) { $v = explode(" ", $val); return $v[0]; } $arr = array_map("format_date", $arr); </code></pre> <p>From the PHP Manual:</p> <blockquote> <p><code>array_map()</code> returns an array containing all the elements of <code>array1</code> after applying the <code>callback</code> function to each one. The number of parameters that the <code>callback</code> function accepts should match the number of arrays passed to the <code>array_map()</code>.</p> </blockquote> <p>Also, when you are dealing with Dates, the right way to do is as follows:</p> <pre><code>return date("Y-m-d", strtotime($val)); </code></pre> <hr> <p>The simple way, using loops is to use a <code>foreach()</code>:</p> <pre><code>foreach($arr as $key =&gt; $date) $arr[$key] = date("Y-m-d", strtotime($date)); </code></pre> <p>This is the most simplest looping way I can think of considering the <code>index</code> to be anything.</p> <hr> <p><strong>Input:</strong></p> <pre><code>&lt;?php $arr = array( "2016-03-03 19:17:59", "2016-03-03 19:20:54", "2016-05-03 19:12:37" ); function format_date($val) { $v = explode(" ", $val); return $v[0]; } $arr = array_map("format_date", $arr); print_r($arr); </code></pre> <p><strong>Output</strong></p> <pre><code>Array ( [0] =&gt; 2016-03-03 [1] =&gt; 2016-03-03 [2] =&gt; 2016-05-03 ) </code></pre> <p><strong>Demo: <a href="http://ideone.com/r9AyYV">http://ideone.com/r9AyYV</a></strong></p>
counting COUNT(*) results in MySQL <p>I need to count the number of records returned from a MySQL query. </p> <pre><code>SELECT COUNT(sa.facility_hmis) AS deployed FROM facility_service_area sa GROUP BY sa.facility_hmis </code></pre> <p>this will give me lets say 6 rows as the result, but i need it to give me a single row with just the number counted rows i.e 6 </p>
<p>If all you need is to count number of distinct <code>facility_hmis</code> you can do that explicitly, without counting of anything else:</p> <pre><code>SELECT COUNT(DISTINCT facility_hmis) FROM facility_service_area </code></pre>
In Highstocks, how do I change the default time/day labels when hovering over graph? <p>I have managed to change the default x-axis labels in highcharts/highstocks with a formatter function, but despite looking in the API I cannot figure out how to change the on-hover title (Example: When I hover over the columns for 'Mark' in the graph, it reads 'Thursday ..' along with the correct values for Mark. But I want it titled 'Mark', along with the values). How do I change this? (I want to use highstocks (not highcharts) because I have much more data than presented)</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="http://code.highcharts.com/stock/highstock.js"&gt;&lt;/script&gt; &lt;script src="http://code.highcharts.com/modules/data.js"&gt;&lt;/script&gt; &lt;div id="container"&gt;&lt;/div&gt; &lt;/body&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; var newLabels = ['Marky', 'Ricky', 'Danny', 'Terry', 'Mikey']; $('#container').highcharts('StockChart', { chart: { type: 'column' }, credits: { enabled: false }, xAxis: { categories: ['Marky', 'Ricky', 'Danny', 'Terry', 'Mikey'], labels: { rotation: -45, formatter: function() { return newLabels[this.value]; }}, }, title: { text: 'Anything But the Index' }, series: [ {name: '1',data:[0.067028837967,0.0,0.0]}, {name: '1a',data:[0.187515270425,0.18818380744,0.0857142857143]}, {name: '1b',data:[0.31600895865,0.0,0.169987200178,0.399354014733,0.0873578570502]}, {name: '2',data:[0.0,0.0,0.0,0.0,1.0]}, {name: '3',data:[0.998898678414,1.0,1.0,0.998898678414,1.0]}, {name: '4',data:[0.0,0.0,0.0,0.0,0.3]}, {name: '6',data:[0.505930477918,0.0,0.190192368338,0.597371635879,0.285892370193]}, ], scrollbar: { enabled: true, }, navigator: { series: { type: 'areaspline', }}, rangeSelector: { enabled:false, }, }); &lt;/script&gt; &lt;/head&gt; &lt;div id="container" style="height: 400px; min-width: 310px"&gt;&lt;/div&gt; &lt;/html&gt; </code></pre>
<p>So you want to customize the tooltip? This is how to do it.</p> <p><a href="https://jsfiddle.net/yfgpg5x2/12/" rel="nofollow">https://jsfiddle.net/yfgpg5x2/12/</a></p> <pre><code> tooltip: { formatter: function() { var curTickLabelString = this.points[0].series.xAxis.ticks[this.x].label.textStr; var tooltipString = "&lt;b&gt;" + curTickLabelString + ":&lt;br&gt;&lt;/b&gt;"; var curName, curValue, curColor, curGraphic; for (var i = 0; i &lt; this.points.length; i++) { curName = this.points[i].series.name; curValue = this.points[i].y; curColor = this.points[i].color; curGraphic = '●'; tooltipString += '&lt;br&gt;'+ curGraphic +' &lt;b style="color: ' + curColor + '"&gt;' + curName + ':&lt;/b&gt; ' + curValue; } return tooltipString; } }, </code></pre> <p><a href="http://i.stack.imgur.com/5PUvW.png" rel="nofollow"><img src="http://i.stack.imgur.com/5PUvW.png" alt="enter image description here"></a></p> <p>Read more about tooltips here:</p> <p><a href="http://api.highcharts.com/highcharts/tooltip" rel="nofollow">http://api.highcharts.com/highcharts/tooltip</a></p>
Python : Hash extension attack in python <p>I want to use h to generate the same md5 as b</p> <p>Here is the code:</p> <pre><code>k = "secret" m = "show me the grade" m2 = "show me the grade and change it to 100" x = " and change it to 100" a = md5(k + m) b = md5(k + m2) print "have---&gt; " + a.hexdigest() #9f4bb32ac843d6db979ababa2949cb52 print "want---&gt; " + b.hexdigest() #aba1d6fede83a87d9d6e22bf75974599 h = md5(state="9f4bb32ac843d6db979ababa2949cb52".decode("hex"),count=512) h.update(x) print h.hexdigest() # these two lines get 958acc96a173fd4d7571ac365db06f65 print md5((k + m + padding(len(k + m)*8))+ x).hexdigest() def padding(msg_bits): """padding(msg_bits) - Generates the padding that should be appended to the end of a message of the given size to reach a multiple of the block size.""" index = int((msg_bits &gt;&gt; 3) &amp; 0x3f) if index &lt; 56: padLen = (56 - index) else: padLen = (120 - index) # (the last 8 bytes store the number of bits in the message) return PADDING[:padLen] + _encode((msg_bits &amp; 0xffffffffL, msg_bits&gt;&gt;32), 8) </code></pre> <p>I don't know why the last line couldn't output aba1d6fede83a87d9d6e22bf75974599. Is there something wrong with the padding?</p>
<p>This is because the hash you expected (aba1..) is the md5 hash of <code>k + m + x</code> while the hash you got (958a..) is the md5 hash of <code>k + m + padding + x</code>.</p> <p>The length extension attack lets you generate a hash <code>h2 = md5(k + m + padding + x)</code> based on only knowing the hash <code>h1 = md5(k + m)</code> and the length of the message <code>l = len(k + m)</code>. However, as far as I know, it doesn't let you get rid of the padding between the messages, so you're left with some garbage in between.</p>
How to join two supplier results <p>I have selected and used sum() over PARTITION for the sales data every month by branch. I have tried group by but then I could not get the branch total sales.</p> <p>And I want to specifically see the results of two suppliers and their value in percentage to total sales. </p> <pre><code>SELECT distinct sv.Branch 'Branch', dim.ExclusiveGroup_KEY 'Exclusive Tag', sum(sv.Revenue) over (PARTITION by sv.branch, dim.ExclusiveGroup_KEY) 'Supplier 1', sum(sv.Revenue) over (PARTITION by sv.branch, dim.ExclusiveGroup_KEY) 'Supplier 2', sum(sv.Revenue) over (PARTITION by sv.Branch) 'Branch Overall', sum(sv.Revenue) over (PARTITION by sv.branch, dim.ExclusiveGroup_KEY)/sum(sv.Revenue) over (PARTITION by sv.Branch) 'Amount %' FROM dbo.SalesView as sv WHERE sv.Time between ? and ? </code></pre> <p>But the output is putting the results on separate lines. </p> <pre><code>|Branch|Exclusive Tag|Supplier 1|Supplier 2|Branch Overall|Amount %| |000001|EXCLSUPPLIER1|700 |700 |25000 |2.8% | |000001|EXCLSUPPLIER2|1400 |1400 |25000 |5.6% | |000002|EXCLSUPPLIER1|1300 |1300 |60000 |2.2% | |000002|EXCLSUPPLIER2|800 |800 |60000 |1.3% | </code></pre> <p>I want the results to be something like this</p> <pre><code>|Branch|Supplier 1|Supplier 2|Branch Overall|Supp1 %|Supp2 %| |000001|700 |1400 |25000 |2.8% |5.6% | |000002|1300 |800 |60000 |2.2% |1.3% | </code></pre> <p>Please let me know what changes I can make to the codes to show the desired results. Any help or suggestion will be greatly appreciated!</p>
<p>It is not the best solution and it is not the final one, but I have not enough information - for example I don't know how do you join to dim table. I guess you should use PIVOT. Here goes some dirtier solution:</p> <pre><code>SELECT sv.Branch [Branch] --,dim.ExclusiveGroup_KEY [Exclusive Tag] ,(SELECT SUM(svint.Revenue) FROM dbo.SalesView svint WHERE svint.Branch=sv.Branch AND dim.ExclusiveGroup_KEY='EXCLSUPPLIER1') [Supplier 1] ,(SELECT SUM(svint.Revenue) FROM dbo.SalesView svint WHERE svint.Branch=sv.Branch AND dim.ExclusiveGroup_KEY='EXCLSUPPLIER2') [Supplier 2] ,SUM(sv.Revenue) [Branch Overall] ,(SELECT SUM(svint.Revenue) FROM dbo.SalesView svint WHERE svint.Branch=sv.Branch AND dim.ExclusiveGroup_KEY='EXCLSUPPLIER1')/SUM(sv.Revenue) [Supp1] ,(SELECT SUM(svint.Revenue) FROM dbo.SalesView svint WHERE svint.Branch=sv.Branch AND dim.ExclusiveGroup_KEY='EXCLSUPPLIER2')/SUM(sv.Revenue) [Supp2] --sum(sv.Revenue) over (PARTITION by sv.branch, dim.ExclusiveGroup_KEY) 'Supplier 1', --sum(sv.Revenue) over (PARTITION by sv.branch, dim.ExclusiveGroup_KEY) 'Supplier 2', --sum(sv.Revenue) over (PARTITION by sv.Branch) 'Branch Overall', --sum(sv.Revenue) over (PARTITION by sv.branch, dim.ExclusiveGroup_KEY)/sum(sv.Revenue) over (PARTITION by sv.Branch) 'Amount %' FROM dbo.SalesView as sv WHERE sv.Time between ? and ? GROUP BY sv.Branch </code></pre>
Hide Android keyboard in Nativescript on input field blur <p>I have a registration form which contains several TextFields and other inputs. When a user taps one of the fields the Android soft keyboard will always show as expected. If I tap outside of the field though the keyboard does not hide. Is there a way to capture this event so that I can hide the keyboard when ever a user taps outside of any of the inputs?</p> <p>It looks like doing the following allows me to hide the keyboard</p> <pre><code>var pageContainer = page.getViewById('registration-container'); if(pageContainer.android) { pageContainer.android.clearFocus(); } </code></pre> <p>But I'm unsure how to capture every tap event that blurs the forms inputs. I'm not even sure if this is possible with Android. </p>
<p>You can put the on tap listener to the parent view so that when you click on it (anywhere outside textfield), it will clear the focus of the textfield that are showing keyboard. The way you are doing is to clear the focus of the container while it should be exactly the textfield:</p> <p>In XML:</p> <pre><code>&lt;Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="onNavigatingTo"&gt; &lt;StackLayout tap="clearTextfieldFocus"&gt; &lt;Label text="Tap the button" class="title"/&gt; &lt;Label text="{{ message }}" class="message" textWrap="true"/&gt; &lt;TextField id="myTextfield" hint="Type here..."/&gt; &lt;/StackLayout&gt; &lt;/Page&gt; </code></pre> <p>In <code>page.js</code>:</p> <pre><code>function clearTextfieldFocus(args) { var layout = args.object; var myTextfield = layout.getViewById("myTextfield"); myTextfield.android.clearFocus(); } exports.clearTextfieldFocus = clearTextfieldFocus; </code></pre> <p>P/s: the tap listener on the textfield will override the parent listener, so clicking on textfield still focus and show keyboard</p>
Why does this While loop cycle twice? <p>I made this while loop that is supposed to fulfill functions for different shapes and after it fulfills the function for that shape, it will keep asking for shapes until the user types "Exit". I have only done Triangles so far so I just have some filler functions to fulfill to make sure that it loops correctly. The problem is, after I'm done with triangles, it will print the menu twice before asking for an input instead of just printing once. Can anyone explain this to me?</p> <pre><code>while(password){ System.out.println(); System.out.println("---Welcome to the Shape Machine---"); System.out.println("Available Options:"); System.out.println("Circles"); System.out.println("Rectangles"); System.out.println("Triangles"); System.out.println("Exit"); String option = keyboard.nextLine(); if(option.equals("Exit")){ System.out.println("Terminating the program. Have a nice day!"); return; } else if(option.equals("Triangles")){ System.out.println("Triangles selected. Please enter the 3 sides:"); int sideA = 0; int sideB = 0; int sideC = 0; do{ sideA = keyboard.nextInt(); sideB = keyboard.nextInt(); sideC = keyboard.nextInt(); if(sideA&lt;0 || sideB&lt;0 || sideC&lt;0) System.out.println("#ERROR Negative input. Please input the 3 sides again."); } while(sideA&lt;0 || sideB&lt;0 || sideC&lt;0); if((sideA+sideB)&lt;=sideC || (sideB+sideC)&lt;=sideA || (sideA+sideC)&lt;=sideB){ System.out.println("#ERROR Triangle is not valid. Returning to menu."); continue; } else { System.out.println("good job!"); } } } </code></pre>
<p>It might be that you are using <code>keyboard.nextLine();</code>. In your code outside the while loop make sure that you are always using <code>.nextLine()</code> and nothing else.</p> <p>Reasoning: If you use <code>.next()</code>, it'll only consume one word so the next time you call <code>.nextLine()</code>, it'll consume the end of that line. </p>
Is there a solution for transpiling Lua labels to ECMAScript3? <p>I'm re-building a Lua to ES3 transpiler (a tool for converting Lua to cross-browser JavaScript). Before I start to spend my ideas on this transpiler, I want to ask if it's possible to convert Lua labels to ECMAScript 3. For example:</p> <pre class="lang-lua prettyprint-override"><code>goto label; :: label :: print "skipped"; </code></pre> <p>My first idea was to separate each body of statements in parts, e.g, when there's a label, its next statements must be stored as a entire next part:</p> <pre><code>some body label (&amp; statements) other label (&amp; statements) </code></pre> <p>and so on. Every statement that has a body (or the program chunk) gets a list of parts like this. Each part of a label should have its name stored in somewhere (e.g, in its own part object, inside a property).</p> <p>Each part would be a function or would store a function on itself to be executed sequentially in relation to the others.</p> <p>A goto statement would lookup its specific label to run its statement and invoke a ES return statement to stop the current statements execution.</p> <p>The limitations of separating the body statements in this way is to access the variables and functions defined in different parts... So, is there a idea or answer for this? Is it impossible to have stable labels if converting them to ECMAScript?</p>
<p>I can't quite follow your idea, but it seems someone already solved the problem: JavaScript allows labelled <code>continue</code>s, which, combined with dummy <code>while</code> loops, permit emulating <code>goto</code> within a function. (And unless I forgot something, that should be all you need for Lua.)</p> <p>Compare pages 72-74 of the ECMAScript spec ed. #3 of 2000-03-24 to see that it should work in ES3, or just look at e.g. <a href="https://stackoverflow.com/a/9751229/805875">this answer to a question about goto in JS</a>. As usual on the 'net, the URLs referenced there are dead but you can get <a href="https://web.archive.org/web/20160304000830/http://summerofgoto.com/" rel="nofollow">summerofgoto.com [archived]</a> at the awesome Internet Archive. (Outgoing GitHub link is also dead, but the scripts are also archived: <a href="https://web.archive.org/web/20160304000830/http://www.summerofgoto.com/js/parseScripts.js" rel="nofollow">parseScripts.js</a>, <a href="https://web.archive.org/web/20160304000830/http://www.summerofgoto.com/js/goto.min.js" rel="nofollow">goto.min.js</a> or <a href="https://web.archive.org/web/20160304000830/http://www.summerofgoto.com/js/goto.js" rel="nofollow">goto.js</a>.)</p> <p>I hope that's enough to get things running, good luck!</p>
jQuery - Not adding class in safari? <p>I've written some jQuery which works with the Image Map Hotspot plugin to add classes to the pop-up based on the icon used. </p> <p>This works across Chrome and Firefox, but not in Safari, I was wondering if anyone could identify why?</p> <pre><code>$(window).load(function() { $('.info-icon').each(function() { var icon = $(this); var bgImg = $(this).css('background-image'); if (bgImg == 'url("http://www.domain.com/client1/wp-content/themes/BespokeTheme/images/purple-circle.svg")') { $(this).prev().addClass('detected-pu purple-popup'); } if (bgImg == 'url("http://www.domain.com/client1/wp-content/themes/BespokeTheme/images/orange-circle.svg")') { $(this).prev().addClass('detected-pu orange-popup'); } if (bgImg == 'url("http://www.domain.com/client1/wp-content/themes/BespokeTheme/images/green-circle.svg")') { $(this).prev().addClass('detected-pu green-popup'); } if (bgImg == 'url("http://www.domain.com/client1/wp-content/themes/BespokeTheme/images/lblue-circle.svg")') { $(this).prev().addClass('detected-pu lblue-popup'); } if (bgImg == 'url("http://www.domain.com/client1/wp-content/themes/BespokeTheme/images/dblue-circle.svg")') { $(this).prev().addClass('detected-pu dblue-popup'); } }) }); </code></pre> <p>Thanks!</p>
<p>Thanks To Jaromanda X - Not sure why I didn't think of logging the bgImg to see what Safari thought it was!</p> <p>Turns out Most browsers were returning the url("http://...") string, whereas Safari was dropping the double quotes, resulting in the url being tracked as url(<a href="http://.." rel="nofollow">http://..</a>.)</p> <p>All resolved now, Thanks Jaromanda for the pointer!</p>
Y86 Code - doesn't return or show rax <p>I am doing a class project which I am to take C code, turn it in x86-64 assembly and then change it to Y86. An in this I am suppose to return the sum of the elements in a linked list to to rax. However, when i try to use the y86 compiler, it doesn't appear. The y86 I made looked like this: </p> <pre><code>.pos 0 irmovq Stack,%rsp irmovq Stack,%rbp jmp Main Main: irmovq ele1,%rax pushq %rax call sum_list halt sum_list: pushq %rbp rrmovq %rsp,%rbp irmovq $24,%rdx subq %rdx,%rsp irmovq $0,%rdx rmmovq %rdx,-8(%rbp) jmp L2 L3: mrmovq 24(%rbp),%rax mrmovq (%rax),%rax mrmovq -8(%rbp),%rdx addq %rax,%rdx rmmovq %rdx,-8(%rbp) mrmovq 24(%rbp),%rax mrmovq -8(%rax),%rax rmmovq %rax,24(%rbp) L2: irmovq $0,%rcx mrmovq 24(%rbp),%rdx subq %rcx,%rdx jne L3 mrmovq -8(%rbp),%rax rrmovq %rbp,%rsp popq %rbp ret #linked-list .align 8 ele1: .quad 0x00d .quad ele2 ele2: .quad 0x0e0 .quad ele3 ele3: .quad 0xf00 .quad 0 .pos 0x500 Stack: </code></pre> <p>And so <code>rax</code> should have 0xfed, but in my result, nothing appears. </p> <p>This is the C code I got it from:</p> <pre><code>typedef struct ELE{ long val; struct ELE *next; } *list_ptr long sum_list(list_ptr ls){ long val = 0; while(ls){ val += ls-&gt;val; ls = ls-&gt;next; } return val; } </code></pre>
<p>Looking at the code, it seems that the pointer to node should be at 16(rbp), not 24(rbp). 0(rbp) = saved rbp value, 8(rbp) = return address, 16(rbp) = pointer to node (to the linked list). I don't see where the extra 8 bytes are pushed onto the stack before rbp is saved.</p> <p>The program ends at a halt instruction. Are you able to determined the content of rax when this happens (such as using a debugger)?</p>
How do I resize a Label's width? <p>I've been trying to resize a label's width for a while, but it seems IMPOSSIBLE, or at least incomprehensible for me...</p> <p>I'll explain my situation with images for the sake of clarity.</p> <p><a href="http://i.stack.imgur.com/buTNI.png" rel="nofollow"><img src="http://i.stack.imgur.com/buTNI.png" alt="enter image description here"></a></p> <p>This is how the Window looks with a "Normal" Label...</p> <p><a href="http://i.stack.imgur.com/PxVRW.png" rel="nofollow"><img src="http://i.stack.imgur.com/PxVRW.png" alt="enter image description here"></a></p> <p>This is how the Window looks with a ridiculously large text...</p> <p><a href="http://i.stack.imgur.com/mf3Q8.png" rel="nofollow"><img src="http://i.stack.imgur.com/mf3Q8.png" alt="enter image description here"></a></p> <p>Now, THIS IS how I want it to look when text is ridiculously large</p> <p>See?</p> <p>Here's the example code:</p> <pre><code># -*- coding: utf-8 -*- import gi import signal import hashlib import random gi.require_version("Gtk", "3.0") from gi.repository import Gtk, Pango class Test(Gtk.Window): def __init__(self): def center(a): a.props.valign = Gtk.Align.CENTER a.props.halign = Gtk.Align.CENTER Gtk.Window.__init__(self, title="Test") self.set_position(Gtk.WindowPosition.CENTER) self.set_border_width(10) self.set_resizable(False) self.connect("delete-event", Gtk.main_quit) Box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10) Button = Gtk.Button("Change Label") Label = Gtk.Label() Test = "I'm a Label, Yay!" center(Box) center(Label) center(Button) Label.set_markup('&lt;span&gt;&lt;big&gt;%s&lt;/big&gt;&lt;/span&gt;' % Test) Label.set_ellipsize(Pango.EllipsizeMode.END) Label.set_justify(Gtk.Justification.LEFT) self.add(Box) Box.add(Label) Box.add(Button) #UNKNOWN/FORBIDDEN/DEPRECIATED/INCOMPREHENSIBLE MAGIC! #Uncomment only one or both, and watch it's magic! #self.set_resizable(True) #Box.set_resize_mode(Gtk.ResizeMode.QUEUE) def change_label(self): Label.set_markup('&lt;span&gt;&lt;big&gt;%s&lt;/big&gt;&lt;/span&gt;' % str(hashlib.sha384(str(random.random())).hexdigest())) Button.connect("clicked", change_label) if __name__ == '__main__': MainWindow = Test() MainWindow.show_all() signal.signal(signal.SIGINT, signal.SIG_DFL) Gtk.main() </code></pre> <p>Please note that the Window IS NOT resizable.</p> <p>If you uncomment one or both of the "Magic" section, you'll see how the Window changes it's behaviour!</p> <p>BUT</p> <p>There are two disadvantages while using each one of this approaches:</p> <ul> <li><p>If you uncomment <code>#self.set_resizable(True)</code> WINDOW WILL BECOME RESIZABLE AGAIN, which I don't want it to happen</p></li> <li><p><code>#Box.set_resize_mode(Gtk.ResizeMode.QUEUE)</code> appears to be the "Perfect" solution, but while it does what I want, it seems it has been "Depreciated" in recent versions of Gtk.</p></li> </ul> <p>Moreover, in some other Window Managers &amp; Themes, It causes some disruptions on Window's dimentions when you change the Label's String a lot of times.</p> <p>Do you have any suggestions on this?</p> <p>I'm totally fed up with this. I've been trying for weeks, with no result :c</p> <p>Maybe there's a way to emulate the behaviour when Window is resizable, while NOT showing Resize Grips &amp; Maximize Button?</p> <p>Or what's the newer method to do <code>set_resize_mode(Gtk.ResizeMode.QUEUE)</code> ?</p> <p>PD: <code>Label.set_max_width_chars()</code> isn't what I'm searching for</p>
<p>You may want to read about frame clock in Gtk 3.12. Here is a good <a href="https://blogs.gnome.org/alexl/2013/11/04/the-modern-gtk-drawing-model/" rel="nofollow">article</a>. The new method to use in order to queue a resize is Gtk.Widget.queue_resize()</p> <blockquote> <p>If some state changes that causes the size of your widget to change you call gtk_widget_queue_resize() which will request a layout phase and mark your widget as needing relayout.</p> </blockquote> <p>I believe the modified sample code below does what you want. The trick consist in having sub-boxes to enclose the <code>Gtk.Label</code> and <code>Gtk.Button</code>. You then set <code>max_width_chars</code> to <code>1</code>, <code>ellipsize</code> to <code>END</code>, <code>hexpand</code> to <code>True</code> and <code>halign</code> to <code>FILL</code> on the label.</p> <pre><code>import signal import hashlib import random gi.require_version("Gtk", "3.0") from gi.repository import Gtk, Pango class Test(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Test") self.set_size_request(250,-1) self.set_position(Gtk.WindowPosition.CENTER) self.set_border_width(10) self.set_resizable(False) self.connect("delete-event", Gtk.main_quit) Box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10) Sub_box_left = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) Sub_box_right = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) Button = Gtk.Button("Change Label") Label = Gtk.Label() Test = "I'm a Label, Yay!" Label.set_markup('&lt;span&gt;&lt;big&gt;%s&lt;/big&gt;&lt;/span&gt;' % Test) Label.set_max_width_chars(1) Label.set_ellipsize(Pango.EllipsizeMode.END) Label.set_hexpand(True) Label.props.halign = Gtk.Align.FILL Label.set_justify(Gtk.Justification.LEFT) self.add(Box) Sub_box_left.add(Label) Sub_box_right.add(Button) Box.add(Sub_box_left) Box.add(Sub_box_right) def change_label(self): Label.set_markup('&lt;span&gt;&lt;big&gt;%s&lt;/big&gt;&lt;/span&gt;'%str(hashlib.sha384(str(random.random())).hexdigest())) Button.connect("clicked", change_label) if __name__ == '__main__': MainWindow = Test() MainWindow.show_all() signal.signal(signal.SIGINT, signal.SIG_DFL) Gtk.main() </code></pre>
JS debug - var bankroll value is way off <p>This is the first JS program I've ever written so any help would be greatly appreciated!</p> <p>I'm getting a bankroll value that is WAY off. For instance if you use</p> <p>runs=1, start=5000, bonusMultiplier = anything between 0 and 1</p> <p>I am usually getting a value for bankroll of 5000500. I've gone over the code for hours now but can't figure it out. In the number 5000500, 5000 comes from var start, and 500 comes from var betsize. I don't know how they get combined into one number. Please help!</p> <pre><code>var profit = 0; var runs = prompt("How many runs?"); var start = prompt("Starting chips?"); var bonusMultiplier = prompt("Bonus? Use decimal."); var inAmt = (start/(1+bonusMultiplier)); var bonusValue = bonusMultiplier * inAmt; function simulation(){ var bankroll = start; function makeBet(){ if (bankroll === 0){ console.log("BUSTO IN " + hands + "HANDS"); betsize = 0; } else if(bankroll &lt;=50) { betsize = bankroll; } else if (bankroll&lt;1000) { betsize = 1/2 * bankroll; } else { betsize = 500; } var odds = Math.floor(Math.random() * 1000+1); //console.log(odds); if (odds&gt;507) { bankroll = bankroll + betsize; } else { bankroll = bankroll - betsize; } console.log("bankroll " + bankroll); console.log("betsize " + betsize); } /*var hands=prompt("hands"); console.log("hands " + hands) for (i = 0; i &lt; hands; i++) { makeBet(); }*/ while (bankroll &gt;0) { if (bankroll&gt;=7000) {break;} makeBet(); } if (bankroll === 0) { profit -= inAmt; } if (bankroll &gt;=7000) { profit += bankroll; profit -= inAmt; }} for (i=0; i&lt;runs; i++) { simulation(); } console.log("start " + start, " bonus multiplier " + bonusMultiplier, " in amount "+ inAmt, " bonus value "+ bonusValue); console.log("profit after " + runs + " runs = $" + profit); </code></pre>
<p><code>start</code> is being interpreted as string. If you sum a string and a number, the number gets converted into a string, which is then concated with the other one. Change </p> <pre><code>start = prompt("Starting chips?"); </code></pre> <p>to </p> <pre><code>start = parseFloat(prompt("Starting chips?")); </code></pre>
How to implement voting system closing date feature? <p>I am implementing a node.js not real-time poll creating and voting system, where the admin can create a poll and set a closing date and then when this date is arrived the system closes the poll, send subscribed users an email and the users can't vote anymore. I have implemented every other feature, but I am struggling with closing the polls on that date. I thought about some persistent cron-like scheduler, where I set the job of closing the poll on the established date, but I don't know if this is the best approach. Do you have any ideas on how to solve this problem? Thanks</p>
<p>There are two basic approaches - in-process and out-of-process. In-process is simpler, but it requires your main program to be running. Out-of-process is more robust, because you can use systems whose primary function is to reliably execute scheduled jobs (cron for example).</p> <p>For the in-process approach in Javascript, I would suggest on startup, go read the poll records that show polls still open (a boolean flag, not a date), subtract the current date from the closing date, and use <code>setTimeout</code> to schedule a function call that far into the future (or immediately if the difference is negative). That function can do whatever you need (send emails, update records, etc.) The last thing it should do is update the original record to indicate "successfully closed". You want this function to be <a href="https://en.wikipedia.org/wiki/Reentrancy_(computing)" rel="nofollow">re-entrant</a> so if your process dies halfway through, the next time it starts it will still see that record of a poll with a closing date in the past, but no "successfully closed" flag, and try again.</p>
ERROR: could not find function "chartJSRadarOutput" deploy <p>My shiny app performs successfully at my local computer, but when I want to deploy it, it says <code>ERROR: could not find function "chartJSRadarOutput"</code> However, I have <code>library(radarchart)</code> already.</p> <p>I also went through this <a href="https://github.com/MangoTheCat/radarchart/tree/master/inst/shiny-examples/basic" rel="nofollow">https://github.com/MangoTheCat/radarchart/tree/master/inst/shiny-examples/basic</a> and did exactly it told to, still failed. Here is part of my ui.R and server.R code:</p> <pre><code> Server.R server &lt;- function(input, output) { library(shiny) library(radarchart) library(ggplot2) library(reshape2) top_version&lt;-read.csv("top_version.csv",header = T) top_version&lt;-top_version[,2:26] output$plot1 &lt;- renderChartJSRadar({ ds&lt;-subset(top_version,top_version$ageInd==input$select1) labs&lt;-c('familiarity','favorability','consideration') scores&lt;-list('Women'=c(nrow(ds[ds$familiarity==1 &amp; ds$gender==2,])/nrow(ds[ds$gender==2,]),nrow(ds[ds$favorability==1 &amp; ds$gender==2,])/nrow(ds[ds$gender==2,]),nrow(ds[ds$consideration==1 &amp; ds$gender==2,])/nrow(ds[ds$gender==2,])), 'Men'=c(nrow(ds[ds$familiarity==1 &amp; ds$gender==1,])/nrow(ds[ds$gender==1,]),nrow(ds[ds$favorability==1 &amp; ds$gender==1,])/nrow(ds[ds$gender==1,]),nrow(ds[ds$consideration==1 &amp; ds$gender==1,])/nrow(ds[ds$gender==1,]))) chartJSRadar(scores=scores, labs=labs,showToolTipLabel = T) })}) ui.R column(width = 12, chartJSRadarOutput("plot1", width = "300", height = "100")) </code></pre> <p>Does anyone have any ideas? Thanks a lot!</p> <p>I run it over shinyapps.io and I have library the package in server.R </p> <p>the local result is :</p> <pre><code>&gt; deployApp('/Users/Qiner/Downloads/ME_Analyst_Assessment_Files/visualapp') Preparing to deploy application...DONE Uploading bundle for application: 130647...DONE Deploying bundle: 581557 for application: 130647 ... Waiting for task: 266968451 building: Parsing manifest building: Building image: 572450 building: Fetching packages building: Installing packages building: Installing files building: Pushing image: 572450 deploying: Starting instances rollforward: Activating new instances terminating: Stopping old instances Application successfully deployed to https://qiner-shiny-home.shinyapps.io/visualapp/ </code></pre> <p>and the error over shinyapps.io is simply:</p> <pre><code>ERROR: could not find function "chartJSRadarOutput" </code></pre> <p>And the sessioninfo for the package is:</p> <pre><code>&gt; sessionInfo(package = "radarchart") R version 3.2.4 (2016-03-10) Platform: x86_64-apple-darwin13.4.0 (64-bit) Running under: OS X 10.11.6 (El Capitan) locale: [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8 attached base packages: character(0) other attached packages: [1] radarchart_0.2.0 loaded via a namespace (and not attached): [1] Rcpp_0.12.6 rstudioapi_0.6 magrittr_1.5 devtools_1.11.1 [5] grDevices_3.2.4 munsell_0.4.3 colorspace_1.2-6 xtable_1.8-2 [9] R6_2.1.2 httr_1.1.0 stringr_1.0.0 plyr_1.8.4 [13] tools_3.2.4 utils_3.2.4 packrat_0.4.7-1 grid_3.2.4 [17] gtable_0.2.0 git2r_0.14.0 withr_1.0.1 htmltools_0.3.5 [21] stats_3.2.4 datasets_3.2.4 yaml_2.1.13 digest_0.6.10 [25] randomForest_4.6-12 base_3.2.4 RJSONIO_1.3-0 shiny_0.13.2 [29] reshape2_1.4.1 ggplot2_2.1.0 bitops_1.0-6 htmlwidgets_0.6 [33] graphics_3.2.4 RCurl_1.95-4.8 curl_0.9.7 rsconnect_0.4.3 [37] memoise_1.0.0 mime_0.4 labeling_0.3 stringi_1.1.1 [41] shinyapps_0.4.1.8 methods_3.2.4 scales_0.4.0 jsonlite_1.0 [45] httpuv_1.3.3 </code></pre> <p>And the logs on shinyapps.io is :</p> <pre><code>2016-10-10T02:13:43.346532+00:00 shinyapps[130647]: LANG: en_US.UTF-8 2016-10-10T02:13:43.346534+00:00 shinyapps[130647]: R version: 3.2.4 2016-10-10T02:13:43.346536+00:00 shinyapps[130647]: shiny version: 0.13.2 2016-10-10T02:13:43.346550+00:00 shinyapps[130647]: rmarkdown version: NA 2016-10-10T02:13:43.346552+00:00 shinyapps[130647]: knitr version: NA 2016-10-10T02:13:43.346558+00:00 shinyapps[130647]: jsonlite version: 1.0 2016-10-10T02:13:43.346564+00:00 shinyapps[130647]: RJSONIO version: 1.3.0 2016-10-10T02:13:43.346593+00:00 shinyapps[130647]: htmltools version: 0.3.5 2016-10-10T02:13:43.523112+00:00 shinyapps[130647]: Using jsonlite for JSON processing 2016-10-10T02:13:43.527991+00:00 shinyapps[130647]: 2016-10-10T02:13:43.527992+00:00 shinyapps[130647]: Starting R with process ID: '59' 2016-10-10T02:13:43.546168+00:00 shinyapps[130647]: Listening on http://0.0.0.0:36262 2016-10-10T02:13:43.546165+00:00 shinyapps[130647]: 2016-10-10T02:13:43.628716+00:00 shinyapps[130647]: Warning: Error in tag: could not find function "chartJSRadarOutput" 2016-10-10T02:13:43.634773+00:00 shinyapps[130647]: 65: fluidRow 2016-10-10T02:13:43.634780+00:00 shinyapps[130647]: 53: navbarPage 2016-10-10T02:13:43.634785+00:00 shinyapps[130647]: 6: eval 2016-10-10T02:13:43.634767+00:00 shinyapps[130647]: Stack trace (innermost first): 2016-10-10T02:13:43.634774+00:00 shinyapps[130647]: 64: tag 2016-10-10T02:13:43.634779+00:00 shinyapps[130647]: 55: div 2016-10-10T02:13:43.634785+00:00 shinyapps[130647]: 5: eval 2016-10-10T02:13:43.634769+00:00 shinyapps[130647]: 72: tag 2016-10-10T02:13:43.634775+00:00 shinyapps[130647]: 62: div 2016-10-10T02:13:43.634779+00:00 shinyapps[130647]: 54: tabPanel 2016-10-10T02:13:43.634786+00:00 shinyapps[130647]: 4: eval 2016-10-10T02:13:43.634770+00:00 shinyapps[130647]: 71: tags$div 2016-10-10T02:13:43.634776+00:00 shinyapps[130647]: 59: bootstrapPage 2016-10-10T02:13:43.634782+00:00 shinyapps[130647]: 11: doTryCatch 2016-10-10T02:13:43.634787+00:00 shinyapps[130647]: 3: eval 2016-10-10T02:13:43.634771+00:00 shinyapps[130647]: 70: div 2016-10-10T02:13:43.634775+00:00 shinyapps[130647]: 61: tagList 2016-10-10T02:13:43.634781+00:00 shinyapps[130647]: 13: runApp 2016-10-10T02:13:43.634787+00:00 shinyapps[130647]: 2: eval.parent 2016-10-10T02:13:43.634771+00:00 shinyapps[130647]: 69: column 2016-10-10T02:13:43.634776+00:00 shinyapps[130647]: 60: attachDependencies 2016-10-10T02:13:43.634782+00:00 shinyapps[130647]: 12: fn 2016-10-10T02:13:43.634788+00:00 shinyapps[130647]: 1: local 2016-10-10T02:13:43.634772+00:00 shinyapps[130647]: 68: tag 2016-10-10T02:13:43.634778+00:00 shinyapps[130647]: 57: tag 2016-10-10T02:13:43.634783+00:00 shinyapps[130647]: 10: tryCatchOne 2016-10-10T02:13:43.634901+00:00 shinyapps[130647]: Error in tag("div", list(...)) : 2016-10-10T02:13:43.634772+00:00 shinyapps[130647]: 67: tags$div 2016-10-10T02:13:43.634778+00:00 shinyapps[130647]: 56: tags$div 2016-10-10T02:13:43.634784+00:00 shinyapps[130647]: 7: connect$retry 2016-10-10T02:13:43.634903+00:00 shinyapps[130647]: could not find function "chartJSRadarOutput" 2016-10-10T02:13:43.634773+00:00 shinyapps[130647]: 66: div 2016-10-10T02:13:43.634777+00:00 shinyapps[130647]: 58: fluidPage 2016-10-10T02:13:43.634783+00:00 shinyapps[130647]: 9: tryCatchList 2016-10-10T02:13:43.634774+00:00 shinyapps[130647]: 63: tags$div 2016-10-10T02:13:43.634781+00:00 shinyapps[130647]: 52: shinyUI 2016-10-10T02:13:43.634784+00:00 shinyapps[130647]: 8: tryCatch </code></pre>
<p>You need to load the package in both files. I tested this on my own shinyapps.io account and the error went away.</p> <p>Your code still has the error I mentioned in the comments (<code>2016-10-10T02:14:15.159934+00:00 shinyapps[130687]: Warning: Error in &lt;-: object 'output' not found</code>) because it's missing data, but this solves the error that your question is about.</p> <pre><code>#Server.R output$plot1 &lt;- renderChartJSRadar({ library(shiny) library(radarchart) ds&lt;-subset(top_version,top_version$ageInd==input$select1) labs&lt;-c('familiarity','favorability','consideration') scores&lt;-list('Women'=c(nrow(ds[ds$familiarity==1 &amp; ds$gender==2,])/nrow(ds[ds$gender==2,]),nrow(ds[ds$favorability==1 &amp; ds$gender==2,])/nrow(ds[ds$gender==2,]),nrow(ds[ds$consideration==1 &amp; ds$gender==2,])/nrow(ds[ds$gender==2,])), 'Men'=c(nrow(ds[ds$familiarity==1 &amp; ds$gender==1,])/nrow(ds[ds$gender==1,]),nrow(ds[ds$favorability==1 &amp; ds$gender==1,])/nrow(ds[ds$gender==1,]),nrow(ds[ds$consideration==1 &amp; ds$gender==1,])/nrow(ds[ds$gender==1,]))) chartJSRadar(scores=scores, labs=labs,showToolTipLabel = T) }) #ui.R require(shiny) library(radarchart) column(width = 12, chartJSRadarOutput("plot1", width = "300", height = "100")) </code></pre>
Alert the user that other datatypes (eg string) was inserted without crashing <p>This is the interface for calculation. The interface has two methods <code>calculateArea</code> and <code>totalCost</code>.</p> <pre><code>public interface ICalculation { int calculateArea();int totalCost() } </code></pre> <p>Here I'm inheriting the interface class. The variables are litre, length, height.</p> <pre><code>public class Calculation : ICalculation { public int litre; public int length; public int height; public Calculation() { litre= 0;length = 0;height = 0; } public Calculation(int litre2, int lenght2, int height2) { this.litre = litre2; this.length = lenght2; this.height = height2; } public int calculateArea() { return length * height; } public int totalCost() { return calculateArea()* litre; } </code></pre> <p>Testing the program to see the output. Create a new object calculation and then prompt the user to fill in the litre, length and height. Calculate the area and total cost after getting the values.</p> <pre><code>class Tester { static void Main(string[] args) { Calculation c = new Calculation(); try{ Console.WriteLine("How much litre?"); c.litre = int.Parse(Console.ReadLine()); Console.WriteLine("What is the lenght"); c.length = int.Parse(Console.ReadLine()); Console.WriteLine("What is the height"); c.height = int.Parse(Console.ReadLine()); Console.WriteLine("The Total area " + c.calculateArea()); Console.WriteLine("The Total cost for the project is " + c.totalCost()); Console.ReadKey(); } catch(FormatException ){ Console.WriteLine("{0}is not an integer, try again!"); // Console.ReadLine(); } } } </code></pre> <p>I want a user to ONLY be able to enter int values from the console namely; the litre, length and height. Alert the user that other datatypes(e.g. string) was inserted and prompt them to try again. The problem is the code crashes as soon a non-int value is inserted at any of the given values. Any thoughts on how to accomplish this?</p>
<p>I would say validate using a while loop.</p> <pre><code>int i; while (true) { var line = Console.ReadLine(); if (int.TryParse(line, out i)) break; Console.WriteLine("Invalid number"); } </code></pre>
Pascal's Triangle Formatting Issue for "n" Rows (Java) <p>I am trying to create and properly format Pascal's Triangle where the user inputs a value "n" for the number of rows that will be output. The issue here is getting the proper format past 13 rows. I am thinking the issue resides with the %4d since numbers that exceed the 13th row will tend to need more than 4 spaces. I just don't know how I can implement something like that for an (essentially) infinite value of n (I know the limitations of the double variable, but I hope you understand what I mean). Also, I would prefer a solution that did not implement the use of arrays.</p> <pre><code>double n; for (int i = 0; i &lt; n; i++){ int number = 1; System.out.printf("%" + (n - i) * 2 + "s", ""); for (int j = 0; j &lt;= i; j++){ System.out.printf("%4d", number); number = number * (i - j) / (j + 1); } System.out.println(); } </code></pre>
<p>This is a possible solution using a matrix...</p> <pre><code>import java.util.Scanner; public class PascalTriangle { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Type N: "); pascalTriangle(scanner.nextInt()); scanner.close(); } public static void pascalTriangle(final int N) { int[][] triangle = new int[N][N]; for (int i = 0; i &lt; N; i++) { for (int j = 0; j &lt;= i; j++) { if (j == 0) triangle[i][0] = 1; else triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j]; System.out.print(triangle[i][j] + "\t"); } System.out.println(); } } } </code></pre> <p>Output:</p> <pre><code>Type N: 13 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 1 10 45 120 210 252 210 120 45 10 1 1 11 55 165 330 462 462 330 165 55 11 1 1 12 66 220 495 792 924 792 495 220 66 12 1 </code></pre>
cronjob can't find file on EC2 <p>I have a script, called <code>script.py</code> that is on an EC2 instance. The script reads a file in the same folder (code: <code>open(data.csv, 'r')</code>) called <code>data.csv</code>. Here is the cron job:</p> <pre><code>* * * * * /home/ubuntu/anaconda3/bin/python /home/ubuntu/project/script.py &gt; /var/log/myjob.log 2&amp;&gt;1 </code></pre> <p>When I run the script myself <code>python script.py</code> is works perfectly. However, when cron runs the script, a python error is printed (as I intended) in the <code>myjob.log</code> file:</p> <pre><code>[Errno 2] No such file or directory: 'data.csv' </code></pre> <p>I suspect cronjob doesn't run the script in the same directory as when I run it myself, however, I do not know how to write the crontab line to tell cron to run the script from the directory that the script is in.</p>
<p>Assuming <code>/home/ubuntu</code>...</p> <pre><code>* * * * * cd /home/ubuntu/ &amp;&amp; ./anaconda3/bin/python ./project/script.py &gt; /var/log/myjob.log 2&gt;&amp;1 </code></pre> <p>Adding <code>2&gt;&amp;1</code> to the end is unrelated to your question, but captures the <code>STDERR</code> output into your log, which you probably also want.</p>
display DateTime format into readable string in PHP <p>i have a stored DateTime with this format [2016-10-05 11:58:04]. What i want to do is, display the stored time into this readable format [Wed, 11:58 AM].</p>
<p>Since you tagged your question with <code>mysqli</code> and <code>php</code> here are solutions for both:</p> <h2>MySQL</h2> <p>You can format the date directly in your query:</p> <pre><code>select DATE_FORMAT(column_name, "%a, %h:%i %p") AS formatted_date FROM table_name </code></pre> <p>See docs: <a href="http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format" rel="nofollow">http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format</a></p> <h2>PHP</h2> <p>If you have this string and need to format it in PHP, use <code>DateTime</code>:</p> <pre><code>$dt = new DateTime("2016-10-05 11:58:04"); echo $dt-&gt;format("D, h:i A"); // Wed, 11:58 AM </code></pre> <p>Working example: <a href="https://3v4l.org/AQeTc" rel="nofollow">https://3v4l.org/AQeTc</a></p>
static constexpr member initialization in header only library <p>I have <a href="https://stackoverflow.com/questions/11709859/how-to-have-static-data-members-in-a-header-only-library">found</a> <a href="https://stackoverflow.com/questions/28226251/static-member-in-header-only-library">questions</a> that are almost exactly as mine but I have 1 extra requirement - I need something that I can use as a default argument.</p> <p>I'm writing a header only template library and I have a code like this:</p> <pre><code>#include &lt;chrono&gt; template &lt;typename T&gt; class Foo { public: using Duration = std::chrono::duration&lt;float&gt;; static constexpr Duration DefaultDuration{1.0f}; Foo(Duration duration = DefaultDuration) : duration{duration} { } private: Duration duration; }; int main(int argc, char* argv[]) { Foo&lt;int&gt; foo; } </code></pre> <p>As you can see, I can't use a function call because it wouldn't work as a default argument, right? Is there a solution?</p>
<p>The issue here does not appear to be the default parameter, but the initialization. By switching to the uniform initialization syntax, and explicitly declared the static class member, this compiles without issues, with gcc 6.2.1:</p> <pre><code>#include &lt;chrono&gt; template &lt;typename T&gt; class Foo { public: static constexpr std::chrono::duration&lt;float&gt; DefaultDuration{1.0f}; Foo(std::chrono::duration&lt;float&gt; duration = DefaultDuration); }; template&lt;typename T&gt; constexpr std::chrono::duration&lt;float&gt; Foo&lt;T&gt;::DefaultDuration; Foo&lt;int&gt; f; int main() { return 0; } </code></pre> <p>gcc 6.2.1 actually lets you skate by without explicitly defining the static const member, but this is technically required, <a href="http://stackoverflow.com/questions/3025997/defining-static-const-integer-members-in-class-definitionhttp://">as explained here</a>.</p>
Websphere 7 jconsole support but with memory and threads <p>I went through these steps and got jconsole to connect to IBM websphere but the memory is greyed out and disabled, I want to be able to monitor memory usage in real time. I see the mbeans configuration. I basically want to use jconsole to connect to a local websphere server and gather the real time changes in memory. I see those tabs greyed out but MBEANS section available. How do I get the memory to show?</p> <pre><code>set WAS_HOME=C:/Program Files (x86)/ibm/WebSphere/AppServer set JAVA_HOME=%WAS_HOME%/java echo %WAS_HOME% set CLASSPATH=%JAVA_HOME%/lib/jconsole.jar set CLASSPATH=%CLASSPATH%;%WAS_HOME%/runtimes/com.ibm.ws.admin.client_8.0.0.jar set CLASSPATH=%CLASSPATH%;%WAS_HOME%/runtimes/com.ibm.ws.ejb.thinclient_8.0.0.jar set CLASSPATH=%CLASSPATH%;%WAS_HOME%/runtimes/com.ibm.ws.orb_8.0.0.jar set HOST=localhost set PORT=9100 &amp;quot;%JAVA_HOME%/bin/jconsole&amp;quot; -J-Djava.class.path=&amp;quot;%CLASSPATH%&amp;quot; ^ service:jmx:iiop://%HOST%:%PORT%/jndi/JMXConnector </code></pre> <p>Do you see any security issues here? Will the jmx connection iiop allow me to see the memory data?</p>
<p>To monitor basic parameters of the IBM JVM you can could use <a href="https://www.ibm.com/support/knowledgecenter/SS3KLZ/com.ibm.java.diagnostics.healthcenter.doc/topics/introduction.html" rel="nofollow">IBM Health Center</a> instead of jConsole. It can be installed either as a add on to IBM Support Assistant, or as plugin to Eclipse (from Eclipse Marketplace).</p> <p>Depending on your Java version and path level you would need to enable it via generic JVM settings:</p> <ul> <li>For Java Version 7 and later, Version 6 service refresh 5 and later, and Version 5 service refresh 10 and later use <code>-Xhealthcenter</code></li> <li>For Version 6 service refreshes 1 through 4, and Version 5 service refreshes 8 and 9 - use <code>-agentlib:healthcenter -Xtrace:output=perfmon.out</code></li> </ul> <p>Check the details <a href="https://www.ibm.com/support/knowledgecenter/SS3KLZ/com.ibm.java.diagnostics.healthcenter.doc/topics/enablingagent.html" rel="nofollow">here</a>.</p>
Java AWT fillOval() not working <p>I'm working on a program that draws a graph, so I would like to draw points! I'd like the points to be circular since that's usually how points are represented, and to the best of my knowledge, <code>g2.fillOval(x, y, height, width)</code> should draw a filled oval with height <code>height</code> and width <code>width</code> at <code>(x, y)</code>. This is my code at the moment:</p> <pre><code>private void drawCenteredCircle(Graphics g, int x, int y, int radius) { Graphics2D g2 = (Graphics2D) g.create(); g2.setColor(pointColor); g2.fillOval(x-radius, y-radius, 2*radius, 2*radius); g2.dispose(); } </code></pre> <p>Which is then called in the <code>paintComponent()</code> method of a <code>JPanel</code>. It does draw, so I know the code is functioning, but for some reason, it draws a square, like so: <a href="http://i.stack.imgur.com/15G83.png" rel="nofollow">my square oval :(</a></p> <p><a href="http://i.stack.imgur.com/15G83.png" rel="nofollow"><img src="http://i.stack.imgur.com/15G83.png" alt="enter image description here"></a></p> <p>I also tried this:</p> <pre><code>private void drawCenteredCircle(Graphics g, int x, int y, int radius) { Graphics2D g2 = (Graphics2D) g.create(); g2.setColor(pointColor); g2.fill(new Ellipse2D.Float(x-radius, y-radius, 2*radius, 2*radius); g2.dispose(); } </code></pre> <p>But got the same result. Any help as to how to draw a filled circle/ellipse would be much appreciated.</p>
<p>You will want to set your Graphic2D's RenderingHints to handle aliasing. This smooths out the jaggies that may be causing your (small) circle to render as a square. Something like:</p> <pre><code>Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); </code></pre>