input
stringlengths
51
42.3k
output
stringlengths
18
55k
Excel: VBA code to DISABLE "Clear ALL or Clear Filters" <p>I have a protected Workbook &amp; Pivot table in an excel file on a filter that I'm sending to certain users based on the filter. ( Drill down is on, but Field List and Field Dialogs are turned off).</p> <p><strong>I want to disable these buttons "CLEAR FILTERS or CLEAR ALL", would anyone know of a code?</strong></p> <p>Thank you!</p>
<p>Answer from here:</p> <p><a href="http://stackoverflow.com/questions/21761027/excel-2013-vba-clear-all-filters-macro">Excel 2013 VBA Clear All Filters macro</a></p> <pre><code>Sub Macro1() Cells.AutoFilter End Sub </code></pre>
How to debugg iterative procedures? <p>I am using Dr. Racket and Racket for educational purposes (studying the SICP book). Dr. Racket is great and it has an awesome tool called "trace".</p> <p>After using:</p> <pre><code>(require trace/racket) (trace function) </code></pre> <p>It is possible to see what is happening in a recursive procedure.</p> <p>However, this feature does not work with iterative procedures. I wish I could "see" what's happening in my code while it is being executed. I wish I could see the change in values of the state variables.</p> <p>Is there an alternative tool or practice to have that kind of information in an iterative procedure?</p>
<p>Tracing is not debugging. In DrRacket you press the DEBUG button and right click on the edge of interesting parts, like a <code>if</code> that determines base case or defautl case in a helper and choose "Pause at this point". Then everytime you hit Go you can see the bound arguments a step at a time.</p> <p>If you want to just trace you can trace a helper like this:</p> <pre><code>(require racket/trace) (define (reverse lst) (define (aux lst acc) (if (null? lst) acc (aux (cdr lst) (cons (car lst) acc)))) (trace aux) ; tracing the helper (aux lst '())) (reverse '(1 2 3 4)) &gt;(aux '(1 2 3 4) '()) &gt;(aux '(2 3 4) '(1)) &gt;(aux '(3 4) '(2 1)) &gt;(aux '(4) '(3 2 1)) &gt;(aux '() '(4 3 2 1)) &lt;'(4 3 2 1) ;==&gt; (4 3 2 1) </code></pre> <p>If you want to use named <code>let</code> just replace it with <code>trace-let</code>:</p> <pre><code>(define (reverse lst) ;; TODO: Put back to let (trace-let aux ((lst lst) (acc '())) (if (null? lst) acc (aux (cdr lst) (cons (car lst) acc))))) </code></pre> <p>Using the debugger is much faster than having to add lines and remove lines in code in order to test it. </p>
String Array dimension set considering user input <p>I wrote some code. The idea is to ask user how many names they wish to enter, get the input and set the string array size accordingly. I have managed to finalise the code apart from setting array size. When I try something like this:</p> <pre><code>import java.util.Scanner; public class StringArray { public static void main(String[] args) { Scanner read = new Scanner(System.in); System.out.println("How many names do you wish to enter?"); int numOfNames = read.nextInt(); String [] names = new String[numOfNames]; </code></pre> <p>I get an error saying String cannot be converted to int. I tried stuff I found online like trying and converting int to string etc but didn't work. My source code is here:</p> <pre><code>import java.util.Scanner; public class ArrayDemoS { public static void main(String[] args) { Scanner read = new Scanner(System.in); System.out.println("How many names do you wish to enter?"); int numOfNames = read.nextInt(); String [] names = new String[6]; System.out.println("Enter the names."); int items = 0; do { names[items] = read.nextLine(); } while ( ++items &lt;= numOfNames); System.out.println("You entered the following names"); for ( int i = 0; i &lt;= numOfNames; i++) { System.out.print(names[i] + " "); } System.out.println(); } } </code></pre> <p>I set the size to 6 assuming the user will enter 5 names. There might be other ways of doing this using ArrayList etc but I haven't learned about them yet. I am able to do the same task when the array is formed of int type data. I would like to be able to do it for String type as well. Thanks in advance :)</p>
<p>This is working fine.</p> <pre><code> public static void main(String[] args) { Scanner read = new Scanner(System.in); System.out.println("How many names do you wish to enter?"); int numOfNames = read.nextInt(); String [] names = new String[numOfNames]; System.out.println("Enter the names."); int items = 0; names[items] = read.nextLine(); while ( items &lt; numOfNames) { names[items] = read.nextLine(); items++; } System.out.println("You entered the following names"); for ( int i = 0; i &lt; numOfNames; i++) { System.out.print(names[i] + " "); } System.out.println(); } </code></pre>
Social network query with MongoDB <p>I have a simple social network implementation with MongoDB. My schema looks like that:</p> <pre><code>User _id name Friend _id user friend Post _id user timestamp text </code></pre> <p>I'm trying to use the <code>aggregate</code> method to get a list of recent posts from all of my friends, but I would like to group together consecutive posts from the same user. So assuming I have 3 friends and they have the following posts:</p> <pre><code>{"user": "user1", timestamp: 1476200010, text: "hello1"} {"user": "user2", timestamp: 1476200009, text: "hello2"} {"user": "user2", timestamp: 1476200008, text: "hello3"} {"user": "user3", timestamp: 1476200007, text: "hello4"} {"user": "user2", timestamp: 1476200006, text: "hello5"} {"user": "user2", timestamp: 1476200005, text: "hello6"} {"user": "user1", timestamp: 1476200004, text: "hello7"} {"user": "user1", timestamp: 1476200003, text: "hello8"} </code></pre> <p>I would like as a result, to receive the following:</p> <pre><code>{"user": "user1", timestamp: 1476200010, text: "hello1"} {"user": "user2", timestamp: 1476200009, text: "hello2"} {"user": "user3", timestamp: 1476200007, text: "hello4"} {"user": "user2", timestamp: 1476200006, text: "hello5"} {"user": "user1", timestamp: 1476200004, text: "hello7"} </code></pre> <p>I'm a bit stuck with my query, any help is appreciated:</p> <pre><code>db.Post.aggregate([ {$sort: {timestamp: -1}}, {$lookup: {from: 'Friend', localField: '_id', foreignField: 'friend', as: 'friend'}}, {$match: {'friend.user': current_user}}, ??? {$limit: 100}, ]) </code></pre>
<p>In aggregation pipeline, all expressions except accumulators used in the group state do not maintain state i.e. they cannot refer to fields from previous documents. Hence, it is not possible to satisfy this using just a Mongo query. It is better to implement this logic in your application code.</p>
Stopping a for loop <p>I've got a home task writing a programme in which the user inputs his name and surname and the output should be the initials. The problem is that applying this programme I get a line of initials which are repeated 10 times.</p> <p>How can I get the output of just one pair of initials?</p> <p>I've already searched the web and this website as well and tried to apply such things as return and break but it didn't help me.</p> <p>Here is the code:</p> <pre><code>#include &lt;cs50.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; int main (int argc, string argv[]) { // get string of the text string s = GetString(); // output the initials of the name if (s != NULL) for (int i = 0; i &lt; argc; i++) // was for (…; i = 0) { for (int j = 0, n = strlen(argv[i]); j &lt; n; j++) // was for (…; j = 0) { printf ("%c%c", argv[1][0], argv[2][0]); } return 0; } } </code></pre>
<p>This is infinite loop as i and j are being reassigned to 0. "for loop" structure should be like: for ( init; condition; increment ) please use below "for loop" in your program.</p> <pre><code>for (int i = 0; i &lt; argc; i++) { for (int j = 0, n = strlen(argv[i]); j &lt; n; j++) </code></pre> <hr> <p>To get initials of Name. Take input (name) as String and find length of string (length_of_input) and use below code:</p> <pre><code>for(int i=0; i&lt; (length_of_input-1); i++){ //First letter is always initial if(i==0){ // print character at i position printf ("%c",name[i]); } //if there is space, then next character is initial if(name[i] == ' '){ printf ("%c",name[i+1]); //print next character } } </code></pre>
Query for empty has_many through <p>How can I query a <code>has_many :through</code> to see which records have an empty association on the other side? (I'm using rails 5)</p> <pre><code>class Specialty has_many :doctor_specialties has_many :doctor_profiles, through: :doctor_specialties class DoctorProfile has_many :doctor_specialties has_many :specialties, through: :doctor_specialties class DoctorSpecialty belongs_to :doctor_profile belongs_to :specialty </code></pre> <p>I can do this by enumerating over <code>Specialty</code> but I'd like to do it in a SQL query. </p> <pre><code>Specialty.includes(:doctor_profiles).all.select{|x| x.doctor_profiles.length == 0 } </code></pre>
<pre><code>Specialty.includes(:doctor_profiles).where(doctor_profiles: { id: nil }) </code></pre> <p>See <a href="http://guides.rubyonrails.org/active_record_querying.html" rel="nofollow">Active Record Query Interface</a> for more info on AR querying.</p> <p>Since you're on Rails >= 5, you could use <a href="http://guides.rubyonrails.org/active_record_querying.html#left-outer-joins" rel="nofollow"><code>left_outer_joins</code></a> (thx <strong>@gmcnaughton</strong>):</p> <pre><code>Specialty.left_outer_joins(:doctor_profiles).where(doctor_profiles: { id: nil }) </code></pre>
word press page template formatting not working <p>im building a word pres theme and have found that formatting is not working. for example if i build a simple list in a post</p> <pre><code>&lt;ul&gt; &lt;li&gt;one&lt;/li&gt; &lt;li&gt;two&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>it works, but when i try it through a page it dose not apply the list element or any other element.</p> <p>I have no idea why my page is not getting any formatting </p> <p><strong>single.php</strong></p> <pre><code>**&lt;?php get_header(); ?&gt; &lt;div class="row"&gt; &lt;div class="col-sm-12"&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); get_template_part( 'content-single', get_post_format() ); if ( comments_open() || get_comments_number() ) : comments_template(); endif; endwhile; endif; ?&gt; &lt;/div&gt; &lt;!-- /.col --&gt; &lt;/div&gt; &lt;!-- /.row --&gt; &lt;?php get_footer(); ?&gt;** </code></pre> <p><strong>content_single.php</strong> </p> <pre><code>&lt;div class="blog-post"&gt; &lt;h2 class="blog-post-title"&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt; &lt;p class="blog-post-meta"&gt;&lt;?php the_date(); ?&gt; by &lt;a href="#"&gt;&lt;?php the_author(); ?&gt;&lt;/a&gt;&lt;/p&gt; &lt;?php the_content(); ?&gt; &lt;?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?&gt; </code></pre> <p></p> <p>//////////// and page /////////////////////</p> <p><strong>page.php</strong></p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="row"&gt; &lt;div class="col-sm-12"&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); get_template_part( 'content', get_post_format() ); endwhile; endif; ?&gt; &lt;/div&gt; &lt;!-- /.col --&gt; &lt;/div&gt; &lt;!-- /.row --&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p><strong>content.php</strong></p> <pre><code>&lt;div class="blog-post"&gt; &lt;h2 class="blog-post-title"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/h2&gt; &lt;p class="blog-post-meta"&gt; &lt;?php the_date(); ?&gt;by &lt;a href="#"&gt;&lt;?php the_author(); ?&gt;&lt;/a&gt; &lt;a href="&lt;?php comments_link(); ?&gt;"&gt; &lt;?php printf(_nx('One Comment', '%1$s Comments', get_comments_number(), 'comments title', 'textdomain'), number_format_i18n(get_comments_number())); ?&gt; &lt;/a&gt; &lt;/p&gt; &lt;?php if ( has_post_thumbnail() ) {?&gt; &lt;div class="row"&gt; &lt;div class="col-md-4"&gt; &lt;?php the_post_thumbnail('thumbnail'); ?&gt; &lt;/div&gt; &lt;div class="col-md-6"&gt; &lt;?php the_excerpt(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } else { ?&gt; &lt;?php the_excerpt(); ?&gt; &lt;?php } ?&gt; &lt;/div&gt;&lt;!-- /.blog-post --&gt; </code></pre>
<p>Ok so in <strong>page.php</strong> I change this </p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="row"&gt; &lt;div class="col-sm-12"&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); get_template_part( 'content', get_post_format() ); endwhile; endif; ?&gt; &lt;/div&gt; &lt;!-- /.col --&gt; &lt;/div&gt; &lt;!-- /.row --&gt; </code></pre> <p>to this</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="row"&gt; &lt;div class="col-sm-12"&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;!-- /.col --&gt; &lt;/div&gt; &lt;!-- /.row --&gt; &lt;?php get_footer(); ?&gt; </code></pre>
Adding a product tag next to WooCommerce product name <p>I am using WooCommerce plugin with extension called Bundled product.</p> <p>When someone views the item, it would show like <a href="https://www.betterce.com/product/property-and-casualty-agent-24-hour-package/" rel="nofollow">this</a>.</p> <p>As you can see from the link, it displays the title of bundled product.</p> <p>I am trying to see if I can add a product tag next to the title.</p> <p><a href="https://i.stack.imgur.com/GJfP7.gif" rel="nofollow"><img src="https://i.stack.imgur.com/GJfP7.gif" alt="enter image description here"></a></p> <p>I believe this should be possible via hooks and filters but i am not quite sure how exactly I could do this?</p>
<blockquote> <p>I'm new to Woocommerce.</p> </blockquote> <p>Yes. You can add tags next to the product title... but the plugin as a different structure and more information is needed to know which hook to apply. An example (This code will Run on Single Product page);</p> <p>I suggest check the sourcecode of the plugin to see if you can modify that template.</p> <pre><code>add_action( 'woocommerce_single_product_summary', 'woocommerce_product_loop_tags', 31 ); function woocommerce_product_loop_tags() { global $post, $product; $tag_count = sizeof( get_the_terms( $post-&gt;ID, 'product_tag' ) ); $idProducto=$product-&gt;id; $product-&gt;get_title(); $product-&gt;get_tags( ', ', '&lt;span class="tagged"&gt;' . _n( 'Tag:', 'Tags:', $tag_count, 'woocommerce' ) . ' ', '.&lt;/span&gt;' ); $producto= wc_get_product( $idProducto ); $Titulo=$producto-&gt;get_title(); echo $Titulo." : ".$product-&gt;get_tags( ', ', '&lt;span class="tagged_as"&gt;' . _n( 'Tag:', 'Tags:', $tag_count, 'woocommerce' ) . ' ', '.&lt;/span&gt;' ); } </code></pre> <p>The above code will show this: 100 ~etc is the name of the product, and The text in bold are the tags.</p>
Wordpress HTACCESS 301 Redirect Querystring index.asp <p>I have a basic WordPress HTACCESS. What I want to accomplish is a 301 Redirect from:</p> <p>/index.asp?id=herhaalrecept_aanvragen-5</p> <p>to</p> <p><a href="https://www.example.nl/aanmelden-nieuwe-patienten/" rel="nofollow">https://www.example.nl/aanmelden-nieuwe-patienten/</a></p> <p>I tried many options with QUERYSTRING but no luck. I removed it from the example below because I think it is not even close.</p> <p>Has anybody got an idea?</p> <p>Tnx in advance</p> <p><strong>Example of my HTACCESS now below:</strong></p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php? [L] Redirect 301 /index.asp?id=herhaalrecept_aanvragen-5 https://www.example.nl/aanmelden-nieuwe-patienten/ &lt;/IfModule&gt; # END WordPress </code></pre>
<p><code>Redirect</code> or <code>RewriteRule</code> doesn't match query string. You need <code>RewriteCond</code> for that also you must keep that rule before other WP rules.</p> <pre><code>RewriteEngine On RewriteBase / RewriteCond %{QUERY_STRING} (?:^|&amp;)id=herhaalrecept_aanvragen-5(&amp;|$) [NC] RewriteRule ^index\.asp$ https://www.example.nl/aanmelden-nieuwe-patienten/? [L,R=301,NC] RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php? [L] </code></pre>
Moving data from one table to another using VBA <p>I am currently moving data from table1(named sheet1) in sheet1 to table2(named sheet2) in sheet2 if a value exists. I am new to List objects, and am unsure how to go about this. Sheet 1 will have a lot of data, while sheet 2 will be an empty table at first. I plan to iterate through the data, and copy the data over, if it has a value. </p> <pre><code>'e will be coming from an array I have set up. e = "Sheet1" Sub GatherData(ByVal e As String) Dim Lo As ListObject, Ros As ListRows, e2 as String Dim Tablesize As Integer, CurrentRow As Integer Dim Sht1 As Worksheet Set Sht1 = ActiveWorkbook.Worksheets(e) Set Lo = Sht1.ListObjects(e) Set Ros = Lo.ListRows Tablesize = Ros.Count e2 = "sheet2" Dim Sht2 As Worksheet Set Sht2 = Worksheets(e2) Set Lo2 = Sht2.ListObjects(e2) Set Ros2 = Lo2.ListRows Tablesize2 = Ros2.Count For CurrentRow = 1 To Tablesize If Lo.ListColumns("Name").DataBodyRange(CurrentRow) &lt;&gt; "" Then 'nesting if loop when I add further functionality to check for further values in other columns If Lo.ListColumns("Name_Value").DataBodyRange(CurrentRow) &lt;&gt; "" Then 'add to new table on sheet 2 'Lo2.ListRows.Add 'sht1.Range("A" &amp; CurrentRow).Copy sht2.Range("A" &amp; Tablesize2) 'sht1.Range("A" &amp; CurrentRow).Copy sht2.Range("B" &amp; Tablesize2) 'sht1.Range("B" &amp; CurrentRow).Copy sht2.Range("C" &amp; Tablesize2) End If End If Next CurrentRow </code></pre> <hr> <pre><code> How the table is set up for ex; Sheet 1 Sheet 2 Name Value Tablename Name Value </code></pre>
<pre><code>Dim e As String e = "Sheet1" Dim Lo As ListObject, Ros As ListRows, e2 As String Dim Tablesize As Integer, CurrentRow As Integer Dim Sht1 As Worksheet Set Sht1 = ThisWorkbook.Worksheets(e) ''Edited this line for best practice Set Lo = Sht1.ListObjects(e) Set Ros = Lo.ListRows Tablesize = Ros.Count e2 = "sheet2" Dim Sht2 As Worksheet Dim Lo2 As ListObject, Ros2 As ListRows, Tablesize2 As Integer ''These variables were not dimensioned Set Sht2 = ThisWorkbook.Worksheets(e2) ''EDITED THIS LINE!! Set Lo2 = Sht2.ListObjects(e2) Set Ros2 = Lo2.ListRows On Error Resume Next Tablesize2 = Lo2.DataBodyRange.Rows.Count ''if no data rows error 91 is thrown If Err.Number = 91 Then Tablesize2 = 0 ElseIf Err Then MsgBox ("An error has occurred, Error Number = " &amp; Err.Number &amp; " The Action is Cancelled") ''add other code to roll back changes Exit Sub End If For CurrentRow = 1 To Tablesize If Lo.ListColumns("Name").DataBodyRange(CurrentRow) &lt;&gt; "" Then 'nesting if loop when I add further functionality to check for further values in other columns If Lo.ListColumns("Value").DataBodyRange(CurrentRow) &lt;&gt; "" Then ''EDITED THIS LINE!! 'add to new table on sheet 2 Lo2.ListRows.Add Tablesize2 = Lo2.DataBodyRange.Rows.Count ''ADDED THIS LINE Lo2.DataBodyRange.Cells(Tablesize2, 1) = Lo.Name Sht1.Range("A" &amp; CurrentRow + 1).Copy (Lo2.DataBodyRange.Cells(Tablesize2, 2)) Sht1.Range("B" &amp; CurrentRow + 1).Copy (Lo2.DataBodyRange.Cells(Tablesize2, 3))(xlPasteValues) ''ADDED LINE End If End If Next CurrentRow </code></pre> <p><code>Tablesize2 = Ros2.Count</code> creates a condition where you can have no data in the table and a count of 0 or no data in the table and a count of 1, in order to avoid this problem I changed to <code>DatabodyRange.Rows.Count</code> which throws an error if there is no data, or a count of the data rows if there are 1 or more rows of data.</p> <p>Note that instead of copying and pasting you could also do this:</p> <pre><code>Lo2.DataBodyRange.Cells(Tablesize2, 1) = Lo.Name Lo2.DataBodyRange.Cells(Tablesize2, 2) = Sht1.Range("A" &amp; CurrentRow + 1).Value Lo2.DataBodyRange.Cells(Tablesize2, 3) = Sht1.Range("B" &amp; CurrentRow + 1).Value </code></pre>
C++ Exceptions in Console App? <p>May be a dumb question, but I would like to use C++ exceptions in a console app (created with the new Win32 Console Application project wizard). I tried many variations on the theme shown below with no joy:</p> <pre><code>try { // do something that may throw an exception } catch( exception e ) { printf( "Exception: %s\n", e.what ); } </code></pre> <p>The compiler complains that identifier 'exception' not found.<br> I tried various things in place of 'exception' (e.g., 'IOException', 'bad_alloc') with no luck. </p> <p>I tried different exception-related options in the project configuration, also with no luck.<br> I <strong>was</strong> able to make it compile using </p> <pre><code>catch(...) { </code></pre> <p>but that gives me no info about the exception.</p> <p>Questions:<br> Are exceptions even <strong>allowed</strong> in non-.NET apps?<br> Am I missing some include file?<br> Some other (dumb) thing I did or didn't do?</p>
<blockquote> <p>Are exceptions even allowed in non-.NET apps?</p> </blockquote> <p>Yes, they are.</p> <blockquote> <p>Am I missing some include file?</p> </blockquote> <p>It looks like you're missing the necessary <code>#include &lt;exception&gt;</code> and/or the namespace scoping with <code>std::</code>.</p> <blockquote> <p>Some other (dumb) thing I did or didn't do?</p> </blockquote> <p>The better way to catch exceptions is by const reference BTW:</p> <pre><code>#include &lt;exception&gt; int main() { try { // do something that may throw an exception } catch(const std::exception&amp; e ) { printf( "Exception: %s\n", e.what ); } } </code></pre>
SQL based on my Example for Month <p>I am new to SQL and Learning on my own. I was wondering if someone can help guiding me to a write SQL.</p> <p>I have the below data:</p> <p><img src="https://i.stack.imgur.com/xWGO3.png" alt="Sample"></p> <p>I am using the following query:</p> <pre><code>SELECT TIMESTAMP DATEPART(Year, TIMESTAMP) Year, DATEPART(Month, TIMESTAMP) Month, COUNT(*) [Total Rows] FROM stage.ACTIVITY_ACCUMULATOR_archive WHERE TIMESTAMP BETWEEN '01-Jan-2014' AND '30-June-2014' GROUP BY DATEPART(Year, TIMESTAMP), DATEPART(Month, TIMESTAMP) ORDER BY Year, Month </code></pre> <p>What I am trying to achieve is to display the <code>Timestamp</code> with year and month between the certain date and group them by month and year.</p> <p>I get an error:</p> <blockquote> <p>Msg 102, Level 15, State 1, Line 1<br> Incorrect syntax near 'Year'</p> </blockquote>
<p>This should work.There was a extra timestamp column in select list. </p> <pre><code>SELECT DATEPART(Year, TIMESTAMP) Year, DATEPART(Month, TIMESTAMP) Month, COUNT(*) [Total Rows] FROM stage.ACTIVITY_ACCUMULATOR_archive WHERE TIMESTAMP BETWEEN '01-Jan-2014' AND '30-June-2014' GROUP BY DATEPART(Year, TIMESTAMP), DATEPART(Month, TIMESTAMP) ORDER BY Year, Month </code></pre>
Android: Record raw audio and record video at the same time <p>I develop an Android app based on sound and video records. I would like to get a real-time playback of the mic audio in the headphones while previewing AND capturing the video and sound.</p> <p>What i have now, working fine alone:</p> <p>1) use Superpowered library to record audio and playing it back in real-time (during preview and record). Behind the scene, it does directly with C++ the work of AudioRecord by pushing the buffer to the output (headphones). The goal is to apply audio effects on the raw sound in real-time.</p> <p>2) capture the video with mediaRecorder</p> <p>When audio playback is running, I try to launch the video record, it crashes starting :</p> <pre><code>E/MediaRecorder: start failed: -2147483648 </code></pre> <p>I imagine that i can't launch two recording process at the same time. I think using the AudioRecord or Superpowered lib is the good way to process the raw audio, but I can't figure out how to record video without conflicting with the current audio recording.</p> <p>So is there a way to achieve my feature?</p> <p>(minSdk 16)</p>
<p>According <a href="http://bigflake.com/mediacodec/" rel="nofollow">bigflake</a> </p> <blockquote> <p>The MediaCodec class first became available in Android 4.1 (API 16). It was added to allow direct access to the media codecs on the device.</p> <p>In Android 4.3 (API 18), MediaCodec was expanded to include a way to provide input through a Surface (via the createInputSurface method). This allows input to come from camera preview or OpenGL ES rendering.</p> </blockquote> <p>So if it's possible please think about increasing MinSDK to 18 and use <a href="https://github.com/saki4510t/AudioVideoRecordingSample" rel="nofollow">AudioVideoRecordingSample</a> or <a href="https://github.com/OnlyInAmerica/HWEncoderExperiments" rel="nofollow">HWEncoderExperiments</a> as examples.</p>
How to include shieldui in asp.net mvc? <p>I'm new to <code>shieldui</code> js and asp.net mvc and I'm doing some examples for a train. I have no problem including the js in a html file but I'm struggling to include it in asp.net mvc. Lets say i have jquery and shield ui in Scripts folder. I did reference <code>Shield.Mvc.UI</code> but I still cant access them via <code>@(Html.XXXX)</code>. </p> <p>Lets say i want to create <code>ShieldCalendar</code> using <code>View.cshtml</code>. The example is:</p> <pre><code>&lt;div class="container"&gt; @(Html.ShieldCalendar() .Name("calendar") .HtmlAttribute("class", "calendar") .Min(new DateTime(2009, 2, 23)) .Max(new DateTime(2039, 3, 1)) .Value(DateTime.Now) .Footer(fb =&gt; fb.Enabled(true).FooterTemlpate("{0:dd.MM.yy}"))) </code></pre> <p></p> <p>I'm a beginner and I may miss something fundamental for asp.net MVC. </p>
<p>Later findings: it looks like some time ago there weren't html helper extension methods for that. Are you sure you have something like that? </p> <p>Question reference: <a href="http://stackoverflow.com/questions/23031573/shield-ui-chart-generate-series-dynamically">shield ui chart: generate series dynamically?</a> (where op is saying that he wrote a custom html helper for .net mvc)</p> <p>Html helpers reference: <a href="http://www.tutorialsteacher.com/mvc/html-helpers" rel="nofollow">http://www.tutorialsteacher.com/mvc/html-helpers</a></p> <p>Are you sure you have html helpers in <code>Shield.Web.UI</code> namespace? (see this question too: <a href="http://stackoverflow.com/questions/22405102/referencing-the-shield-ui-asp-net-mvc-javascript-modules">Referencing the Shield UI ASP.NET MVC javascript modules</a>)</p> <p><strong>1st approach</strong> </p> <p>You can create a bundle with those two javascript files for now. </p> <p>Open the <code>App_Start\BundleConfig.cs</code>, there you will have a <code>RegisterBundles</code> method where you can create a bundle with those two files.</p> <pre><code> public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jqueryand") .Include("~/Scripts/jquery-3.1.1.js")) .Include("~/Scripts/shieldui.js"); // i don't know exactly the name of the library } </code></pre> <p>And in your <code>Global.asax.cs</code>, you need to register this bundle:</p> <p>In Application_Start method, add the following line:</p> <pre><code> BundleConfig.RegisterBundles(BundleTable.Bundles); </code></pre> <p>Then in your <code>_Layout</code> or your more specific view, you'll have to add <code>@Scripts.Render("~/bundles/jquery")</code></p> <p>More about this approach here: <a href="https://www.asp.net/mvc/overview/performance/bundling-and-minification" rel="nofollow">https://www.asp.net/mvc/overview/performance/bundling-and-minification</a> </p> <p>And here: <a href="http://stackoverflow.com/questions/21668280/how-do-i-add-bundleconfig-cs-to-my-project">How do I add BundleConfig.cs to my project?</a> (probably this question is very useful) </p> <p><strong>2nd approach</strong></p> <p>Use something like RequireJs for .NET, which will bring some features to your application, but will also add some complexity.</p> <p>See my answer for the question below:</p> <p><a href="http://stackoverflow.com/questions/29942322/requirejs-asp-net-mvc-bundle-script/30641224#30641224">RequireJS - ASP.NET MVC Bundle Script</a></p> <p>About this part of your problem: </p> <blockquote> <p>but I still cant access them via @(Html.XXXX).</p> </blockquote> <p>Maybe your intellisense is broken, you can give it a try after you add the script to the page/layout and after you make sure that you have </p> <pre><code>@using Shield.Web.UI </code></pre> <p>for your page/layout.</p>
Xcode 8: class_getProperty is Null for Core Data Category <p>I would like to check for properties with <code>class_getProperty</code> on Core Data related classes and categories.</p> <p><strong>Structure</strong>:</p> <pre><code>@interface Person : NSManagedObject @end @interface Person (CoreDataProperties) @property (nullable, nonatomic, retain) NSString *name; @end </code></pre> <p><strong>Code</strong>:</p> <pre><code>objc_property_t property = class_getProperty([Person class], [@"name" cStringUsingEncoding:NSUTF8StringEncoding]); // NULL !? const char *propertyAttributes = property_getAttributes(property); </code></pre> <p><strong>Problem:</strong></p> <p>Since Xcode 8 <code>property</code> is Null and <code>property_getAttributes()</code> will let the App crash.</p> <p>I found older questions, but no solution to my problem. </p>
<p>Arg...bad and stupid error.</p> <p>I forgot to add the Categories to the target. Sometimes it is so simple.</p>
AndroidStudio Error After configured SDK path <p>I download the (android studio and android sdk) zip file.</p> <p><a href="https://i.stack.imgur.com/cAPNN.png" rel="nofollow">After configured SDK path, open the configuration has been loading the SDK Manager</a></p> <pre> 2016-10-11 22:58:43,193 [1355018] INFO - nfigure.SdkUpdaterConfigurable - Parsing J:\Android\sdk\add-ons\addon-google_apis-google-23\package.xml 2016-10-11 22:58:43,193 [1355018] INFO - nfigure.SdkUpdaterConfigurable - Parsing J:\Android\sdk\build-tools\23.0.3\package.xml 2016-10-11 22:58:43,209 [1355034] INFO - nfigure.SdkUpdaterConfigurable - Parsing J:\Android\sdk\build-tools\24.0.0\package.xml 2016-10-11 22:58:43,209 [1355034] INFO - nfigure.SdkUpdaterConfigurable - Parsing legacy package: J:\Android\sdk\build-tools\24.0.3 2016-10-11 22:58:43,225 [1355050] ERROR - pplication.impl.LaterInvocator - tried to access method com.android.sdklib.AndroidVersion$AndroidVersionException.(Ljava/lang/String;Ljava/lang/Throwable;)V from class com.android.sdklib.AndroidVersionHelper java.lang.IllegalAccessError: tried to access method com.android.sdklib.AndroidVersion$AndroidVersionException.(Ljava/lang/String;Ljava/lang/Throwable;)V from class com.android.sdklib.AndroidVersionHelper at com.android.sdklib.AndroidVersionHelper.create(AndroidVersionHelper.java:71) at com.android.sdklib.repository.legacy.local.LocalSdk.scanPlatforms(LocalSdk.java:908) at com.android.sdklib.repository.legacy.local.LocalSdk.getPkgsInfos(LocalSdk.java:548) at com.android.sdklib.repository.legacy.LegacyLocalRepoLoader.parseLegacyLocalPackage(LegacyLocalRepoLoader.java:100) at com.android.repository.impl.manager.LocalRepoLoaderImpl.parsePackages(LocalRepoLoaderImpl.java:176) at com.android.repository.impl.manager.LocalRepoLoaderImpl.getPackages(LocalRepoLoaderImpl.java:154) at com.android.repository.impl.manager.RepoManagerImpl$LoadTask.run(RepoManagerImpl.java:653) at com.android.repository.api.RepoManager$DummyProgressRunner.runSyncWithProgress(RepoManager.java:398) at com.android.repository.impl.manager.RepoManagerImpl.load(RepoManagerImpl.java:387) at com.android.repository.api.RepoManager.loadSynchronously(RepoManager.java:290) at com.android.sdklib.repository.AndroidSdkHandler$RepoConfig.createRepoManager(AndroidSdkHandler.java:695) at com.android.sdklib.repository.AndroidSdkHandler.getSdkManager(AndroidSdkHandler.java:269) at com.android.tools.idea.updater.configure.SdkUpdaterConfigurable.getRepoManager(SdkUpdaterConfigurable.java:128) at com.android.tools.idea.updater.configure.SdkUpdaterConfigPanel.validate(SdkUpdaterConfigPanel.java:462) at com.android.tools.idea.updater.configure.SdkUpdaterConfigPanel.refresh(SdkUpdaterConfigPanel.java:444) at com.android.tools.idea.updater.configure.SdkUpdaterConfigPanel.reset(SdkUpdaterConfigPanel.java:532) at com.android.tools.idea.updater.configure.SdkUpdaterConfigurable.reset(SdkUpdaterConfigurable.java:262) at com.intellij.openapi.options.ex.ConfigurableWrapper.reset(ConfigurableWrapper.java:187) at com.intellij.openapi.options.ex.ConfigurableCardPanel.reset(ConfigurableCardPanel.java:124) at com.intellij.openapi.options.ex.ConfigurableCardPanel$1.compute(ConfigurableCardPanel.java:80) at com.intellij.openapi.options.ex.ConfigurableCardPanel$1.compute(ConfigurableCardPanel.java:65) at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:962) at com.intellij.openapi.options.ex.ConfigurableCardPanel.create(ConfigurableCardPanel.java:65) at com.intellij.openapi.options.newEditor.ConfigurableEditor$1.create(ConfigurableEditor.java:70) at com.intellij.openapi.options.newEditor.ConfigurableEditor$1.create(ConfigurableEditor.java:67) at com.intellij.ui.CardLayoutPanel.createValue(CardLayoutPanel.java:87) at com.intellij.ui.CardLayoutPanel.select(CardLayoutPanel.java:115) at com.intellij.ui.CardLayoutPanel.access$100(CardLayoutPanel.java:40) at com.intellij.ui.CardLayoutPanel$1$1.run(CardLayoutPanel.java:134) at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:345) at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:329) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:726) at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:857) at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:658) at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:386) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:109) at java.awt.WaitDispatchSupport$2.run(WaitDispatchSupport.java:184) at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:229) at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:227) at java.security.AccessController.doPrivileged(Native Method) at java.awt.WaitDispatchSupport.enter(WaitDispatchSupport.java:227) at java.awt.Dialog.show(Dialog.java:1084) at com.intellij.openapi.ui.impl.DialogWrapperPeerImpl$MyDialog.show(DialogWrapperPeerImpl.java:792) at com.intellij.openapi.ui.impl.DialogWrapperPeerImpl.show(DialogWrapperPeerImpl.java:465) at com.intellij.openapi.ui.DialogWrapper.invokeShow(DialogWrapper.java:1661) at com.intellij.openapi.ui.DialogWrapper.show(DialogWrapper.java:1610) at com.intellij.openapi.options.newEditor.SettingsDialog.access$001(SettingsDialog.java:41) at com.intellij.openapi.options.newEditor.SettingsDialog$1.run(SettingsDialog.java:80) at com.intellij.openapi.project.DumbPermissionServiceImpl.allowStartingDumbModeInside(DumbPermissionServiceImpl.java:37) at com.intellij.openapi.project.DumbService.allowStartingDumbModeInside(DumbService.java:283) at com.intellij.openapi.options.newEditor.SettingsDialog.show(SettingsDialog.java:77) at com.intellij.ide.actions.ShowSettingsUtilImpl.showSettingsDialog(ShowSettingsUtilImpl.java:114) at com.android.tools.idea.updater.configure.RunSdkConfigAction.actionPerformed(RunSdkConfigAction.java:47) at com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame$FlatWelcomeScreen$IconsFreeActionGroup$1.actionPerformed(FlatWelcomeFrame.java:652) at com.intellij.ui.popup.PopupFactoryImpl$ActionPopupStep.performAction(PopupFactoryImpl.java:861) at com.intellij.ui.popup.PopupFactoryImpl$ActionPopupStep$1.run(PopupFactoryImpl.java:847) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:726) at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:857) at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:658) at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:386) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) 2016-10-11 22:58:43,225 [1355050] ERROR - pplication.impl.LaterInvocator - Android Studio 2.2.1 Build #AI-145.3330264 2016-10-11 22:58:43,225 [1355050] ERROR - pplication.impl.LaterInvocator - JDK: 1.8.0_76-release 2016-10-11 22:58:43,225 [1355050] ERROR - pplication.impl.LaterInvocator - VM: OpenJDK 64-Bit Server VM 2016-10-11 22:58:43,225 [1355050] ERROR - pplication.impl.LaterInvocator - Vendor: JetBrains s.r.o 2016-10-11 22:58:43,225 [1355050] ERROR - pplication.impl.LaterInvocator - OS: Windows 7 2016-10-11 22:58:43,225 [1355050] ERROR - pplication.impl.LaterInvocator - Last Action: </pre>
<p><a href="https://code.google.com/p/android/issues/detail?id=222920&amp;sort=-modified&amp;colspec=ID%20Type%20Status%20Owner%20Summary%20Stars%20Modified" rel="nofollow">Try this</a>.Hope it solve your problem too.</p>
Problems ionic and iOS10 builds <p>My ionic application for iOS worked fine, 'till today when I wanted to make a new build.</p> <p>This is what get's returned by Apple:</p> <blockquote> <p>Dear developer,</p> <p>We have discovered one or more issues with your recent delivery for "AppName". To process your delivery, the following issues must be corrected:</p> <p>This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSPhotoLibraryUsageDescription key with a string value explaining to the user how the app uses this data.</p> <p>This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSCameraUsageDescription key with a string value explaining to the user how the app uses this data.</p> <p>Though you are not required to fix the following issues, we wanted to make you aware of them:</p> <p>Missing Push Notification Entitlement - Your app includes an API for Apple's Push Notification service, but the aps-environment entitlement is missing from the app's signature. To resolve this, make sure your App ID is enabled for push notification in the Provisioning Portal. Then, sign your app with a distribution provisioning profile that includes the aps-environment entitlement. This will create the correct signature, and you can resubmit your app. See "Provisioning and Development" in the Local and Push Notification Programming Guide for more information. If your app does not use the Apple Push Notification service, no action is required. You may remove the API from future submissions to stop this warning. If you use a third-party framework, you may need to contact the developer for information on removing the API.</p> </blockquote> <p>This are my dependencies:</p> <ul> <li><code>"ngstorage": "~0.3.10",</code></li> <li><code>"ion-image-lazy-load": "*",</code></li> <li><code>"ngCordova": "~0.1.24-alpha",</code></li> </ul> <p>And I use the Barcode scanner in ngCordova. So I did this: <code> $ cordova plugin rm phonegap-plugin-barcodescanner $ cordova plugin add phonegap-plugin-barcodescanner --variable CAMERA_USAGE_DESCRIPTION="Scan QR-Codes" --save </code></p> <p>The <code>config.xml</code> has this in the bottom now:</p> <pre><code> &lt;plugin name="cordova-plugin-camera" spec="~1.2.0"&gt; &lt;variable name="CAMERA_USAGE_DESCRIPTION" value="description" /&gt; &lt;variable name="PHOTOLIBRARY_USAGE_DESCRIPTION" value="description" /&gt; &lt;/plugin&gt; &lt;plugin name="phonegap-plugin-barcodescanner" spec="https://github.com/phonegap/phonegap-plugin-barcodescanner.git"&gt; &lt;variable name="CAMERA_USAGE_DESCRIPTION" value="Scan QR-Codes" /&gt; &lt;/plugin&gt; </code></pre> <p>But still I get the same e-mail from Apple that my app has one or more issues..</p>
<p>Found the solution: <code>$ cordova plugin list</code> and re-install all plugins and read their docs of how to install them regarding the NSPhotoLibraryUsageDescription etc .</p>
Why does setting android:background on a Button cause loss of L/R padding? <p>I am using Android Studio 2.2.1 with project with these settings:</p> <pre><code>compileSdkVersion 24 buildToolsVersion "24.0.2" minSdkVersion 16 targetSdkVersion 24 </code></pre> <p>If I use the GUI to change the button background, it adds this to the layout:</p> <pre><code>android:background="@color/colorPrimary" </code></pre> <p>Then, if I run the app on a 4.4 virtual device (Microsoft's Android Emulator because I'm on an AMD system and I want a fast emulator), or on a Samsung Galaxy S6 with Android 6.0.1, the button has the correct color but loses left and right padding and the text runs right to the left and right edge of the button.</p> <p>If I set only the backgroundTint, then the button has the correct padding on the virtual device, but not the correct color. However, on the S6, it has the correct color and padding.</p> <p>This seems like a bug somewhere, but where? Is it in the code generation or is this a bug in Android 4.4? </p> <p>I think Android Studio should be doing whatever needed to make it work correct on both platform levels, whether it is as complex as some of these solutions:</p> <p><a href="http://stackoverflow.com/questions/1521640/standard-android-button-with-a-different-color">Standard Android Button with a different color</a></p> <p>or something more succinct.</p> <p>My styles.xml file shows:</p> <pre><code>&lt;resources&gt; &lt;!-- Base application theme. --&gt; &lt;style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"&gt; &lt;!-- Customize your theme here. --&gt; &lt;item name="colorPrimary"&gt;@color/colorPrimary&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/colorPrimaryDark&lt;/item&gt; &lt;item name="colorAccent"&gt;@color/colorAccent&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre> <p>and my AndroidManifest theme setting is:</p> <pre><code>&lt;application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" </code></pre>
<blockquote> <p>This seems like a bug somewhere, but where?</p> </blockquote> <p>Right here:</p> <pre><code>android:background="@color/colorPrimary" </code></pre> <blockquote> <p>Is it in the code generation or is this a bug in Android 4.4? </p> </blockquote> <p>No, it is your replacement background. It is a color, without any intrinsic padding, and without being wrapped in a <code>StateListDrawable</code>.</p> <p>The stock background of <code>Button</code> widgets has some amount of padding enforced as part of the background itself (e.g., via some transparent pixels in the nine-patch PNG used for the background). The actual background itself is a <code>StateListDrawable</code>, which chooses one of several other drawable resources to apply based on the state of the <code>Button</code> (e.g., normal, pressed, focused, disabled).</p> <p>To replace a <code>Button</code> background, you need to first use a <code>StateListDrawable</code> of your own. Otherwise, your <code>Button</code> will not appear to respond visually to click events or other state changes (e.g., being disabled). Then, you can either incorporate some padding into the backgrounds for your states, or put padding on the <code>Button</code> widget itself, as you see fit.</p> <blockquote> <p>I think Android Studio should be doing whatever needed to make it work correct on both platform levels</p> </blockquote> <p>Android Studio assumes that you know what you are doing. There is no hard-and-fast requirement that <code>Button</code> backgrounds have this sort of padding, and there is no hard-and-fast requirement that a <code>Button</code> be something that makes sense to users (versus "hey, why does this button seem to not respond visually when I tap on it?"). There will be scenarios where developers <em>do</em> want <code>Button</code> widgets to have no padding, such as in an implementation of a segmented-list-control sort of compound widget.</p> <p>Personally, I think the decision to have some intrinsic padding in the <code>Button</code> background is regrettable. But, that's the way it was implemented back in Android 1.0, and Google has elected to maintain the approach, even with newer themes, presumably for backwards compatibility.</p> <blockquote> <p>If I set only the backgroundTint, then the button has the correct padding on the virtual device, but not the correct color</p> </blockquote> <p>I have not played with <code>backgroundTint</code> with <code>appcompat-v7</code>. It is possible that you are seeing a bug there. You might consider posting a separate question with a complete example, plus screenshots, to get more specific help with that particular concern.</p>
How to lazy load a custom attribute on a Laravel model? <p>Is there any possible way to lazy load a custom attribute on a Laravel model <strong>without</strong> loading it every time by using the <code>appends</code> property? I am looking for something akin to way that you can <a href="https://laravel.com/docs/5.2/eloquent-relationships#lazy-eager-loading" rel="nofollow">lazy load Eloquent relationships</a>.</p> <p>For instance, given this accessor method on a model:</p> <pre><code>public function getFooAttribute(){ return 'bar'; } </code></pre> <p>I would love to be able to do something like this:</p> <pre><code>$model = MyModel::all(); $model-&gt;loadAttribute('foo'); </code></pre> <p>This question is <strong>not</strong> the same thing as <a href="http://stackoverflow.com/questions/17232714/add-a-custom-attribute-to-a-laravel-eloquent-model-on-load">Add a custom attribute to a Laravel / Eloquent model on load?</a> because that wants to load a custom attribute on every model load - I am looking to <strong>lazy load</strong> the attribute only when specified.</p> <p>I suppose I could assign a property to the model instance with the same name as the custom attribute, but this has the performance downside of calling the accessor method <strong>twice</strong>, might have unintended side effects if that accessor affects class properties, and just feels dirty.</p> <pre><code>$model = MyModel::all(); $model-&gt;foo = $model-&gt;foo; </code></pre> <p>Does anyone have a better way of handling this?</p>
<p>Is this for serialization? You could use the <code>append()</code> method on the Model instance:</p> <pre><code>$model = MyModel::all(); $model-&gt;append('foo'); </code></pre> <p>The <code>append</code> method can also take an array as a parameter.</p>
Rethinkdb update nested object <p>I have a document like below-</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>{ "badgeCount": { "0e2f8e0c-2a18-499d-8e64-75b5d284e31a": 0 , "c0d07f5c-25ff-4829-8145-c33c0871f889": 0 } , "createdDate": Mon Oct 10 2016 19:25:10 GMT+00:00 , "deleted": false , "id": "1330c8b8-38a2-46e4-b93d-f7ff84a423ed", "joinedUserIds": [ "0e2f8e0c-2a18-499d-8e64-75b5d284e31a" ] }</code></pre> </div> </div> </p> <p>What I want to do is remove joinedUserId "0e2f8e0c-2a18-499d-8e64-75b5d284e31a" and update badgeCount by removing first property "0e2f8e0c-2a18-499d-8e64-75b5d284e31a": 0 in the same query.</p> <p>I tried updating badgeCount like below-</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> r.db('mydb').table('discussion').filter({"id": "1330c8b8-38a2-46e4-b93d-f7ff84a423ed"}) .update(function(s){ return { badgeCount: s('badgeCount').without("0e2f8e0c-2a18-499d-8e64-75b5d284e31a") } })</code></pre> </div> </div> </p> <p>But it does not working. Not sure what I am missing. </p> <p>Thanks Anup</p>
<p>Rethink doesn't work like this. It doesn't rewrite object with <code>update</code>.</p> <p>So, for this case you need to <code>replace</code> current object. And, btw, better to use <code>get</code> instead of <code>filter</code>, cause it's faster. There are doing the same in this situation 'cause id field is unique.</p> <p>So, if you want to remove <code>"0e2f8e0c-2a18-499d-8e64-75b5d284e31a"</code> from <code>badgeCount</code>, you should use <a href="https://rethinkdb.com/api/javascript/replace/" rel="nofollow"><code>replace</code></a>:</p> <pre><code>r.db('mydb').table('discussion').get("1330c8b8-38a2-46e4-b93d-f7ff84a423ed").replace(function(s){ return s.without({badgeCount : {"0e2f8e0c-2a18-499d-8e64-75b5d284e31a" : true}}).without("joinedUserIds").merge({ joinedUserIds : s("joinedUserIds").filter(function(id){ return id.ne("0e2f8e0c-2a18-499d-8e64-75b5d284e31a"); }) }); }) </code></pre>
Stored image in SQLite is not shown in Gridview <p>Yesterday I asked <a href="http://stackoverflow.com/questions/39963294/attempt-to-invoke-interface-method-int-android-database-cursor-getcount-on-a/39963507?noredirect=1#comment67207166_39963507">this</a> question where I was putting some static data to sqlite via a content provider. Now I want to go one step further. I download some data from a webserver(with Volley) and store them again in SQLite. Next I want to read them with a CursorLoader. However I can only display the titles of the images in the Gridview. So let me start with my code.</p> <p><strong>MainActivityFragment</strong></p> <pre><code>public class MainActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks&lt;Cursor&gt;{ static public ArrayList&lt;MyCity&gt; cityList; private static final String LOG_TAG = MainActivityFragment.class.getSimpleName(); private MyCityAdpapter myCityAdpapter; private static final int CURSOR_LOADER_ID = 0; private GridView mGridView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public MainActivityFragment() { // Required empty public constructor } @Override public void onActivityCreated(Bundle savedInstanceState) { Cursor c = getActivity().getContentResolver().query(MyCityContract.MyCityEntry.CONTENT_URI, new String[]{MyCityContract.MyCityEntry._ID}, null, null, null); if (c.getCount() == 0){ updateImagesList(); } // initialize loader getLoaderManager().initLoader(CURSOR_LOADER_ID, null, this); super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment // inflate fragment_main layout final View rootView = inflater.inflate(R.layout.fragment_main_activity, container, false); cityList = new ArrayList&lt;&gt;(); // initialize our FlavorAdapter myCityAdpapter = new MyCityAdpapter(getActivity(), null, 0, CURSOR_LOADER_ID); // initialize mGridView to the GridView in fragment_main.xml mGridView = (GridView) rootView.findViewById(R.id.flavors_grid); // set mGridView adapter to our CursorAdapter mGridView.setAdapter(myCityAdpapter); return rootView; } @Override public Loader&lt;Cursor&gt; onCreateLoader(int id, Bundle args){ return new CursorLoader(getActivity(), MyCityContract.MyCityEntry.CONTENT_URI, null, null, null, null); } @Override public void onLoadFinished(Loader&lt;Cursor&gt; loader, Cursor data) { myCityAdpapter.swapCursor(data); } public void updateImagesList() { // Instantiate the RequestQueue. RequestQueue queue = Volley.newRequestQueue(getActivity()); // Request a string response from the provided URL. JsonArrayRequest jsObjRequest = new JsonArrayRequest(Request.Method.GET, API.API_URL, new Response.Listener&lt;JSONArray&gt;() { @Override public void onResponse(JSONArray response) { cityList.clear(); Log.d(TAG, response.toString()); //hidePD(); // Parse json data. // Declare the json objects that we need and then for loop through the children array. // Do the json parse in a try catch block to catch the exceptions try { for (int i = 0; i &lt; response.length(); i++) { //insert images information into the database JSONObject post = response.getJSONObject(i); MyCity item = new MyCity(); item.setName(post.getString("title")); item.setImage(API.IMAGE_URL + post.getString("image")); ContentValues imageValues = new ContentValues(); imageValues.put(MyCityContract.MyCityEntry._ID, post.getString("id")); imageValues.put(MyCityContract.MyCityEntry.COLUMN_NAME, post.getString("title")); imageValues.put(MyCityContract.MyCityEntry.COLUMN_ICON, post.getString("image")); getActivity().getContentResolver().insert(MyCityContract.MyCityEntry.CONTENT_URI, imageValues); cityList.add(item); } } catch (JSONException e) { e.printStackTrace(); } // Update list by notifying the adapter of changes myCityAdpapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); //hidePD(); } }); queue.add(jsObjRequest); } @Override public void onLoaderReset(Loader&lt;Cursor&gt; loader){ myCityAdpapter.swapCursor(null); } </code></pre> <p>}</p> <p><strong>MyCityAdapter</strong></p> <pre><code>public class MyCityAdpapter extends CursorAdapter { private static final String LOG_TAG = MyCityAdpapter.class.getSimpleName(); private Context mContext; private static int sLoaderID; public MyCityAdpapter(Context context, Cursor c, int flags,int loaderID) { super(context, c, flags); Log.d(LOG_TAG, "MyCityAdpapter"); mContext = context; sLoaderID = loaderID; } public static class ViewHolder { public final ImageView imageView; public final TextView textView; public ViewHolder(View view){ imageView = (ImageView) view.findViewById(R.id.flavor_image); textView = (TextView) view.findViewById(R.id.flavor_text); } } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { int layoutId = R.layout.flavor_item; Log.d(LOG_TAG, "In new View"); View view = LayoutInflater.from(context).inflate(layoutId, parent, false); ViewHolder viewHolder = new ViewHolder(view); view.setTag(viewHolder); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder viewHolder = (ViewHolder) view.getTag(); Log.d(LOG_TAG, "In bind View"); int versionIndex = cursor.getColumnIndex(MyCityContract.MyCityEntry.COLUMN_NAME); final String versionName = cursor.getString(versionIndex); Log.i(LOG_TAG, "Text reference extracted: " + versionName); viewHolder.textView.setText(versionName); int imageIndex = cursor.getColumnIndex(MyCityContract.MyCityEntry.COLUMN_ICON); int image = cursor.getInt(imageIndex); Log.i(LOG_TAG, "Image reference extracted: " + image); viewHolder.imageView.setImageResource(image); } } </code></pre> <p>Plese bare in mind that the logcat of this class gives me</p> <pre><code>I/MyCityAdpapter: Text reference extracted: Ancient Theatre - Larissa I/MyCityAdpapter: Image reference extracted: 0 I/MyCityAdpapter: Text reference extracted: Old trains I/MyCityAdpapter: Image reference extracted: 0 </code></pre> <p>and so on.</p> <p><strong>MyCityContract</strong></p> <pre><code>public class MyCityContract { public static final String CONTENT_AUTHORITY = "theo.testing.customloaders.app"; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); public static final class MyCityEntry implements BaseColumns{ //table name public static final String TABLE_MY_CITY = "my_city"; //columns public static final String _ID = "_id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_ICON = "icon"; // create content uri public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon() .appendPath(TABLE_MY_CITY).build(); // create cursor of base type directory for multiple entries public static final String CONTENT_DIR_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + TABLE_MY_CITY; // create cursor of base type item for single entry public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE +"/" + CONTENT_AUTHORITY + "/" + TABLE_MY_CITY; // for building URIs on insertion public static Uri buildFlavorsUri(long id){ return ContentUris.withAppendedId(CONTENT_URI, id); } } } </code></pre> <p>Maybe there is something wrong with my <strong>MyCityDbHelperClass</strong> where I store all the data.</p> <pre><code>public class MyCityDbHelper extends SQLiteOpenHelper{ public static final String LOG_TAG = MyCityDbHelper.class.getSimpleName(); //name &amp; version public static final String DATABASE_NAME = "city.db"; public static final int DATABASE_VERSION = 7; // Create the database public MyCityDbHelper(Context context) { super(context, DATABASE_NAME,null,DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { final String SQL_CREATE_MY_CITY_TABLE = "CREATE TABLE " + MyCityContract.MyCityEntry.TABLE_MY_CITY + "(" + MyCityContract.MyCityEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MyCityContract.MyCityEntry.COLUMN_NAME + " TEXT NOT NULL, " + MyCityContract.MyCityEntry.COLUMN_ICON + " INTEGER NOT NULL);"; sqLiteDatabase.execSQL(SQL_CREATE_MY_CITY_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { Log.w(LOG_TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ". OLD DATA WILL BE DESTROYED"); // Drop the table sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + MyCityContract.MyCityEntry.TABLE_MY_CITY); sqLiteDatabase.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + MyCityContract.MyCityEntry.TABLE_MY_CITY + "'"); // re-create database onCreate(sqLiteDatabase); } } </code></pre> <p>and finally I have my provider.</p> <pre><code>public class MyCityProvider extends ContentProvider { private static final String LOG_TAG = MyCityProvider.class.getSimpleName(); private static final UriMatcher sUriMatcher = buildUriMatcher(); private MyCityDbHelper myCityDbHelper; //Codes for UriMatcher private static final int MY_CITY = 100; private static final int MY_CITY_WITH_ID = 200; private static UriMatcher buildUriMatcher(){ // Build a UriMatcher by adding a specific code to return based on a match // It's common to use NO_MATCH as the code for this case. final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = MyCityContract.CONTENT_AUTHORITY; //add code for each URI matcher.addURI(authority,MyCityContract.MyCityEntry.TABLE_MY_CITY,MY_CITY); matcher.addURI(authority,MyCityContract.MyCityEntry.TABLE_MY_CITY + "/#",MY_CITY_WITH_ID); return matcher; } @Override public boolean onCreate() { myCityDbHelper = new MyCityDbHelper(getContext()); return true; } @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match){ case MY_CITY: { return MyCityContract.MyCityEntry.CONTENT_DIR_TYPE; } case MY_CITY_WITH_ID:{ return MyCityContract.MyCityEntry.CONTENT_ITEM_TYPE; } default:{ throw new UnsupportedOperationException("Unknown uri: " + uri); } } } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder){ Cursor retCursor; switch(sUriMatcher.match(uri)){ // All Flavors selected case MY_CITY:{ retCursor = myCityDbHelper.getReadableDatabase().query( MyCityContract.MyCityEntry.TABLE_MY_CITY, projection, selection, selectionArgs, null, null, sortOrder); return retCursor; } // Individual flavor based on Id selected case MY_CITY_WITH_ID:{ retCursor = myCityDbHelper.getReadableDatabase().query( MyCityContract.MyCityEntry.TABLE_MY_CITY, projection, MyCityContract.MyCityEntry._ID + " = ?", new String[] {String.valueOf(ContentUris.parseId(uri))}, null, null, sortOrder); return retCursor; } default:{ // By default, we assume a bad URI throw new UnsupportedOperationException("Unknown uri: " + uri); } } } @Override public Uri insert(Uri uri, ContentValues contentValues) { final SQLiteDatabase db = myCityDbHelper.getWritableDatabase(); Uri returnUri; switch (sUriMatcher.match(uri)){ case MY_CITY: long _id = db.insertWithOnConflict(MyCityContract.MyCityEntry.TABLE_MY_CITY,null,contentValues,SQLiteDatabase.CONFLICT_REPLACE); Log.d("id",String.valueOf(_id)); // insert unless it is already contained in the database if(_id&gt;0){ returnUri = MyCityContract.MyCityEntry.buildFlavorsUri(_id); }else { throw new android.database.SQLException("Failed to insert row into: " + uri); } break; default: { throw new UnsupportedOperationException("Unknown uri: " + uri ); } } getContext().getContentResolver().notifyChange(uri,null); return returnUri; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { final SQLiteDatabase db = myCityDbHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int numDeleted; switch(match){ case MY_CITY: numDeleted = db.delete( MyCityContract.MyCityEntry.TABLE_MY_CITY, selection, selectionArgs); // reset _ID db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + MyCityContract.MyCityEntry.TABLE_MY_CITY + "'"); break; case MY_CITY_WITH_ID: numDeleted = db.delete(MyCityContract.MyCityEntry.TABLE_MY_CITY, MyCityContract.MyCityEntry._ID + " = ?", new String[]{String.valueOf(ContentUris.parseId(uri))}); // reset _ID db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + MyCityContract.MyCityEntry.TABLE_MY_CITY + "'"); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } return numDeleted; } @Override public int update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs){ final SQLiteDatabase db = myCityDbHelper.getWritableDatabase(); int numUpdated = 0; if (contentValues == null){ throw new IllegalArgumentException("Cannot have null content values"); } switch(sUriMatcher.match(uri)){ case MY_CITY:{ numUpdated = db.update(MyCityContract.MyCityEntry.TABLE_MY_CITY, contentValues, selection, selectionArgs); break; } case MY_CITY_WITH_ID: { numUpdated = db.update(MyCityContract.MyCityEntry.TABLE_MY_CITY, contentValues, MyCityContract.MyCityEntry._ID + " = ?", new String[] {String.valueOf(ContentUris.parseId(uri))}); break; } default:{ throw new UnsupportedOperationException("Unknown uri: " + uri); } } if (numUpdated &gt; 0){ getContext().getContentResolver().notifyChange(uri, null); } return numUpdated; } } </code></pre> <p>So why the image is not there? I always wanted to solve the issue of storing dynamic data and read them in offline mode too:). </p> <p>Thanks,</p> <p>Theo.</p>
<p>You are storing image url in your database, but you are reading an Integer in your <code>MyCityAdapter</code>. You need to get image url again in <code>bindView()</code> method. Once you get the url of the image, you will have to download and store the image itself. But there is no need to write it all yourself. I recommend <a href="http://square.github.io/picasso/" rel="nofollow">Picasso</a> library. Once you add this library to your dependecies, you can set image to your imageView like following: <code>Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);</code></p> <p>So, your <code>bindView()</code> method body will be something like this:</p> <pre><code>@Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder viewHolder = (ViewHolder) view.getTag(); Log.d(LOG_TAG, "In bind View"); int versionIndex = cursor.getColumnIndex(MyCityContract.MyCityEntry.COLUMN_NAME); final String versionName = cursor.getString(versionIndex); Log.i(LOG_TAG, "Text reference extracted: " + versionName); viewHolder.textView.setText(versionName); int imageIndex = cursor.getColumnIndex(MyCityContract.MyCityEntry.COLUMN_ICON); String imageUrl = cursor.getString(imageIndex); Log.i(LOG_TAG, "Image reference extracted: " + image); Picasso.with(context).load(imageUrl).into(viewHolder.imageView); } </code></pre>
Android Studio Emulator Showing Up; Not Working <p>Following online instructions, I created an app that converts kilometers to miles, and miles to kilometers. I tried to run the app, and I turned on the emulator. It showed up, but it didn't run the program. That's all I know about the problem. Any suggestions? (I really wish I had more info)</p> <p>EDIT:</p> <p>It says:</p> <pre><code>emulator: WARNING: VM heap size set below hardware specified minimum of 384MB Warning: requested ram_size 1536M too big, reduced to 1024M emulator: WARNING: Setting VM heap size to 384MB Hax is enabled Hax ram_size 0x40000000 HAX is working and emulator runs in fast virt mode. console on port 5554, ADB on port 5555 </code></pre>
<p>I believe your emulator is complaining because you don't have enough ram to give to the emulator. </p> <p>I think you go to tools > Android > AVD manager and then select the emulator you want to use. Once selected you should be able to reduce the amount of ram to 1024m like it's asking you to do. I'm not on my pc at the moment so I hope my memory serves me well!</p> <p>If that doesn't work hopefully this android document can help: <a href="https://developer.android.com/studio/run/managing-avds.html" rel="nofollow">https://developer.android.com/studio/run/managing-avds.html</a></p>
REST API, HTTP status code and result code <p>This is more a "philosophical" question than a technical one.</p> <p>Assume that you have a message, and users that are allowed (or not) to access this message. Let's assume we have an api to do that, here would be the endpoints :</p> <ul> <li>/message/(id_message)/allow/(user_id)</li> <li>/message/(id_message)/forbid/(user_id)</li> </ul> <p>Let's say now that, in addition to the HTTP status code, we have a field <code>result_code</code> that return a number that reflects exactly what happens in the code.</p> <p>Let's say we allow the first time a user. The HTTP status code of this method should be 200, and let's say the <code>result_code</code> is 20.</p> <p>If we straight call this method again, what should be the HTTP status code, the <code>result_code</code>, and why ?</p>
<p>Surely this is not a philosophical question but one about what the standard says and about real advantages of obeying these standards.</p> <p>HTTP specifies GET, PUT and DELETE operations to be <a href="http://www.restapitutorial.com/lessons/idempotency.html" rel="nofollow">idempotent</a>. This means that repeating the call needs to have the same effect. </p> <p>Making these operations idempotent is important because messages can get lost and the caller needs to have a way to handle that. There are no transactions in REST, so repeating an idempotent operation ensures that it is carried out when the caller is unsure whether the first call had an effect. In your example allowing a user twice should be the same as allowing it once.</p> <p><a href="https://tools.ietf.org/html/rfc7231#section-4.2.2" rel="nofollow">RFC7231</a> defines idempotence as follows:</p> <blockquote> <p>A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. [...] Idempotent methods are distinguished because the request can be repeated automatically if a communication failure occurs before the client is able to read the server's response. [...] It knows that repeating the request will have the same intended effect, even if the original request succeeded, though the response might differ.</p> </blockquote> <p>The server side (main) effect needs to be the same. The RFC allows the response to be different. Especially in the case of DELETE this is often the case as a successful deletion normally results in a <code>204 No Content</code> and a repeated deletion results in a <code>404 Not Found</code>.</p> <p>Although responses needn't be identical, it is nevertheless helpful if they are. This simplifies client logic. The client can assume that a repeated call has the same effect so it should be able to handle it using the same code. The aforementioned exception with DELETE returning either 204 or 404 is quite common (as this simplifies server logic). Other exceptions are rare and should be only made if there is a good reason for that.</p> <p>POST and PATCH operations are, strictly speaking, not required to be idempotent. Especially with PATCH it can be helpful, though. </p> <p>POST operations are meant to be not idempotent. Or rather the other way around: If you have an operation that you cannot make idempotent, it should be a POST operation.</p> <p>Speaking of standards and REST: A REST resource for the purpose mentioned by you should rather look like the following:</p> <pre><code>GET /messages/{messageId}/allowed-users </code></pre> <p>Returns the list of allowed users. Note that resources which represent lists are named in plural (so <code>messages</code> not <code>message</code>).</p> <pre><code>PUT /messages/{messageId}/allowed-users/{userId} </code></pre> <p>Add a new user to the list of allowed users.</p> <pre><code>DELETE /messages/{messageId}/allowed-users/{userId} </code></pre> <p>Revoke the right previously given.</p> <p>All these operations should be idempotent.</p> <p>Using a POST operation would look like the following:</p> <pre><code>POST /messages/{messageId}/allowed-users { "userId": "1324" } </code></pre> <p>POST adds a new element to a list-like resource. You are not required to make this idempotent but I'd consider is advisable in this case.</p> <p>You can return additional result codes as a header or as a result object. Just as you mentioned. But if you like to: there were some folks who already thought about that in detail and came up with <a href="https://tools.ietf.org/html/rfc7807" rel="nofollow">problem-detail</a>.</p>
How to change element CSS when hover on a link <p>I have a working wordpress theme, but I want to change some visual aspects. I want to change the background of a couple of elements when I hover the mouse on a specific menu option, something like on this site: <a href="http://www.tecmundo.com.br/teste-de-velocidade.htm" rel="nofollow">http://www.tecmundo.com.br/teste-de-velocidade.htm</a></p> <p>What I need to know to perform that? It seems like I need to use some JS, with CSS only this looks impossible. Thanks.</p>
<p>By adding <code>:hover</code> after your class name in your css file and then define a new class (like that : <code>.yourClass:hover{}</code> , that should be your new class (don't touch the <code>.yourClass</code>, just create a new one with the <code>:hover</code> with the style you want).</p>
Form not reading information from database <p>I am configuring a sign in form from a framework I use every now and then. However, for some reason the <code>$tryagain</code> error keeps populating. I know the information is correct in my database and I even edited the password within the database to remove the hash to eliminate this as the problem. </p> <p>Does anyone have a clue as to why it keeps throwing the try again error saying the information is wrong? I am able to register a user and then I redirect them to this page to allow them to sign in, so the sign in is the only issue.</p> <p>Please let me know if you need more code from the framework. I did not want to post loads of code.</p> <pre><code>ini_set('display_errors', 1); error_reporting(E_ALL); require_once 'core/init.php'; if(Input::exists()) { if(Token::check(Input::get('token'))) { $validate = new Validate(); $validation = $validate-&gt;check($_POST, array( 'username' =&gt; array('required' =&gt; true), 'password' =&gt; array('required' =&gt; true) )); if($validation-&gt;passed()) { $user = new User(); $remember = (Input::get('remember') === 'on') ? true : false; $login = $user-&gt;login(Input::get('username'), Input::get('password'), $remember); //var_dump($login); if($login) { Redirect::to('index'); } else { echo $tryagain = '&lt;span class="signinpanel"&gt;' . "The information you entered did not match our records." . '&lt;/span&gt;'; } } else { foreach($validation-&gt;errors() as $error) { echo $error, '&lt;br&gt;'; } } } } </code></pre> <p>Form</p> <pre><code>&lt;?php if(Session::exists('home')) { echo '&lt;p&gt;' . Session::flash('home') . '&lt;/p&gt;'; } ?&gt; &lt;form name="Sign In" action="" method="POST" autocomplete="on" accept-charset= "utf-8"&gt; &lt;div class="field"&gt; &lt;label for="username"&gt;Username&lt;/label&gt; &lt;input type="text" name="username" autocomplete="on" required&gt; &lt;/div&gt; &lt;div class="field"&gt; &lt;label for="password"&gt;Password&lt;/label&gt; &lt;input type="password" name="password" autocomplete="off" required&gt; &lt;/div&gt; &lt;div class="field"&gt; &lt;label for="remember"&gt; &lt;input type="checkbox" name="remember" id="remember"&gt; Remember me &lt;/label&gt; &lt;/div&gt;&lt;br&gt; &lt;input type="hidden" name="token" value="&lt;?php echo Token::generate(); ?&gt;"&gt; &lt;input type="submit" value="Sign In"&gt; &lt;/form&gt; </code></pre> <p>Login function</p> <pre><code>public function login($username = null, $password = null, $remember = false) { if(!$username &amp;&amp; !$password &amp;&amp; $this-&gt;exists()) { Session::put($this-&gt;_sessionName, $this-&gt;data()-&gt;id); } else { $user = $this-&gt;find($username); if($user) { if($this-&gt;data()-&gt;password === Hash::make($password, $this-&gt;data()-&gt;salt)) { Session::put($this-&gt;_sessionName, $this-&gt;data()-&gt;id); if($remember) { $hash = Hash::unique(); $hashCheck = $this-&gt;_db-&gt;get('users_session', array('user_id', '=', $this-&gt;data()-&gt;id)); if(!$hashCheck-&gt;count()) { $this-&gt;_db-&gt;insert('users_session', array( 'user_id' =&gt; $this-&gt;data()-&gt;id, 'hash' =&gt; $hash )); } else { $hash = $hashCheck-&gt;first()-&gt;hash; } Cookie::put($this-&gt;_cookieName, $hash, Config::get('remember/cookie_expiry')); } return true; } } } return false; </code></pre> <p>}</p> <p>Hash file</p> <pre><code>class Hash { public static function make($string, $salt = '') { return hash('sha256', $string . $salt); } public static function salt($length) { return mcrypt_create_iv($length); } public static function unique() { return self::make(uniqid()); } } </code></pre>
<p>I think your error lies in the check you are making here:</p> <pre><code>if($this-&gt;data()-&gt;password === Hash::make($password, $this-&gt;data()-&gt;salt)) { Session::put($this-&gt;_sessionName, $this-&gt;data()-&gt;id); </code></pre> <p>If I read this correctly you are taking the value that the user has entered and are then creating a brand new Hash of the password with a new random salt being fed in. This value will change every time the code is executed but is (very) unlikely to ever be identical to the input password.</p> <p>Initially this answer was based on the Laravel libraries:</p> <p>Instead of using <code>Hash:make</code> use <code>Hash::check</code> as the guard to entering that block:</p> <pre><code>if(Hash::check($this-&gt;data()-&gt;password, $password)){ Session::put($this-&gt;_sessionName, $this-&gt;data()-&gt;id); </code></pre> <p>This should give a pathway to let the <code>login()</code> function return <code>true</code>.</p> <p>However, as @becky indicated that they weren't using Laravel a more general answer was needed:</p> <p>The underlying problem that you have is that you're checking the plaintext password against the encrypted (hashed) password. In all good algorithms this won't be the same thing which is why it's never going to return true from the function.</p> <p>What you need to do is check the hashed version of what the user has entered: <code>Hash::make($password, $this-&gt;data()-&gt;salt)</code> with the value that you've stored (because you only store the hashed version). If you can change the code to compare those two values they should be the same and so the identity operator <code>===</code> will return a <code>true</code> value.</p> <p>Further discussions, and some debugging, indicated that what was coming back from the DB wasn't what was being created on the page by the </p> <pre><code>Hash::make($password, $this-&gt;data()-&gt;salt) </code></pre> <p>statement. On closer inspection it emerged that the length of the column on the db had been reduced from 64 characters to 50. As the <code>Hash::make()</code> function returned a 64-character hash the two could never equate. Remaking that DB column and regenerating the password hashes fixed the problem.</p>
Error when sending email using postal MVC? <p><strong>Requirement:</strong></p> <p>Send emails to all users dynamically everyday at a particular time, say 6:00 AM.</p> <p><strong>What I did so far:</strong></p> <p>I use a third party library called Quartz.net from Nuget.</p> <pre><code>public class TaskScheduler : IJob { public void Execute(IJobExecutionContext context) { try { UserRepository userRepo = new UserRepository(); var users = userRepo.GetUsers(); DashBoardRepository repo = new DashBoardRepository(); foreach (var rec in users) { var tasks = repo.GetIncompleteTasks(rec.UserID); var appointments = repo.GetUpcomingAppointments(rec.UserID); if (tasks.Count &gt; 0 || appointments.Count &gt; 0) { dynamic email = new Email("TaskEmail"); email.To = rec.Email; email.From = "no-reply@xyz.com"; email.Subject = "Pending items in XYZ"; email.Tasks = tasks; email.Appointments = appointments; email.Send(); } } } catch(Exception ex) { clsLog.LogMessageToFile(ex.ToString()); } } } public static class JobScheduler { public static void Start() { IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler(); scheduler.Start(); IJobDetail job = JobBuilder.Create&lt;TaskScheduler&gt;().Build(); ITrigger trigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s =&gt; s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(6, 0)) ) .Build(); scheduler.ScheduleJob(job, trigger); } } protected void Application_Start() { JobScheduler.Start(); } </code></pre> <p>I am using Postal in MVC to send the email.</p> <p>This works fine in my local if I run from my Visual Studio. But once I deploy it onto IIS, I get the error below:</p> <pre><code> System.ArgumentException: The virtual path '/' maps to another application, which is not allowed. at System.Web.CachedPathData.GetVirtualPathData(VirtualPath virtualPath, Boolean permitPathsOutsideApp) at System.Web.HttpContext.GetFilePathData() ------------- </code></pre> <p>I am hosting this application as a sub directory in the IIS. So it is something like <a href="http://www.maindemosite.com/xyz">http://www.maindemosite.com/xyz</a></p> <p><a href="https://i.stack.imgur.com/JOAs2.png"><img src="https://i.stack.imgur.com/JOAs2.png" alt="enter image description here"></a></p> <p><strong>Web.Config:</strong></p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=301880 --&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /&gt; &lt;section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /&gt; &lt;section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5v361934e089" requirePermission="false" /&gt; &lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&gt; &lt;/configSections&gt; &lt;connectionStrings&gt; &lt;add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-XYZ-201405202911.mdf;Initial Catalog=aspnet-XYZ-20140534102911;Integrated Security=True" providerName="System.Data.SqlClient" /&gt; &lt;add name="XYZEntities" connectionString="metadata=res://*/DAL.XYZEntities.csdl|res://*/DAL.XYZEntities.ssdl|res://*/DAL.XYZEntities.msl;provider=System.Data.SqlClient;provider connection string=&amp;quot;data source=SERVER\MSSQL;initial catalog=XYZTest;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&amp;quot;" providerName="System.Data.EntityClient" /&gt; &lt;/connectionStrings&gt; &lt;appSettings&gt; &lt;add key="webpages:Version" value="3.0.0.0" /&gt; &lt;add key="webpages:Enabled" value="false" /&gt; &lt;add key="ClientValidationEnabled" value="true" /&gt; &lt;add key="UnobtrusiveJavaScriptEnabled" value="true" /&gt; &lt;add key="AuthenticationSlide" value="100" /&gt; &lt;add key="DocumentsPath" value="C:/Users/KKK/Documents/Documents/" /&gt; &lt;add key="XYZDeployment" value="http://localhost:51641" /&gt; &lt;/appSettings&gt; &lt;system.identityModel.services&gt; &lt;federationConfiguration&gt; &lt;cookieHandler requireSsl="false" name="ABCAuthorization" /&gt; &lt;/federationConfiguration&gt; &lt;/system.identityModel.services&gt; &lt;system.net&gt; &lt;mailSettings&gt; &lt;smtp&gt; &lt;network host="smtp.ABC.com" port="25" userName="xxx@xxx.ca" password="!@abc99" /&gt; &lt;/smtp&gt; &lt;/mailSettings&gt; &lt;/system.net&gt; &lt;system.identityModel&gt; &lt;identityConfiguration&gt; &lt;securityTokenHandlers&gt; &lt;remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /&gt; &lt;add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /&gt; &lt;/securityTokenHandlers&gt; &lt;/identityConfiguration&gt; &lt;/system.identityModel&gt; &lt;system.web&gt; &lt;sessionState mode="InProc" timeout="1" /&gt; &lt;compilation debug="true" targetFramework="4.5" /&gt; &lt;httpRuntime targetFramework="4.5" maxRequestLength="1048576" /&gt; &lt;authentication mode="Forms"&gt; &lt;forms loginUrl="~/Account/Login" timeout="2880" /&gt; &lt;/authentication&gt; &lt;/system.web&gt; &lt;system.webServer&gt; &lt;security&gt; &lt;requestFiltering&gt; &lt;requestLimits maxAllowedContentLength="1073741824" /&gt; &lt;/requestFiltering&gt; &lt;/security&gt; &lt;modules runAllManagedModulesForAllRequests="true"&gt; &lt;add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /&gt; &lt;/modules&gt; &lt;handlers&gt; &lt;remove name="ExtensionlessUrlHandler-Integrated-4.0" /&gt; &lt;remove name="OPTIONSVerbHandler" /&gt; &lt;remove name="TRACEVerbHandler" /&gt; &lt;add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /&gt; &lt;/handlers&gt;&lt;/system.webServer&gt; &lt;runtime&gt; &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="Microsoft.AspNet.Identity.Core" publicKeyToken="31bf3856ad364e35" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-2.1.0.0" newVersion="2.1.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="Microsoft.Practices.Unity" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-3.5.0.0" newVersion="4.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /&gt; &lt;/dependentAssembly&gt; &lt;/assemblyBinding&gt; &lt;/runtime&gt; &lt;entityFramework&gt; &lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"&gt; &lt;parameters&gt; &lt;parameter value="v11.0" /&gt; &lt;/parameters&gt; &lt;/defaultConnectionFactory&gt; &lt;providers&gt; &lt;provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /&gt; &lt;/providers&gt; &lt;/entityFramework&gt; &lt;system.serviceModel&gt; &lt;bindings /&gt; &lt;client /&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre> <p><strong>Complete Error Message:</strong></p> <pre><code> Log Entry : 10:09:40 AM Friday, October 14, 2016 : :System.ArgumentException: The virtual path '/' maps to another application, which is not allowed. at System.Web.CachedPathData.GetVirtualPathData(VirtualPath virtualPath, Boolean permitPathsOutsideApp) at System.Web.HttpContext.GetFilePathData() at System.Web.Configuration.RuntimeConfig.GetConfig(HttpContext context) at System.Web.Configuration.HttpCapabilitiesBase.GetBrowserCapabilities(HttpRequest request) at System.Web.HttpRequest.get_Browser() at System.Web.HttpRequestWrapper.get_Browser() at System.Web.WebPages.BrowserHelpers.GetOverriddenBrowser(HttpContextBase httpContext, Func`2 createBrowser) at System.Web.WebPages.DisplayModeProvider.&lt;.ctor&gt;b__2(HttpContextBase context) at System.Web.WebPages.DisplayModeProvider.&lt;GetAvailableDisplayModesForContext&gt;d__4.MoveNext() at System.Web.Mvc.VirtualPathProviderViewEngine.GetPath(ControllerContext controllerContext, String[] locations, String[] areaLocations, String locationsPropertyName, String name, String controllerName, String cacheKeyPrefix, Boolean useCache, String[]&amp; searchedLocations) at System.Web.Mvc.VirtualPathProviderViewEngine.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache) at System.Web.Mvc.ViewEngineCollection.&lt;&gt;c__DisplayClass6.&lt;FindView&gt;b__4(IViewEngine e) at System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup, Boolean trackSearchedPaths) at System.Web.Mvc.ViewEngineCollection.FindView(ControllerContext controllerContext, String viewName, String masterName) at Postal.EmailViewRenderer.CreateView(String viewName, ControllerContext controllerContext) at Postal.EmailViewRenderer.Render(Email email, String viewName) at Postal.EmailService.Send(Email email) at XYZ.Utilities.TaskScheduler.Execute(IJobExecutionContext context) in D:\Applications\XYZ\Utilities\TaskScheduler.cs:line 33 </code></pre>
<p>According to this issue: <a href="https://github.com/andrewdavey/postal/issues/65" rel="nofollow">Postal Issue #65</a>, it seems that you have <code>HttpContext.Current</code> contains null value when trying to get relative path of your project root directory in IIS deployment server. Here was the checklist to do:</p> <ol> <li><p>Try moving <code>JobScheduler.Start()</code> method from <code>Application_Start</code> to <code>Application_AuthenticateRequest</code> method call during application startup. AFAIK, the <code>Application_Start</code> method doesn't contain <code>HttpContext.Current</code> instance as <code>Application_AuthenticateRequest</code> has.</p> <pre><code>protected void Application_AuthenticateRequest() { JobScheduler.Start(); } </code></pre></li> <li><p>Check if your IIS deployment server setting set to integrated mode. In this mode Application_Start doesn't contain <code>HttpContext.Current</code> due to design changes on integrated pipeline. As Mike Volodarsky said:</p></li> </ol> <blockquote> <p>Basically, if you happen to be accessing the request context in <code>Application_Start</code>, you have two choices:</p> <ol> <li>Change your application code to not use the request context (recommended).</li> <li>Move the application to Classic mode (NOT recommended).</li> </ol> </blockquote> <p>The first choice means it was some alternatives beside <code>Application_AuthenticateRequest</code>, which uses <code>Application_BeginRequest</code> or any other event methods that includes <code>HttpContext.Current</code> instance.</p> <ol start="3"> <li><p>If absolute path was used, check if it is exist on deployment server. The relative path is more preferred in web.config file, thus you may change paths like this:</p> <pre><code>&lt;add key="DocumentsPath" value="~/Documents/Documents/" /&gt; </code></pre></li> </ol> <p>Afterwards, ensure <code>Application_Start</code> method doesn't contain any other method that contains <code>HttpContext.Current</code> instance, including database context if any.</p> <p>References:</p> <p><a href="http://stackoverflow.com/questions/19509672/why-is-httpcontext-current-null">Why is HttpContext.Current null?</a></p> <p><a href="http://mvolo.com/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-applicationstart/" rel="nofollow">IIS7 Integrated mode: Request is not available in this context exception in Application_Start</a></p> <p>Related problem:</p> <p><a href="http://stackoverflow.com/questions/2518057/request-is-not-available-in-this-context">Request is not available in this context</a></p>
node imap attempting to update flags: Error: Command received in Invalid state. <p>Submitting this question and its answer because SA (and for that matter Google) was VERY unhelpful about this.</p> <p>I need to delete all messages in my INBOX. Irrelevant lines below cut for clarity:</p> <pre><code>function openInbox(cb){ imap.openBox('INBOX', true, cb); } imap.once('ready', function() { openInbox(function(err,box){ if (err) throw err; var f = imap.seq.fetch('1:*', { bodies: 'HEADER.FIELDS (FROM)', struct: true }); f.on('message', function(msg, seqno){ console.log('Message #%d', seqno); imap.seq.addFlags(seqno, 'Deleted', function(err){ console.log(err); }); }); f.once('end', function(){ imap.end(); }); }); }); imap.connect(); </code></pre> <p>It all looks good, when I pepper it with console.log, I see that it's reading emails just fine. Everything looks like it ought to be good, but I get:</p> <pre><code>{ [Error: Command received in Invalid state.] textCode: undefined, source: 'protocol' } </code></pre>
<p>The problem is you've opened the INBOX in read-only mode. That's the 'true' in the second argument right here:</p> <pre><code>function openInbox(cb){ imap.openBox('INBOX', true, cb); } </code></pre> <p>Change that to</p> <pre><code>function openInbox(cb){ imap.openBox('INBOX', false, cb); } </code></pre> <p>And suddenly it'll all work.</p>
How to use find_in_set with join in codeigniter <p>I have 4 tables, and I want to fetch data from all the tables, I can do this by fetching data one by one from each table but I want to do it by using JOIN.</p> <p><a href="https://i.stack.imgur.com/oJon0.png" rel="nofollow">Main Table (which contains ids of other table data)</a></p> <p><a href="https://i.stack.imgur.com/FSrAz.png" rel="nofollow">2, 3, 4 tables</a></p> <p>now I want to fetch these fields.</p> <p>from Table 1 (Main Table) - franchise_name, franchise_phone</p> <p>from Table 2 (State Table) - state_name</p> <p>from Table 3 (City Table) - city_name</p> <p>from Table 4 (Area Table) - area_name</p> <p>the first table contains ids of everything which I need to fetch from other tables. but area_id in the main table is inserted as a string in the same row separated by (,) in field franchise_area.</p> <p>I tried using FIND_IN_SET but did not work.</p>
<p>Read all 1-1 referred data using Join, cycle through data exploding area_id column</p> <pre><code>area_id -------&gt; ($value = explode($row-&gt;area_id, ',') </code></pre> <p>then read data from database and insert into response array (or object). Of course all of this operation must be done into the model...</p>
Angular2 component reloads twice for no reason <p>Im working on an angular2 RC4 app and I started to notice something weird. I have a bunch components I can route to:</p> <pre><code>Parent(A) - ManyChildren(B,C,D,E) </code></pre> <p>My component A gets the ID, talks to a service to get an item and updates the state. Other components listen to state "selectedItem" with BehaviorSubjects. </p> <pre><code> path: ':id/steps', </code></pre> <p>Everything works, except for some unpredictable behavior when I try to navigate by URL as a completely new reload(new window).</p> <p>When I try to reload my page completely (assuming the user wants to bookmark a page), I get routed to the correct page and all the values are set properly. HOWEVER, as I try to navigate into the same tree, component A reloads AGAIN.</p> <p>I would go to </p> <pre><code>localhost/items/1/steps/step1 </code></pre> <p>Parent A constructor runs. As I go to </p> <pre><code>localhost/items/1/steps/step2 </code></pre> <p>Parent A constructor runs again. This is really unacceptable to me as I expect my component to be loaded once and exactly once.Am I missing something?(RC4)</p>
<p>I don't know the reason of this behaviour. It's strange. But as the documentation says in <a href="https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html" rel="nofollow">https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html</a> you should keep your service logic into ngOnInit() instead of constructor:</p> <blockquote> <p>Don't fetch data in a component constructor. You shouldn't worry that a new component will try to contact a remote server when created under test or before you decide to display it. Constructors should do no more than set the initial local variables to simple values.</p> </blockquote> <p>I don't know if it'll fix your problem. Try it and let us know.</p>
Upload file to MS SharePoint using Python OneDrive SDK <p>Is it possible to upload a file to the <strong>Shared Documents</strong> library of a <strong>Microsoft SharePoint</strong> site with the <strong><a href="https://github.com/OneDrive/onedrive-sdk-python" rel="nofollow">Python OneDrive SDK</a></strong>? </p> <p><strong><a href="https://dev.onedrive.com/readme.htm" rel="nofollow">This documentation</a></strong> says it should be (in the first sentence), but I can't make it work.</p> <p>I'm able to authenticate (with Azure AD) and upload to a <strong>OneDrive</strong> folder, but when trying to upload to a <strong>SharePoint</strong> folder, I keep getting this error:</p> <blockquote> <p>"Exception of type 'Microsoft.IdentityModel.Tokens.<strong>AudienceUriValidationFailedException</strong>' was thrown."</p> </blockquote> <p>The code I'm using that returns an object with the error:</p> <pre><code>(...authentication...) client = onedrivesdk.OneDriveClient('https://{tenant}.sharepoint.com/{site}/_api/v2.0/', auth, http) client.item(path='/drive/special/documents').children['test.xlsx'].upload('test.xlsx') </code></pre> <p><a href="http://i.stack.imgur.com/ZQEj4.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZQEj4.png" alt="where I&#39;d like to upload on the web"></a></p> <p>I can successfully upload to <code>https://{tenant}-my.sharepoint.com/_api/v2.0/</code> (notice the "<strong>-my</strong>" after the <code>{tenant}</code>) with the following code:</p> <pre><code>client = onedrivesdk.OneDriveClient('https://{tenant}-my.sharepoint.com/_api/v2.0/', auth, http) returned_item = client.item(drive='me', id='root').children['test.xlsx'].upload('test.xlsx') </code></pre> <p>How could I upload the same file to a <strong>SharePoint</strong> site?</p> <p><em>(Answers to similar questions (<a href="http://stackoverflow.com/questions/37451835/onedrive-api-refer-to-sharepoint-file-to-upload-or-download-invalid-audience">1</a>,<a href="http://stackoverflow.com/questions/37233669/onedrive-api-python-sdk-points-to-login-live-com-not-mydomain-sharepoint-com">2</a>,<a href="http://stackoverflow.com/questions/29635758/onedrive-sharepoint-oauth-invalid-audience-error">3</a>,<a href="http://stackoverflow.com/questions/39822092/which-sdk-or-api-should-i-use-to-list-and-upload-files-into-office-365-sharepoin">4</a>) on Stack Overflow are either too vague or suggest using a different API. My question is if it's possible using the OneDrive Python SDK, and if so, how to do it.)</em></p> <hr> <p><strong>Update</strong>: Here is my full code and output. (<em>Sensitive original data replaced with similarly formatted gibberish.</em>)</p> <pre><code>import re import onedrivesdk from onedrivesdk.helpers.resource_discovery import ResourceDiscoveryRequest # our domain (not the original) redirect_uri = 'https://example.ourdomain.net/' # our client id (not the original) client_id = "a1234567-1ab2-1234-a123-ab1234abc123" # our client secret (not the original) client_secret = 'ABCaDEFGbHcd0e1I2fghJijkL3mn4M5NO67P8Qopq+r=' resource = 'https://api.office.com/discovery/' auth_server_url = 'https://login.microsoftonline.com/common/oauth2/authorize' auth_token_url = 'https://login.microsoftonline.com/common/oauth2/token' http = onedrivesdk.HttpProvider() auth = onedrivesdk.AuthProvider(http_provider=http, client_id=client_id, auth_server_url=auth_server_url, auth_token_url=auth_token_url) should_authenticate_via_browser = False try: # Look for a saved session. If not found, we'll have to # authenticate by opening the browser. auth.load_session() auth.refresh_token() except FileNotFoundError as e: should_authenticate_via_browser = True pass if should_authenticate_via_browser: auth_url = auth.get_auth_url(redirect_uri) code = '' while not re.match(r'[a-zA-Z0-9_-]+', code): # Ask for the code print('Paste this URL into your browser, approve the app\'s access.') print('Copy the resulting URL and paste it below.') print(auth_url) code = input('Paste code here: ') # Parse code from URL if necessary if re.match(r'.*?code=([a-zA-Z0-9_-]+).*', code): code = re.sub(r'.*?code=([a-zA-Z0-9_-]*).*', r'\1', code) auth.authenticate(code, redirect_uri, client_secret, resource=resource) # If you have access to more than one service, you'll need to decide # which ServiceInfo to use instead of just using the first one, as below. service_info = ResourceDiscoveryRequest().get_service_info(auth.access_token)[0] auth.redeem_refresh_token(service_info.service_resource_id) auth.save_session() # Save session into a local file. # Doesn't work client = onedrivesdk.OneDriveClient( 'https://{tenant}.sharepoint.com/sites/{site}/_api/v2.0/', auth, http) returned_item = client.item(path='/drive/special/documents') .children['test.xlsx'] .upload('test.xlsx') print(returned_item._prop_dict['error_description']) # Works, uploads to OneDrive instead of SharePoint site client2 = onedrivesdk.OneDriveClient( 'https://{tenant}-my.sharepoint.com/_api/v2.0/', auth, http) returned_item2 = client2.item(drive='me', id='root') .children['test.xlsx'] .upload('test.xlsx') print(returned_item2.web_url) </code></pre> <p>Output:</p> <pre><code>Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown. https://{tenant}-my.sharepoint.com/personal/user_domain_net/_layouts/15/WopiFrame.aspx?sourcedoc=%1ABCDE2345-67F8-9012-3G45-6H78IJKL9M01%2N&amp;file=test.xlsx&amp;action=default </code></pre>
<p>I finally found a solution, with the help of (<em>SO user</em>) sytech.</p> <p>The answer to my original question is that using the original <strong><a href="https://github.com/OneDrive/onedrive-sdk-python" rel="nofollow">Python OneDrive SDK</a></strong>, it's <strong>not possible</strong> to upload a file to the <code>Shared Documents</code> folder of a <code>SharePoint Online</code> site (at the moment of writing this): when the SDK queries the <a href="https://dev.onedrive.com/auth/aad_oauth.htm#step-3-discover-the-onedrive-for-business-resource-uri" rel="nofollow"><strong>resource discovery service</strong></a>, it drops all services whose <code>service_api_version</code> is not <code>v2.0</code>. However, I get the SharePoint service with <code>v1.0</code>, so it's dropped, although it could be accessed using API v2.0 too.</p> <p><strong>However</strong>, by extending the <code>ResourceDiscoveryRequest</code> class (in the OneDrive SDK), we can create a workaround for this. I managed to <strong>upload a file</strong> this way:</p> <pre><code>import json import re import onedrivesdk import requests from onedrivesdk.helpers.resource_discovery import ResourceDiscoveryRequest, \ ServiceInfo # our domain (not the original) redirect_uri = 'https://example.ourdomain.net/' # our client id (not the original) client_id = "a1234567-1ab2-1234-a123-ab1234abc123" # our client secret (not the original) client_secret = 'ABCaDEFGbHcd0e1I2fghJijkL3mn4M5NO67P8Qopq+r=' resource = 'https://api.office.com/discovery/' auth_server_url = 'https://login.microsoftonline.com/common/oauth2/authorize' auth_token_url = 'https://login.microsoftonline.com/common/oauth2/token' # our sharepoint URL (not the original) sharepoint_base_url = 'https://{tenant}.sharepoint.com/' # our site URL (not the original) sharepoint_site_url = sharepoint_base_url + 'sites/{site}' file_to_upload = 'C:/test.xlsx' target_filename = 'test.xlsx' class AnyVersionResourceDiscoveryRequest(ResourceDiscoveryRequest): def get_all_service_info(self, access_token, sharepoint_base_url): headers = {'Authorization': 'Bearer ' + access_token} response = json.loads(requests.get(self._discovery_service_url, headers=headers).text) service_info_list = [ServiceInfo(x) for x in response['value']] # Get all services, not just the ones with service_api_version 'v2.0' # Filter only on service_resource_id sharepoint_services = \ [si for si in service_info_list if si.service_resource_id == sharepoint_base_url] return sharepoint_services http = onedrivesdk.HttpProvider() auth = onedrivesdk.AuthProvider(http_provider=http, client_id=client_id, auth_server_url=auth_server_url, auth_token_url=auth_token_url) should_authenticate_via_browser = False try: # Look for a saved session. If not found, we'll have to # authenticate by opening the browser. auth.load_session() auth.refresh_token() except FileNotFoundError as e: should_authenticate_via_browser = True pass if should_authenticate_via_browser: auth_url = auth.get_auth_url(redirect_uri) code = '' while not re.match(r'[a-zA-Z0-9_-]+', code): # Ask for the code print('Paste this URL into your browser, approve the app\'s access.') print('Copy the resulting URL and paste it below.') print(auth_url) code = input('Paste code here: ') # Parse code from URL if necessary if re.match(r'.*?code=([a-zA-Z0-9_-]+).*', code): code = re.sub(r'.*?code=([a-zA-Z0-9_-]*).*', r'\1', code) auth.authenticate(code, redirect_uri, client_secret, resource=resource) service_info = AnyVersionResourceDiscoveryRequest().\ get_all_service_info(auth.access_token, sharepoint_base_url)[0] auth.redeem_refresh_token(service_info.service_resource_id) auth.save_session() client = onedrivesdk.OneDriveClient(sharepoint_site_url + '/_api/v2.0/', auth, http) # Get the drive ID of the Documents folder. documents_drive_id = [x['id'] for x in client.drives.get()._prop_list if x['name'] == 'Documents'][0] items = client.item(drive=documents_drive_id, id='root') # Upload file uploaded_file_info = items.children[target_filename].upload(file_to_upload) </code></pre> <p>Authenticating for a different service gives you a different token.</p>
How to check Drop date time of an ORACLE view <p>Where can I see at what time a view was dropped from database.</p> <p>For other object types such as Indexes and tables , I use dba_recyclebin to check the droptime , but for a view I do not think that ORACLE captures details in this table. </p>
<p>Assuming that the drop was recent enough that the data is still present in your <code>UNDO</code> tablespace (likely a few hours but up to a few days depending on your workload and configuration) you should be able to use a flashback query on <code>dba_views</code>. You'd need to have the <code>FLASHBACK ANY TABLE</code> privilege.</p> <pre><code>SELECT text FROM dba_views AS OF TIMESTAMP( systimestamp - interval '1' hour ) WHERE owner = &lt;&lt;owner of view&gt;&gt; AND view_name = &lt;&lt;name of view&gt;&gt; </code></pre> <p>Beyond that, you could look at your archived logs using <code>dbms_logmnr</code> to look for <code>drop view</code> statements over a longer time fram. That is likely to be more effort, however.</p>
How to resolve Angular 2 - Base64 404 Resource not found Error? <p>After doing a fresh <code>npm install</code>, the system is broken. I'm getting an error saying "404 Resourse not found." </p> <p>I have tried the following, which didn't help...</p> <ul> <li>Deleted node_modules and typings folders followed by 'npm install'.</li> <li>Updated dependencies and devDependencies to the latest version and<br> removed '^' prefix from the version numbers, followed by 'npm install'.</li> <li>Tried adding base64 reference in index.html and/or systemjs.config.js</li> </ul> <blockquote> <p><a href="http://localhost:3000/js-base64" rel="nofollow">http://localhost:3000/js-base64</a></p> </blockquote> <p>My package.json file looks like the following,</p> <pre><code>"dependencies": { "@angular/common": "2.0.2", "@angular/compiler": "2.0.2", "@angular/core": "2.0.2", "@angular/forms": "2.0.2", "@angular/http": "2.0.2", "@angular/platform-browser": "2.0.2", "@angular/platform-browser-dynamic": "2.0.2", "@angular/router": "3.0.2", "@angular/upgrade": "2.0.2", "angular2-jwt": "^0.1.24", "auth0-lock": "^10.4.0", "bootstrap": "^3.3.7", "core-js": "^2.4.1", "metismenu": "^2.5.2", "moment": "^2.15.1", "ng2-fontawesome": "0.0.6", "ng2-toasty": "2.1.0", "reflect-metadata": "0.1.8", "rxjs": "5.0.0-rc.1", "systemjs": "0.19.39", "typings": "1.4.0", "zone.js": "0.6.25"}, "devDependencies": { "gulp": "3.9.1", "gulp-clean": "0.3.2", "gulp-concat": "2.6.0", "gulp-less": "3.1.0", "gulp-sourcemaps": "2.0.0", "gulp-typescript": "3.0.2", "gulp-uglify": "2.0.0", "concurrently": "3.1.0", "lite-server": "2.2.2", "tslint": "3.15.1", "typescript": "2.0.3"} </code></pre> <p>My tsconfig.js looks like the following,</p> <pre><code>{ "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": true, "suppressImplicitAnyIndexErrors": true }, "exclude": [ "node_modules", "wwwroot" ] } </code></pre> <p>My system.config.js looks like the following,</p> <pre><code> // map tells the System loader where to look for things var map = { 'app': 'app', '@angular': 'node_modules/@angular', 'angular2-jwt': 'node_modules/angular2-jwt/angular2-jwt.js', 'ng2-toasty': 'node_modules/ng2-toasty', 'rxjs': 'node_modules/rxjs' }; // packages tells the System loader how to load when no filename and/or no extension var packages = { 'app': { main: 'main.js', defaultExtension: 'js' }, 'angular2-jwt': { defaultExtension: 'js' }, 'ng2-toasty': { main: 'index.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' } }; </code></pre> <p>My index.html file looks like the following,</p> <pre><code>&lt;!-- Polyfill(s) for older browsers --&gt; &lt;script src="node_modules/core-js/client/shim.min.js"&gt;&lt;/script&gt; &lt;script src="node_modules/zone.js/dist/zone.js"&gt;&lt;/script&gt; &lt;script src="node_modules/reflect-metadata/Reflect.js"&gt;&lt;/script&gt; &lt;script src="node_modules/systemjs/dist/system.src.js"&gt;&lt;/script&gt; &lt;!-- Auth0 Lock script --&gt; &lt;script src="http://cdn.auth0.com/js/lock/10.0.0/lock.min.js"&gt;&lt;/script&gt; &lt;!-- Configure SystemJS --&gt; &lt;script src="systemjs.config.js"&gt;&lt;/script&gt; &lt;script&gt; System.import('app').catch(function(err){ console.error(err); }); &lt;/script&gt; </code></pre> <p><a href="https://i.stack.imgur.com/6U4zT.png" rel="nofollow">Error while loading Angular 2 SPA</a></p>
<p>I have a similiar issue and in my case it seems to be angular2-jwt loading js-base64. I can't seem to figure out how to correct the issue. However, I also came across this that may be relevant. <a href="https://auth0.com/forum/t/angular2-jwt-unexpected-token-syntax-error-from-system-config/1807" rel="nofollow">https://auth0.com/forum/t/angular2-jwt-unexpected-token-syntax-error-from-system-config/1807</a></p>
Grouping while maintaining next record <p>I have a table (NerdsTable) with some of this data:</p> <pre><code>-------------+-----------+---------------- id name school -------------+-----------+---------------- 1 Joe ODU 2 Mike VCU 3 Ane ODU 4 Trevor VT 5 Cools VCU </code></pre> <p>When I run the following query</p> <pre><code>SELECT id, name, LEAD(id) OVER (ORDER BY id) as next_id FROM dbo.NerdsTable where school = 'ODU'; </code></pre> <p>I get these results:</p> <pre><code>[id=1,name=Joe,nextid=3] [id=3,name=Ane,nextid=NULL] </code></pre> <p>I want to write a query that does not need the static check for </p> <pre><code>where school = 'odu' </code></pre> <p>but gives back the same results as above. In another words, I want to select all results in the database, and have them grouped correctly as if i went through individually and ran queries for:</p> <pre><code>SELECT id, name, LEAD(id) OVER (ORDER BY id) as next_id FROM dbo.NerdsTable where school = 'ODU'; SELECT id, name, LEAD(id) OVER (ORDER BY id) as next_id FROM dbo.NerdsTable where school = 'VCU'; SELECT id, name, LEAD(id) OVER (ORDER BY id) as next_id FROM dbo.NerdsTable where school = 'VT'; </code></pre> <p>Here is the output I am hoping to see:</p> <pre><code>[id=1,name=Joe,nextid=3] [id=3,name=Ane,nextid=NULL] [id=2,name=Mike,nextid=5] [id=5,name=Cools,nextid=NULL] [id=4,name=Trevor,nextid=NULL] </code></pre> <p>Here is what I have tried, but am failing miserably:</p> <pre><code>SELECT id, name, LEAD(id) OVER (ORDER BY id) as next_id FROM dbo.NerdsTable ORDER BY school; -- Problem, as this does not sort by the id. I need the lowest id first for the group SELECT id, name, LEAD(id) OVER (ORDER BY id) as next_id FROM dbo.NerdsTable ORDER BY id, school; -- Sorts by id, but the grouping is not correct, thus next_id is wrong </code></pre> <p>I then looked on the <a href="https://msdn.microsoft.com/en-us/library/ms173454.aspx" rel="nofollow">Microsoft doc site</a> for aggregate functions, but do not see how i can use any to group my results correctly. I tried to use GROUPING_ID, as follows:</p> <pre><code>SELECT id, GROUPING_ID(name), LEAD(id) OVER (ORDER BY id) as next_id FROM dbo.NerdsTable group by school; </code></pre> <p>But I get an error: </p> <pre><code>is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause </code></pre> <p>Any idea as to what I am missing here?</p>
<p>From your desired output it looks like you are just trying to order the records by school. You can do that like this:</p> <pre><code>SELECT id, name FROM dbo.NerdsTable ORDER BY school ASC, id ASC </code></pre> <p>I don't know what next ID is supposed to mean.</p>
Acquire x-axis values in Python matplotlib <p>Before I ask this question, I have already searched the internet for a while without success. To many experts this surely appears to be fairly simple. Please bear with me. </p> <p>I am having a plot made by matplotlib and it is returned as a plf.Figure. See the following: </p> <pre><code>def myplotcode(): x = np.linspace(0, 2*np.pi) y = np.sin(x) print("x in external function", x) y2 = np.cos(x) fig = plf.Figure() ax = fig.add_subplot(111) ax.plot(x, y, 'bo', x, y2,'gs') ax.set_ylabel("Some function") return fig, ax </code></pre> <p>What I want to do in the function that call this one is to be able to get all these x values from the returned ax or fig. Well, I understand one simple solution is just to return x array too. However, I am trying to keep the number of returns as small as possible.</p> <p>So, my question is: Can I acquire this x-axis array from fig or ax?</p> <p>Thank you so much in advance. </p>
<p>You can do:</p> <pre><code>l = ax.axes.lines[0] # If you have more curves, just change the index x, y = l.get_data() </code></pre> <p>That will give you two arrays, with the <code>x</code> and <code>y</code> data</p>
"Extra data" error trying to load a JSON file with Python <p>I'm trying to load the following JSON file, named <code>archived_sensor_data.json</code>, into Python:</p> <pre><code>[{"timestamp": {"timezone": "+00:00", "$reql_type$": "TIME", "epoch_time": 1475899932.677}, "id": "40898785-6e82-40a2-a36a-70bd0c772056", "name": "Elizabeth Woods"}][{"timestamp": {"timezone": "+00:00", "$reql_type$": "TIME", "epoch_time": 1475899932.677}, "id": "40898785-6e82-40a2-a36a-70bd0c772056", "name": "Elizabeth Woods"}, {"timestamp": {"timezone": "+00:00", "$reql_type$": "TIME", "epoch_time": 1475816130.812}, "id": "2f896308-884d-4a5f-a8d2-ee68fc4c625a", "name": "Susan Wagner"}] </code></pre> <p>The script I'm trying to run (from the same directory) is as follows:</p> <pre><code>import json reconstructed_data = json.load(open("archived_sensor_data.json")) </code></pre> <p>However, I get the following error:</p> <pre><code>ValueError: Extra data: line 1 column 164 - line 1 column 324 (char 163 - 323) </code></pre> <p>I'm not sure where this is going wrong, because from <a href="http://www.json.org/" rel="nofollow">www.json.org</a> it seems like valid JSON syntax for an array of dictionaries. Any ideas what is causing the error?</p>
<p>It is not a valid json; There are two list in here; one is</p> <pre><code>[{"timestamp": {"timezone": "+00:00", "$reql_type$": "TIME", "epoch_time": 1475899932.677}, "id": "40898785-6e82-40a2-a36a-70bd0c772056", "name": "Elizabeth Woods"}] </code></pre> <p>and the other one</p> <pre><code>[{"timestamp": {"timezone": "+00:00", "$reql_type$": "TIME", "epoch_time": 1475899932.677}, "id": "40898785-6e82-40a2-a36a-70bd0c772056", "name": "Elizabeth Woods"}, {"timestamp": {"timezone": "+00:00", "$reql_type$": "TIME", "epoch_time": 1475816130.812}, "id": "2f896308-884d-4a5f-a8d2-ee68fc4c625a", "name": "Susan Wagner"}] </code></pre> <p>You can see the validation error in here; <a href="http://www.jsoneditoronline.org/?id=569644c48d5753ceb21daf66483d80cd" rel="nofollow">http://www.jsoneditoronline.org/?id=569644c48d5753ceb21daf66483d80cd</a></p>
Shell script: top command and date command at once <p>I would like to print in a file the % of cpu usage of a process (top command) + the date when this top command gets the information, for each 0.5 seconds (each line with the date + this cpu information) If I write in a shell script, I would do something like</p> <pre><code>while [ ! -f $STOP_FILE ] do echo "$(date +%s.%N)" &gt;&gt; $REPORT_FILE top -b -n 1 -p myProcessPID | grep myProcessName | awk -F " " '{print $12 "\t" $9}' &gt;&gt; result.txt sleep 0.5 done </code></pre> <p>But I can not use the -n 1 option in top to get the cpu information because the first iteration is <a href="http://stackoverflow.com/questions/4940250/top-command-first-iteration-always-returns-the-same-result">"from system boot until now"</a> so I need the other iterations.</p> <p>Therefore, I am looking for some combination of commands to get the process information with top command + a date with nanoseconds (date +%s.%N) (The top command also results a time in the first line in the header, but I want the milliseconds)</p> <p>I am trying something like,</p> <pre><code>echo $(date +%s.%N) $(top -d 0.5 -n 100 -p myProcessPID | grep myProcessName) &gt;&gt; results.txt </code></pre> <p>But the date is only printed the first iteration.</p> <p>Any ideas?</p> <p>Sorry if I am not very accurate with the question, I am new with this scripts and writing here..</p>
<p>You can achieve this by piping the output of <code>top</code> through <code>awk</code>, and having <code>awk</code> run <code>date</code>. For example:</p> <pre><code>top -d 0.5 -n 100 -p myProcessPID \ | awk '/myProcessName/ { system("date +%s"); print $0 }' </code></pre> <p>You can exert arbitrary control over the format of the output by adjusting the <code>awk</code> program. Note also that you do not need a separate <code>grep</code>, since <code>awk</code>'s internal pattern matching serves perfectly well.</p>
How to access to each attribute of an object array using a loop? <p>I have a <code>Person</code> object:</p> <pre><code>class Person{ var name: String var city: String var country: String init(name: String, city: String, country: String){ self.name = name self.city = city self.country = country } } </code></pre> <p>and two arrays. One array of <code>Person</code> objects and one with the names of each of the attributes of the array.</p> <pre><code>var values = [Person]() var attributes = ["name","city","country"] </code></pre> <p>and for example if I add two new <code>Person</code> objects to the array:</p> <pre><code>values.append(Person(name: "Peter" as! String, city: "Paris" as! String, country: "France" as! String)) values.append(Person(name: "Andrew" as! String, city: "Madrid" as! String, country: "Spain" as! String)) </code></pre> <p>I would like to retrieve each of the attributes of each object of the array.</p> <p>If I want to retrieve all the attributes of the first element I can do:</p> <pre><code>values[0].name values[0].city values[0].country </code></pre> <p>but I would like to do it in the way:</p> <pre><code>let totalAttributes = attributes.count - 1 for i in 0...totalAttributes{ var attribute = attributes[i] values[0].attribute } </code></pre> <p>but this, as I supposed, did not work.</p> <p>In this case I can do it manually because there are only three attributes but I will not like to do the same when I will have more than 20 attributes inside the object.</p> <p>Is there a way to do it within a loop?</p> <p>Thanks in advance!</p>
<p>You can make use of reflection and MirrorType</p> <pre><code>let firstObj = values[0] let personMirror = Mirror(reflecting: firstObj) for child in personMirror.children { let (propertyName, propertyValue) = child print(propertyName) print(propertyValue) } </code></pre> <p>You can access a specific property by the property name. </p> <p>Example: Get the value of property named <code>name</code></p> <pre><code>personMirror.descendant("name") </code></pre>
Adjusting width of TextAreaFor <p>I have a form that has a few <code>TextBoxFor</code> and 1 <code>TextAreaFor</code></p> <p>Here it is:</p> <pre><code>&lt;div class="form-horizontal"&gt; &lt;div class="form-group"&gt; @Html.LabelFor(m =&gt; m.FromName, new { @class = "col-md-2 control-label" }) &lt;div class="col-md-10"&gt; @Html.TextBoxFor(m =&gt; m.FromName, new { @class = "form-control" }) @Html.ValidationMessageFor(m =&gt; m.FromName) &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; @Html.LabelFor(m =&gt; m.FromEmail, new { @class = "col-md-2 control-label" }) &lt;div class="col-md-10"&gt; @Html.TextBoxFor(m =&gt; m.FromEmail, new { @class = "form-control" }) @Html.ValidationMessageFor(m =&gt; m.FromEmail) &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; @Html.LabelFor(m =&gt; m.ToEmail, new { @class = "col-md-2 control-label" }) &lt;div class="col-md-10"&gt; @Html.TextBoxFor(m =&gt; m.ToEmail, new { @class = "form-control" }) @Html.ValidationMessageFor(m =&gt; m.ToEmail) &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; @Html.LabelFor(m =&gt; m.Message, new { @class = "col-md-2 control-label" }) &lt;div class="col-md-10"&gt; @Html.TextAreaFor(m =&gt; m.Message,60, 150, new { @class = "form-control" }) @Html.ValidationMessageFor(m =&gt; m.Message) &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;div class="col-md-offset-2 col-md-10"&gt; &lt;input type="submit" class="btn btn-primary" value="Send" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>A picture of what it looks like:</p> <p><a href="https://i.stack.imgur.com/0VQeX.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/0VQeX.jpg" alt="enter image description here"></a></p> <p>The problem is that I am unable to adjust the width of the <code>TextAreaFor</code>.</p> <p>I know that Bootstrap grid system is restricting this, but I don't think this should be impossible to simply keep the label where it is, but make the textareafor wider instead of taller.</p> <p>What I am looking for, is my <code>TextAreaFor</code> to be wider than the regular <code>TextBoxFor</code>. I have tried inserting outrageous numbers into the <code>int rows</code> &amp;&amp; <code>int columns</code> parameters of <code>TextAreaFor</code> but the only one that seems to work is <code>int rows</code>.</p> <p>Any idea on how I can get my <code>TextAreaFor</code> to expand across the page?</p> <p>Any help is appreciated.</p> <p><strong>UPDATE</strong>:</p> <p>I have created this <a href="http://www.bootply.com/4d8iRRAOMz" rel="nofollow">Bootply</a> for all of you.</p>
<p>I have figured this out. After Inspecting the Elements, I saw that all of the <code>input</code>, <code>textarea</code>, and <code>select</code> had a <code>max-width</code> of <code>280px</code>.</p> <p>So all I had to do was give the <code>textarea</code> a class and set its <code>max-width</code> to something that I prefer.</p>
Convert an Int to a date field <p>I'm trying to convert an integer field to an actual date field. Someone created a "date" field that just sticks in a "date" that is actually an integer. I'm trying to convert it to an actual date. </p> <p>I have tried the following to no avail:</p> <pre><code>CAST(CAST(last_purch_date AS CHAR) AS DATE) as Create, CAST( last_purch_date as datetime) as Created, convert(datetime,last_purch_date) as Created1, ISDATE(CONVERT(CHAR(8),last_purch_date)) as PleaseDearGodWORK </code></pre>
<p>Simple cast as date could work</p> <pre><code>Select cast(cast(20161011 as varchar(8)) as date) </code></pre> <p>Returns</p> <pre><code>2016-10-11 </code></pre> <p>If your data is suspect, you could also use Try_Convert()</p> <pre><code>Select Try_Convert(date,cast(2610 as varchar(8))) </code></pre> <p>Returns </p> <pre><code>NULL </code></pre>
Difference between page and image request <p>My basic question is do browsers handle these two requests differently?</p> <p><code>&lt;a href='imageGenerator.php?id=1'&gt;Browser Request&lt;/a&gt;</code></p> <p>vs</p> <p><code>&lt;img src='imageGenerator.php?id=1' /&gt;</code></p> <p>Both generate an image stream on-the-fly (unless the file already exists). However, the image request will timeout rapidly before completing the image generation sporadically via <code>&lt;img&gt;</code> tag, while the other request will not. See code below:</p> <pre><code>public function generateThumbnail($url) { ignore_user_abort(true); set_time_limit(0); // [...] $pub_path = public_path() . "/{$pathToFile}"; if (!\File::exists($pub_path)) { // PhantomJS to screen cap $screenCapture = new Capture($url); $screenCapture-&gt;save($pub_path); } return response()-&gt;file($pub_path); } </code></pre> <p>Code has been shortened for brevity, but the question remains, shouldn't both requests be treated relatively the same?</p>
<p>I found out that it had to do with Laravel throwing an error when it couldn't read the env file on occasion.</p>
Limit Kafka batches size when using Spark Streaming <p>Is it possible to limit the size of the batches returned by the Kafka consumer for Spark Streaming?</p> <p>I am asking because the first batch I get has hundred of millions of records and it takes ages to process and checkpoint them.</p>
<p>I think your problem can be solved by <strong>Spark Streaming Backpressure</strong>.</p> <p>Check <code>spark.streaming.backpressure.enabled</code> and <code>spark.streaming.backpressure.initialRate</code>.</p> <p>By default <code>spark.streaming.backpressure.initialRate</code> is <strong>not set</strong> and <code>spark.streaming.backpressure.enabled</code> is <strong>disabled</strong> by default so I suppose spark will take as much as he can.</p> <p>From <a href="http://spark.apache.org/docs/latest/configuration.html" rel="nofollow">Apache Spark Kafka configuration</a> </p> <p><strong><code>spark.streaming.backpressure.enabled</code>:</strong></p> <blockquote> <p>This enables the Spark Streaming to control the receiving rate based on the current batch scheduling delays and processing times so that the system receives only as fast as the system can process. Internally, this dynamically sets the maximum receiving rate of receivers. This rate is upper bounded by the values <code>spark.streaming.receiver.maxRate</code> and <code>spark.streaming.kafka.maxRatePerPartition</code> if they are set (see below).</p> </blockquote> <p>And since you want to control first batch, or to be more specific - number of messages in first batch, I think you need <code>spark.streaming.backpressure.initialRate</code></p> <p><strong><code>spark.streaming.backpressure.initialRate</code>:</strong></p> <blockquote> <p>This is the initial maximum receiving rate at which each receiver will receive data for the first batch when the backpressure mechanism is enabled.</p> </blockquote> <p>This one is good when your Spark job (respectively Spark workers at all) is able to process let say 10000 messages from kafka, but kafka brokers give to your job 100000 messages. </p> <p>Maybe you will be also interested to check <code>spark.streaming.kafka.maxRatePerPartition</code> and also some research and suggestions for these properties on real example by <a href="https://vanwilgenburg.wordpress.com/2015/10/06/spark-streaming-backpressure/" rel="nofollow">Jeroen van Wilgenburg on his blog</a>.</p>
Converting a nested array into a pandas dataframe in python <p>I'm attempting to convert several dictionaries contained in an array to a pandas dataframe. The dicts are saved as such: </p> <pre><code>[[{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.309886', u'longitude': u'0.496902'},u'month': u'2015-01'},{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.306209', u'longitude': u'0.490475'},u'month': u'2015-02'}]] </code></pre> <p>I'm trying to format my data to the format below:</p> <pre><code> Category Latitude Longitude 0 anti-social 524498.597 175181.644 1 anti-social 524498.597 175181.644 2 anti-social 524498.597 175181.644 . ... ... . ... ... . ... ... </code></pre> <p>I've tried to force the data into a dataframe with the below code but it doesn't produce the intended output.</p> <pre><code>for i in crimes: for x in i: print pd.DataFrame([x['category'], x['location']['latitude'], x['location']['longitude']]) </code></pre> <p>I'm very new to Python so any links/tips to help me build this dataframe would be highly appreciated!</p>
<p>You are on the right track, but you are creating a new dataframe for each row and not giving the proper <code>columns</code>. The following snippet should work:</p> <pre><code>import pandas as pd import numpy as np crimes = [[{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.309886', u'longitude': u'0.496902'},u'month': u'2015-01'},{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.306209', u'longitude': u'0.490475'},u'month': u'2015-02'}]] # format into a flat list formatted_crimes = [[x['category'], x['location']['latitude'], x['location']['longitude']] for i in crimes for x in i] # now pass the formatted list to DataFrame and label the columns df = pd.DataFrame(formatted_crimes, columns=['Category', 'Latitude', 'Longitude']) </code></pre> <p>The result is:</p> <pre><code> Category Latitude Longitude 0 anti-social-behaviour 52.309886 0.496902 1 anti-social-behaviour 52.306209 0.490475 </code></pre>
Button positioning in Highcharts and name of chart type <p><a href="https://i.stack.imgur.com/YyF51.png" rel="nofollow"><img src="https://i.stack.imgur.com/YyF51.png" alt="enter image description here"></a></p> <p>I need to create a chart using Highcharts like on the picture above.</p> <p>So, I need to know:</p> <ol> <li>How can range selector buttons be positioned like in the picture? or is it possible?</li> </ol> <p>1.1 If range buttons are impossible to position like that, can I use simple html buttons? and in that case how can I interact with Highcharts data.</p> <ol start="2"> <li>What is the name of the chart with a bar within a black circle and red to green gradient (gauge?).</li> </ol>
<p>Taken from <a href="http://stackoverflow.com/questions/15935837/how-to-display-a-range-input-slider-vertically">this question</a>:</p> <blockquote> <p>setting height greater than width is needed to get the layout right between browsers. Applying left and right padding will also help with layout and positioning.</p> <p>For Chrome, use -webkit-appearance: slider-vertical.</p> <p>For IE, use writing-mode: bt-lr.</p> <p>For Firefox, add an orient="vertical" attribute to the html. Pity that they did it this way. Visual styles should be controlled via CSS, not HTML.</p> </blockquote> <p>You're welcome to view the code at the original question.</p> <p>About the gradient thing, it can be easily accomplished by setting the background with css to a linear gradient. The full code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>input[type=range][orient=vertical] { writing-mode: bt-lr; /* IE */ -webkit-appearance: slider-vertical; /* WebKit */ width: 20px; height: 175px; padding: 0 5px; } .gradientbg{ background: -webkit-linear-gradient(green, white, red); background: -o-linear-gradient(green, white, red); background: -moz-linear-gradient(green, white, red); background: linear-gradient(green, white, red); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input class="gradientbg" type="range" orient="vertical"&gt;</code></pre> </div> </div> </p>
d3.js format axis uniformly in millions <p>I found <a href="http://stackoverflow.com/questions/19907206/format-y-axis-values-original-figures-in-millions-only-want-to-show-first-thre/39981718#39981718">this thread</a> and it got me halfway to where I need to be and I'm wondering if anyone knows how I can adjust the solution to fit my needs.</p> <p>So if I have some values in the thousands, and some values in the millions, does anyone know how I can set all of the ticks to be formatted in the millions? For instance, if I have a value for 800k it would show up as 0.8million instead. </p> <p>This is what I get when using the above solution without adjusting it. <a href="https://i.stack.imgur.com/UauLJ.png" rel="nofollow"><img src="https://i.stack.imgur.com/UauLJ.png" alt="enter image description here"></a></p>
<p>You don't need to use a SI prefix in this case. Given this domain:</p> <pre><code>var scale = d3.scaleLinear().domain([200000,1800000]) </code></pre> <p>Going from 200 thousand to 1.8 million, you can simply divide the tick value by 1,000,000 and add a "million" string.</p> <p>Here is the demo:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var svg = d3.select("body") .append("svg") .attr("width", 600) .attr("height", 100); var scale = d3.scaleLinear().domain([200000,1800000]).range([20,550]); var axis = d3.axisBottom(scale).tickFormat(function(d){return d/1000000 + " Million"}); var gX = svg.append("g").attr("transform", "translate(20, 50)").call(axis);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://d3js.org/d3.v4.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p><strong>EDIT</strong>: According to the comments, you want to show "million" only in the last tick. Thus, we have to check if the tick is the last one and conditionally formatting it:</p> <pre><code>var axis = d3.axisBottom(scale).tickFormat(function(d){ if(this.parentNode.nextSibling){ return d/1000000; } else { return d/1000000 + " Million"; } }); </code></pre> <p>Here is the demo:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var svg = d3.select("body") .append("svg") .attr("width", 600) .attr("height", 100); var scale = d3.scaleLinear().domain([200000,1800000]).range([20,550]); var axis = d3.axisBottom(scale).tickFormat(function(d){ if(this.parentNode.nextSibling){ return d/1000000} else { return d/1000000 + " Million"}}); var gX = svg.append("g").attr("transform", "translate(20, 50)").call(axis);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://d3js.org/d3.v4.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
SAS: What is the fileref referring to in a DDE link? <p>Can someone please explain what a statement like</p> <pre><code>filename fileref dde 'excel|system'; </code></pre> <p>does within SAS?</p> <p>According to <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms648774(v=vs.85).aspx" rel="nofollow">Microsoft</a>, Dynamic Data Exchange (DDE)</p> <blockquote> <p>sends messages between applications that share data and uses shared memory to exchange data between applications.</p> </blockquote> <p>This makes DDE sound like some sort of I/O stream. </p> <p>Yet, the <a href="http://support.sas.com/documentation/cdl/en/hostwin/67962/HTML/default/viewer.htm#p0nfh32rqmc1xdn1e0rs1it8qy35.htm" rel="nofollow">DDE Syntax within SAS</a> requires a <em>fileref</em> within a <code>FILENAME</code> statement, where a</p> <blockquote> <p>fileref is a valid fileref (as described in Referencing External Files).</p> </blockquote> <p>The <a href="http://support.sas.com/documentation/cdl/en/hostwin/67962/HTML/default/viewer.htm#n07buc7sg08fdrn1c1jmmr8hl78r.htm" rel="nofollow">Referencing External Files</a> then goes on to define a <em>fileref</em> as</p> <blockquote> <p>A fileref is a logical name associated with an external file.</p> </blockquote> <p>What external file? </p> <p>My naive understanding is that it opens some sort of communication channel between Excel and SAS, hence my want to call it a stream. This has implications such as the above statement must be declared <em>after</em> Excel has been opened.</p>
<p>As far as I know, there's not a physical file involved in DDE. Rather, as you note, it is a stream. SAS and C are fairly similar in that sense; files really are more like devices. There are plenty of other similar examples - the <code>pipe</code> device, for example, which allows you to interact with the system console as if it were a file.</p> <p>What's really happening as far as I can tell behind the scenes, is that SAS is writing to the Global Atom Table, discussed by Microsoft <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms649053(v=vs.85).aspx" rel="nofollow">here</a>. That causes a message to be broadcast that Excel will read and react to.</p>
How to achieve test isolation with Symfony forms and data transformers? <p><strong><em>Note:</strong> This is Symfony &lt; 2.6 but I believe the same overall issue applies regardless of version</em></p> <p>To start, consider this form type that is designed to represent one-or-more entities as a hidden field (namespace stuff omitted for brevity)</p> <pre><code>class HiddenEntityType extends AbstractType { /** * @var EntityManager */ protected $em; public function __construct(EntityManager $em) { $this-&gt;em = $em; } public function buildForm(FormBuilderInterface $builder, array $options) { if ($options['multiple']) { $builder-&gt;addViewTransformer( new EntitiesToPrimaryKeysTransformer( $this-&gt;em-&gt;getRepository($options['class']), $options['get_pk_callback'], $options['identifier'] ) ); } else { $builder-&gt;addViewTransformer( new EntityToPrimaryKeyTransformer( $this-&gt;em-&gt;getRepository($options['class']), $options['get_pk_callback'] ) ); } } /** * See class docblock for description of options * * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver-&gt;setDefaults(array( 'get_pk_callback' =&gt; function($entity) { return $entity-&gt;getId(); }, 'multiple' =&gt; false, 'identifier' =&gt; 'id', 'data_class' =&gt; null, )); $resolver-&gt;setRequired(array('class')); } public function getName() { return 'hidden_entity'; } /** * {@inheritdoc} */ public function getParent() { return 'hidden'; } } </code></pre> <p>This works, it's straightforward, and for the most part looks like like all the examples you see for adding data transformers to a form type. Until you get to unit testing. See the problem? The transformers can't be mocked. "But wait!" you say, "Unit tests for Symfony forms are integration tests, they're supposed to make sure the transformers don't fail. Even says so <a href="http://symfony.com/doc/current/form/unit_testing.html">in the documentation</a>!"</p> <blockquote> <p>This test checks that none of your data transformers used by the form failed. The isSynchronized() method is only set to false if a data transformer throws an exception</p> </blockquote> <p>Ok, so then you live with the fact you can't isolate the transformers. No big deal? </p> <p>Now consider what happens when unit testing a form that has a field of this type (assume that <code>HiddenEntityType</code> has been defined &amp; tagged in the service container)</p> <pre><code>class SomeOtherFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder -&gt;add('field', 'hidden_entity', array( 'class' =&gt; 'AppBundle:EntityName', 'multiple' =&gt; true, )); } /* ... */ } </code></pre> <p>Now enters the problem. The unit test for <code>SomeOtherFormType</code> now needs to implement <code>getExtensions()</code> in order for the <code>hidden_entity</code> type to function. So how does that look?</p> <pre><code>protected function getExtensions() { $mockEntityManager = $this -&gt;getMockBuilder('Doctrine\ORM\EntityManager') -&gt;disableOriginalConstructor() -&gt;getMock(); /* Expectations go here */ return array( new PreloadedExtension( array('hidden_entity' =&gt; new HiddenEntityType($mockEntityManager)), array() ) ); } </code></pre> <p>See where that comment is in the middle? Yeah, so for this to work correctly, all of the mocks and expectations that are in the unit test class for the <code>HiddenEntityType</code> now effectively need to be duplicated here. I'm not OK with this, so what are my options?</p> <ol> <li><p>Inject the transformer as one of the options</p> <p>This would be very straightforward and would make mocking simpler, but ultimately just kicks the can down the road. Because in this scenario, <code>new EntityToPrimaryKeyTransformer()</code> would just move from one form type class to another. Not to mention that I feel form types <em>should</em> hide their internal complexity from the rest of the system. This option means pushing that complexity outside the boundary of the form type.</p></li> <li><p>Inject a transformer factory of sorts into the form type</p> <p>This is a more typical approach to removing "newables" from within a method, but I can't shake the feeling that this is being done just to make the code testable, and is not actually making the code better. But if that was done, it would look something like this</p> <pre><code>class HiddenEntityType extends AbstractType { /** * @var DataTransformerFactory */ protected $transformerFactory; public function __construct(DataTransformerFactory $transformerFactory) { $this-&gt;transformerFactory = $transformerFactory; } public function buildForm(FormBuilderInterface $builder, array $options) { $builder-&gt;addViewTransformer( $this-&gt;transformerFactory-&gt;createTransfomerForType($this, $options); ); } /* Rest of type unchanged */ } </code></pre> <p>This feels ok until I consider what the factory will actually look like. It will need the entity manager injected, for starters. But what then? If I look further down the road, this supposedly-generic factory could need all sorts of dependencies for creating data transformers of different kinds. That is clearly not a good long-term design decision. So then what? Re-label this as an <code>EntityManagerAwareDataTransformerFactory</code>? It's starting to feel messy in here.</p></li> <li><p>Stuff I'm not thinking of...</p></li> </ol> <p>Thoughts? Experiences? Solid advice?</p>
<p>First of all, I have next to no experience with Symfony. However, I think you missed a third option there. In Working Effectively with Legacy Code, Michael Feathers outlines a way to isolate dependencies by using inheritance (he calls it "Extract and Override").</p> <p>It goes like this:</p> <pre><code>class HiddenEntityType extends AbstractType { /* stuff */ public function buildForm(FormBuilderInterface $builder, array $options) { if ($options['multiple']) { $builder-&gt;addViewTransformer( $this-&gt;createEntitiesToPrimaryKeysTransformer($options) ); } } protected function createEntitiesToPrimaryKeysTransformer(array $options) { return new EntitiesToPrimaryKeysTransformer( $this-&gt;em-&gt;getRepository($options['class']), $options['get_pk_callback'], $options['identifier'] ); } } </code></pre> <p>Now to test, you create a new class, <code>FakeHiddenEntityType</code>, that extends <code>HiddenEntityType</code>.</p> <pre><code>class FakeHiddenEntityType extends HiddenEntityType { protected function createEntitiesToPrimaryKeysTransformer(array $options) { return $this-&gt;mock; } } </code></pre> <p>Where <code>$this-&gt;mock</code> obviously is whatever you need it to be.</p> <p>The two most prominent advantages are that there are no factories involved, thus complexity is still encapsulated, and there is virtually no chance that this change breaks existing code.</p> <p>The disadvantage being that this technique requires an extra class. More importantly, it requires a class that knows about the internals of the class under test.</p>
I can't inflate a view in a custom infowindow in Mapbox <p>I am doing a map guide for Android using Mapbox and Android Studio IDE, but I am having a hard time dealing with the custom infowindow. </p> <p>I want to inflate the infowindow (the one after I click on a marker) but as of yet I want to use an XML for that for an easy customization (I am open for suggestions, I still need to add a different image for each of the markers.). I am using a customization in the code itself just for testing, but I want to inflate an XML for that purporse. </p> <p>The following images below show the prototype I am developing for the view and the next image shows what I am actually getting from the test (The code is inside the getInfoWindow function) I am developing with the code below:</p> <p><a href="https://i.stack.imgur.com/fnObO.png" rel="nofollow">Prototype in XML (Where as: ID-Translation-Type)</a></p> <p><a href="https://i.stack.imgur.com/zYrKW.png" rel="nofollow">What I am getting</a></p> <p>Here follows the part of the map code I am using, and the next code shows the XML code.</p> <p><strong>Main code (Mapa.Java):</strong></p> <pre><code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MapboxAccountManager.start(this,getString(R.string.access_token)); setContentView(R.layout.activity_main); mapView = (MapView) findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(MapboxMap mapboxMap) { IconFactory iconFactory = IconFactory.getInstance(Mapa.this); Drawable iconDrawable = ContextCompat.getDrawable(Mapa.this, R.drawable.infoicon); Icon icon = iconFactory.fromDrawable(iconDrawable); mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() { @Override public View getInfoWindow(@NonNull Marker marker) { View v = getLayoutInflater().inflate(R.layout.janela_infowindow, null); TextView titulo = (TextView) v.findViewById(R.id.titulo); TextView desc = (TextView) v.findViewById(R.id.descricao); titulo.setText(marker.getTitle()); desc.setText(marker.getSnippet()); titulo.setTextColor(Color.WHITE); desc.setTextColor(Color.WHITE); v.setBackgroundColor(Color.rgb(27,77,62)); v.setPadding(10, 10, 10, 10); return v; } }); mapboxMap.addMarker(new MarkerOptions() .position(new LatLng(-15.76363, -47.86949)) .title("ICC Centro") .snippet(getString(R.string.desc_ICC_Centro)) .icon(icon)); mapboxMap.addMarker(new MarkerOptions() .position(new LatLng(-15.7629936, -47.86717415)) .title("Reitoria") .snippet(getString(R.string.desc_Reitoria)) .icon(icon)); mapboxMap.addMarker(new MarkerOptions() .position(new LatLng(-15.76196106, -47.87008166)) .title("FAU") .snippet(getString(R.string.desc_FAU)) .icon(icon)); } }); } </code></pre> <p><strong>XML code (janela_infowindow.xml):</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="200dp" android:layout_height="270dp" android:weightSum="1"&gt; &lt;ImageView android:layout_width="200dp" android:layout_height="0dp" android:id="@+id/imagem" android:adjustViewBounds="true" android:layout_gravity="end" android:contentDescription="@string/nome_local" android:layout_weight="0.11" /&gt; &lt;TextView android:layout_width="200dp" android:layout_height="wrap_content" android:layout_marginTop="-30dp" android:gravity="center" android:textAlignment="center" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/titulo" android:typeface="serif" android:textStyle="bold"/&gt; &lt;TextView android:layout_width="200dp" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/descricao" /&gt; </code></pre> <p></p> <p>EDIT: I am not sure if this is correct, but every time I am going to set the <strong>height, width or set the image</strong>, it gives me this error message (This message error was given after setting the height and width):</p> <pre><code>FATAL EXCEPTION: main Process: afinal.projeto.unb.guiadoaluno, PID: 8979 java.lang.NullPointerException: Attempt to write to field 'int android.view.ViewGroup$LayoutParams.height' on a null object reference at afinal.projeto.unb.guiadoaluno.Mapa$1$1.getInfoWindow(Mapa.java:87) at com.mapbox.mapboxsdk.annotations.Marker.showInfoWindow(Marker.java:165) at com.mapbox.mapboxsdk.maps.MapboxMap.selectMarker(MapboxMap.java:1295) at com.mapbox.mapboxsdk.maps.MapView$GestureListener.onSingleTapConfirmed(MapView.java:1792) at android.view.GestureDetector$GestureHandler.handleMessage(GestureDetector.java:280) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:5940) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184) </code></pre>
<p>Have a look at <a href="https://github.com/mapbox/mapbox-android-demo/blob/master/MapboxAndroidDemo/src/main/java/com/mapbox/mapboxandroiddemo/examples/annotations/CustomInfoWindowActivity.java" rel="nofollow">this example</a> found in the <a href="https://github.com/mapbox/mapbox-android-demo" rel="nofollow">Mapbox Android Demo app</a> which might help you. The important snippet of code found in the example:</p> <pre><code>mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() { @Nullable @Override public View getInfoWindow(@NonNull Marker marker) { // The info window layout is created dynamically, parent is the info window // container LinearLayout parent = new LinearLayout(CustomInfoWindowActivity.this); parent.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); parent.setOrientation(LinearLayout.VERTICAL); // Depending on the marker title, the correct image source is used. If you // have many markers using different images, extending Marker and // baseMarkerOptions, adding additional options such as the image, might be // a better choice. ImageView countryFlagImage = new ImageView(CustomInfoWindowActivity.this); switch (marker.getTitle()) { case "spain": countryFlagImage.setImageDrawable(ContextCompat.getDrawable( CustomInfoWindowActivity.this, R.drawable.flag_of_spain)); break; case "egypt": countryFlagImage.setImageDrawable(ContextCompat.getDrawable( CustomInfoWindowActivity.this, R.drawable.flag_of_egypt)); break; default: // By default all markers without a matching title will use the // Germany flag countryFlagImage.setImageDrawable(ContextCompat.getDrawable( CustomInfoWindowActivity.this, R.drawable.flag_of_germany)); break; } // Set the size of the image countryFlagImage.setLayoutParams(new android.view.ViewGroup.LayoutParams(150, 100)); // add the image view to the parent layout parent.addView(countryFlagImage); return parent; } }); } }); } </code></pre> <p>Let me know if you are still having info window issues.</p> <p><strong>EDIT:</strong> i've successfully inflated your layout by changing some of the XML code you provided to this:</p> <p> </p> <pre><code>&lt;ImageView android:id="@+id/imagem" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="end" android:adjustViewBounds="true"/&gt; &lt;TextView android:id="@+id/titulo" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textAlignment="center" android:textAppearance="?android:attr/textAppearanceLarge" android:textStyle="bold" android:typeface="serif"/&gt; &lt;TextView android:id="@+id/descricao" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge"/&gt; </code></pre> <p></p>
How to get the last executed command in a Telegram bot? <p>I have a <strong>telegram bot</strong> like this:</p> <ul> <li>Getting updates by <code>webhook</code></li> <li>Language: C# <em>(I welcome answers with other languages too)</em></li> <li><p>We have the following scenario for the user:</p> <ol> <li>Send <code>/MyPhoto a_parameter</code> command to the bot</li> <li>Send a photo to the bot</li> <li>Send another photo to the bot</li> <li>Send another photo to the bot</li> </ol></li> </ul> <p><strong>Base question:</strong></p> <p>What is the <em>best way</em> to make sure the sent photo by the user is right after sending <code>/MyPhoto a_parameter</code> command?</p> <p><strong>Some ways:</strong></p> <ul> <li>I can save every executed command by each user in the <em>database</em> and fetch the last executed command by the current user and compare it with <code>/MyPhoto</code>, if they are equal then i sure the user is sending a photo after <code>/MyPhoto</code> command.</li> <li>Create a <em>cache</em> system to hold the <em>last executed command</em> by each user (Mix with db)</li> </ul> <blockquote> <p>But if it is possible, I want prevent fetch the <em>last executed command</em> from database to <strong>improve performance</strong>.</p> </blockquote> <p>Do you know a better solution? For example using some thing in telegram bot API to keep last executed command as hidden in send/receive messages between user and bot .</p> <hr> <p>I edited the question with adding steps 3 &amp; 4 in the above scenario.</p>
<p>Question 1:</p> <blockquote> <p>What is the best way to make sure the sent photo by the user is right after sending /MyPhoto a_parameter command?</p> </blockquote> <p>I think the best solution is to store /MyPhoto <code>update_id</code> for each user and compare it with uploaded photos <code>update_id</code>. </p> <p>See the Telegram docs: </p> <blockquote> <p>The update‘s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.</p> </blockquote> <p>Question 2:</p> <blockquote> <p>Do you know a better solution? For example using some thing in telegram bot API to keep last executed command as hidden in send/receive messages between user and bot.</p> </blockquote> <p>Using InlineKeyboardMarkup with last executed command as callback data. When the user selects an inline button, you can fetch your callback data from its update.</p>
Apache httpd.conf for redirecting ip to hostname - SSL <p>In a similar problem addressed <a href="http://stackoverflow.com/questions/11649944/apache-httpd-conf-for-redirecting-ip-to-hostname">here <em>(Apache httpd.conf for redirecting ip to hostname)</em></a><br /> I would like to know how to do a redirect from an <strong><em>HTTPS</em></strong> over <strong><em>SSL</em></strong> static ip to hostname.</p> <p>I am currently using the configuration posted below but when I test it I get the warning and I actually have to click "Proceed to site" before it redirects. I tried removing the <code>SSLEngine on</code> segment but then it will not connect outright.</p> <pre><code>Listen 443 &lt;VirtualHost *:443&gt; ServerName 192.168.1.1 #Not the actual IP of server ServerAlias 192.168.1.1 #Not the actual IP of server SSLEngine on SSLCertificateFile /var/ssl/website/cert.crt SSLCertificateKeyFile /var/ssl/website/privkey.key RewriteEngine On RewriteCond %{HTTP_HOST} !^website.com$ RewriteRule /.* https://website.com/ [R] &lt;/VirtualHost&gt; </code></pre> <p>Any idea on what needs to be done to avoid having to click "Proceed to site" to allow it to redirect?</p>
<p>To redirect from some https site to anything else you need to have a valid certificate for this site, i.e. a certificate where the subject matches the name in the URL. In your case the certificate probably does not include the IP address and that's why the access to the site will result in a certificate validation error which you've explicitly ignored by clicking "Proceed to site".</p>
Postgres: Statistical functions on date time intervals <p>I need to run some statistical analysis on intervals i.e. difference between two datetime fields in a table. </p> <p>According to the aggregate function documentation <a href="https://www.postgresql.org/docs/current/static/functions-aggregate.html" rel="nofollow">here</a>. The aggregate functions for <code>MAX</code>, <code>MIN</code>, <code>AVG</code> etc i.e. general aggregate functions accept arguments for date-time and interval fields. </p> <p>However for more advanced statistical functions like <code>stddev_pop</code>, <code>var_pop</code>, <code>var_sam</code> and <code>std_samp</code> the input supported seem to be numeric or similar only. Although the documentation suggests there is no difference between the two types of functions</p> <blockquote> <p>... (These are separated out merely to avoid cluttering the listing of more-commonly-used aggregates.)...</p> </blockquote> <p>Is there any easy way to calculate these parameters ? and why is interval type as argument not supported ? These types of statistical aggregate functions are unit invariant ?</p> <p>P.S. I am not sure I can extract epoch and use it, as some values may be negative.</p>
<p>As I said in a comment, to work out sample standard deviation manually, at some point you multiply an interval by an interval. PostgreSQL doesn't support that.</p> <p>To work around that issue, reduce the interval to hours or minutes or seconds (or whatever). This turns out to be a lot simpler than working out the calculation manually, and it suggests why PostgreSQL doesn't support this kind of calculation out of the box.</p> <p>First, a function from the <a href="https://www.postgresql.org/message-id/CAHsw44-mWjPm%3D1WaeuU35BAZi1ouoyDngTwQpzaKeDRA1oCwww%40mail.gmail.com" rel="nofollow">PostgreSQL general mailing list</a></p> <pre><code>CREATE OR REPLACE FUNCTION interval_to_seconds(interval) RETURNS double precision AS $$ SELECT (extract(days from $1) * 86400) + (extract(hours from $1) * 3600) + (extract(minutes from $1) * 60) + extract(seconds from $1); $$ LANGUAGE SQL; </code></pre> <p>Now we can take the standard deviation of a simple set of intervals.</p> <pre><code>with intervals (i) as ( values (interval '1 hour'), (interval '2 hour'), (interval '3 hour'), (interval '4 hour'), (interval '5 hour') ) , intervals_as_seconds as ( select interval_to_seconds(i) as seconds from intervals ) select stddev(seconds), stddev(seconds)/60 from intervals_as_seconds </code></pre> <pre> in_sec in_min double precision double precision -- 5692.09978830308 94.8683298050514 </pre> <p>You can verify the results however you like.</p> <p>Now let's say you wanted hour granularity instead of seconds. Clearly, the choice of granularity is highly application dependent. You might define another function, <code>interval_to_hours(interval)</code>. You can use a very similar query to calculate the standard deviation.</p> <pre><code>with intervals (i) as ( values (interval '1 hour'), (interval '2 hour'), (interval '3 hour'), (interval '4 hour'), (interval '5 hour') ) , intervals_as_hours as ( select interval_to_hours(i) as hours from intervals ) select stddev(hours) as stddev_in_hrs from intervals_as_hours </code></pre> <pre> stddev_in_hrs double precision -- 1.58113883008419 </pre> <p>The value for standard deviation in hours is clearly different from the value in minutes or in seconds. But they measure exactly the same thing. The point is that the "right" answer depends on the granularity (units) you want to use, and there are a lot of choices. (From microseconds to centuries, I imagine.)</p> <p>Also, consider this statement.</p> <pre><code>select interval_to_hours(interval '45 minutes') </code></pre> <pre> interval_to_hours double precision -- 0 </pre> <p>Is that the right answer? You can't say; the right answer is application-dependent. I can imagine applications that would want 45 minutes to be considered as 1 hour. I can also imagine applications that would want 45 minutes to be considered as 1 hour for <em>some</em> calculations, and as 0 hours for <em>other</em> calculations.</p> <p>And think about this question. How many seconds are in a month? The expression <code>select interval '1' month;</code> is valid; the number of seconds depends on how many days are in the month. </p> <p>And I think <em>that's</em> why PostgreSQL doesn't support this kind of calculation out of the box. The right way to do it with interval arguments is too application-dependent.</p> <p><strong>Later . . .</strong></p> <p>I found this discussion on one of the PostgreSQL mailing lists.</p> <p><a href="https://www.postgresql.org/message-id/37ed240d0605200814y5dfbd443s9d6938dbf3bd9aa4%40mail.gmail.com" rel="nofollow">No stddev() for interval?</a></p>
angular databinding 2 numbers to equal another <p>I have 2 divs that must always equal 100%. So they each start out 50%. The one on the left, can be changed from 1-99 (as an input), and the other must match that so they both always stay 100%.</p> <p>for example: div A = 35%, div B must auto-change to 65%. I know how to two databind values, but not so that they each equal another value combined.</p>
<p>just keep subtracting div a from b first div</p> <pre><code>&lt;div&gt;{{A}}&lt;/div&gt; </code></pre> <p>second div</p> <pre><code>&lt;div&gt;{{100-A}}&lt;/div&gt; </code></pre>
What data structure should be used to represent this table? <p>Given the following dataset.</p> <pre><code>| | English | Maths | Science | Total | |-------|---------|-------|---------|-------| | Alice | 7 | 4 | 6 | ? | | Bob | 3 | 5 | 1 | ? | | Total | ? | ? | ? | ? | </code></pre> <p>Which data structure should I represent this data with, that will allow me to calculate the values marked with question mark efficiently?</p>
<p>You can simply keep a HashMap where key is the 'Name' and the value is the structure of 'English,Hindi... Total'. Apart from all the names in the Key, have a special Name - 'Total' in the Key. So, every time you are adding a student's name, lets say, Alice and subject : English, you need to search for 2 keys: Alice and Total.</p> <p>For each key, update the subject English and Total.</p> <p>No need to have a complicated data structure for this. Keep it simple. </p>
Extra Input Tags appear in HTML <p>Recently found an issue when trying to write some Automation Tests for a component in my webapp, I am using Anglur for the front end, and am trying to create a type ahead input textbox</p> <pre><code> &lt;div class="row"&gt; &lt;div class="col-md-4"&gt; &lt;label ng-bind="::'ENVIRONMENT' | translate"&gt;&lt;/label&gt; &lt;/div&gt; &lt;div class="col-md-8" ng-class="{ 'has-error' : iliCtl.noEnvResults &amp;&amp; iliForm.envs.$viewValue !== '' }"&gt; &lt;input name="envs" id="envs" type="text" ng-model="iliCtl.selectedEnv" uib-typeahead="env.name for env in iliCtl.environmentData | filter:{name:$viewValue} | limitTo:50" typeahead-no-results="iliCtl.noEnvResults" typeahead-show-hint="true" typeahead-min-length="0" typeahead-on-select="onEnvSelect($item)" placeholder="-- Select --" class="form-control"&gt; &lt;div class="error-class" ng-show="iliCtl.noEnvResults &amp;&amp; iliForm.envs.$viewValue !== ''" ng-bind="::'ERROR_207' | translate"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The above code works fine until I inspect the element, the the generated HTML appears to generate two input tags as per image below.</p> <p><a href="https://i.stack.imgur.com/tzt68.png" rel="nofollow"><img src="https://i.stack.imgur.com/tzt68.png" alt="Generated HTML Code"></a> </p> <p>Any ideas as to why this would be happening, as you can see the Input tags contain mostly the same properties the major differences seem to be styling properties. But I cant see why this would be happening.</p>
<p>I found the answer, and it isn't a bug as I first assumed.</p> <p>The Input Tag property <code>typeahead-show-hint="true"</code> is responsible for generating the second input box in the HTML, It is used to display a suggested item in the text box.</p>
Getting rid of || or's in C programming <p>I'm using <code>||</code> so that if the user types in a <code>Y</code> or <code>y</code> it equals the same. Example: <code>(option=='y' || option =='Y')</code> I know there's a single function to get rid of this so that the user types in <code>Y</code> or <code>y</code> it equals the same.</p> <p>What would be the best way to do this?</p>
<p>You could try to use <code>tolower((unsigned char)option) == 'y'</code> as described on <a href="https://www.tutorialspoint.com/c_standard_library/c_function_tolower.htm" rel="nofollow">https://www.tutorialspoint.com/c_standard_library/c_function_tolower.htm</a> (you need to add <code>#include &lt;ctype.h&gt;</code>).</p> <p>Or use a switch statement with fallthrou cases for 'Y' and 'y'.</p> <p>I suppose if you often have <code>(option=='y' || option =='Y')</code> I suppose the best way is to put it into a separate function in your favourite way and call the function ;)</p>
urls don't work with linkify.js <p>I am trying to use linkify.js library to convert any urls in the text to hyperlinks. The returned string does not come back with hyperlinks and I don't see any errors either. Please find the code below and advise why this is not working. Thanks.</p> <pre><code>npm install linkifyjs var linkify = require('linkifyjs'); var linkifyHtml = require('linkifyjs/html'); require('linkifyjs/plugins/hashtag')(linkify); // optional var testStr = 'http://google.com. This is awesome.'; linkifyHtml(testStr, { defaultProtocol: 'https' }); </code></pre>
<pre><code>var linkified = linkifyHtml(testStr, { defaultProtocol: 'https' }); console.log(linkified); </code></pre> <p>gives me </p> <pre><code>&lt;a href="http://google.com" class="linkified" target="_blank"&gt;http://google.com&lt;/a&gt;. This is awesome. </code></pre>
Conditional Filtering breaks with whitespace <p>I'm retrieving a subset of database records based on user-entered criteria.</p> <p>Searching by name successfully retrieves all records containing the string ONLY if the string is one word without whitespace. When adding another word or a space it returns an empty result.</p> <p>Controller:</p> <pre><code>public IEnumerable&lt;Product&gt; GetProducts(ProductSearchModel searchModel) { var result = db.Products.AsQueryable(); if (searchModel != null) { if (searchModel.Id.HasValue) result = result.Where(x =&gt; x.ProductId == searchModel.Id); if (!string.IsNullOrEmpty(searchModel.Name)) result = result.Where(x =&gt; x.Name.Contains(searchModel.Name)); if (!string.IsNullOrEmpty(searchModel.Colour)) result = result.Where(x =&gt; x.Colour.Contains(searchModel.Colour)); if (!string.IsNullOrEmpty(searchModel.Brand)) result = result.Where(x =&gt; x.Brand.Contains(searchModel.Brand)); if (!string.IsNullOrEmpty(searchModel.Genre)) result = result.Where(x =&gt; x.Genre.Contains(searchModel.Genre)); if (searchModel.PriceFrom.HasValue) result = result.Where(x =&gt; x.Price &gt;= searchModel.PriceFrom); if (searchModel.PriceTo.HasValue) result = result.Where(x =&gt; x.Price &lt;= searchModel.PriceTo); } return result.AsEnumerable(); } </code></pre> <p>Section of view (implementation of all fields same as Model.Name):</p> <pre><code>&lt;div class="row"&gt; &lt;i class="fa fa-search"&gt;&lt;/i&gt; @Html.LabelFor(model =&gt; model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) @Html.EditorFor(model =&gt; model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model =&gt; model.Name, "", new { @class = "text-danger" }) &lt;span class="glyphicon glyphicon-chevron-down" id="advancedSearchToggle"&gt;&lt;/span&gt; &lt;/div&gt; ... &lt;div class="form-group"&gt; &lt;div class="col-md-offset-2 col-md-10"&gt; &lt;input type="submit" value="Save" class="btn btn-default" /&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Does anyone know what might be the issue?</p> <p>Thanks</p>
<p>Try and remove the spaces.</p> <p>result = result.Where(x => x.Name.Replace(" ","").Contains(searchModel.Name));</p>
decode JavaScript code ? <p>I found this code in the blog template,Already used it. I am afraid to be harmful blog,Or be an injection ..I'm trying to decode it but failed , so please help ? because i want to be sure what is it , </p> <pre> document.write( unescape( &#39;%3C%73%63%72%69%70%74%20%73%72%63%3D%27%68%74%74%70%73%3A%2F%2F%61%72%6C%69%6E%61%2D%64%65%73%69%67%6E%2E%67%6F%6F%67%6C%65%63%6F%64%65%2E%63%6F%6D%2F%73%76%6E%2F%76%69%65%77%6D%65%2E%6A%73%27%20%74%79%70%65%3D%27%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%27%2F%3E&#39; )) </pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>console.log( unescape( '%3C%73%63%72%69%70%74%20%73%72%63%3D%27%68%74%74%70%73%3A%2F%2F%61%72%6C%69%6E%61%2D%64%65%73%69%67%6E%2E%67%6F%6F%67%6C%65%63%6F%64%65%2E%63%6F%6D%2F%73%76%6E%2F%76%69%65%77%6D%65%2E%6A%73%27%20%74%79%70%65%3D%27%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%27%2F%3E' ))</code></pre> </div> </div> </p> <p>As suggested in the comments above, use console.log to view the contents. This yields <code>https://arlina-design.googlecode.com/svn/viewme.js</code> which seems to get a 404 error, but if the owner put it back up, then they could run that code-- the code that THEY control. If you include it, it can access your webpage, and it IS a security hole.</p>
Avoiding infinite recursion but still using unbound parameter passing only <p>I have the following working program: (It can be tested on this site: <a href="http://swish.swi-prolog.org" rel="nofollow">http://swish.swi-prolog.org</a>, I've removed the direct link to a saved program, because I noticed that anybody can edit it.)</p> <p>It searches for a path between two points in an undirected graph. The important part is that the result is returned in the scope of the "main" predicate. (In the Track variable)</p> <pre><code>edge(a, b). edge(b, c). edge(d, b). edge(d, e). edge(v, w). connected(Y, X) :- ( edge(X, Y); edge(Y, X) ). path(X, X, _, []) :- connected(X, _). path(X, Y, _, [X, Y]) :- connected(Y, X). path(X, Z, Visited, [X|Track]) :- connected(X, Y), not(member(X, Visited)), path(Y, Z, [X|Visited], Track). main(X, Y) :- path(X, Y, [], Track), print(Track), !. </code></pre> <p>Results:</p> <pre><code>?- main(a, e). [a, b, d, e] true ?- main(c, c). [] true ?- main(b, w). false </code></pre> <p>My questions:</p> <ol> <li><p>The list of visited nodes is passed down to the predicates in 2 different ways. In the bound Visited variable and in the unbound Track variable. What are the names of these 2 different forms of parameter passing?</p></li> <li><p>Normally I only wanted to use the unbound parameter passing (Track variable), to have the results in the scope of the main predicate. But I had to add the Visited variable too, because the member checking didn't work on the Track variable (I don't know why). Is it possible to make it work with only passing the Track in an unbound way? (without the Visited variable)</p></li> </ol> <p>Many thanks!</p>
<p>The short answer: no, you cannot avoid the extra argument without making everything much messier. This is because this particular algorithm for finding a path needs to keep a state; basically, your extra argument is your state.</p> <p>There might be other ways to keep a state, like using a global, mutable variable, or dynamically changing the Prolog data base, but both are more difficult to get right and will involve more code.</p> <p>This extra argument is often called an <em>accumulator</em>, because it accumulates something as you go down the <a href="http://www.learnprolognow.org/lpnpage.php?pagetype=html&amp;pageid=lpn-htmlse6" rel="nofollow">proof tree</a>. The simplest example would be traversing a list:</p> <pre><code>foo([]). foo([X|Xs]) :- foo(Xs). </code></pre> <p>This is fine, unless you need to know what elements you have already seen before getting here:</p> <pre><code>bar(List) :- bar_(List, []). bar_([], _). bar_([X|Xs], Acc) :- /* Acc is a list of all elements so far */ bar_(Xs, [X|Acc]). </code></pre> <p>This is about the same as what you are doing in your code. And if you look at this in particular:</p> <pre><code>path(X, Z, Visited, /* here */[X|Track]) :- connected(X, Y), not(member(X, Visited)), path(Y, Z, [X|Visited], /* and here */Track). </code></pre> <p>The last argument of <code>path/4</code> has <strong>one element more</strong> at a <strong>depth of one less</strong> in the proof tree! And, of course, the third argument is one longer (it grows as you go down the proof tree).</p> <p>For example, you can reverse a list by adding another argument to the silly <code>bar</code> predicate above:</p> <pre><code>list_reverse(L, R) :- list_reverse_(L, [], R). list_reverse_([], R, R). list_reverse_([X|Xs], R0, R) :- list_reverse_(Xs, [X|R0], R). </code></pre> <p>I am not aware of any special name for the last argument, the one that is free at the beginning and holds the solution at the end. In some cases it could be an <em>output argument</em>, because it is meant to capture the output, after transforming the input somehow. There are many cases where it is better to avoid thinking about arguments as strictly input or output arguments. For example, <code>length/2</code>:</p> <pre><code>?- length([a,b], N). N = 2. ?- length(L, 3). L = [_2092, _2098, _2104]. ?- length(L, N). L = [], N = 0 ; L = [_2122], N = 1 ; L = [_2122, _2128], N = 2 . % and so on </code></pre> <p><strong>Note</strong>: there are quite a few minor issues with your code that are not critical, and giving that much advice is not a good idea on Stackoverflow. If you want you could submit this as a question on <a href="http://codereview.stackexchange.com/questions/tagged/prolog">Code Review</a>.</p> <p><strong>Edit</strong>: you should definitely study <a href="http://stackoverflow.com/questions/30328433/definition-of-a-path-trail-walk">this question</a>.</p> <p>I also provided a somewhat simpler solution <a href="http://swish.swi-prolog.org/p/find-path.pl" rel="nofollow">here</a>. Note the use of <code>term_expansion/2</code> for making directed edges from undirected edges at compile time. More important: you don't need the main, just call the predicate you want from the top level. When you drop the cut, you will get all possible solutions when one or both of your From and To arguments are free variables.</p>
xcode 8 UIStackView. How to make round buttons? <p>I am using <code>UIStackView</code> and I am trying to make the buttons round. My first four buttons have user defined runtime attributes:</p> <pre><code>layer.cornerRadius Number 10 layer.masksToBounds Boolean true </code></pre> <p><a href="https://i.stack.imgur.com/NsEi1.png" rel="nofollow"><img src="https://i.stack.imgur.com/NsEi1.png" alt="enter image description here"></a></p>
<p>I don't know why your attempt to use user-defined runtime attributes is not working; it's a legitimate technique, and I've used it.</p> <p>That said, here's another approach: use a UIButton subclass. Define your subclass to set these values in its initializer (here, <code>init(coder:)</code> is what you'll need to implement). Then, in the storyboard, use the Identity inspector to make these buttons instances of this subclass.</p> <p>This is actually a <em>better</em> approach than yours, because it encapsulates in <em>one</em> place what <em>all</em> the buttons have in common. Having to define the <em>same</em> attributes for <em>four buttons separately</em> was always a Bad Smell!</p>
How to analyze a photo sent through JSON <p>I have a Web Service that takes a photo through a POST statement and returns a modified copy of that photo back. We are making changes to the way it processes the photo, and I want to verify that the photo at least has different properties coming back than it did before our changes went into effect.</p> <p>The photo is being returned as a byte stream inside one of the fields of a JSON object. I can analyze the JSON object pretty easily, but I'm trying to figure out how to get the byte stream into an Java image object so that I can get its dimensions.</p>
<p>Possible duplicate of <a href="http://stackoverflow.com/questions/672916/how-to-get-image-height-and-width-using-java">this question</a></p> <blockquote> <p>... I'm trying to figure out how to get the byte stream into an Java image object so that i can get its dimensions.</p> </blockquote> <p>I'd suggest using a <code>BufferedImage</code> in the following format/snippet. Note: I load my image in from disk for the example and use try-with-resources (which you may revert to 1.6-prior if needed).</p> <pre><code> String fp = "C:\\Users\\Nick\\Desktop\\test.png"; try (FileInputStream fis = new FileInputStream(new File(fp)); BufferedInputStream bis = new BufferedInputStream(fis)) { BufferedImage img = ImageIO.read(bis); final int w = img.getWidth(null); final int h = img.getHeight(null); } </code></pre>
SQL query for Length and Between <p>I need to write a query for finding the length of the word between <code>value1</code> and <code>value2</code>. I tried the query below:</p> <pre><code>select * from table_name where LENGTH (column_name (BETWEEN 1 and 2) ); </code></pre>
<p>You can do it like this:</p> <pre><code>SELECT * FROM table_name WHERE LENGTH (column_name) BETWEEN 1 and 2; </code></pre>
Exit code non-zero and unable to see output logs <p>How do I view stdout/stderr output logs for cloud ML? I've tried using gcloud beta logging read and also gcloud beta ml jobs stream-logs and nothing... all I see are the INFO level logs generated by the system i.e. "Tearing down TensorFlow".</p> <p>Also in the case where I have an error that shows the docker container exited with non zero code. It links me to a GUI page that shows the same stuff as gcloud beta ml jobs stream-logs. Nothing that shows me the actual output from the console of what my job produced...</p> <p>Help please??</p>
<p>It may be the case that the Cloud ML service account does not have permissions to write to your project's StackDriver Logs, or the Logging API is not enabled on your project.</p> <p>First check whether the Stackdriver Logging API is enabled for the project by going to the API manager: <a href="https://console.cloud.google.com/apis/api/logging.googleapis.com/overview?project=[YOUR-PROJECT-ID]" rel="nofollow">https://console.cloud.google.com/apis/api/logging.googleapis.com/overview?project=[YOUR-PROJECT-ID]</a></p> <p>Then check that you've either run the Cloud ML project init operation: gcloud beta ml init-project which adds the Cloud ML service account as an Editor to the project, and therefore allows it to write to the project logs, or that you've manually given the Cloud ML service account LogWriter permissions.</p> <p>If you are unsure of the service account used by Cloud ML, this page has instructions on how to find it: <a href="https://cloud.google.com/ml/docs/how-tos/using-external-buckets" rel="nofollow">https://cloud.google.com/ml/docs/how-tos/using-external-buckets</a></p>
System.env and values in Properties file are not being read on Slave Nodes of Spark Cluster <p>I do have a multi node spark cluster and submitting my spark program on node where master resides.</p> <p>When the job submitted to slave nodes, the HOSTNAME paramter is giving null value. Here is the line where properties are being read as null.</p> <p>System.getenv(HOSTNAME) is not being read from slave node.</p> <pre><code> System.out.println("line 76 System.getenv(HOSTNAME)=" + System.getenv("HOSTNAME")); </code></pre> <p>AUDIT_USER, AUDIT_PASSWORD also null when being read(they both were on properties file).</p> <p>If i submit job with one node i have no issues with these parameters. But, if u submit job on standalone mode with 6 nodes i am getting this issue.</p> <p>I have created the same folder for properties file on all nodes.</p> <p>Here is my code. could you please let me know why System.env is not giving null and my properties are null?</p> <pre><code>package com.fb.cpd.myapp; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.concurrent.Future; import org.apache.commons.configuration.ConfigurationConverter; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.spark.TaskContext; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function; import org.apache.spark.streaming.Duration; import org.apache.spark.streaming.api.java.JavaInputDStream; import org.apache.spark.streaming.api.java.JavaStreamingContext; import org.apache.spark.streaming.kafka.KafkaUtils; import kafka.common.TopicAndPartition; import kafka.message.MessageAndMetadata; import kafka.serializer.DefaultDecoder; import kafka.serializer.StringDecoder; public class GenericLogic implements Serializable { /** * */ private static final long serialVersionUID = 1L; private static final Logger logger = LogManager.getLogger(GenericLogic.class); private PropertiesConfiguration props; private Producer&lt;String, String&gt; producer = null; private Future&lt;RecordMetadata&gt; receipt = null; private RecordMetadata receiptInfo = null; private ConnectToRDBMS auditor = null; private ConnectToRDBMS df = null; private static String myId = null; private Map&lt;TopicAndPartition, Long&gt; getOffsets(String topic) throws SQLException { String appName = "myapp"; String TopicName = topic; Map&lt;TopicAndPartition, Long&gt; topicMap = new HashMap&lt;&gt;(); // System.out.println("line 64 before making connection"); try { props = new PropertiesConfiguration("/app/lock/conf/empty.properties"); } catch (ConfigurationException e) { // TODO Auto-generated catch block System.out.println("Line 70"); e.printStackTrace(); } try { System.out.println("line 76 System.getenv(HOSTNAME)=" + System.getenv("HOSTNAME")); auditor = new ConnectToRDBMS(System.getenv("HOSTNAME"), "lockSparkCollector", null, null, null, null, null, 0, props.getString("AUDIT_USER"), props.getString("AUDIT_PASSWORD"), props.getString("AUDIT_DB_URL")); } catch (SQLException e) { logger.error("ASSERT: run() ERROR CONNECTING TO AUDIT DB " + e.getMessage()); } System.out.println("line 64 after making connection"); Statement stmt = null; String query = "select va_application, topic_name, partition_id, from_offset,until_offset from lock_spark_offsets where va_application = " + "'" + appName + "'" + " and topic_name= " + "'" + TopicName + "'"; System.out.println("query" + query); System.out.println("before query exection"); try { stmt = auditor.dbConnection.createStatement(); System.out.println("line 81"); ResultSet rs = stmt.executeQuery(query); System.out.println("line 83"); while (rs.next()) { System.out.println("pass 1 of Resultset"); System.out.println("getOffsets=" + topic.trim() + " " + rs.getInt("partition_id") + " " + rs.getString("until_offset") + " " + rs.getString("until_offset")); Integer partition = rs.getInt("partition_id"); TopicAndPartition tp = new TopicAndPartition(topic.trim(), partition); System.out.println("102"); Long.parseLong(rs.getString("until_offset")); topicMap.put(tp, Long.parseLong(rs.getString("until_offset"))); System.out.println("105"); } System.out.println("after populating topic map"); } catch ( SQLException e) { System.out.println("printing exception"); e.printStackTrace(); } finally { if (stmt != null) { System.out.println("closing statement"); stmt.close(); } } return topicMap; } public void setDefaultProperties() { FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy(); strategy.setRefreshDelay(10000); System.out.println("Line 45"); // supply the properties file. try { props = new PropertiesConfiguration("/app/lock/conf/empty.properties"); } catch (ConfigurationException e) { // TODO Auto-generated catch block System.out.println("Line 51"); e.printStackTrace(); } props.setReloadingStrategy(strategy); System.out.println("Line 56"); // Producer configs if (!props.containsKey("acks")) { props.setProperty("acks", "1"); } if (!props.containsKey("retries")) { props.setProperty("retries", "1000"); } if (!props.containsKey("compression.type")) { props.setProperty("compression.type", "gzip"); } if (!props.containsKey("request.timeout.ms")) { props.setProperty("request.timeout.ms", "600000"); } if (!props.containsKey("batch.size")) { props.setProperty("batch.size", "32768"); } if (!props.containsKey("buffer.memory")) { props.setProperty("buffer.memory", "134217728"); } if (!props.containsKey("block.on.buffer.full")) { props.setProperty("block.on.buffer.full", "true"); } if (!props.containsKey("SHUTDOWN")) { props.setProperty("SHUTDOWN", "false"); } if (!props.containsKey("producer.topic")) { props.setProperty("producer.topic", "mytopic1"); } Properties producer_props = ConfigurationConverter.getProperties(props); producer_props.setProperty("bootstrap.servers", props.getString("target.bootstrap.servers")); producer_props.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); producer_props.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); // ???? this.producer = new KafkaProducer&lt;String, String&gt;(producer_props); System.out.println("Line 107"); } public void PublishMessages(String st) { try { System.out.println("Line 111"); String key = UUID.randomUUID().toString().replace("-", ""); System.out.println("Started Producing..."); receipt = producer.send(new ProducerRecord&lt;String, String&gt;(props.getString("producer.topic"), key, // Key st)); System.out.println("After Completion of Producing Producing"); } catch (Exception e) { e.printStackTrace(); System.out.println("Exception in PublishMessages "); } } public void DBConnect() { try { auditor = new ConnectToRDBMS(System.getenv("HOSTNAME"), "myapp", props.getString("consumer.topic"), null, null, null, null, 0, props.getString("AUDIT_USER"), props.getString("AUDIT_PASSWORD"), props.getString("AUDIT_DB_URL")); } catch (SQLException e) { logger.error("ASSERT: run() ERROR CONNECTING TO AUDIT DB " + e.getMessage()); return; } } private void writeToDB(Long startTime, Integer partnId, String fromOffset, String untilOffset, Integer count) { this.auditor.audit(startTime, partnId, fromOffset, untilOffset, count); } /** * * @param jsc * @param topicSet * @throws Exception */ public static void main(String[] args) { String topicNames = "MySourceTopic"; GenericLogic ec = new GenericLogic(); Map&lt;TopicAndPartition, Long&gt; topicMap = null; try { topicMap = ec.getOffsets("MySourceTopic"); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } boolean clusterMode = false; Integer batchDuration = Integer.parseInt("30000"); JavaSparkContext sparkConf = new JavaSparkContext("abcd.net:7077", "Kafka-Spark-Integration"); sparkConf.getConf().set("spark.local.ip", "lock-dt-a4d.xyz.com"); sparkConf.getConf().set("spark.eventLog.enabled", "false"); sparkConf.getConf().set("spark.shuffle.blockTransferService", "nio"); JavaStreamingContext jsc = new JavaStreamingContext(sparkConf, new Duration(10000)); Map&lt;String, String&gt; kafkaParams = new HashMap&lt;String, String&gt;(); String pollInterval = "10000"; String zookeeper = "lock-dt-a5d.xyz.com:2181,lock-dt-a6d.xyz.com:2181"; kafkaParams.put("metadata.broker.list", "lock-dt-a5d.xyz.com:9092,lock-dt-a6d.xyz.com:9092"); kafkaParams.put("group.id", "Consumer"); kafkaParams.put("client.id", "Consumer"); kafkaParams.put("zookeeper.connect", zookeeper); JavaInputDStream&lt;byte[]&gt; directKafkaStream = KafkaUtils.createDirectStream(jsc, String.class, byte[].class, StringDecoder.class, DefaultDecoder.class, byte[].class, kafkaParams, topicMap, (Function&lt;MessageAndMetadata&lt;String, byte[]&gt;, byte[]&gt;) MessageAndMetadata::message); directKafkaStream.foreachRDD(rdd -&gt; { if (rdd.isEmpty()) { System.out.println("No events polled in last " + pollInterval + " milli seconds"); return; } rdd.foreachPartition(itr -&gt; { Integer partnId = TaskContext.get().partitionId(); Long systime = System.nanoTime(); Map&lt;String, String&gt; hmap = new HashMap&lt;String, String&gt;(); GenericLogic ec2 = new GenericLogic(); ec2.setDefaultProperties(); ec2.DBConnect(); try { while (itr.hasNext()) { System.out.println("232"); } } catch (Exception e) { logger.error(e.getMessage(), e); } }); }); jsc.start(); jsc.awaitTermination(); } } </code></pre>
<p>Can you please let us know OS of all the nodes and if you have ensured that noting on Master node is exporting the HOSTNAME. Answering your question will be better if you let us know about your OS detail.</p> <p>May not be correctly related to your context but just for information System.getenv("HOSTNAME") may not provide hostname in all the platforms (for example Ubuntu or Mac). </p> <p>Better is why not export the HOSTNAME. </p> <p>Note: I am assuming you have already checked that props is not null or empty? If not debug and check whether properties files is loaded or not and if loaded it is not the empty properties file and hence it has loaded the properties from the file. </p> <p>Looking at your problem (not only environment variable but properties are also not returning, there may be something wrong with properties file or its relative location on different computers. If it is not exact copy which is placed at different computers, please also check if it is a file good for Linux (not written and edited in windows and put in linux).</p>
How can i fix this error in expressjs <p>i'm using expressjs with jade. I'm trying to do a factorial with an input, but i can't display the answer for example if i input 5 the result is 120, but display a big error. How can i make this? Please can you help me? <a href="https://i.stack.imgur.com/r0nGw.png" rel="nofollow">error</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>routes/index.js var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index.jade', { title: 'Express' }); }); router.get('/factorial', function(req, res, next) { res.render('factorial.jade', { title: 'Factorial' }); }); module.exports = router;</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>views/factorial extends layout block content h1= title p Welcome to #{title} p Ingrese un numero form(method="POST", action="/factorial", name="myForm",onsubmit='return validateForm()') input(type='number', name='numero') input(type='submit', value='Enviar')</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;strong&gt;archive app.js&lt;/strong&gt; var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); //agregado var bodyParser = require('body-parser'); var engine = require('ejs-mate'); var routes = require('./routes/index'); var users = require('./routes/users'); var app = express(); // instruct the app to use the `bodyParser()` middleware for all routes app.use(bodyParser()); // view engine setup app.engine('ejs', engine); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'bower_components'))); app.use('/', routes); app.use('/users', users); app.post('/factorial', function(req, res) { var num=req.body.numero; dd(num); for(var i=1;i&lt;=num;i++) i=i*num; res.send('/factorial'+i); }); // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;</code></pre> </div> </div> </p>
<p>I can see at least one mistake: </p> <pre><code>res.send(/factorial + i) </code></pre> <p>isn't in any known way of sending an answer, and probably is the cause of the error . In fact the errro is telling you that you send an invalid result code (45), probably becuase interprets the first char of your response (/) as return code, as yor're not providing the correct response headers</p> <p>Also, except the ddd(num) call is something magic you algorythm for calculating a factorial isn't correct. Supose you send a 5, (result should be <strong>5*4*3*2*1 =120</strong>). Then</p> <ul> <li><p>loop pass it retuns 1</p></li> <li><p>loop pass it retuns 10 </p></li> <li><p>and exits because i is currently bigger than 5</p></li> </ul> <p>a numerically working version could be:</p> <pre><code>app.post('/factorial', function(req, res) { var num=req.body.numero; dd(num); // &lt;&lt; dont know what it does function fact(n) { if (n &lt; 2) return n else return n*fact(n-1) } var result = fact(num) ... }); </code></pre> <p>For correctly send the result, you should read the related docs. Too long to answer here</p>
How to modify an existing Google Maps marker in an iOS app? <p>I have a small problem. When the user searches for an address, if it exists I zoom to the marker and then I want to give it a different color. I am trying to use this :<a href="https://developers.google.com/maps/documentation/ios-sdk/marker" rel="nofollow">https://developers.google.com/maps/documentation/ios-sdk/marker</a> but can't seems to succeed.</p> <p>Here I put all the markers on the map:</p> <pre><code>PFQuery *query = [PFQuery queryWithClassName:@"Test2"]; [query selectKeys:@[@"googlid"]]; [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { if (!error) { NSLog(@" objects : %@", objects); for (NSDictionary *dic in objects) { NSString *placeID = [dic valueForKey:@"googlid"]; _placesclient = [[GMSPlacesClient alloc] init]; [_placesclient lookUpPlaceID:placeID callback:^(GMSPlace *place, NSError *error) { if (error != nil) { NSLog(@"Place Details error %@", [error localizedDescription]); return; } if (place != nil) { GMSMarker *marker = [[GMSMarker alloc] init]; marker.position = CLLocationCoordinate2DMake( place.coordinate.latitude, place.coordinate.longitude); marker.title = place.name; marker.snippet = @"Push to see feedbacks"; marker.map = _mapview; } else { NSLog(@"No place details for %@", placeID); } }]; } </code></pre> <p>Here I try to modify the marker:</p> <pre><code> if (exist) { UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *exist = [UIAlertAction actionWithTitle:@"Place exist" style:UIAlertActionStyleDefault handler:nil]; GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:place.coordinate.latitude longitude:place.coordinate.longitude zoom:15]; self.mapview.camera = camera; _targetMarker = [GMSMarker markerWithPosition:CLLocationCoordinate2DMake( place.coordinate.latitude, place.coordinate.longitude)]; _targetMarker.map = _mapview; _targetMarker.icon = [GMSMarker markerImageWithColor:[UIColor blackColor]]; </code></pre>
<p>Try this..</p> <pre><code>_targetMarker.icon = [UIImage imageNamed:@"marker-icon"]; </code></pre> <p><strong>Note: Marker must be initialised.</strong></p>
Java enum pass as an constructor <p>I am trying to pass a reference of an enum type from a constructor to test some lambdas, method reference, and <code>Stream</code>s. When I try to instantiate the class I am getting a error on the enum. </p> <pre><code>public class Book { private String title; private List&lt;String&gt; authors; private int pageCount[]; private Year year; private double height; private Topic topic; public Book (String title, ArrayList&lt;String&gt; author, int pageCount [], Year year, double height, Topic topic ) { this.title = title; this.authors = author; this.pageCount = pageCount; this.topic = topic; this.year = year; this.height = height; } public enum Topic { MEDICINE, COMPUTING, FICTION, HISTORY } public String getTitle(){ return title; } public List&lt;String&gt; getAhuthors(){ return authors; } public int [] getPageCounts(){ return pageCount; } public Topic getTopic() { return topic; } public Year getPubDate(){ return year; } public double getHeight() { return height; } public static void main(String args [] ) { Book nails = new Book("Fundamentals of Chinese Fingernail image", Arrays.asList("Li", "Fun", "Li"), new int [] {256}, Year.of(2014), 25.2, COMPUTING); Topic test = Topic.COMPUTING; System.out.println(test); } } </code></pre> <p>this is what I am getting :</p> <pre><code>Exception in thread "main" java.lang.Error: Unresolved compilation problem: COMPUTING cannot be resolved to a variable at Book.main(Book.java:70) </code></pre>
<p>Replace </p> <pre><code>Book nails = new Book("Fundamentals of Chinese Fingernail image", Arrays.asList("Li", "Fun", "Li"), new int [] {256}, Year.of(2014), 25.2, COMPUTING); </code></pre> <p>by</p> <pre><code>Book nails = new Book("Fundamentals of Chinese Fingernail image", Arrays.asList("Li", "Fun", "Li"), new int [] {256}, Year.of(2014), 25.2, Topic.COMPUTING); </code></pre> <p>EDIT:</p> <p>Like @Voltboyy pointed out, you must change qhat i pointed out before and replace the <code>ArrayList&lt;String&gt;</code> in the constructor to <code>List&lt;String&gt;</code> like this:</p> <pre><code>public Book(String title, List&lt;String&gt; list, int pageCount[], Year year, double height, Topic topic) { this.title = title; this.authors = list; this.pageCount = pageCount; this.topic = topic; this.year = year; this.height = height; } </code></pre> <p>and you program will work.</p>
Three.js change rotation on click <p>I want to change/start an animated rotation of an object when I click a button. I understand that the render funciton is an infinite loop and that cylinder.rotation.x += 0.1 adds up the angle and makes the thing go round. I want to change start this parameter using a button. So far I only managed to add to the rotation once, while the button is clicked. Maybe the working example will explain better:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;3D Cube&lt;/title&gt; &lt;style&gt; canvas { width: 100%; height: 100% } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;script src="three.js"&gt;&lt;/script&gt; &lt;script&gt; var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000); var renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); var cylindergeometry = new THREE.CylinderGeometry(0.1, 0.1, 2, 50, false); var cylindermaterial = new THREE.MeshLambertMaterial({wireframe: true, color: 0x000000}); var cylinder = new THREE.Mesh(cylindergeometry, cylindermaterial); cylinder.position.set(0,0,0); scene.add(cylinder); camera.position.z = 5; var render = function () { requestAnimationFrame(render); cylinder.rotation.x = 0.1; renderer.render(scene, camera); }; render(); var btn = document.createElement("BUTTON"); var t = document.createTextNode("CLICK ME"); btn.appendChild(t); document.body.appendChild(btn); btn.onclick=function(){ // start animation // change cylinder.rotation.x = 0.1; to cylinder.rotation.x += 0.1; }; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>Just move <code>render()</code> inside <code>onclick</code>.</p> <pre><code>var render = function () { requestAnimationFrame(render); cylinder.rotation.x += 0.1; renderer.render(scene, camera); }; btn.onclick = function() { render(); }; </code></pre> <p>This works for your specific problem, but probably isn't a good solution if you wanted to do more complicated logic. Instead, you could separate the rendering and cylinder logic into something like this:</p> <pre><code>/* global render function */ var render = function() { requestAnimationFrame(render); renderer.render(scene, camera); }; render(); /* cylinder rotation logic */ var rotateCylinder = function() { requestAnimationFrame(rotateCylinder); cylinder.rotation.x += 0.1; }; /* start the rotation */ btn.onclick = function() { rotateCylinder(); }; </code></pre> <p>This is totally off the top of my head and might have its own drawbacks.</p>
Empty If Optimization <p>Consider the following:</p> <pre class="lang-c prettyprint-override"><code>int status = 0; while(status &lt; 3) { switch(status) { case 0: // Do something break; case 1: if(cond1 &amp;&amp; cond2 || cond3 &amp;&amp; cond4) ; // status = 1 else if(cond5) status = 2; else status = 0; // there could be more else-if statements break; case 2: // Do something else break; } status++; } </code></pre> <p>Given that the first if-statement is only there for the sake of readability and that, as showed, its body is empty (because redundant), I was wondering how could a compiler (either a ahead-of-time or just-in-time compiler) possibly optimize this (if any optimization is possible).</p>
<p>For a general purpose compiler, the answer is no.</p> <p>Two optimizations that are closely related however, are the <a href="https://en.wikipedia.org/wiki/Optimizing_compiler#Data-flow_optimizations" rel="nofollow">Data flow optimizations</a>, which aims to eliminate double calculations and impossible paths in code. Another is <a href="https://en.wikipedia.org/wiki/Currying" rel="nofollow">Currying</a>, which aims to optimize a general function with regards to the specific parameter.</p>
Clean # symbol from Json object in Javascript <p>I have this json string, turned into a Javascript object which on one of its levels returns something like this</p> <pre><code>"link": { "#tail": "\n\n\t\t", "#text": "http://static2.server.com/file.mp3" }, </code></pre> <p>I need to get the value of "text" on Javascript but the "#" symbol is making it imposible to access it.</p> <p>I have tried cleaning the string like this:</p> <pre><code>var myJSONString = JSON.stringify(response); var myEscapedJSONString = myJSONString.replace(/[^\u0000-\u007F]+/g, "").replace("#","t"); </code></pre> <p>But it does not clean the "key" part, even after it has been turned into a string using stringify.</p>
<p>What about stripping out the <code>#</code>s before you use the object?</p> <pre><code>function stripHashes(obj) { var strippedObj = {}; Object.keys(obj).forEach(function(key) { strippedObj[key.substr(1)] = link[key]; }); return strippedObj; } </code></pre> <p>This will return a new object with the hashes stripped from the input object's keys.</p>
Upload multiple files in angularjs and backend using laravel (without form tag) <p>I want to upload multiple files without using form tag and using angular js and i am using laravel 5.2. Below code i tried sending only 1 file it works but on multiple files it fails.</p> <p>HTML Code</p> <pre><code>&lt;input type="file" class="upload_file pull-right" multiple /&gt; </code></pre> <p>JQuery Code</p> <pre><code>$(".upload_file").change(function () { if (this.files &amp;&amp; this.files.length &gt; 0) { scope.uploadFile(this.files); } }); </code></pre> <p>AngularJs Code</p> <pre><code>scope = $scope; $scope.uploadFile = function(files) { var fd = new FormData(); fd.append("file", files); $http.post(API_URL + '/offline_upload/file/?token=' + token,fd, { withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: angular.identity }) .success(function(data) { alert('Done'); }); }; </code></pre> <p>Laravel PHP Code</p> <pre><code>$files = $request-&gt;file('file'); Log::info(count($files)); </code></pre> <p>Here the count is always 0</p> <p>In angularjs instead of files if i send files[0] then only 1 file is sent. But how to send multiple files and retrieve it.</p> <p>Can someone please help me solve this issue.</p>
<p>You can try that with <a href="https://github.com/nervgh/angular-file-upload" rel="nofollow">https://github.com/nervgh/angular-file-upload</a>, it supports input type file with multiple parameter and you don't need jquery.</p> <p>You just instate new uploader object: <code>$scope.uploader = new FileUploader({var options;});</code> and put directive into upload form <code>&lt;input type="file" nv-file-select uploader="uploader"/&gt;</code> inside your html.</p>
Azure Worker role and blob storage c# - Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (400) Bad Request <p>I have uploaded files in blob storage. I am trying to download those files from worker role to do some processing on it. The container name is sent from the WebApi2 to the queue. </p> <p>The worker role first fetches the container name from the queue and then tries to download the blobs within that container.</p> <p>Below is the code for the name:</p> <pre><code> public override void Run() { Trace.WriteLine("Starting processing of messages"); // Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump. Client.OnMessage((receivedMessage) =&gt; { try { // Process the message Trace.WriteLine("Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString()); string msg = "Container Name: " + receivedMessage.GetBody&lt;String&gt;(); Trace.WriteLine("Processing Service Bus message: " + msg); CloudStorageAccount storageAccount = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting("MyStorage")); CloudBlobContainer imagesContainer = null; CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); imagesContainer = blobClient.GetContainerReference(msg); // Create the container if it doesn't already exist. imagesContainer.CreateIfNotExists(); imagesContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); var blobs = imagesContainer.ListBlobs(); var listOfFileNames = new List&lt;string&gt;(); foreach (var blob in blobs) { var blobFileName = blob.Uri.Segments.Last(); listOfFileNames.Add(blobFileName); Trace.WriteLine(listOfFileNames); } if (listOfFileNames == null) { Trace.WriteLine("present"); } for (i = 1; i &lt; 3; i++) { CloudBlockBlob signBlob = imagesContainer.GetBlockBlobReference(i + ".txt"); MemoryStream lms = new MemoryStream(); signBlob.DownloadToStream(lms); lms.Seek(0, SeekOrigin.Begin); StreamReader SR = new StreamReader(lms); Trace.WriteLine(SR); } } catch(Microsoft.WindowsAzure.Storage.StorageException e) { // Handle any message processing specific exceptions here Trace.WriteLine("Error:" + e); } }); CompletedEvent.WaitOne(); } </code></pre> <p>I am getting the below Exception:</p> <pre><code>enter code hereException thrown: 'Microsoft.WindowsAzure.Storage.StorageException' in Microsoft.WindowsAzure.Storage.dll </code></pre> <p>Error:Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (400) Bad Request. ---> System.Net.WebException: The remote server returned an error: (400) Bad Request. at System.Net.HttpWebRequest.GetResponse() at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand<code>1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 677 --- End of inner exception stack trace --- at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand</code>1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 604 at Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer.CreateIfNotExists(BlobContainerPublicAccessType accessType, BlobRequestOptions requestOptions, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlobContainer.cs:line 199 at WorkerRoleWithSBQueue1.WorkerRole.b__4_0(BrokeredMessage receivedMessage)</p> <p>Any help would be highly appreciated.</p>
<p>Looking at your code, you're doing the following:</p> <pre><code>string msg = "Container Name: " + receivedMessage.GetBody&lt;String&gt;(); </code></pre> <p>And then you're doing the following:</p> <pre><code> imagesContainer = blobClient.GetContainerReference(msg); // Create the container if it doesn't already exist. imagesContainer.CreateIfNotExists(); </code></pre> <p>So basically you're creating a container name of which starts with <code>Container Name</code> which is an invalid value for the container name. This is why you're getting the error.</p> <p>Please see this link for valid naming convention for blob container: <a href="https://msdn.microsoft.com/en-us/library/azure/dd135715.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/azure/dd135715.aspx</a>.</p>
async/await in ASP.NET with synchronous Sql Server connection <p>Is there any real benefit of using async/await in an ASP.NET application if the only I/O calls are to a backend SQL Server database that is not using the ASYNC parameter in its connection string? </p>
<p>Most likely, <code>async</code> is not going to help you in your situation (that is, with a single SQL Server instance). This is assuming that most (or all) I/O-bound ASP.NET requests hit the database.</p> <p>As I stated in my <a href="https://msdn.microsoft.com/en-us/magazine/dn802603.aspx" rel="nofollow">intro to <code>async</code> on ASP.NET article</a>:</p> <blockquote> <p>A decade ago, a common architecture was to have one ASP.NET Web server that talked to one SQL Server database back end. In that kind of simple architecture, usually the database server is the scalability bottleneck, not the Web server. Making your database calls asynchronous would probably not help; you could certainly use them to scale the Web server, but the database server will prevent the system as a whole from scaling.</p> </blockquote> <p>In contrast, for Azure SQL (or even SQL Server clusters), <code>async</code> on ASP.NET may be beneficial. For even more scalable backends (NoSQL or web APIs), <code>async</code> is even more likely to be beneficial.</p>
How to input and compare a string <p>I'm new to C and I need help. This code doesn't work, even if I type London into the input I recieve the message from else: "Try again".</p> <pre><code>int main() { char capitalCity; scanf("%s", &amp;capitalCity); if (capitalCity == 'London'){ printf("Is the capital city of UK."); } else{ printf("Try again."); } return 0; } </code></pre>
<p>There is no <code>string</code> data type in C programming language. <code>Strings</code> in C are represented as array of characters.</p> <p>In C, <code>char</code> is a data type to represent a character (<strong>char</strong> in C represents the character type, suitable for storing a simple character—traditionally one from the ASCII encoding.). So, all you need to do is declare a array of char data type to represent a <code>string</code> in C. Each element in that array will hold a character of your string.</p> <p>Also, operators in C like ==, !=, +=, + are defined for build-in data types in C and since, there is no operator overloading in C, you can't use these operators with your C-String as C-Strings are not build-in data type in C programming language.</p> <p>Note: C-Strings are actually Null-terminated array of char data types. That means, last character in any C-String in C will be used to store a Null Character ('\0') which marks the end of the string.</p> <p>The Header file has predefined functions that you can use to operate on C-String(Null-terminated array of char data type). You can read more about it over here.</p> <p>So, your program should look like:</p> <pre><code>#define MAX_CSTR_LEN 100 int main() { char capitalCity[MAX_CSTR_LEN + 1]; ///An extra position to store Null Character if 100 characters are to be stored in it. scanf("%s", capitalCity); // Use strcmp to compare values of two strings. // If strcmp returns zero, the strings are identical if (strcmp(capitalCity, "London") == 0) { printf("Is the capital city of UK."); } else { printf("Try again."); } return 0; } </code></pre> <p>Also, you have to use single quotes for character literals and double quotes for strings in C.</p>
can synchronized at method level be replaced by Lock? <p>When writing a thread safe class, we use <code>synchronized</code> keyword at two places in code, </p> <p>1.Method level synchronization</p> <p>2.Synchronized blocks</p> <p>As far as I can think of, interfaces like <code>Lock</code> (<code>java.util.concurrent.locks.Lock</code>)can be used in place of <code>synchronized</code>only at block level but not at method level. or is there a way? </p> <p>I don't have any real need of it but just curios since heard discussions that <code>Lock</code>can be a replacement for <code>synchronized</code>. </p> <pre><code>public class SampleClass { public synchronized void method(){ ..... } } </code></pre>
<p>There is no special syntax for "acquire the Lock at the beginning of the method, and release it at the end," like there is for <code>synchronized</code>.</p> <p>You can, of course, just do that yourself:</p> <pre><code>public void method() { lock.lock(); try { // rest of the method } finally { lock.unlock(); } } </code></pre>
Converting factor value to new variable which stores count of how many times it occured in the factor <p>I have ATP data set from kaggle. I am working on it in R.In the data set I have various variables like match date, city, tournament name, winner name, loser name, total set won by match winner, total set won by match loser, total games won by winner, total games won by loser and so on.</p> <p>My attention is on match winner and match loser columns. These columns are factor variables which have the value of player name.</p> <p>Now what I want is to plot a graph of match win-loss ratio for different player(say top 5 or top 10 players having highest win-loss ratio) where the x-axis represents the name of player and y-axis represents the win-loss ratio of that player.</p> <p>How do I create this specific graph. I have tried using pipe lining in dplyr package as follows: Winner and Loser are factorial variables.</p> <pre><code>roger_wins &lt;- atp %&gt;% filter(Winner == "Federer R.") %&gt;% count(Winner) roger_loss &lt;- atp %&gt;% filter(Loser == "Federer R.") %&gt;% count(Loser) </code></pre> <p>But using this way it has to be hard coded for each player. How to I do this using code for top 5 or top 10 players(according to win-loss) Please provide the solution in R. This is the page where the data set can be found: <a href="https://www.kaggle.com/jordangoblet/atp-tour-20002016" rel="nofollow">https://www.kaggle.com/jordangoblet/atp-tour-20002016</a></p>
<p>If I understand your problem, you can do something like this:</p> <ol> <li>Use the <strong>table</strong> function to colapse the data</li> <li>Then you can use the <strong>apply</strong> function over the output of the first point</li> </ol>
Codeigniter send mail with gmail smtp on localhost <p>I know that question has a couple of duplicates but I think I've tried them all.</p> <p>My mail is never send calling it with the following settings:</p> <pre><code>$config = Array( 'protocol' =&gt; 'smtp', 'smtp_host' =&gt; 'smtp.gmail.com', //'smtp_host' =&gt; 'localhost', 'smtp_port' =&gt; 465, 'mailpath' =&gt; 'C:\xampp\sendmail', // tried without sendmail 'smtp_user' =&gt; 'correct email', 'smtp_pass' =&gt; 'correct pass', 'mailtype' =&gt; 'html', 'charset' =&gt; 'utf-8', 'starttls' =&gt; true, // changing makes no difference 'smtp_crypto' =&gt;'ssl', // tried without ssl on port 25 as wel, google not responding '_smtp_auth' =&gt; true // tried removing this ); $this-&gt;load-&gt;library('email', $config); $this-&gt;email-&gt;from('tkd.tongil.neeroeteren@gmail.com', 'Tong-Il Neeroeteren'); //verzender (magic e-cards) $this-&gt;email-&gt;to($email); //ontvanger $this-&gt;email-&gt;subject($subject); //onderwerp toevoegen //inhoud van het bericht met activatiecode als link. $this-&gt;email-&gt;message($message); if (!$this-&gt;email-&gt;send()) { $errors = $this-&gt;email-&gt;print_debugger(); return false; } else { return true; } </code></pre> <p>The message in $errors is always the same:</p> <pre><code>220 smtp.gmail.com ESMTP h11sm1190535ljh.15 - gsmtp &lt;br /&gt;&lt;pre&gt;hello: 250-smtp.gmail.com at your service, [2a02:1810:9d16:bf00:eda1:6150:23ed:ba70] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING 250 SMTPUTF8 &lt;/pre&gt;Failed to authenticate password. Error: 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8 https://support.google.com/mail/?p=BadCredentials h11sm1190535ljh.15 - gsmtp &lt;br /&gt;&lt;pre&gt;from: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1 https://support.google.com/mail/?p=WantAuthError h11sm1190535ljh.15 - gsmtp &lt;/pre&gt;The following SMTP error was encountered: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1 https://support.google.com/mail/?p=WantAuthError h11sm1190535ljh.15 - gsmtp &lt;br /&gt;&lt;pre&gt;to: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1 https://support.google.com/mail/?p=WantAuthError h11sm1190535ljh.15 - gsmtp &lt;/pre&gt;The following SMTP error was encountered: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1 https://support.google.com/mail/?p=WantAuthError h11sm1190535ljh.15 - gsmtp &lt;br /&gt;&lt;pre&gt;data: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1 https://support.google.com/mail/?p=WantAuthError h11sm1190535ljh.15 - gsmtp &lt;/pre&gt;The following SMTP error was encountered: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1 https://support.google.com/mail/?p=WantAuthError h11sm1190535ljh.15 - gsmtp &lt;br /&gt;502 5.5.1 Unrecognized command. h11sm1190535ljh.15 - gsmtp &lt;br /&gt;The following SMTP error was encountered: 502 5.5.1 Unrecognized command. h11sm1190535ljh.15 - gsmtp &lt;br /&gt;Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.&lt;br /&gt;&lt;pre&gt;User-Agent: CodeIgniter Date: Mon, 10 Oct 2016 19:34:18 +0200 From: "Tong-Il Neeroeteren" &lt;tkd.tongil.neeroeteren@gmail.com&gt; Return-Path: &lt;tkd.tongil.neeroeteren@gmail.com&gt; To: robbie.vercammen@gmail.com Subject: =?utf-8?Q?Activeer_uw_account?= Reply-To: "tkd.tongil.neeroeteren@gmail.com" &lt;tkd.tongil.neeroeteren@gmail.com&gt; X-Sender: tkd.tongil.neeroeteren@gmail.com X-Mailer: CodeIgniter X-Priority: 3 (Normal) Message-ID: &lt;57fbd11ad5a9f@gmail.com&gt; Mime-Version: 1.0 Content-Type: multipart/alternative; boundary=&amp;quot;B_ALT_57fbd11ad5b41&amp;quot; This is a multi-part message in MIME format. Your email application may not support this format. --B_ALT_57fbd11ad5b41 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit // Too much info --B_ALT_57fbd11ad5b41 Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: quoted-printable // Too much info --B_ALT_57fbd11ad5b41--&lt;/pre&gt; </code></pre> <p>My php.ini</p> <pre><code>[mail function] SMTP=ssl://smtp.gmail.com smtp_port=465 sendmail_from = tkd.tongil.neeroeteren@gmail.com sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t" mail.add_x_header=On </code></pre> <p>And my sendmail.ini</p> <pre><code>smtp_server=smtp.gmail.com smtp_port=465 smtp_ssl=auto auth_username=correct email auth_password=correct password force_sender=tkd.tongil.neeroeteren@gmail.com </code></pre> <p>I have enabled less secure access and tried the unlock captcha method to no avail. How do I get this working for localhost.</p> <p>I'm also at a loss at how to configure this once it's been deployed to my hosted domain. Any help would be appreciated</p>
<p>I found the answer...</p> <p>This is what I ended up using</p> <pre><code>$config = Array( "protocol" =&gt; "smtp", "smtp_host" =&gt; "smtp.gmail.com", //"smtp_host" =&gt; "localhost", "smtp_port" =&gt; 587, "mailpath" =&gt; "C:\\xampp\\sendmail", "smtp_user" =&gt; "", "smtp_pass" =&gt; "", "mailtype" =&gt; "html", "charset" =&gt; "ISO-8859-1", "starttls" =&gt; true, "smtp_crypto" =&gt;"tls", "smpt_ssl" =&gt; "auto", "send_multipart"=&gt; false ); $this-&gt;load-&gt;library('email', $config); $this-&gt;email-&gt;set_newline("\r\n"); // rest remains the same </code></pre> <p>I believe <code>$this-&gt;email-&gt;set_newline("\r\n");</code> was the missing link. Why there was no other error message except authentication failed... we shall never know.</p>
CGRect init error in swift3 <p>The following code returns a couple of compiler errors after converting to swift3:</p> <pre><code>override init(frame: CGRect) { //Initializer does not override a designated initializer from its superclass super.init(frame: frame) //Must call a designated initializer of the superclass 'MKAnnotationView' } </code></pre> <p>How do I go about fixing this?</p>
<p>I am guessing (from the comment in your code) that you are trying to create a subclass of MKAnnotationView. If thats true, try this.</p> <pre><code>class myAnnot : MKAnnotationView{ override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } </code></pre>
How do I parse complex XML file using DOM? <p>How do I parse complex XML file using DOM ? I need to access each child of grade but I am getting all the classes within xml files.How do I access grade , child , student and teacher elements . </p> <pre><code>public SchoolM readFileNBuildModel(String filePath) { File file = new File(filePath); if (file.exists()) { AppLauncher.getLog().log(Level.INFO, " File Exist : " + filePath,filePath); try { AppLauncher.getLog().log(Level.INFO, " Parsing File : " + filePath,filePath); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder; documentBuilder = dbf.newDocumentBuilder(); Document doc = documentBuilder.parse(file); doc.getDocumentElement().normalize(); Element schoolNode = doc.getDocumentElement(); NodeList gradeList = doc.getElementsByTagName("grade"); SortedSet&lt;GradeM&gt; gradeSet = new TreeSet&lt;GradeM&gt;(); for (int temp = 0; temp &lt; gradeList.getLength(); temp++) { Node gradeNode = gradeList.item(temp); Element gradeElemet = (Element) gradeNode; GradeM gradeM = new GradeM(gradeElemet.getAttribute("id")); SortedSet&lt;ClassM&gt; classSet = new TreeSet&lt;ClassM&gt;(); NodeList classList = doc.getElementsByTagName("classroom"); for (int classIndex = 0; classIndex &lt; classList.getLength(); classIndex++) { Node classNode = classList.item(classIndex); Element classElement = (Element) classNode; ClassM classM = new ClassM(classElement.getAttribute(CSVColumnAttributeEnum.CLASSROOM_ID.getXmlMapColumnName()), classElement.getAttribute(CSVColumnAttributeEnum.CLASSROOM_NAME.getXmlMapColumnName())); SortedSet&lt;TeacherM&gt; teacherSet = new TreeSet&lt;TeacherM&gt;(); SortedSet&lt;StudentM&gt; studentSet = new TreeSet&lt;StudentM&gt;(); NodeList teacherList = doc.getElementsByTagName("teacher"); NodeList studentList = doc.getElementsByTagName("student"); for (int studentIndex = 0; studentIndex &lt; studentList.getLength(); studentIndex++) { Node studentNode = studentList.item(studentIndex); Element studentElement = (Element) studentNode; if(studentElement != null){ StudentM studentM = new StudentM(studentElement.getAttribute(CSVColumnAttributeEnum.STUDENT_ID.getXmlMapColumnName()), studentElement.getAttribute(CSVColumnAttributeEnum.STUDENT_FIRST_NAME.getXmlMapColumnName()), studentElement.getAttribute(CSVColumnAttributeEnum.STUDENT_LAST_NAME.getXmlMapColumnName()), studentElement.getAttribute(CSVColumnAttributeEnum.STUDENT_GRADE.getXmlMapColumnName())); studentSet.add(studentM); } } for (int teacherIndex = 0; teacherIndex &lt; teacherList.getLength(); teacherIndex++) { Node teacherNode = teacherList.item(classIndex); Element teacherElement = (Element) teacherNode; if(teacherElement != null){ TeacherM teacherM = new TeacherM(teacherElement.getAttribute(CSVColumnAttributeEnum.TEACHER1_ID.getXmlMapColumnName()), teacherElement.getAttribute(CSVColumnAttributeEnum.TEACHER1_LAST_NAME.getXmlMapColumnName()), teacherElement.getAttribute(CSVColumnAttributeEnum.TEACHER1_FIRST_NAME.getXmlMapColumnName())); teacherSet.add(teacherM); } } classM.setStudentSet(studentSet); classM.setTeacherSet(teacherSet); classSet.add(classM); } gradeM.setClassSet(classSet); gradeSet.add(gradeM); } SchoolM schoolM = new SchoolM(schoolNode.getAttribute("id"), schoolNode.getAttribute("schoolName"),gradeSet); return schoolM; } catch (ParserConfigurationException e) { AppLauncher.getLog().log(Level.SEVERE, " File Conversion failed because of : /n" + e.toString()); } catch (SAXException e) { AppLauncher.getLog().log(Level.SEVERE, " File Conversion failed because of : /n" + e.toString()); } catch (IOException e) { AppLauncher.getLog().log(Level.SEVERE, " File Conversion failed because of : /n" + e.toString()); } }else{ AppLauncher.getLog().log(Level.WARNING, " File Does Not Exist : " + filePath,filePath); } return new SchoolM(); </code></pre> <p>XML Files:</p> <p></p> <pre><code>&lt;grade id="1"&gt; &lt;classroom id="101" name="Mrs. Jones' Math Class"&gt; &lt;teacher id="10100000001" first_name="Barbara" last_name="Jones"/&gt; &lt;student id="10100000010" first_name="Michael" last_name="Gil"/&gt; &lt;student id="10100000011" first_name="Kimberly" last_name="Gutierrez"/&gt; &lt;student id="10100000013" first_name="Toby" last_name="Mercado"/&gt; &lt;student id="10100000014" first_name="Lizzie" last_name="Garcia"/&gt; &lt;student id="10100000015" first_name="Alex" last_name="Cruz"/&gt; &lt;/classroom&gt; &lt;classroom id="102" name="Mr. Smith's PhysEd Class"&gt; &lt;teacher id="10200000001" first_name="Arthur" last_name="Smith"/&gt; &lt;teacher id="10200000011" first_name="John" last_name="Patterson"/&gt; &lt;student id="10200000010" first_name="Nathaniel" last_name="Smith"/&gt; &lt;student id="10200000011" first_name="Brandon" last_name="McCrancy"/&gt; &lt;student id="10200000012" first_name="Elizabeth" last_name="Marco"/&gt; &lt;student id="10200000013" first_name="Erica" last_name="Lanni"/&gt; &lt;student id="10200000014" first_name="Michael" last_name="Flores"/&gt; &lt;student id="10200000015" first_name="Jasmin" last_name="Hill"/&gt; &lt;student id="10200000016" first_name="Brittany" last_name="Perez"/&gt; &lt;student id="10200000017" first_name="William" last_name="Hiram"/&gt; &lt;student id="10200000018" first_name="Alexis" last_name="Reginald"/&gt; &lt;student id="10200000019" first_name="Matthew" last_name="Gayle"/&gt; &lt;/classroom&gt; &lt;classroom id="103" name="Brian's Homeroom"&gt; &lt;teacher id="10300000001" first_name="Brian" last_name="O'Donnell"/&gt; &lt;/classroom&gt; &lt;/grade&gt; </code></pre> <p></p>
<p>Use the <code>getElementsByTagName</code> method on the element you are processing e.g. use <code>gradeElemet.getElementByTagName("classroom")</code> instead of <code>doc.getElementsByTagName("classroom")</code>. Then inside all of your nested loops continue that approach to call the method on the currently processed element and not on the complete document.</p>
how to send a request to Google with curl <p>I work on Linux and try to use <code>curl</code> to send requests to Google and save its reply as a html file.<br></p> <p>When I use Google to search something, such as a string "abc", I find that the link of Google is: <a href="https://www.google.lu/#q=abc" rel="nofollow">https://www.google.lu/#q=abc</a><br></p> <p>So I try like this:<br></p> <pre><code>curl https://www.google.lu/#q=abc -o res.html </code></pre> <p>But the <code>res.html</code> is just the main page of Google, instead of the result of searching "abc".<br></p> <p>How to do it?</p>
<p>Anything after the <code>#</code> is handled client side with JavaScript, which is why it doesn't work with <code>curl</code>.</p> <p>You can instead use the traditional, non-AJAX interface on <code>https://www.google.com/search?q=abc</code></p> <p>It appears to block you unless you also spoof the user agent, so all in all:</p> <pre><code>curl \ -A 'Mozilla/5.0 (MSIE; Windows 10)' \ -o res.html \ https://www.google.com/search?q=abc </code></pre>
Override interface property with constructor parameter with different name <p>I have this code:</p> <pre><code>class AnyUsernamePersistentNodePath(override val value: String) : AnyPersistenceNodePath { override val key = "username" } </code></pre> <p>and </p> <pre><code>interface AnyPersistenceNodePath { val key: String val value: String } </code></pre> <p>So far, so good. Now I want parameter <code>value</code> in the constructor to be named <code>username</code>, instead of <code>value</code>. But, obviously, keep overriding interface's property <code>value</code>. Is that possible in Kotlin?</p> <p>I know that I can do:</p> <pre><code>class AnyUsernamePersistentNodePath(val username: String) : AnyPersistenceNodePath { override val key = "username" override val value = username } </code></pre> <p>but I'd like to avoid it.</p>
<p>You can do what you want simply by removing <code>val</code> from the constructor parameter, so that it is a parameter and not a member. Your final class would be:</p> <pre><code>class AnyUsernamePersistentNodePath(username: String) : AnyPersistenceNodePath { override val key = "username" override val value = username } </code></pre> <p>You cannot otherwise change the name of something that you are truly overriding. But you can pass in the value to be assigned to a member later during construction, as my slightly modified version of your code shows. </p>
Unable to focus ListView <p>Situation: In MVVM pattern, I have some inputbindings on a listview which work only when the listview is focused. However, whenever user clicks, the listview goes out of focus and user is unable to execute the inputbindings.</p> <p>Problem: <strong>I want to bring the focus on the listview (on button click) in a way that the inputbindings work</strong>.</p> <p>What I tried: I tried using attached property IsFocused (where I focus using UIElement.Focus() and/or Keyboard.Focus()) and binding it to a bool variable in the ViewModel which I would set using an ICommand. </p> <p>I also tried a separate example where I can use the System.Windows.Input.Keyboard.Focus(item) method in the code behind (I mean the .xaml.cs file with the same name) to focus the listview and it works! But, I don't know how to implement the similar thing in a ViewModel which is connected using a d:DesignInstance attribute. </p> <p>I believe that the mouseclick event is bubbled up and handled somewhere else which causes the list to unfocus as soon as I click it. Like, if I find a way to set the event as handled that will help, but again I don't know how to do that in a viewmodel. Here is my attached property : </p> <p>FocusExtension.cs</p> <pre><code>public static class FocusExtension { public static bool GetIsFocused(DependencyObject obj) { return (bool)obj.GetValue(IsFocusedProperty); } public static void SetIsFocused(DependencyObject obj, bool value) { obj.SetValue(IsFocusedProperty, value); } public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached( "IsFocused", typeof(bool), typeof(FocusExtension), new UIPropertyMetadata(false, OnIsFocusedPropertyChanged)); private static void OnIsFocusedPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var uie = (UIElement)d; if ((bool)e.NewValue) { uie.Focus(); } } } </code></pre> <p>XAML File: </p> <pre><code> &lt;ListView x:Name="lv" Grid.Column="2" Margin="2" MinWidth="250" Height="400" ToolTip="the List" HorizontalContentAlignment="Stretch" ItemsSource="{Binding ListBindingInVM}" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.CanContentScroll="False" dd:DragDrop.IsDragSource="True" dd:DragDrop.IsDropTarget="True" dd:DragDrop.DropHandler="{Binding }" behaviour:ListViewAutoScroll.AutoScrollToEnd="True" ScrollViewer.VerticalScrollBarVisibility="Visible" &gt; &lt;ListView.Style&gt; &lt;Style TargetType="ListView" &gt; &lt;Setter Property="ViewModels:FocusExtension.IsFocused" Value="{Binding ListFocused, Mode=TwoWay}"&gt;&lt;/Setter&gt; &lt;!--The one below is not clean, but worked. However, list goes out of focus on click. --&gt; &lt;Style.Triggers&gt; &lt;Trigger Property="IsMouseOver" Value="True"&gt; &lt;Setter Property="ViewModels:FocusExtension.IsFocused" Value="True"&gt;&lt;/Setter&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/ListView.Style&gt; &lt;i:Interaction.Triggers&gt; &lt;i:EventTrigger EventName="MouseDown"&gt; &lt;!--This command sets the ListFocused to true--&gt; &lt;i:InvokeCommandAction Command="{Binding BringListToFocus }"&gt;&lt;/i:InvokeCommandAction&gt; &lt;/i:EventTrigger&gt; &lt;/i:Interaction.Triggers&gt; &lt;ListView.InputBindings&gt; &lt;!-- Bindings that don't work when list is not focused--&gt; &lt;KeyBinding Modifiers="Control" Key="C" Command="{Binding CopyCommand}"/&gt; &lt;KeyBinding Modifiers="Control" Key="V" Command="{Binding PasteCommand}"/&gt; &lt;/ListView.InputBindings&gt; &lt;ListView.ContextMenu&gt; &lt;ContextMenu&gt; &lt;MenuItem Header="Copy" Command= "{Binding CopyCommand}"&gt;&lt;/MenuItem&gt; &lt;MenuItem Header="Paste" Command= "{Binding PasteCommand}"&gt;&lt;/MenuItem&gt; &lt;/ContextMenu&gt; &lt;/ListView.ContextMenu&gt; </code></pre>
<p>The focus behavior that you describe is easily implemented from the codebehind, and doing so does not violate the MVVM pattern. Consider Josh Smith's post, below:</p> <p><a href="https://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090097" rel="nofollow">https://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090097</a></p> <blockquote> <p>The use of a ViewModel here makes it much easier to create a view that can display a Customer object and allow for things like an "unselected" state of a Boolean property. It also provides the ability to easily tell the customer to save its state. If the view were bound directly to a Customer object, the view would require a lot of code to make this work properly. In a well-designed MVVM architecture, the codebehind for most Views should be empty, or, at most, only contain code that manipulates the controls and resources contained within that view. Sometimes it is also necessary to write code in a View's codebehind that interacts with a ViewModel object, such as hooking an event or calling a method that would otherwise be very difficult to invoke from the ViewModel itself.</p> </blockquote>
Retrieve Index When Passing Object to Function <p>I'm passing an Object from an array of objects to a function. Is it possible to still retrieve the index number somehow from the object in the function? I'm doing this in javaScript specifically within the controller of AngularJS. </p> <p>For instance</p> <pre><code>var array= [ { name: "name1" }, { name: "name2" } ]; function( passedInObjectFromArray ) { return passedInObjectFromArray.indexVal; } </code></pre>
<p>Yes you can do,</p> <pre><code>$scope.retrieveIndex = function(passedInObjectFromArray){ return array.indexOf(passedInObjectFromArray); } </code></pre>
NetLogo: Multiple colors with the scale-color reporter <p>Is there a way to get the <code>scale-color</code> reporter to work with multiple colors instead of just one? I'm trying to get multiple groups of patches to be different colors instead of being just different shades of the same color.</p> <pre><code>set m (1) loop [ if m &gt; 5000 [stop] let targetedGroup patches with [population = m] ask targetedGroup [set pcolor scale-color [red green blue] population 1 50] set m (m + 1) ] </code></pre>
<p>You can't use <code>scale-color</code> with multiple colors, but you can do that kind of thing with the built-in <a href="https://ccl.northwestern.edu/netlogo/docs/palette.html" rel="nofollow">palette extension</a>. Something like this might do what you want:</p> <pre><code>palette:scale-gradient [[255 0 0] [0 255 0] [0 0 255]] population 1 50 </code></pre>
iterating over object in an array throws Cannot read property of undefined <p>I have two arrays <code>caNCourbeData</code> and <code>caN_1CourbeData</code> , each one contains 12 objects, and they have the same object structure.</p> <p>this is an example of an object :</p> <p><a href="https://i.stack.imgur.com/rrKnx.png" rel="nofollow"><img src="https://i.stack.imgur.com/rrKnx.png" alt="enter image description here"></a></p> <p>So what I want to do is to create a new array (<code>caCourbe</code>) that will contains a list of object as following :</p> <pre><code>{ y : '2016-01', chiffreAffaireN : 1256.92, chiffreAffaireN_1 : -141559.33 } </code></pre> <p><code>chiffreAffaireN</code> from <code>caNCourbeData[i].chiffreAffaire</code> and <code>chiffreAffaireN_1</code> from <code>caN_1CourbeData[i].chiffreAffaire</code>.</p> <p>So I did as the following :</p> <pre><code>var caCourbe = new Array(); caNCourbeData.forEach(function(i, caNCourbeDataElement){ caCourbeElement = new Object(); caCourbeElement.y = '2016-'+(i+1).toLocaleString(undefined, {minimumIntegerDigits: 2, useGrouping:false}); caCourbeElement.chiffreAffaireN = caNCourbeDataElement.chiffreAffaire; caCourbeElement.chiffreAffaireN_1 = caN_1CourbeData[i].chiffreAffaire; caCourbe.push(caCourbeElement); }); </code></pre> <p>but then I get this error :</p> <p><a href="https://i.stack.imgur.com/pwn0n.png" rel="nofollow"><img src="https://i.stack.imgur.com/pwn0n.png" alt="enter image description here"></a></p> <p>in my code I logged <code>caN_1CourbeData</code> and I get the array in the console, but I dont know why I'm getting that is undefined :</p> <p><a href="https://i.stack.imgur.com/Ua8qP.png" rel="nofollow"><img src="https://i.stack.imgur.com/Ua8qP.png" alt="enter image description here"></a></p> <p>How can I solve this ?</p> <h1>Edit 1 :</h1> <p>I tried to use forEach with <code>caN_1CourbeData</code> instead of <code>caNCourbeData</code> since they have the same length as the following :</p> <pre><code>caN_1CourbeData.forEach(function(i, caN_1CourbeDataElement){ caCourbeElement = new Object(); caCourbeElement.y = '2016-'+(i+1).toLocaleString(undefined, {minimumIntegerDigits: 2, useGrouping:false}); caCourbeElement.chiffreAffaireN = caNCourbeData[i].chiffreAffaire; caCourbeElement.chiffreAffaireN_1 = caN_1CourbeDataElement.chiffreAffaire; caCourbe.push(caCourbeElement); }); </code></pre> <p>but I always get the same error and this time in this line : <code>caCourbeElement.chiffreAffaireN = caNCourbeData[i].chiffreAffaire;</code></p> <h1>Edit 2:</h1> <pre><code>var caNCourbeData = [{ "mois": 1, "nbFactures": 2, "nbFacturesReglees": 1, "nbdossiersRealise": 1, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 1256.92, "id": 0 }, { "mois": 2, "nbFactures": 4, "nbFacturesReglees": 2, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 413.00, "id": 1 }, { "mois": 3, "nbFactures": 3, "nbFacturesReglees": 3, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 30.00, "id": 2 }, { "mois": 4, "nbFactures": 0, "nbFacturesReglees": 0, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "id": 3 }, { "mois": 5, "nbFactures": 0, "nbFacturesReglees": 0, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "id": 4 }, { "mois": 6, "nbFactures": 9, "nbFacturesReglees": 1, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 2253.31, "id": 5 }, { "mois": 7, "nbFactures": 0, "nbFacturesReglees": 0, "nbdossiersRealise": 0, "nbContrat": 2, "nbContratConverti": 0, "id": 6 }, { "mois": 8, "nbFactures": 0, "nbFacturesReglees": 0, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "id": 7 }, { "mois": 9, "nbFactures": 0, "nbFacturesReglees": 0, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "id": 8 }, { "mois": 10, "nbFactures": 2, "nbFacturesReglees": 0, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 450.60, "id": 9 }, { "mois": 11, "nbFactures": 0, "nbFacturesReglees": 0, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "id": 10 }, { "mois": 12, "nbFactures": 0, "nbFacturesReglees": 0, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "id": 11 }]; var caN_1CourbeData = [{ "mois": 1, "nbFactures": 36, "nbFacturesReglees": 0, "nbdossiersRealise": 3, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": -141559.33, "id": 0 }, { "mois": 2, "nbFactures": 144, "nbFacturesReglees": 0, "nbdossiersRealise": 23, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 19662.80, "id": 0 }, { "mois": 3, "nbFactures": 39, "nbFacturesReglees": 0, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 10835.42, "id": 0 }, { "mois": 4, "nbFactures": 30, "nbFacturesReglees": 0, "nbdossiersRealise": 2, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 12166.74, "id": 0 }, { "mois": 5, "nbFactures": 73, "nbFacturesReglees": 0, "nbdossiersRealise": 1, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 19391.04, "id": 0 }, { "mois": 6, "nbFactures": 36, "nbFacturesReglees": 0, "nbdossiersRealise": 5, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 23929.57, "id": 0 }, { "mois": 7, "nbFactures": 24, "nbFacturesReglees": 0, "nbdossiersRealise": 1, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 5446.59, "id": 0 }, { "mois": 8, "nbFactures": 24, "nbFacturesReglees": 0, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 3019.31, "id": 0 }, { "mois": 9, "nbFactures": 20, "nbFacturesReglees": 0, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 3178.76, "id": 0 }, { "mois": 10, "nbFactures": 1, "nbFacturesReglees": 0, "nbdossiersRealise": 0, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 10.00, "id": 0 }, { "mois": 11, "nbFactures": 14, "nbFacturesReglees": 0, "nbdossiersRealise": 2, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 6020.56, "id": 0 }, { "mois": 12, "nbFactures": 21, "nbFacturesReglees": 0, "nbdossiersRealise": 6, "nbContrat": 0, "nbContratConverti": 0, "chiffreAffaire": 4709.05, "id": 0 }]; </code></pre>
<p>switch the order of the arguments passed to your forEach callback, index is the second parameter, this works in my console:</p> <pre><code>caN_1CourbeData.forEach(function(caN_1CourbeDataElement, i){ caCourbeElement = new Object(); caCourbeElement.y = '2016-'+(i+1).toLocaleString(undefined, {minimumIntegerDigits: 2, useGrouping:false}); caCourbeElement.chiffreAffaireN = caNCourbeData[i].chiffreAffaire; caCourbeElement.chiffreAffaireN_1 = caN_1CourbeDataElement.chiffreAffaire; caCourbe.push(caCourbeElement); }); </code></pre> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Parameters">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Parameters</a></p>
Update/create a relationship with a specific WHERE clause <p>I have the following tables</p> <pre><code>client -id -name client_additional_info -client_id -content client_additional_type -additional_info_id -description </code></pre> <p>The relationships are</p> <p>client <code>has many</code> client_additional_info</p> <p>client_aditional_info <code>has one</code> client_additional_type</p> <p><strong>What i want to implement</strong></p> <p>Receiving a <code>clint_id</code> and a <code>new_content</code> I want to update if exist (if not exist insert new) <code>client_additional_info::content</code> for the associated <code>client_id</code> WHERE <code>client_addition_type::description</code> equals to <code>sometext</code>.</p>
<p>Try a combination of using join for your SQL query followed by a simple if and else statement. </p>
google word tree chart last child fade away <p>I implemented a word tree from this link <a href="https://developers.google.com/chart/interactive/docs/gallery/wordtree#implicit-and-explicit-word-trees" rel="nofollow">Google explicit word tree example</a></p> <p>All the settings are same, on that link last child is not fading away, but in my implementation its fading away as shown in attached image.</p> <p><a href="https://i.stack.imgur.com/ILqIb.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/ILqIb.jpg" alt="enter image description here"></a></p> <p>As you can see "wk9" on top right corner, only half string is shown and also no tool tip popup as it does on others. Anything to pass in options? read documentation found nothing.</p> <blockquote> <p>When I set width to 3000 in options, complete tree is loading, but this will cause problem as width is always 3000 irrespective of chart, any way to dynamically change the width would be helpful. I want the chart to overflow, only when necessary.</p> </blockquote>
<p>You need to set a higher width. As you can see on this example:</p> <p><a href="https://jsfiddle.net/pm9knypd/" rel="nofollow">https://jsfiddle.net/pm9knypd/</a></p> <p>if I set the width like this: </p> <pre><code>&lt;div id="wordtree_basic" style="width: 300px; height: 500px;"&gt;&lt;/div&gt; </code></pre> <p>it fades away at the middle. Its part of the implementation. Just set a higher width</p>
Exchanging out specific lines of a file <p>I don't know if this should be obvious to the more tech savvy among us but is there a specific way to read a line out of a text file, then edit it and insert it back into the file in the original location? I have looked on the site but all the solutions I find seem to be for python 2.7. </p> <p>Below is an example of what I am looking for:</p> <pre><code> with open example.txt as file: for line in file: if myline in file: file.edit("foo","fah") </code></pre>
<p>In 95% cases, replacing data (e.g. text) in a file usually means</p> <ol> <li>Read the file in chunks, e.g. line-by-line</li> <li>Edit the chunk</li> <li>Write the edited chunk to a new file</li> <li>Replace the old file with a new file.</li> </ol> <p>So, a simple code will be:</p> <pre><code>import os with open(in_path, 'r') as fin: with open(temp_path, 'w') as fout: for line in fin: line.replace('foo', 'fah') fout.write(line) os.rename(temp_path, in_path) </code></pre> <p>Why not in-place replacements? Well, a file is a fixed sequence of bytes, and the only way to grow it - is to append to the end of file. Now, if you want to replace the data of the same length - no problems. However if the original and new sequences' lengths differ - there is a trouble: a new sequence will be overwriting the following characters. E.g. </p> <pre><code>original: abc hello abc world replace abc -&gt; 12345 result: 12345ello 12345orld </code></pre>
What's "watermark" in VSTS <p>I'm looking at doing some queries in VSTS. I see a "watermark" field. It looks like it's some kind of ID, but I can't figure out what it means. Does anyone know?</p>
<p>Yes, it likes a revision number. The difference is that, the revision increase in work item level while the watermark increase in collection level.</p> <p>For example, you have two workitems:</p> <blockquote> <p>WorkitemA rev:1 watermark: 1</p> <p>WorkitemB rev:1 watermark: 2</p> </blockquote> <p>When you update WorkitemA and save it, you will get:</p> <blockquote> <p>WorkitemA rev:2 watermark: 3</p> <p>WorkitemB rev:1 watermark: 2</p> </blockquote>
Could not find gem 'refinerycms-disqus (~> 0.0.1) - Ruby <p>I'm Trying to install disqus comments for RefineryCMS-products, first i'm following the steps of <a href="https://github.com/keram/refinerycms-disqus" rel="nofollow">Github</a> , but to add the line gem <code>'refinerycms-disqus', '~&gt; 0.0.1'</code> to the gemfile and run <code>bundle install</code> I get this error <code>Could not find gem 'refinerycms-disqus (~&gt; 0.0.1) x86-mingw32' in any of the gem</code></p> <p>The version of my RefineryCMS is 3-0-stable and the version of my rails is 4.2.7.1</p> <p>This is my gemfile:</p> <pre><code>source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'tzinfo-data', platforms: [:mingw, :mswin, :jruby] # Use sqlite3 as the database for Active Record group :development, :test do gem 'sqlite3' end # Use SCSS for stylesheets gem 'sass-rails', '~&gt; 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '&gt;= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~&gt; 4.1.0' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'turbolinks' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~&gt; 2.0' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~&gt; 0.4.0', group: :doc gem 'bourbon' gem 'neat' gem 'meta-tags', '~&gt; 2.0.0' # Use ActiveModel has_secure_password # gem 'bcrypt', '~&gt; 3.1.7' # Use Unicorn as the app server # gem 'unicorn' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug' end group :development do # Access an IRB console on exception pages or by using &lt;%= console %&gt; in views gem 'web-console', '~&gt; 2.0' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' end group :production do gem 'pg' gem 'rails_12factor' gem 'dragonfly-s3_data_store' end group :staging do gem 'rails_12factor' end gem 'refinerycms', git: 'https://github.com/refinery/refinerycms', branch: '3-0-stable' gem 'quiet_assets', group: :development # Add support for searching inside Refinery's admin interface. gem 'refinerycms-acts-as-indexed', ['~&gt; 2.0', '&gt;= 2.0.0'] # Add support for Refinery's custom fork of the visual editor WYMeditor. gem 'refinerycms-wymeditor', ['~&gt; 1.0', '&gt;= 1.0.6'] # The default authentication adapter gem 'refinerycms-authentication-devise', '~&gt; 1.0' gem 'mailchimp-api', require: 'mailchimp' gem 'disqus_rails' gem 'figaro' gem 'refinerycms-blog', git: 'https://github.com/refinery/refinerycms-blog', branch: 'master' gem 'puma' gem 'refinerycms-disqus', '~&gt; 0.0.1' gem 'refinerycms-productos', path: 'vendor/extensions' </code></pre> <p>this is the complete log after run bundle install</p> <pre><code>C:\Sites\ifurniture&gt;bundle install Your Gemfile lists the gem rails_12factor (&gt;= 0) more than once. You should probably keep only one of them. While it's not a problem now, it could cause errors if you change the version of just one of them later. Fetching gem metadata from https://rubygems.org/ Fetching version metadata from https://rubygems.org/ Fetching dependency metadata from https://rubygems.org/ Could not find gem 'refinerycms-disqus (~&gt; 0.0.1)' in any of the gem sources listed in your Gemfile or available on this machine. </code></pre>
<p><code>gem 'refinerycms-disqus', github: 'keram/refinerycms-disqus'</code> should do the trick.</p>
API service return 200, but it is really a 404 <p>I have this VUEJS / VUEJS Resources snippet that is fetching data from an API service.</p> <pre><code>fetchData: function(name){ var self = this; self.$http.get('http://www.apiservice.com/', { params: { city: name }, }).then((response) =&gt; { // success callback toastr.success('Success!'); console.debug(response); }, (response) =&gt; { // error toastr.error('Something went wrong!') }); } </code></pre> <p>And it will always return a 200 OK response... So i don't really know how to show the <code>toastr.error</code>, if its always a "success".</p> <p>The false response looks like this: <code>{Response: "False", Error: "City not found!"}</code>.</p> <h1>My question</h1> <p>How can I fetch the <code>false</code> in the Response of a 200 ok return, and throw an error?</p>
<p>It seems like bad API design to return a "no response found" as HTTP 200, but if you have no control over the API, you'll just have to handle that in your success function.</p> <p>Put your error handling code in a function and call it accordingly:</p> <pre><code>fetchData: function(name){ var self = this; self.$http.get('http://www.apiservice.com/', { params: { city: name }, }).then((response) =&gt; { // success callback if (response.Response === "False") { onError(response) } else { toastr.success('Success!'); console.debug(response); } }, onError); } function onError(response) { toastr.error('Something went wrong!') } </code></pre>
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement <p>I'm trying to get into PDO details. So I coded this:</p> <pre><code>&lt;?php namespace news\system\worker; use news\data\news\NewsEditor; use wcf\data\object\type\ObjectTypeCache; use wcf\system\database\util\PreparedStatementConditionBuilder; use wcf\system\search\SearchIndexManager; use wcf\system\user\activity\point\UserActivityPointHandler; use wcf\system\worker\AbstractRebuildDataWorker; use wcf\system\WCF; /** * Worker actions for news entries. * * @author Pascal Bade * @copyright 2013 voolia.de * @license Creative Commons CC-BY-ND &lt;http://creativecommons.org/licenses/by-nd/3.0/deed.de&gt; * @package de.voolia.news */ class NewsDataWorker extends AbstractRebuildDataWorker { /** * @see \wcf\system\worker\AbstractRebuildDataWorker::$objectListClassName */ protected $objectListClassName = 'news\data\news\NewsList'; /** * @see \wcf\system\worker\AbstractWorker::$limit */ protected $limit = 250; /** * @see \wcf\system\worker\AbstractRebuildDataWorker::initObjectList */ protected function initObjectList() { parent::initObjectList(); $this-&gt;objectList-&gt;sqlOrderBy = 'news.newsID'; } /** * @see \wcf\system\worker\IWorker::execute() */ public function execute() { parent::execute(); if (!count($this-&gt;objectList)) { return; } if (!$this-&gt;loopCount) { // remove the activity points UserActivityPointHandler::getInstance()-&gt;reset('de.voolia.news.activityPointEvent.news'); // remove the entry from search index SearchIndexManager::getInstance()-&gt;reset('de.voolia.news.entry'); } // get news attachments $attachmentObjectType = ObjectTypeCache::getInstance()-&gt;getObjectTypeByName('com.woltlab.wcf.attachment.objectType', 'de.voolia.news.entry'); $sql = "SELECT COUNT(*) AS attachments FROM wcf".WCF_N."_attachment WHERE objectTypeID = ? AND objectID = ?"; $attachments = WCF::getDB()-&gt;prepareStatement($sql); // calculate the cumulative likes $conditions = new PreparedStatementConditionBuilder(); $conditions-&gt;add("objectID IN (?)", array($this-&gt;objectList-&gt;getObjectIDs())); $conditions-&gt;add("objectTypeID = ?", array(ObjectTypeCache::getInstance()-&gt;getObjectTypeIDByName('com.woltlab.wcf.like.likeableObject', 'de.voolia.news.likeableNews'))); $sql = "SELECT objectID, cumulativeLikes FROM wcf".WCF_N."_like_object ".$conditions; $statement = WCF::getDB()-&gt;prepareStatement($sql); $statement-&gt;execute($conditions-&gt;getParameters()); $likes = array(); while ($row = $statement-&gt;fetchArray()) { $likes[$row['objectID']] = $row['cumulativeLikes']; } // update the news entries $userItems = array(); foreach ($this-&gt;objectList as $news) { // new EntryEditor $editor = new NewsEditor($news); // update search index SearchIndexManager::getInstance()-&gt;add('de.voolia.news.entry', $news-&gt;newsID, $news-&gt;message, $news-&gt;subject, $news-&gt;time, $news-&gt;userID, $news-&gt;username, $news-&gt;languageID); // news data $newsData = array(); // likes $newsData['cumulativeLikes'] = (isset($likes[$news-&gt;newsID])) ? $likes[$news-&gt;newsID] : 0; // attachments $attachments-&gt;execute(array($attachmentObjectType-&gt;objectTypeID, $news-&gt;newsID)); $row = $attachments-&gt;fetchArray(); $newsData['attachments'] = $row['attachments']; if ($news-&gt;userID) { if (!isset($userItems[$news-&gt;userID])) { $userItems[$news-&gt;userID] = 0; } $userItems[$news-&gt;userID]++; } $editor-&gt;update($newsData); } // update activity points UserActivityPointHandler::getInstance()-&gt;fireEvents('de.voolia.news.activityPointEvent.news', $userItems, false); } } </code></pre> <p>But i receive this</p> <blockquote> <p>SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.</p> </blockquote> <p>Somebody who can shed a light for this?</p>
<p>I receive this error:</p> <p>SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.</p> <p>Stacktrace:</p> <h1>0 /var/www/clients/client1/web5/web/wcf/lib/data/DatabaseObjectEditor.class.php(68): wcf\system\database\Database->prepareStatement('UPDATE\tnews1_ne...')</h1> <h1>1 /var/www/clients/client1/web5/web/news/lib/system/worker/NewsDataWorker.class.php(108): wcf\data\DatabaseObjectEditor->update(Array)</h1> <h1>2 /var/www/clients/client1/web5/web/wcf/lib/acp/action/WorkerProxyAction.class.php(93): news\system\worker\NewsDataWorker->execute()</h1> <h1>3 /var/www/clients/client1/web5/web/wcf/lib/action/AbstractAction.class.php(49): wcf\acp\action\WorkerProxyAction->execute()</h1> <h1>4 /var/www/clients/client1/web5/web/wcf/lib/action/AJAXInvokeAction.class.php(63): wcf\action\AbstractAction->__run()</h1> <h1>5 /var/www/clients/client1/web5/web/wcf/lib/system/request/Request.class.php(58): wcf\action\AJAXInvokeAction->__run()</h1> <h1>6 /var/www/clients/client1/web5/web/wcf/lib/system/request/RequestHandler.class.php(139): wcf\system\request\Request->execute()</h1> <h1>7 /var/www/clients/client1/web5/web/acp/index.php(10): wcf\system\request\RequestHandler->handle('wbb', true)</h1> <h1>8 {main}</h1>
Select Distinct rows from the joining of two SQL tables <p>I'm trying to determine the following from the joining of two tables: TableA: Contains 1 column consisting of unique IDs TableB: Contains multiple columns, one with consisting of the same set of unique IDs but also with a date column for each day of the year. For example:</p> <pre><code>Table A Unique ID 1 2 3 Table B UniqueID Date Column3 Column4 1 10/11/15 2 10/11/15 1 11/11/15 2 11/11/15 3 11/11/15 </code></pre> <p>I want the query to output the a table with the unique IDs and the first day on which they appear in table B. So for unique 1 and 2, to output only the first date, and for unique 3, only the second date.</p> <p>Is this possible?</p> <p>Thanks</p>
<p>The JOIN portion is unnecessary given your example above, but in the event that you actually only want records that are included in the first table, you could do an <code>INNER JOIN</code> like so.</p> <pre><code>SELECT tb.UniqueID, MIN(DATE) as [Date] FROM [Table B] tb INNER JOIN [Table_A] ta ON ta.[Unique ID] = tb.UniqueID GROUP BY tb.UniqueID </code></pre> <p>I've used your table and column names, despite the lack of naming consistency, and the fact that your tables and columns have spaces in them. (Personally, I'd advise against this in any SQL implementation, but that's a separate issue.)</p> <p>Without the join you'd just need to do...</p> <pre><code>SELECT UniqueID, MIN(DATE) as [Date] FROM [Table B] GROUP BY UniqueID </code></pre>
Automatic update of calculated fields (Excel Pivot table) <p>I am creating a top 10 product by sales calculation off of a pivot table I am running. My question is, I would like this table to populate automatically to the latest week when I refresh the table and am not sure how to do this.</p> <p>Furthermore, there are some additional calculations like YoY growth for the particular product against the current week last year, 3 month growth, etc.. that I am note sure will update properly when placing in the new data. </p> <p>I have attached a dummy file so you can get an idea of what I am working with. </p> <p><a href="https://www.dropbox.com/s/a1q9aqhn6rsn9hv/pivot-questions.xlsx?dl=0" rel="nofollow">https://www.dropbox.com/s/a1q9aqhn6rsn9hv/pivot-questions.xlsx?dl=0</a></p>
<p>In regards to the date filtering, see my answer at <a href="http://stackoverflow.com/questions/39004607/filtering-pivot-table-with-vba">Filtering pivot table with vba</a> In regards to the calculations, if you use a paramatized GETPIVOTDATA function then you can easily accomplish what you want.</p>
how to make django manage a table that wasnt in the migration but in the database? <p>Ok, where i work we are using a database that we would like to continue using but instead connect it to a different front end. Django 1.8</p> <p>we did a inspectdb and we did a makemigration based on that infomation and migrated </p> <p>but still wont work. the other tables work fine but the other tables didnt exist before the migration (and wont taken from another database ) and the table we are looking at had information we wanted to keep for testing</p> <p>the error we get is </p> <pre><code>column plans_to_lodge.id does not exist LINE 1: SELECT "plans_to_lodge"."id", "plans_to_lodge"."sm_sequence"... </code></pre>
<p>If I got the question correctly, you wan't to use Django models with tables created outside Django, right?</p> <p>It seems that you don't have the <code>id</code> column in that table. Django requires one PRIMARY KEY column or it will try to use <code>id</code> as a default.</p> <p>Try setting an AutoField to a sutitable column: <a href="https://docs.djangoproject.com/en/1.8/topics/db/models/#automatic-primary-key-fields" rel="nofollow">https://docs.djangoproject.com/en/1.8/topics/db/models/#automatic-primary-key-fields</a></p>
Custom sorting of R datatable column for numbers stored as strings <p>I have a Shiny dashboard in which I use the DataTable package (code closely following the approach in the <a href="http://shiny.rstudio.com/gallery/datatables-options.html" rel="nofollow">Shiny documentation</a>) to build my tables.</p> <p>Everything is working fine but for aesthetic reasons I want to display the numbers with comma separators, so <code>1000000</code> is rendered <code>1,000,000</code>.</p> <p>My approach so far has been use just reformat a numeric column like: </p> <pre><code>table$col &lt;- formatC(table$col, format="d", big.mark=',') </code></pre> <p>and this works fine, but when I want to use the standard function to sort the tables in the webpage I get a sort in lexicographical order because the numbers are now encoded as strings.</p> <p>Is there anyway to either modify the table sort function or encode the numbers in a way that they'll render with comma separators but the sort will behave as expected for these essentially numeric columns?</p> <p>In case it is useful this could be reproduced as simply as adding this to a server.R file:</p> <pre><code>table &lt;- morley table$Speed &lt;- formatC(table$Speed, format="d", big.mark=',') output$table &lt;- DT::renderDataTable( DT::datatable(table) ) </code></pre>
<p>Section 4.5 - Row Rendering of this DT document has your answer: <a href="https://rstudio.github.io/DT/options.html" rel="nofollow">https://rstudio.github.io/DT/options.html</a></p>
Checking current git branch with ifneq in Makefile <p>I'm trying to get my makefile to check that it's running on the correct branch and throw and error if not. </p> <p>I'm using <code>ifneq</code> to compare them and <code>git rev-parse --abbrev-ref HEAD</code> to get the checked out branch, but it will not see them as equal. How can I fix this?</p> <p>Right now the the code looks like this:</p> <pre><code>ifneq ($(git rev-parse --abbrev-ref HEAD), master) $(error Not on branch master) else git checkout gh-pages git merge master git checkout master endif </code></pre> <p>Thanks.</p>
<p>There is no such make function as <code>$(git ...)</code>, so that variable reference expands to the empty string. You're always running:</p> <pre><code>ifneq (, master) </code></pre> <p>which will be always true.</p> <p>You want to use the <code>shell</code> GNU make function:</p> <pre><code>ifneq ($(shell git rev-parse --abbrev-ref HEAD),master) </code></pre>
RotatingFileHandler does not continue logging after error encountered <pre><code>Traceback (most recent call last): File "/usr/lib64/python2.6/logging/handlers.py", line 76, in emit if self.shouldRollover(record): File "/usr/lib64/python2.6/logging/handlers.py", line 150, in shouldRollover self.stream.seek(0, 2) #due to non-posix-compliant Windows feature ValueError: I/O operation on closed file </code></pre> <p>I have a line in my script:</p> <pre><code>handler = logging.handlers.RotatingFileHandler(cfg_obj.log_file,maxBytes = maxlog_size, backupCount = 10) </code></pre> <p>It runs fine when there are no error messages. But when there's an error log, the logs after the error are not written to the file unless the process is restarted. We do not want to restart the process every time there is an error. Thanks for your help in advance!</p>
<p>I highly recommend you to use a configuration file. The configuration code below "logging.conf" has different handlers and formatters just as example: </p> <pre><code>[loggers] keys=root [handlers] keys=consoleHandler, rotatingFileHandler [formatters] keys=simpleFormatter, extendedFormatter [logger_root] level=DEBUG handlers=consoleHandler, rotatingFileHandler [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [handler_rotatingFileHandler] class=handlers.RotatingFileHandler level=INFO formatter=extendedFormatter args=('path/logs_file.log', 'a', 2000000, 1000) [formatter_simpleFormatter] format=%(asctime)s - %(levelname)s - %(message)s datefmt= [formatter_extendedFormatter] format= %(asctime)s - %(levelname)s - %(filename)s:%(lineno)s - %(funcName)s() %(message)s datefmt= </code></pre> <p>Now how to use it "main.py":</p> <pre><code>import logging.config # LOGGER logging.config.fileConfig('path_to_conf_file/logging.conf') LOGGER = logging.getLogger('root') try: LOGGER.debug("Debug message...") LOGGER.info("Info message...") except Exception as e: LOGGER.exception(e) </code></pre> <p>Let me know if you need more help.</p>
How to open a screen from appdelegate.m handleOpenURL method with REFrosted Sliding Menu & storyboards? <p>I am updating one of my application that uses URL Scheme. I used to have application:handleOpenURL method in appdelegate.m with following code that used to work fine from long time (without Storyboards)</p> <pre><code> urlOpenedMsg2 *nextview=[[urlOpenedMsg2 alloc] initWithNibName:@"urlOpenedMsg2" bundle:Nil]; [self.navigationController pushViewController:nextview animated:YES]; </code></pre> <p>Now I have updated my app with <a href="https://github.com/romaonthego/REFrostedViewController" rel="nofollow">REFrostedViewController Sliding Menu</a> and Story-boards. In hadleOpenURL method , I am just trying to open new screen "urlOpenedMsg2ViewController" and I can't open it.</p> <p>I am using following code now</p> <pre><code> UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; urlOpenedMsg2ViewController *nextview = [storyboard instantiateViewControllerWithIdentifier:@"urlOpenedMsg2"]; [(UINavigationController*)self.window.rootViewController pushViewController:nextview animated:NO]; </code></pre> <p>Now my navigationViewController is not self.window.rootViewController so following line doesn't work and it opens home screen instead of urlOpenedMsg2 Screen</p> <pre><code>[(UINavigationController*)self.window.rootViewController pushViewController:nextview animated:NO]; </code></pre> <p>Now I have RootViewController , NavigationViewController and MenuTableViewController for REFrostedViewController and RootViewController is initial view controller. Please see attached screenshot.</p> <p><a href="https://i.stack.imgur.com/LqC18.png" rel="nofollow">StoryBoards Setup</a></p> <p>I don't know how to fix it. </p> <p>How can I open "urlOpenedMsg2ViewController" screen from appdelegate.m handleOpenURL method ? </p> <p>Thanks in advance.</p>
<p>You need to call it like this:-</p> <pre><code>UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; urlOpenedMsg2ViewController *nextview = [storyboard instantiateViewControllerWithIdentifier:@"urlOpenedMsg2"]; UINavigationController *navigationVC = [[UINavigationController alloc] init]; self.window.rootViewController = navigationVC; [navigationVC pushViewController:nextview animated:NO]; </code></pre>
SQL Query: How to Select across rows and columns <p>I'm certain that this is a simple WHERE clause. I'm just not sure how to write it.</p> <p>Let's say I have the following data where a,b,c(numbers) and d(varchar):</p> <p><a href="https://i.stack.imgur.com/dIdfk.png" rel="nofollow"><img src="https://i.stack.imgur.com/dIdfk.png" alt="enter image description here"></a></p> <p>What I'd like to do is select rows that have the following conditions:</p> <ul> <li>Column b must be the same as at least one other row. </li> <li>Column c must have at least one row with a value and one without or one with 0 as a value.</li> </ul> <p>I'd like to pull in col a and d. But only if b and c meet those conditions.</p> <p>For example the green data is something I'd like to select, and the red is obviously data I don't care about. Thanks in advance.</p>
<p>If you just want the <code>b</code> values, using aggregation and <code>having</code>:</p> <pre><code>select b from t group by b having count(*) &gt; 1 and max(c) &gt; 0 and min(coalesce(c, 0)) = 0; </code></pre> <p>This assumes that <code>c</code> is always positive. Similar logic can be formulated if <code>c</code> can be negative.</p> <p>If you want the original rows, you can join these results back to the table, or use <code>in</code>.</p>
Ruby sysread IO much too slow <p>I have a command like this where <code>input</code> is a string that receives the input:</p> <pre><code>STDIN.sysread(1000,input) </code></pre> <p>If it reads more than 100 characters it takes more than 0.1 seconds.</p> <p>I tried it with alternatives such as <code>partialread</code> and nonblocking reading and <code>read</code>, but I didn't find a faster alternative so far.</p> <p>Do you know any faster possibility to simply read this?</p> <hr> <pre><code>t=Time.now STDIN.sysread(1000,input) stdin_time=Time.now-t </code></pre> <p><code>stdin_time</code> is bigger than 0.1 <code>if input.length &gt; 100</code></p> <p>I read mouse movements from terminal within X-Window.</p> <p>Does <code>sysread</code> wait for more input than available before it finishes execution?</p> <hr> <p>Even that doesn't work:</p> <pre><code>t=Time.now Thread.new{ input=STDIN.sysread(1000) }.join(0.001) stdin_time=Time.now-t </code></pre> <p><code>stdin_time</code> is still >0.01, just as before.</p> <hr> <p>The 0.01 seconds are visible on the screen when moving the mouse. It's not only a theoretical number problem, but it's visible. The problem is definitely there.</p>
<p>There is probably something odd in your benchmarking setup. What comes to mind first is that your sender might not write fast enough.</p> <p>The following benchmark (using <a href="https://github.com/evanphx/benchmark-ips" rel="nofollow">benchmark-ips</a>) resulted in approximately one read every 1.3 micro-seconds on my 4-years-old Macbook on Ruby 2.2.5.</p> <p>This benchmark contains additional code to verify that we are reading exactly 1000-character strings. This makes the benchmark almost 50% slower, but still <em>much</em> faster than you claim.</p> <pre><code>require 'benchmark/ips' sysread_1k_strings = 0 read_1k_strings = 0 Benchmark.ips do |x| input = '' x.warmup = 0 x.report('sysread') { STDIN.sysread(1000, input) sysread_1k_strings += 1 if input.length == 1000 } x.report('read') { STDIN.read(1000, input) read_1k_strings += 1 if input.length == 1000 } end puts "Comparison --------------------------------------" puts "sysread".rjust(20) + "#{sysread_1k_strings.to_s.rjust(11)} 1000 byte strings read" puts "read".rjust(20) + "#{read_1k_strings.to_s.rjust(11)} 1000 byte strings read" </code></pre> <p>When reading from <code>/dev/zero</code> this resulted in the following benchmark result:</p> <pre><code>$ ruby benchmark.rb &lt; /dev/zero Warming up -------------------------------------- sysread 1.000 i/100ms read 1.000 i/100ms Calculating ------------------------------------- sysread 210.517k (±13.5%) i/s - 915.780k in 4.529414s read 475.210k (±10.4%) i/s - 1.956M in 4.209967s Comparison -------------------------------------- sysread 915780 1000 byte strings read read 1955737 1000 byte strings read </code></pre>