input
stringlengths
51
42.3k
output
stringlengths
18
55k
indoor atlas: using the API offline? <p>I am using the indoor atlas API. I am wondering if there is a way to work with the API affline and have a valid magnetic map offline, so my application wont be dependant on the state of the cloud servor?</p>
<p>Unfortunately there's no offline solution today. Newest SDK can handle the situations when the network breaks for a while, but the accuracy decreases the longer you stay offline.</p>
Suppress Windows c# built in message box errors <p>I want to suppress the c# windows form message box errors. Like in my application there is a config file for the printer configuration, so when there is no printer attached or there's an issue with the port it gives an error. I want to suppress that built in windows error. Is there a way of doing this? Any help would be appreciated. Thanks in advance. :)</p>
<p>Being forms you could add a try catch on Application.Run:</p> <pre><code> try { Application.Run(new Form1()); } catch (Exception ex) { //MessageBox.Show(ex.Message); } </code></pre> <p>Or would recommend handling the event as per <a href="http://stackoverflow.com/questions/8148156/winforms-global-exception-handling">winforms-global-exception-handling </a></p>
Password not resetting on a database through an ASP.Net application <p>I am trying to reset a password to an employee number on a database through a ASP.Net application. The trouble is that it is not actually resetting the password on DB even though I am getting a confirmation message that the password has been reset.</p> <p>Here is my current code</p> <pre><code>SqlConnection sqlcon = new SqlConnection(); SqlCommand sqlCmd = new SqlCommand(); string empNo = ""; empNo = txtEmpNo.Text; empReset = txtEmpNo.Text; // sql statement to check if employee number exists in DB SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM tbl_Login WHERE (Emp_ID = @user)", sqlcon); check_User_Name.Parameters.AddWithValue("@user", empNo); int UserExist = (int)check_User_Name.ExecuteScalar(); if (UserExist &gt; 0) { //EmpNo exists sqlCmd = new SqlCommand("update tbl_Login set Emp_Pass=@Pass where Emp_ID=@EmpID", sqlcon); sqlCmd.Parameters.AddWithValue("@EmpID", empNo); sqlCmd.Parameters.AddWithValue("@Pass", "1234"); lblExists.Text = "Password reset!"; }// end if else { //EmpNo doesnt exist lblExists.Text = "Employee doesnt exists"; }//end else </code></pre>
<p>you missed </p> <pre><code>sqlCmd.ExecuteNonQuery(); </code></pre>
JQuery hidden element input issue traversing <p>I have a problem I just can't figure out. I have a set of DIV's which are <code>display: none;</code> by default:</p> <pre><code>&lt;div id="pivot"&gt; &lt;div id="leftcol"&gt;Pivot&lt;/div&gt; &lt;div id="rightcol"&gt; &lt;input class="small" value="030-" disabled /&gt; &lt;input class="input" id="pi" maxlength="6" /&gt; &lt;span id="pit"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="pos1"&gt; &lt;div id="leftcol"&gt;Position 1&lt;/div&gt; &lt;div id="rightcol"&gt; &lt;input class="small" value="031-" disabled /&gt; &lt;input class="input" id="p1" maxlength="6" /&gt; &lt;span id="p1t"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="pos2"&gt; &lt;div id="leftcol"&gt;Position 2&lt;/div&gt; &lt;div id="rightcol"&gt; &lt;input class="small" value="031-" disabled /&gt; &lt;input class="input" id="p2" maxlength="6" /&gt; &lt;span id="p2t"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="pos3"&gt; &lt;div id="leftcol"&gt;Position 3&lt;/div&gt; &lt;div id="rightcol"&gt; &lt;input class="small" value="031-" disabled /&gt; &lt;input class="input" id="p3" maxlength="6" /&gt; &lt;span id="p3t"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="pos4"&gt; &lt;div id="leftcol"&gt;Position 4&lt;/div&gt; &lt;div id="rightcol"&gt; &lt;input class="small" value="031-" disabled /&gt; &lt;input class="input" id="p4" maxlength="6" /&gt; &lt;span id="p4t"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="pos5"&gt; &lt;div id="leftcol"&gt;Position 5&lt;/div&gt; &lt;div id="rightcol"&gt; &lt;input class="small" value="031-" disabled /&gt; &lt;input class="input" id="p5" maxlength="6" /&gt; &lt;span id="p5t"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="pos6"&gt; &lt;div id="leftcol"&gt;Position 6&lt;/div&gt; &lt;div id="rightcol"&gt; &lt;input class="small" value="031-" disabled /&gt; &lt;input class="input" id="p6" maxlength="6" /&gt; &lt;span id="p6t"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Then this code unhides the relevant section:</p> <pre><code>$.ajax({ url: "getSerial.asp", data: { term: term }, dataType: "json", success: function(data) { $('option:selected').append('-' + data[0].sn) $('#prefix').attr('disabled', true) var code = data[0].partno.substring(6, 12); len = code.length; $('#pivot').show(0); for (var i = 0; i &lt; len; i++) { if (code.substr(i, 1) != "-") { $('#pos' + code.substr(i, 1)).show(0); } } $('div').find('input:enabled').first().focus(); } }); </code></pre> <p>So that works perfectly fine. Then what I'm trying to do is as you type in 6 characters, it automatically jumps down to the next visible input (<code>class="input"</code>). My code for that is very un-glamorous and works ONLY with the next logical div (pos1, pos2 etc). The combination may be pos1,pos3,pos3 so missing out number 2 (as it is still hidden).</p> <pre><code>$(this).parent('div').parent('div').next('div').find('.input:visible').focus() </code></pre> <p>This doesn't work for the above combination. How do I traverse successfully only to the next visible .input class?</p>
<p>Use <code>:has()</code> in the selector to match a DIV that contains a visible input.</p> <pre><code>$(this).parent('div').parent('div').nextAll('div:has(.input:visible)').first().find('.input:visible').focus(); </code></pre>
How do I pass two meta value to WP_Query <p>I'm having issues with my WP_Query. So I have two select boxes created using ACF one for Country and one for sector. When I select country and leave sector empty I get all the posts with the selected country and like wise for the sector. What I need to do is filter it further so if both are selected and not just one I get all posts from that country and sector. My args below any help is appreciated.</p> <pre><code>$field_key_country = "field_57b4439b5e371"; $field_country = get_field_object($field_key_country); $country_sector = isset($_POST['country_select'])? sanitize_text_field($_POST['country_select']) : false; $sector_key = "field_57e15152d896d"; $sector_field = get_field_object($sector_key); $sector = isset($_POST['sector_select'])? sanitize_text_field($_POST['sector_select']) : false; $args = array( 'post_type' =&gt; 'distributer_search', 'posts_per_page' =&gt; -1, 'meta_query' =&gt; array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'dis_country', 'value' =&gt; $country_sector, ), array( 'key' =&gt; 'dis_sector', 'value' =&gt; $sector, ) ) ); </code></pre>
<p>Please try following code with relation AND &amp; compare operator. Also please check WP_Query class at <a href="https://codex.wordpress.org/Class_Reference/WP_Query" rel="nofollow">https://codex.wordpress.org/Class_Reference/WP_Query</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-html lang-html prettyprint-override"><code>&lt;?php $country_sector = isset($_POST['country_select'])? sanitize_text_field($_POST['country_select']) : ''; $sector = isset($_POST['sector_select'])? sanitize_text_field($_POST['sector_select']) : ''; $args = array( 'post_type' =&gt; 'distributer_search', 'posts_per_page' =&gt; -1, 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array( 'key' =&gt; 'dis_country', 'value' =&gt; $country_sector, 'compare' =&gt; '=', ), array( 'key' =&gt; 'dis_sector', 'value' =&gt; $sector, 'compare' =&gt; '=', ) ) ); ?&gt;</code></pre> </div> </div> </p> 'distributer_search', 'posts_per_page' => -1, 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'dis_country', 'value' => $country_sector, 'compare' => '=', ), array( 'key' => 'dis_sector', 'value' => $sector, 'compare' => '=', ) ) ); ?>
Component with attribute selector causes child elements not to render <p>I have created a component with attribute selector. When I use this attribute, the child elements of the original element are not rendered. Is this normal? I want both the original children and the applied component to be rendered because I cannot do otherwise in svg which is my current concern. There is a plnkr <a href="http://plnkr.co/edit/DVdhCv8HDFoZAWO1syHD?p=preview" rel="nofollow">http://plnkr.co/edit/DVdhCv8HDFoZAWO1syHD?p=preview</a></p> <pre><code>import { Component } from '@angular/core'; @Component({ selector: '[attr-component]', template: '&lt;div style="width:50px; height:50px; background-color:red"&gt; &lt;/div&gt;' }) export class AttrComponent { } @Component({ selector: 'local-component', template: ` &lt;div attr-component&gt; &lt;div style="width:50px; height:50px; background-color:green"&gt;&lt;/div&gt; &lt;/div&gt; ` }) export class LocalComponent { } @Component({ selector: 'app-root', template: '&lt;div&gt;&lt;local-component&gt;&lt;/local-component&gt;&lt;/div&gt;' }) export class AppComponent { } </code></pre>
<p>You need to add</p> <pre><code>&lt;ng-content&gt;&lt;/ng-content&gt; </code></pre> <p>in the parent component for child components to be rendered</p> <p><a href="http://plnkr.co/edit/kLxUZLUhCnevxQEB1uSe?p=preview" rel="nofollow"><strong>Plunker example</strong></a></p>
"Win32_Printer Where Network = TRUE" return no result in visual studio installer project <p>Using the following code, I can find and delete the print queue</p> <pre><code>Dim scope = New ManagementScope(ManagementPath.DefaultPath) scope.Connect() Dim printers = New ManagementObjectSearcher(scope, New SelectQuery("Select * from Win32_Printer Where Network = TRUE")).[Get]() MsgBox("Print count: " &amp; printers.Count) For Each printer As ManagementObject In printers Dim nameOfPrinter = printer("Name").ToString() If nameOfPrinter.Contains("BROTHER") OrElse nameOfPrinter.Contains("HP") Then printer.Delete() End If Next </code></pre> <p>However, when I move the code to installer.vb (which is added to installer project as primary output (active)), the printers.count is returned 0</p> <p><strong>UPDATED: if I remove the where cause, I can get the local print queues</strong></p> <pre><code>&lt;Security.Permissions.SecurityPermission(Security.Permissions.SecurityAction.Demand)&gt; _ Public Overrides Sub Commit(ByVal savedState As _ System.Collections.IDictionary) Dim scope = New ManagementScope(ManagementPath.DefaultPath) scope.Connect() Dim printers = New ManagementObjectSearcher(scope, New SelectQuery("Select * from Win32_Printer Where Network = TRUE")).[Get]() MsgBox("Print count: " &amp; printers.Count) For Each printer As ManagementObject In printers Dim nameOfPrinter = printer("Name").ToString() If nameOfPrinter.Contains("BROTHER") OrElse nameOfPrinter.Contains("HP") Then printer.Delete() End If Next </code></pre> <p>Is there anything I have missed to add? Please advise, thanks.</p>
<p>The most likely explanation is that network resources printers (and other network items like mapped drive letters) are specific to the user context. In Visual Studio setups that run for Everyone the custom actions run with the local system account (which is required for them to be elevated) so it won't find them. You're asking if the system account has any network printers (and the system account has no network access anyway). It finds the local printers that are hard-wire connected because they are available to all users.</p> <p>There isn't really a good detour for this in Visual Studio setups. The kind of thing you're doing is often best achieved with a configuration program that runs when the application first runs. It's not clear to me why you want to delete the print queue during an install, but if it's something that might need to be done several times then the user can rerun the program at a later time, and maybe if a printer of that type is installed after your install something might need configuring again. </p>
How can I get the position from FlowDocumentScrollViewer? <p>I'm trying to get the position from FlowDocumentScrollViewer. And save it to db.</p> <p>After that, close and re-open the program. At that time, the scroll should be set to what I saved position.</p> <p>Simply, I hope to save that I watched position. and later, when I open it, I want to see the position which I watched last time.</p> <p>Now, I'm watching this class, but I couldn't find some method or variables about this feature. FlowDocumentPageViewer has GoToPage(), so I hope to get this kind of method from FlowDocumentScrollViewer.</p> <p>How can I create thesas feature?</p>
<p>as described <a href="http://stackoverflow.com/a/561319/5018591">here</a> you need to get the scollviewer property of your FlowDocumentScrollViewer. than you can get scrollbar position with myScrollViewer.VerticalOffset and set it with myScrollViewer.ScrollToVerticalOffset(double value)</p>
Create a batch file to rename some files <p>I need a batch file that renames my files in according to the folder name.</p> <p>For example I have this folder:</p> <pre><code>E:\PROGET\01_Progetti\1_TRATTATIVE\IT.16.9291_Fabbricato ad Milano (MI) - Ing. Bianchi\03-CALCOLO\02-XLS\ </code></pre> <p>Which contains </p> <pre><code>CB-Tech_92XX - .xls Punz_92XX - .xls </code></pre> <p>I want to rename them to </p> <pre><code>CB-Tech_9291 - .xls Punz_9291 - .xls </code></pre> <p>Is it possible?</p> <p>EDIT:</p> <p>I've found this code from a guy who asked for code and didn't get any complain <a href="http://stackoverflow.com/questions/9383032/rename-all-files-in-a-directory-with-a-windows-batch-script">Rename all files in a directory with a Windows batch script</a></p> <p>I've changed it a little bit: </p> <pre><code>@echo off setlocal enableDelayedExpansion for %%F in (*92XX*) do ( set "name=%%F" ren "!name!" "!name:92XX=9XXX!" ) @pause </code></pre> <p>Now I just have to understand how to get the path (done), extract only the numbers (not yet) and store in a variable (done).</p> <p>To set a variable should be something like that</p> <pre><code>set "number=projectnumber" SET mypath=%~dp0 </code></pre> <p>ok now I've the path, need to extract only 4 characters after the IT.16.</p> <p>Will edit later :)</p> <p>EDIT 2:</p> <pre><code>@echo off setlocal enableDelayedExpansion SET mypath=%~dp0 set projectnumber=%mypath:~41,4% for %%F in (*92XX*) do ( set "name=%%F" ren "!name!" "!name:92XX=%projectnumber:~0%!" ) @pause </code></pre> <p><strong>YEAH! This works for this specific folder!!</strong></p> <p>Now I just need to understand how to search and extract the number inside the path to make it more general.</p> <p>I'm looking for a function that returns the position of the first char of the string IT.16. Any advice?</p>
<p>This is the complete solution of this question:</p> <pre><code>@echo off setlocal enableDelayedExpansion SET mypath=%~dp0 set "projectnumber=%mypath:*IT.16.=%" set "projectnumber=%projectnumber:~,4%" for %%F in (*92XX*) do ( set "name=%%F" ren "!name!" "!name:92XX=%projectnumber:~0%!" ) </code></pre>
What data type should be used as an alternative for boolean in Postgres, HSQL, MSSQL? <p>We are using Oracle, Postgres, HSQL, MSSQL.</p> <p>Since boolean is not supported by Oracle, we are using number(1,0) . So, other databases are getting affected. </p> <p>What is the data type to be used in Postgres, HSQL, MSSQL, when we cannot use boolean data type?</p> <p>For example: bit ?</p>
<p><code>number</code> and <code>*-int</code>were the most common methods I've encountered so far, whereas <code>number</code> was used more frequently.</p> <p>Edit:</p> <p>As @a_horse_with_no_name mentionied, you're probably fine using number.</p>
How to Combine multiple column into one in php SQL <p><a href="https://i.stack.imgur.com/FfpXh.png" rel="nofollow">I have this data. Can someone help how can I combine them into one?</a></p> <pre><code>id employeeID date timein timeout timein1 timeout1 1 12286 2016-09-10 08:08:00 00:00:00 00:00:00 00:00:00 2 12286 2016-09-10 00:00:00 12:08:32 00:00:00 00:00:00 3 12286 2016-09-10 00:00:00 00:00:00 12:41:54 00:00:00 4 12286 2016-09-10 00:00:00 00:00:00 00:00:00 17:10:05 5 12286 2016-10-10 07:41:05 00:00:00 00:00:00 00:00:00 6 12286 2016-10-10 00:00:00 12:15:00 00:00:00 00:00:00 7 12286 2016-10-10 00:00:00 00:00:00 12:35:15 00:00:00 8 12286 2016-10-10 00:00:00 00:00:00 00:00:00 17:15:15 </code></pre> <p><a href="https://i.stack.imgur.com/06qvV.png" rel="nofollow">This is the output that I wanted. Help me. Thanks</a></p> <pre><code>id employeeID date timein timeout timein1 timeout1 1 12286 2016-09-10 08:08:00 12:08:32 12:41:54 17:10:05 2 12286 2016-10-10 07:41:05 12:15:00 12:35:15 17:15:15 </code></pre>
<p>If it was me, I'd probably adopt a schema roughly as follows:</p> <pre><code>id employeeID datetime activity 1 12286 2016-09-10 08:08:00 in 2 12286 2016-09-10 12:08:32 out 3 12286 2016-09-10 12:41:54 in 4 12286 2016-09-10 17:10:05 ... </code></pre>
How to map unique dns names to service fabric port <p>I have a local service fabric cluster which has 6-7 custom http endpoints exposed. I use fiddler to redirect these to my service like so:</p> <p>127.0.0.1:44300 identity.mycompany.com </p> <p>127.0.0.1:44310 docs.mycompany.com</p> <p>127.0.0.1:44320 comms.mycompany.com</p> <p>etc..</p> <p>I've never deployed a cluster in azure before, so there's some intricacies that i'm not familiar with and I can't find any documentation on. I've tried a multiple times to deploy and tinker with the load balancers/public ips with no luck. </p> <p>I know DNS CNAMES can't specify ports, so I guess that I have to have separate public IP for each hostname I want to use and then somehow internally map that to the port. So i end up with something like this:</p> <p>identity.mycompany.com => azure public ip => internal redirect / map => myservicefabrichostname.azure.whatever:44300</p> <p>my questions are: </p> <p>1) is this the right way to go about it? or is there some fundamental method that i'm missing</p> <p>2) do I have to specify all these endpoints (44300, 44310, 44320...) when creating the cluster (it appears to set up a load of load balancer rules/probes) or will this be unnecessary if I have multiple public IPs), i'm unsure if this is for internal or external access.</p> <p>thanks</p> <p>EDIT:</p> <p>looks like the azure portal is broken :( been on phone with microsoft support and it looks like it's not displaying the backendpools in the load balancer correctly, so you can't set up any new nat rules. </p> <p>Might be able to write a powershell script to get round this though</p> <p>EDIT 2: </p> <p>looks like Microsoft have fixed the bug in the portal, happy times</p>
<p>Instead of using multiple ip addresses you can use a <a href="https://en.wikipedia.org/wiki/Reverse_proxy" rel="nofollow">reverse proxy</a>. Like <a href="http://www.haproxy.org/" rel="nofollow">HAProxy</a>, <a href="https://www.iis.net/downloads/microsoft/url-rewrite" rel="nofollow">IIS</a> (with rewriting), the <a href="https://azure.microsoft.com/en-us/documentation/articles/service-fabric-reverseproxy/" rel="nofollow">built-in reverse proxy</a>, or something you build yourself or <a href="https://github.com/weidazhao/Hosting" rel="nofollow">reuse</a>. The upside of that is that is allows for flexibility in adding and removing underlying services.</p> <p>All traffic would come in on one endpoint, and then routed in the right direction (your services running on various ports inside the cluster). Do make sure your reverse proxy is high available. </p>
Swift 3: Stop it from converting [NSString] to [String] <p>I have this Objective-C method.</p> <pre><code>+ (NSArray&lt;NSString *&gt; *_Nullable)getValues; </code></pre> <p>which is converted in Swift to [String] and must be passed to another Objective-C method in Swift, which looks in Objective-C like</p> <pre><code>- initWith:(NSArray&lt;NSObject*&gt; *_Nonnull)parameter; </code></pre> <p>So I have this Swift code :</p> <pre><code>let bla = C.getValues() MyClass(bla) </code></pre> <p>This works flawlessly in Objective-C, but in Swift, it complains of course that [String] is no child of [NSObject], because it auto converted it from [NSString] to [String].<br><br> How can I stop Swift from doing that?<br></p> <pre><code>let bla = C.getValues() as! [NSString] </code></pre> <p>does not work, because in its infinite wisdom it converts it first from Objective-C to Swift Objects and then tries to convert it back to Objective-C Objects.<br> Message here: 'NSObject' is not a subtype of 'String'.</p> <p>PS: I know I can iterate over everything and make an array of converted copies, but there must be a better way than that:</p> <pre><code>var strings: [NSObject] = [] for string in bla! { strings.append(string as NSString) } </code></pre>
<p>Because the <code>getValues</code> returning array can be null, you have to cast it to <code>[NSString]?</code>:</p> <pre><code>let bla = C.getValues() as [NSString]? </code></pre> <p>Then, since the init method requires a non-null parameter, you have to force unwrap <code>bla</code>:</p> <pre><code>MyClass(bla!) </code></pre> <p>or fall back to a default value:</p> <pre><code>MyClass(bla ?? []) </code></pre> <p>EXTRA:</p> <p><code>as!</code> is used for <strong>down</strong>casting. <code>C.getValues() as! [NSString]</code> is not equal to <code>(C.getValues() as [NSString]?)!</code>.</p>
Text and line drawn on ToggleButton canvas appear on screen but not on screenshot <p>I have created a view <code>MyToggleButton</code> that extends <code>ToogleButton</code>. I overwrite the Togglebutton's <code>onDraw</code> method to draw a line on the button and to rotate it's text.</p> <p>Here is <code>MyToggleButton</code>:</p> <pre><code>package com.example.gl.myapplication; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.text.TextPaint; import android.widget.ToggleButton; public class MyToggleButton extends ToggleButton { public float textRotation=0; public MyToggleButton(Context context, float rotationValue) { super(context); textRotation=rotationValue; } @Override protected void onDraw(Canvas canvas){ TextPaint textPaint = getPaint(); textPaint.setColor(getCurrentTextColor()); textPaint.drawableState = getDrawableState(); canvas.save(); //paint Paint paint = new Paint(); paint.setColor(Color.BLACK); paint.setStrokeWidth(7); paint.setStrokeCap(Paint.Cap.ROUND); canvas.drawLine(canvas.getWidth() / 2, canvas.getHeight() / 2, (float) (canvas.getHeight() / 2 + 400), (canvas.getHeight() / 2), paint); canvas.rotate(textRotation, canvas.getWidth() / 2, canvas.getHeight() / 2); getLayout().draw(canvas); canvas.restore(); } } </code></pre> <p>After that I want to get a screenshot of and view it and for that I use the <code>takeScreenshot()</code> method that is called by pressing the 3rd button on screen. The screenshot code is based on <a href="http://stackoverflow.com/questions/2661536/how-to-programmatically-take-a-screenshot-in-android">How to programmatically take a screenshot in Android?</a>. The same approach is followed in other posts on stackoverflow, and in various sites and tutorials I found around.</p> <p>Here is the <code>MainActivity</code> that I use:</p> <pre><code>package com.example.gl.myapplication; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AbsListView; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.util.Date; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //add 3 buttons addButtons(); } private void addButtons(){ LinearLayout linear1= (LinearLayout) findViewById(R.id.vert1); //MyToggleButton with rotated text MyToggleButton btn1 = new MyToggleButton(this,0); btn1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); btn1.setTextOff("Button 1 not rotated"); btn1.setTextOn("Button 1 not rotated"); btn1.setText("Button 1 not rotated"); linear1.addView(btn1); //MyToggleButton with normal text MyToggleButton btn2 = new MyToggleButton(this,50); btn2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); btn2.setTextOff("Button 2 rotated"); btn2.setTextOn("Button 2 rotated"); btn2.setText("Button 2 rotated"); linear1.addView(btn2); //button to create screenshot Button btn3 = new Button(this); btn3.setText("Create bitmap"); btn3.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { takeScreenshot(); } }); linear1.addView(btn3); } //Screenshotcreator private void takeScreenshot() { try { View v1 = getWindow().getDecorView().getRootView(); // create bitmap screen capture v1.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache()); v1.setDrawingCacheEnabled(false); ImageView imageView1 =(ImageView) findViewById(R.id.imageView1); imageView1.setImageBitmap(bitmap); } catch (Throwable e) { e.printStackTrace(); } } } </code></pre> <p>Here is the layout of <code>MainActivity</code>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.gl.myapplication.MainActivity" android:id="@+id/relative1"&gt; &lt;LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/vert1"&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="250dp" android:id="@+id/imageView1" /&gt; &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p>The problem is that although everything looks ok on the screen, the screenshot's bitmap lacks the drawn line and the rotated text. </p> <p><a href="https://i.stack.imgur.com/1uNc2.png" rel="nofollow"><img src="https://i.stack.imgur.com/1uNc2.png" alt="You can see the problem here. Screen is OK, screenshot is not."></a></p> <p>What could be the reason for that strange result in the bitmap?</p> <p>Notice that that the devices back-home-recents buttons are missing from the screenshot, as also the status bar information (time etc). I doubt that this has to do something with my issue. Those elements do not belong in my app so it is expected for them to not appear in the view I get with get with <code>v1 = getWindow().getDecorView().getRootView();</code> But the canvas on which I draw the rotated text and the line do belong to that view.</p> <p>My question is: Why does the drawn line and the rotated text do not appear on the screenshot, and how can I modify my code to get a screenshot with them on too? </p> <p>I don't want to do something that needs a rooted device and also I cannot use MediaProjection API because this was added in API 21 but I want my app to run on android 4.4 (API 19) too. Finally, I am aware of the existence of external libraries such as Android Screenshot Library or this: <a href="http://android-arsenal.com/details/1/2793" rel="nofollow">https://android-arsenal.com/details/1/2793</a> , but I would rather not use any external library.</p> <p>P.S. maybe this is related:<a href="http://stackoverflow.com/questions/18316861/surfaceview-screenshot-with-line-ellipse-drawn-over-it?rq=1">Surfaceview screenshot with line/ellipse drawn over it</a></p>
<p>The problem is that both <code>btn1.isDrawingChaceEnabled()</code> and <code>btn2.isDrawingChaceEnabled()</code> return <code>false</code>. </p> <p>Even if you call <code>setDrawingCacheEnabled(true)</code> on the RootView, it is not set as <code>true</code> recursively on all his Children View (I tested it with Log.d).<br> That means that the drawing cache of your ToggleButton will be empty as explained in the <code>android.view.View.getDrawingCache()</code> javadoc.</p> <pre><code>/** * &lt;p&gt;Calling this method is equivalent to calling &lt;code&gt;getDrawingCache(false)&lt;/code&gt;.&lt;/p&gt; * * @return A non-scaled bitmap representing this view or null if cache is disabled. * * @see #getDrawingCache(boolean) */ </code></pre> <p>So make sure you set <code>setDrawingCacheEnabled(true)</code> for each of the views you are interested in.<br> For example I added the following lines to your code:<br> in MainActivity</p> <pre><code> btn1.setDrawingCacheEnabled(true); btn2.setDrawingCacheEnabled(true); </code></pre> <p><a href="https://i.stack.imgur.com/iMmwz.png" rel="nofollow">And it looks like this</a></p>
Storing the data in table ( SQL) <p>I am new to this programming field basically i from electrical field. now i learn SQL concepts.i have one database in that database had two table. my database name is "<strong>MyDataBase</strong>",and first table name is "Assets" then my second tale name is "<strong>AssetAssigneeMapper</strong>".</p> <p>First table columns are (Assets)</p> <pre><code> assetId int (Identity), assetName varChar(100), modelNo varChar(100), price decimal, quantity int. </code></pre> <p>My second table columns are (AssetAssigneeMapper)</p> <pre><code> assignId int (Identity), assetId int(Foreign Key ), assignedQty int, employeeName varChar(100). </code></pre> <p>I successfully store the data in my first table (Assets) by my coding but when i try to store data in second table, Compile is jumped to "catch" part. </p> <p>here is my code</p> <p>This code is for store data in first table </p> <pre><code>try { Console.WriteLine("Enter the asset name"); string assetName = (Console.ReadLine()).ToLower(); Console.WriteLine("Enter the model number"); string modelNo = Console.ReadLine(); Console.WriteLine("Enter the price of the asset"); decimal price = decimal.Parse(Console.ReadLine()); Console.WriteLine("Enter the quantity "); int quantity = int.Parse(Console.ReadLine()); using (var db = new MyDataBaseEntities()) { db.Assets.Add(new Asset() { assetName = assetName, modelNo = modelNo, price = price, quantity = quantity }); db.SaveChanges(); Console.WriteLine("New asset '{0}' Added in database successfully", assetName); } } catch { Console.WriteLine("Enter the proper input"); AddSingleAsset(); } </code></pre> <p>My code for store the data in second table is </p> <pre><code>try { Console.WriteLine("Enter the asset name to assign"); string assetName = Console.ReadLine().ToLower(); using (var database = new MyDataBaseEntities()) { var Check = database.Assets.FirstOrDefault (x =&gt; x.assetName == assetName); if (Check.assetName == assetName) { Console.WriteLine("How many asset to be assigned to employee"); string qty = Console.ReadLine(); int quantity; if (int.TryParse(qty, out quantity)) { if (Check.quantity &gt;= quantity) { Console.WriteLine("Enter the name of the employee"); String employeeName = Console.ReadLine(); database.AssetAssigneeMappers.Add(new AssetAssigneeMapper() { assignedQty = quantity, employeeName = employeeName }); database.SaveChanges(); Check.quantity = Check.quantity - quantity; database.SaveChanges(); Console.WriteLine("{0}[{1}]-Quantity has successfully assigned to {2}", assetName, Check.modelNo, employeeName); } else { Console.WriteLine("Quantity level is lower than your requirment"); } } else { Console.WriteLine("Given Quantity input is INVALID"); } } else { Console.WriteLine("Given Asset name is not available in database"); } } } catch { Console.WriteLine("Invalid input"); } </code></pre> <p>When i compile above(<strong>AssetAssigneeMapper</strong>) code, my result is below </p> <p><a href="https://i.stack.imgur.com/jtjQl.jpg" rel="nofollow">SAMPLE OUTPUT</a></p> <p>Any one please point out what i did wrong also suggest me right way </p>
<p>i got my desired output, what i did in here is ,i defined "assetId" is a "not null" type.In above code i didn`t add text to store <strong>assetId</strong> so only i get wrong output.</p> <p>right code is below</p> <pre><code>database.AssetAssigneeMappers.Add(new AssetAssigneeMapper() { assignedQty = quantity, employeeName = employeeName, assetId=Check.assetId }); database.SaveChanges(); </code></pre>
arduino and GSM shield <p>I wanted to connect arduino mega with GSM shield(mounting) and a ultrasound sensor with a battery(9V) to post data and send SMS. but it was working for 10 minutes and stops working i.e the lights are on but the signal is not constant(checked with all the networks and signal strengths : no issues there). It is working properly with new battery for 10 minutes(tested with several new batteries)Is this power issue. If yes, please help me resolve this issue. </p> <p>-Is GSM shield mounting creating the problem? -how to get a long battery life with arduino and GSM shield.</p> <p>Thanks, Sandeep</p>
<p>This is power issue, GSM modem uses 1W (200mA at 5V) of power on 850/900 MHz, and 2W on 1800/1900 MHz, and GSM shield requires peaks of up to 2A current. You need more batteries or dc power supply.</p>
Reading and closing large amount of files in new class result in OSError: Too many open files <p>I have large amount of files and I need to traverse them and search for some strings, when string is found, the file is copied into new folder, otherwise its closed.</p> <p>Here is example code:</p> <pre><code>import os import stringsfilter def apply_filter(path, filter_dict): dirlist = os.listdir(path) for directory in dirlist: pwd = path + '/' + directory filelist = os.listdir(pwd) for filename in filelist: if filename.split('.')[-1] == "stats": sfilter = stringsfilter.StringsFilter(pwd, filename, filter_dict["strings"]) sfilter.find_strings_and_move() </code></pre> <p>and here is stringsfilter.py:</p> <pre><code>import main import codecs import os import shutil class StringsFilter: strings = None def __init__(self, filepath, filename, strings): self.filepath = filepath self.filename = filename self.strings = strings self.logger = main.get_module_logger("StringsFilter") self.file_desc = codecs.open(self.filepath + '/' + self.filename, 'r', encoding="utf-8-sig") self.logger.debug("[-] Strings: " + str(self.strings)) self.logger.debug("[-] Instantiating class Strings Filter, filename: %s " % self.filename) def find_strings_and_move(self): for line in self.file_desc.readlines(): for string in self.strings: if string in line: self.move_to_folder() return self.close() def move_to_folder(self): name = self.filename.split('.')[0] os.mkdir(self.filepath + '/' + name) shutil.copyfile(self.filepath + '/' + self.filename, self.filepath + '/' + name + '/' + self.filename) self.close() def close(self): if self.file_desc: self.logger.debug("[-] Closing file %s" % self.filename) self.file_desc.close() </code></pre> <p>main.py:</p> <pre><code>import logging def get_module_logger(name): # create logger logger = logging.getLogger(name) # set logging level to log everything logger.setLevel(logging.DEBUG) # create file handler which logs everything fh = logging.FileHandler('files.log') fh.setLevel(logging.DEBUG) # create console handler ch = logging.StreamHandler() ch.setLevel(logging.INFO) # create formatter and add it to the handlersi formatter = logging.Formatter('[%(asctime)s] [%(name)-17s] [%(levelname)-5s] - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to the logger logger.addHandler(fh) logger.addHandler(ch) return logger </code></pre> <p>in log I can see following:</p> <pre><code>[2016-10-13 10:07:07,002] [StringsFilter ] [DEBUG] - [-] Strings: ['DEVICE_PROBLEM'] [2016-10-13 10:07:07,002] [StringsFilter ] [DEBUG] - [-] Instantiating class Strings Filter, filename: file1.stats [2016-10-13 10:07:07,003] [StringsFilter ] [DEBUG] - [-] Closing file file1.stats [2016-10-13 10:07:07,003] [StringsFilter ] [DEBUG] - [-] Strings: ['DEVICE_PROBLEM'] [2016-10-13 10:07:07,003] [StringsFilter ] [DEBUG] - [-] Strings: ['DEVICE_PROBLEM'] [2016-10-13 10:07:07,004] [StringsFilter ] [DEBUG] - [-] Instantiating class Strings Filter, filename: file2.stats [2016-10-13 10:07:07,004] [StringsFilter ] [DEBUG] - [-] Instantiating class Strings Filter, filename: file2.stats [2016-10-13 10:07:07,004] [StringsFilter ] [DEBUG] - [-] Closing file file2.stats [2016-10-13 10:07:07,004] [StringsFilter ] [DEBUG] - [-] Closing file file2.stats [2016-10-13 10:07:07,005] [StringsFilter ] [DEBUG] - [-] Strings: ['DEVICE_PROBLEM'] [2016-10-13 10:07:07,005] [StringsFilter ] [DEBUG] - [-] Strings: ['DEVICE_PROBLEM'] [2016-10-13 10:07:07,005] [StringsFilter ] [DEBUG] - [-] Strings: ['DEVICE_PROBLEM'] [2016-10-13 10:07:07,005] [StringsFilter ] [DEBUG] - [-] Instantiating class Strings Filter, filename: file3.stats [2016-10-13 10:07:07,005] [StringsFilter ] [DEBUG] - [-] Instantiating class Strings Filter, filename: file3.stats [2016-10-13 10:07:07,005] [StringsFilter ] [DEBUG] - [-] Instantiating class Strings Filter, filename: file3.stats [2016-10-13 10:07:07,006] [StringsFilter ] [DEBUG] - [-] Closing file file3.stats [2016-10-13 10:07:07,006] [StringsFilter ] [DEBUG] - [-] Closing file file3.stats [2016-10-13 10:07:07,006] [StringsFilter ] [DEBUG] - [-] Closing file file3.stats </code></pre> <p>And it goes on, it seems like with every iteration, each statement from <strong>init</strong> is done once more, until there are too many files open and program ends with </p> <pre><code>OSError: [Errno 24] Too many files open </code></pre> <p>I can't understand, why statements from <strong>init</strong> are called multiple times each time the instance is created.</p>
<p>Reason why you have same thing logged multiple times: Every time <code>main.get_module_logger("StringsFilter")</code> is called, you call <code>logger.addHandler(...)</code> on <strong>the same logger</strong> returned from <code>logging.getLogger(name)</code>, so you get multiple handlers in one logger. Better make module-level logger</p> <pre><code>import ... LOG = main.get_module_logger("StringsFilter") class StringsFilter:... </code></pre> <p>Regarding open files, I don't see the reason, but consider using <code>with open(filename) as f:</code> syntax in <code>find_strings_and_move()</code>. </p> <pre><code>LOG = main.get_module_logger("StringsFilter") class StringsFilter: strings = None def __init__(self, filepath, filename, strings): self.filepath = filepath self.filename = filename self.strings = strings LOG.debug("[-] Strings: " + str(self.strings)) LOG.debug("[-] Instantiating class Strings Filter, filename: %s " % self.filename) def find_strings_and_move(self): with open(self.filepath + '/' + self.filename, 'r') as file_desc: lines = file_desc.readlines() for line in lines: for string in self.strings: if string in line: self.move_to_folder() return def move_to_folder(self): name = self.filename.split('.')[0] os.mkdir(self.filepath + '/' + name) shutil.copyfile(self.filepath + '/' + self.filename, self.filepath + '/' + name + '/' + self.filename) </code></pre> <p>This way you make sure the file is closed 1) before move 2) always</p>
Posting meassages form PC to Slack by using JavaScript <p>I am trying to post messages from an app on my PC to Slack by using JavaScript. </p> <p>Could anyone tell me how to do that and I would be grateful if it was with simple example.</p> <p>Thank you very much in advance </p>
<p>You can use <a href="https://github.com/slackhq/node-slack-sdk" rel="nofollow">Slack</a> recommended <code>node-slack-sdk</code> library to do this.</p> <p>Samples are given in the <a href="https://github.com/slackhq/node-slack-sdk#send-messages" rel="nofollow">GitHub</a> page.</p>
Dynamic select fluent nhibernate <p>First of all, sorry for my bad english.</p> <p>I have a little trobule figurering this one out. I have three tables and I need to make it so that the user can decide witch columns to fetch from the database. I have tried using Dynamic nuget, but wont work. The code i need is something like the line below.</p> <pre><code>var res = session.QueryOver&lt;MyObject&gt;().Select(x =&gt; x.decidedByUser).List(); </code></pre> <p>Is this even possible or do I need to make some kind of workaround? Maybe something like getting all the values and then select? :-)</p>
<p>var columnProjection = Projections.Property(() => aliasForTable.Column1)</p> <p>you can use above variable in nhibernate select statement to decide which column you want to fetch. Create this assignment for each of your case and you're done</p>
Creating and using Sequence in Oracle stored procedure - Sequence doesn't exist <pre><code> DECLARE v_emp_id NUMBER; empid NUMBER; stmt VARCHAR2(1000); BEGIN SELECT MAX(emp_id) + 1 INTO v_emp_id FROM employees; BEGIN dbms_output.put_line(v_emp_id ); stmt := 'CREATE SEQUENCE emp_seq start with ' ||v_emp_id|| ' increment by 1 NOCYCLE'; EXECUTE IMMEDIATE stmt; COMMIT; END; insert into emp_new select emp_seq.nextval,empname from (select * from employee where active = 0); dbms_output.put_line(empid); END; / </code></pre> <p>When executing above procedure, I get the following errors ORA-06550: line 13, column 10: PL/SQL: ORA-02289: sequence does not exist ORA-06550: line 13, column 3: PL/SQL: SQL Statement ignored</p> <p>But when executing the below procedure, it is successful and sequence is created.</p> <pre><code> DECLARE v_emp_id NUMBER; empid NUMBER; stmt VARCHAR2(1000); BEGIN SELECT MAX(emp_id) + 1 INTO v_emp_id FROM employees; BEGIN dbms_output.put_line(v_emp_id ); stmt := 'CREATE SEQUENCE emp_seq start with ' ||v_emp_id|| ' increment by 1 NOCYCLE'; EXECUTE IMMEDIATE stmt; COMMIT; END; dbms_output.put_line(empid); END; / </code></pre>
<p>During compile time sequence not exists so compiler returns error. Execute immediate will be executed on runtime but compiler don't know that it will create sequence you called later in code.</p> <pre><code>create or replace procedure createtest as begin execute immediate 'create table t1 (c1 number)'; insert into t1 values (1); end; / </code></pre> <p>Gives the same error as yours as table t1 not exists. So insert statement is invalid. This is error during compilation of PL/SQL.</p> <pre><code>create table t1 (c1 number); </code></pre> <p>After that I can create procedure but when I do:</p> <pre><code>exec createtest; </code></pre> <p>I got error that table already exists. But compiler didn't knew that I'm trying create again same table so it will be returned on run not during compilation.</p> <p>If you really need to do it such way please do:</p> <pre><code>create or replace procedure createtest as begin execute immediate 'create table t1 (c1 number)'; execute immediate 'insert into t1 values (1)'; end; / </code></pre> <p>In you case:</p> <pre><code>execute immediate 'SELECT emp_seq.nextval FROM dual' INTO empid; </code></pre> <p>[EDIT] What I understand is you want to be sure that sequence is set to max(empid) so please do not try to create it inside procedure. Create sequence once then in procedure body execute:</p> <pre><code>select max(empid) into maxempid from employee; select emp_seq.currval into maxseq from dual; if(empid-maxseq&gt;0) then execute immediate 'alter sequence emp_seq increment by ' || empid-maxseq; end if; </code></pre>
How can I page query database without lost records? <p>We want to programmably copy all records from one table to another periodically.</p> <p>Now I use <code>SELECT * FROM users LIMIT 2 OFFSET &lt;offset&gt;</code> for fetch records.</p> <p>The table records like below:</p> <pre><code>user_1 user_2 user_3 user_4 user_5 user_6 </code></pre> <p>When I fetched the first page (user_1, user_2), then the record "user_2" was be deleted at the source table. </p> <p>And now I fetched the second page is (user_4, user_5), the third page is (user_6). </p> <p>This lead to I lost the records "user_3" at the destination table.</p> <p>And the real source table may be has 1000 000 records, How can I resolve the problem effectively?</p>
<p>First you should use an unique index on the source table and use it in an order clause to make sure that the order or the rows is consistent over time. Next you do not use offsets but start after the last element fetched.</p> <p>Something like:</p> <pre><code>SELECT * FROM users ORDER BY id LIMIT 2; </code></pre> <p>for the first time, and then</p> <pre><code>SELECT * FROM users WHERE ID &gt; last_recieved_id ORDER BY id LIMIT 2; </code></pre> <p>for the next ones.</p> <p>This will be immune to asynchronous deletions.</p> <hr> <p>I you have no unique index but have a non unique one in your table, you can still apply the above solution with a non-strict comparison operator. You will consistently re-get the last rows and it would certainly break with a limit 2, but it could work for reasonable values.</p> <p>If you have no index - which is known to cause different other problems - the only reliable way is to have one single big select and use the SQL cursor to page.</p>
Unable to start activity: bind value at index 1 is null <p>I write below codes, but when running application show me <strong>Force Close</strong> error.<br></p> <p><strong>Database helper codes:</strong></p> <pre><code>public boolean checkFavPost(String title) { // 1. get reference to writable DB SQLiteDatabase db = this.getWritableDatabase(); // 2. set cursor for read row Cursor cursor = db.rawQuery("SELECT * FROM " + FavContract.favInfo.TABLE_NAME + " WHERE " + FavContract.favInfo.FAV_TBL_PTitle + " = ?", new String[]{title}); boolean exists = (cursor.getCount() &gt; 0); db.close(); return exists; } </code></pre> <p><strong>Activity codes:</strong></p> <pre><code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.post_show_page); bindActivity(); // Initialize context = PostShow_page.this; favDB = new FavHelper(context); postShow_favPost = (ShineButton) mToolbar.findViewById(R.id.post_FavImage); post_cover = (ImageView) findViewById(R.id.postShow_cover_image); postShow_title = (TextView) findViewById(R.id.postShow_title); postShow_title2 = (TextView) findViewById(R.id.postShow_titleBig); //postShow_content = (TextView) findViewById(R.id.postShow_content_text); postShow_dateTime = (TextView) findViewById(R.id.postShow_man_date_text); postShow_author = (TextView) findViewById(R.id.postShow_man_author_text); postShow_category = (TextView) findViewById(R.id.postShow_man_category_text); title_sliding = (TextView) findViewById(R.id.post_sliding_title); comment_Recyclerview = (RecyclerView) findViewById(R.id.comment_recyclerView); post_content_web = (WebView) findViewById(R.id.postShow_content_web); mLayoutManager = new LinearLayoutManager(this); mAdaper = new CommentAdapter2(context, models); //Give Data Bundle bundle = getIntent().getExtras(); if (bundle != null) { postID = bundle.getInt("postID"); title = bundle.getString("title"); image = bundle.getString("image"); content = bundle.getString("content"); dateTime = bundle.getString("dateTime"); author = bundle.getString("author"); category = bundle.getString("category"); categoryID = bundle.getString("categoryID"); } Intent intent = getIntent(); String action = intent.getAction(); Uri data = intent.getData(); mAppBarLayout.addOnOffsetChangedListener(this); // Setup comment RecyclerView comment_Recyclerview.setLayoutManager(mLayoutManager); comment_Recyclerview.setHasFixedSize(true); postShow_favPost.init(this); postShow_favPost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* if (postShow_favPost.isChecked()) { /// Add to Database favDB.insertFAV(context, title, image, content, dateTime, author, category); } else { TastyToast.makeText(context, "برای حذفش به علاقه مندی ها برو", TastyToast.LENGTH_LONG, TastyToast.WARNING); }*/ if (postFavState == 0) { /// Add to Database favDB.insertFAV(context, title, image, content, dateTime, author, category); postFavState++; } else { postShow_favPost.setBtnColor(ContextCompat.getColor(context, R.color.favColorON)); postShow_favPost.setBtnFillColor(ContextCompat.getColor(context, R.color.favColorON)); TastyToast.makeText(context, "برای حذفش به علاقه مندی ها برو", TastyToast.LENGTH_LONG, TastyToast.WARNING); } } }); if (favDB.checkFavPost(title)) { postShow_favPost.setBtnColor(ContextCompat.getColor(context, R.color.favColorON)); postShow_favPost.setBtnFillColor(ContextCompat.getColor(context, R.color.favColorOFF)); } else { postShow_favPost.setBtnColor(ContextCompat.getColor(context, R.color.favColorOFF)); postShow_favPost.setBtnFillColor(ContextCompat.getColor(context, R.color.favColorON)); } //mToolbar.inflateMenu(R.menu.post_menu); mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.menu_share: break; } return true; } }); startAlphaAnimation(mTitle, 0, View.INVISIBLE); // Set Data into views if (title != null) { postShow_title.setText(title); postShow_title2.setText(title); title_sliding.setText(getResources().getString(R.string.comment_title) + " " + title); } loadPostProgressDialog.createAndShow(this); if (image != null) { Glide.with(this) .load(image) .placeholder(R.drawable.post_image) .listener(new RequestListener&lt;String, GlideDrawable&gt;() { @Override public boolean onException(Exception e, String model, Target&lt;GlideDrawable&gt; target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target&lt;GlideDrawable&gt; target, boolean isFromMemoryCache, boolean isFirstResource) { loadPostProgressDialog.dissmis(); return false; } }) .into(post_cover); } if (content != null) { //postShow_content.setText(Html.fromHtml(content)); post_content_web.getSettings().setJavaScriptEnabled(true); WebSettings settings = post_content_web.getSettings(); settings.setDefaultTextEncodingName("utf-8"); post_content_web.loadData(content, "text/html; charset=utf-8", "utf-8"); } if (dateTime != null) { postShow_dateTime.setText(dateTime); } if (author != null) { postShow_author.setText(author); } if (category != null) { postShow_category.setText(category); } post_cover.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { BlurBehind.getInstance().execute(PostShow_page.this, new OnBlurCompleteListener() { @Override public void onBlurComplete() { startActivity(new Intent(PostShow_page.this, DialogImage_page.class) .setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION) .putExtra("imageCover", image)); } }); } }); postShow_category.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (categoryID != null) { startActivity(new Intent(PostShow_page.this, Category_page.class) .putExtra("categoryID", categoryID) .putExtra("categoryTitle", category)); } } }); //Sliding Up slideHandleButton = (ImageView) findViewById(R.id.image_sliding); slidingDrawer = (SlidingDrawer) findViewById(R.id.SlidingDrawer); slidingDrawer.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() { @Override public void onDrawerOpened() { slideHandleButton.setImageResource(R.drawable.ic_down_arrow_sliding); title_sliding.setText(getResources().getString(R.string.comment_title) + " " + title); // Load Comment data bindData(); } }); slidingDrawer.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() { @Override public void onDrawerClosed() { slideHandleButton.setImageResource(R.drawable.ic_up_arrow_sliding); title_sliding.setText(getResources().getString(R.string.comment_title) + " " + title); } }); } private void bindActivity() { mToolbar = (Toolbar) findViewById(R.id.postShow_toolbar); mTitle = (TextView) findViewById(R.id.postShow_title); mTitleContainer = (LinearLayout) findViewById(R.id.postShow_linearlayout_title); mAppBarLayout = (AppBarLayout) findViewById(R.id.postShow_appBar); } private void bindData() { // Setup Connect Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class); Call&lt;R_CatModelResponse&gt; call = apiInterface.getCatResponse(postID); Log.d("PostID", "Post : " + postID); call.enqueue(new Callback&lt;R_CatModelResponse&gt;() { @Override public void onResponse(Call&lt;R_CatModelResponse&gt; call, Response&lt;R_CatModelResponse&gt; response) { if (response != null) { models.addAll(response.body().getCat_posts().get(0).getComments()); mAdaper.notifyDataSetChanged(); Toast.makeText(PostShow_page.this, "GoTo Adapter", Toast.LENGTH_SHORT).show(); comment_Recyclerview.setAdapter(mAdaper); } } @Override public void onFailure(Call&lt;R_CatModelResponse&gt; call, Throwable t) { Toast.makeText(PostShow_page.this, "Failed", Toast.LENGTH_SHORT).show(); } }); } </code></pre> <p>Show me error for this codes:</p> <pre><code>if (favDB.checkFavPost(title)) { postShow_favPost.setBtnColor(ContextCompat.getColor(context, R.color.favColorON)); postShow_favPost.setBtnFillColor(ContextCompat.getColor(context, R.color.favColorOFF)); } else { postShow_favPost.setBtnColor(ContextCompat.getColor(context, R.color.favColorOFF)); postShow_favPost.setBtnFillColor(ContextCompat.getColor(context, R.color.favColorON)); } </code></pre> <p><strong>Force Close error :</strong> </p> <blockquote> <p>FATAL EXCEPTION: main Process: com.tellfa.colony, PID: 21513 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tellfa.colony/com.tellfa.colony.Activities.PostShow_page}: java.lang.IllegalArgumentException: the bind value at index 1 is null at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5349) 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:908) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703) Caused by: java.lang.IllegalArgumentException: the bind value at index 1 is null at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:164) at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200) at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47) at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1426) at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1365) at com.tellfa.colony.DBhelper.FavHelper.checkFavPost(FavHelper.java:141) at com.tellfa.colony.Activities.PostShow_page.onCreate(PostShow_page.java:179) at android.app.Activity.performCreate(Activity.java:6020) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2284) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)  at android.app.ActivityThread.access$800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5349)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)</p> </blockquote> <p>How can i fix this error?</p>
<p>Okay, so first thing's first: This is the main reason why your app crashed:</p> <pre><code> java.lang.IllegalArgumentException: the bind value at index 1 is null </code></pre> <p>This is from a wrong binding parameter of a PreparedStatement. There are possibilities of <code>title</code> being passed into <code>checkFavPost</code> is <code>null</code>. You have to prepare for this.</p> <p>So, to fix it, do something like this:</p> <pre><code> public boolean checkFavPost(String title) { if (title == null) return false; // 1. get reference to writable DB SQLiteDatabase db = this.getWritableDatabase(); // 2. set cursor for read row Cursor cursor = db.rawQuery("SELECT * FROM " + FavContract.favInfo.TABLE_NAME + " WHERE " + FavContract.favInfo.FAV_TBL_PTitle + " = ?", new String[]{title}); boolean exists = (cursor.getCount() &gt; 0); db.close(); return exists; } </code></pre>
function template as a function argument <p>I want to implement a function which acts as MATLAB sort(). I defined a structure and a function template in a head file, as below.</p> <pre><code>template&lt;typename T_val&gt; struct SORT_DATA { T_val value; // int index; }; template&lt;typename T_var&gt; bool ccmp(SORT_DATA&lt;T_var&gt; &amp; var_a, SORT_DATA&lt;T_var&gt; &amp; var_b) { return var_a.value &lt; var_b.value; } </code></pre> <p>In main(), I use a structure variable and pass the ccmp() as an argument to C++ sort(), as below.</p> <pre><code>//SORT_DATA&lt;double&gt; * data1 = new SORT_DATA&lt;double&gt;[15]; SORT_DATA&lt;double&gt; data1[15]; double tmp_data[15] = {25, 23, 1, 32, 0, 43, 98, 8, 7, 11, 34, 52, 32, -53, 6}; for(int i=0; i&lt;15; i++) { data1[i].value = tmp_data[i]; data1[i].index = i; } //sort(data1, data1+15, ccmp); for(int i=0; i&lt;15; i++) std::cout&lt;&lt;setw(5)&lt;&lt;data1[i].value&lt;&lt;" "; std::cout&lt;&lt;std::endl; for(int i=0; i&lt;15; i++) std::cout&lt;&lt;setw(5)&lt;&lt;data1[i].index&lt;&lt;" "; </code></pre> <p>I got several problems: 1. It seems that memory was failed to allocate for the structure variable. 2. I got an error message from VS2010 telling that function template cannot be used as a function argument.</p> <pre><code>#pragma once #include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;algorithm&gt; #include "customizedalg.h" // This is simply the declaration of the struct and bool cmp(). using namespace std; int main(int argc, char ** argv) { SORT_DATA&lt;double&gt; * data1 = new SORT_DATA&lt;double&gt;[15]; //SORT_DATA&lt;double&gt; data1[15]; double tmp_data[15] = {25, 23, 1, 32, 0, 43, 98, 8, 7, 11, 34, 52, 32, -53, 6}; for(int i=0; i&lt;15; i++) { data1[i].value = tmp_data[i]; data1[i].index = i; } sort(data1, data1+15, ccmp&lt;double&gt;); for(int i=0; i&lt;15; i++) std::cout&lt;&lt;setw(5)&lt;&lt;data1[i].value&lt;&lt;" "; std::cout&lt;&lt;std::endl; for(int i=0; i&lt;15; i++) std::cout&lt;&lt;setw(5)&lt;&lt;data1[i].index&lt;&lt;" "; std::cout&lt;&lt;std::endl; std::cin.ignore(); return 0; } </code></pre>
<p>You should <strong>specify template</strong> of <code>ccmp</code> function, as Piotr commented, but you do not need to take address of function:</p> <p><code> std::sort(data1, data1+15, ccmp&lt;double&gt;); </code></p> <p><a href="http://cpp.sh/72ia" rel="nofollow">Here is working sample</a></p> <p>And if your compiler fails to use templated function, you can try making a struct with overloaded operator():</p> <pre><code>template&lt;typename T_var&gt; struct ccmp { bool operator()(SORT_DATA&lt;T_var&gt; &amp; var_a, SORT_DATA&lt;T_var&gt; &amp; var_b) const { return var_a.value &lt; var_b.value; } }; ... std::sort(data1, data1+15, ccmp&lt;double&gt;()); </code></pre> <p><a href="http://cpp.sh/8j3tc" rel="nofollow">Sample</a></p>
Should we write dependent: destroy on a join table model? <p>I have 3 models A, B and C. B is the join table between A &amp; C. The association is made through a <code>has_many :through</code>.</p> <p>I was wondering if the non-join-table models (A &amp; C in my case) should have <code>dependent: :destroy</code> with the join table association or if it's taken care automatically by rails ?</p> <p>Is it the same answer for a HABTM association ?</p>
<p>No, because you can delete records without instantiating them which wouldn't call dependent destroy and you'd be left with orphaned records.</p> <p>For example <a href="http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-delete_all" rel="nofollow">delete_all</a></p> <p>Instead if you add a foreign key the database will handle the delete and it doesn't matter if you instantiate the object or not.</p> <p>For example in a migration you can add</p> <pre><code>def change add_foreign_key :as, :bs, on_delete: :cascade end </code></pre> <p>Or in the table creation migration</p> <pre><code>t.belongs_to :a, foreign_key: { on_delete: :cascade } </code></pre>
Kotlin, instantiation issue and generic <p>I have a class Vec3i that extends Vec3t</p> <pre><code>data class Vec3i( override var x: Int = 0, override var y: Int = 0, override var z: Int = 0 ) : Vec3t(x, y, z) </code></pre> <p>that has as one secondary constructor as follow</p> <pre><code>constructor(v: Vec3t&lt;Number&gt;) : this(v.x.toInt(), v.y.toInt(), v.z.toInt()) </code></pre> <p>and another class Vec3ub that extends always Vec3t</p> <pre><code>data class Vec3ub( override var x: Ubyte = Ubyte(0), override var y: Ubyte = Ubyte(0), override var z: Ubyte = Ubyte(0) ) : Vec3t(x, y, z) </code></pre> <p>Where Vec3t is in turn</p> <pre><code>abstract class Vec3t&lt;T : Number&gt;( override var x: T, override var y: T, open var z: T ) : Vec2t(x, y) </code></pre> <p>And Ubyte extends Number</p> <p>I'd like to instantiate a Vec3i from a Vec3ub</p> <pre><code>Vec3i(vec3ub) </code></pre> <p>but the compilers complains that there is no constructor for that.. </p> <p>why isn't valid the secondary constructor I quoted previously?</p>
<p>For completeness, as stated in my comment, the following compiles correctly:</p> <pre><code>data class Vec3i( override var x: Int = 0, override var y: Int = 0, override var z: Int = 0 ) : Vec3t&lt;Int&gt;(x, y, z) { constructor(v: Vec3t&lt;out Number&gt;) : this(v.x.toInt(), v.y.toInt(), v.z.toInt()) } data class Vec3ub( override var x: Ubyte, override var y: Ubyte, override var z: Ubyte ) : Vec3t&lt;Ubyte&gt;(x, y, z) abstract class Vec3t&lt;T&gt;( override var x: T, override var y: T, open var z: T ) : Vec2t&lt;T&gt;(x, y) open class Vec2t&lt;T&gt;( open var x: T, open var y: T ) fun test(vec3ub: Vec3ub) { val vec3i = Vec3i(vec3ub) } abstract class Ubyte : Number() </code></pre> <p>Note the <code>constructor(v : Vec3t&lt;out Number&gt;) : ...</code> and all other added generic parameter types. <code>Vec3t&lt;out Number&gt;</code> is necessary instead of just <code>Vec3t&lt;Number&gt;</code> here since you don't pass a <code>Number</code>, but rather a subclass of it.</p>
Unable to get the reason for compiler errors on increment operators for variable and constant <p>I am testing the below scenario using increment operator</p> <pre><code>int i=3; int j=2; System.out.println("data: "+(i+++j)); </code></pre> <p>Here I am getting the expected output, but if I change it to</p> <pre><code>System.out.println("data: "+(2+++3)); // compiler error (Invalid argument to operation ++/--) </code></pre> <p>Could anyone please elaborate? Is it the using of constant? And why?</p>
<p>By using <code>+(i+++j)</code> the increment operators work on variables i.e i++ is the same as i+=1 by using <code>+(2+++3)</code> since 2 is not a variable,you cannot increment it i.e 2+=1 is not a legal statement in java</p>
Semantic HTML: where to place my form buttons? <p>Consider the next form:</p> <pre><code>&lt;form&gt; &lt;h2&gt;Form&lt;/h2&gt; &lt;fieldset&gt; &lt;legend&gt;Simple list with Create/Delete&lt;/legend&gt; [...] &lt;footer&gt; &lt;button&gt;Add&lt;/button&gt; &lt;button&gt;Remove&lt;/button&gt; &lt;button&gt;Remove all&lt;/button&gt; &lt;/footer&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;legend&gt;Single input&lt;/legend&gt; &lt;input type="file" /&gt; &lt;footer&gt; &lt;button&gt;Save as PDF&lt;/button&gt; &lt;button&gt;Save as XLS&lt;/button&gt; &lt;button&gt;Save as SVG&lt;/button&gt; &lt;/footer&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;legend&gt;Dynamic wizard&lt;/legend&gt; [...] &lt;footer&gt; &lt;button&gt;Next&lt;/button&gt; &lt;/footer&gt; &lt;/fieldset&gt; [...] &lt;footer&gt; &lt;button&gt;Reset&lt;/button&gt; &lt;button&gt;Cancel&lt;/button&gt; &lt;button&gt;Save&lt;/button&gt; &lt;/footer&gt; &lt;/form&gt; </code></pre> <p>I feel comfortable with the idea of using <code>&lt;footer&gt;</code> inside a <code>&lt;form&gt;</code> or a <code>&lt;fieldset&gt;</code>, but im not sure if it's correct, it looks a bit saturated with footers</p> <p>I could use <code>&lt;div&gt;</code> instead of <code>&lt;footer&gt;</code> but it feels "semantically poor", and <code>&lt;menu&gt;</code> feels awkward when using a single button.</p> <p>Maybe the solution is to place them directly under <code>&lt;form&gt;</code> or <code>&lt;fieldset&gt;</code>.</p> <pre><code>&lt;form&gt; &lt;h2&gt;Form&lt;/h2&gt; [...] &lt;button&gt;Reset&lt;/button&gt; &lt;button&gt;Cancel&lt;/button&gt; &lt;button&gt;Save&lt;/button&gt; &lt;/form&gt; </code></pre> <p>¿What do you guys recommend?</p>
<p>You can place your form fields and buttons in separate <code>section</code> blocks.</p> <pre><code>&lt;form&gt; &lt;section class="fields"&gt; &lt;fieldset&gt; &lt;legend&gt;Simple list with Create/Delete&lt;/legend&gt; ... &lt;/fieldset&gt; &lt;/section&gt; &lt;section class="fields"&gt; &lt;fieldset&gt; &lt;legend&gt;Single input&lt;/legend&gt; ... &lt;/fieldset&gt; &lt;/section&gt; &lt;section class="buttons"&gt; &lt;button type="button"&gt;Reset&lt;/button&gt; &lt;button type="button"&gt;Cancel&lt;/button&gt; &lt;button type="submit"&gt;Save&lt;/button&gt; &lt;/section&gt; &lt;/form&gt; </code></pre>
Set radio buttons using Jquery and html <p>My Jquery code is as follows</p> <pre><code>&lt;script type='text/javascript'&gt; window.onload=function(){ $(document).ready(function() { $('input[type=radio][name=name]').change(function() { if (this.value == 'value1') { $("#myModal1").modal('show'); } else if(this.value == 'value2') { $("#myModal2").modal('show'); } }); }); } &lt;/script&gt; </code></pre> <p>my html code is here,</p> <pre><code>&lt;input type="radio" name="name" value="value1"&gt;Male&lt;br&gt; &lt;input type="radio" name="name" value="value2"&gt;Femal&lt;br&gt; </code></pre> <p>and myModal1 is here</p> <pre><code>&lt;div id="myModal1" class="modal fade"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;&amp;times;&lt;/button&gt; &lt;h4 class="modal-title"&gt;Male&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12"&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;input type="checkbox"&gt;Amal &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-xs-12"&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;input type="checkbox"&gt;kamal &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-xs-12"&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;input type="checkbox"&gt;Nimal &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-primary pull-right" data-dismiss="modal"&gt;Save&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>What I want to do is to set radio buttons like below, if I click on "male" radio button then myModel1 should be appeared, and if I click on "female" radio button then myModel2 should be appeared. And both radio buttons should be selected. But I am unable to do that because I am a very beginner to jquery. If I want to select only one radio button and to get its modal, this code really works. Could anyone please help me to set the code as what I need?</p>
<p>Radio buttons are meant for mutually exclusive choices - not to be selected at the same time (use checkboxes for that):</p> <p>also you can simplify your logic a bit: set the value to either 1 or 2 for the radio buttons - on the change event - grab the value from the radio buttons and use that as a variable to trigger the modal to show.</p> <p>Note that I am just consol.logging the changed value and have commented out the actual .'show') command since I don't have the modal in therte - but you would be able to apply this to your code and trigger the required modal.</p> <p>I would also suggest only having the one modal and swap the display of different divbs within it to display the two states. Better than replicating the code for two modals.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){ $('input[type=radio][name=name]').change(function() { var option =$(this).val(); console.log('modal ' + option +' would be triggered'); //$("#myModal" + option).modal('show'); }) })</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;input type="radio" name="name" value="1"/&gt;Male&lt;br&gt; &lt;input type="radio" name="name" value="2"/&gt;Female&lt;br&gt;</code></pre> </div> </div> </p>
How to run this project on Eclipse Mars? <p>I imported an android project from <a href="https://drive.google.com/file/d/0B0z3LFuVZAYYQ214VVVtODh3OWM/view?usp=sharing" rel="nofollow">here</a>, it says min SDK 10 and max SDK 19, so I downloaded the API versions from 10 to 19, also in layout -> main.xml -> in Android version to use for rendering layout I chose API 19.</p> <p>When I am running this app on my phone (Note 2, Kitkat). I keep getting error that the application has been stopped. I have attached below the image of the screenshot of the logcat. </p> <p><a href="https://i.stack.imgur.com/jV7Ue.png" rel="nofollow"><img src="https://i.stack.imgur.com/jV7Ue.png" alt="enter image description here"></a></p>
<p>Taken from the 3rd red line of the shared image</p> <blockquote> <pre><code>java.lang.RuntimeException: Unable to instantiate application com.foxdogstudios.peepers.PeeperspAplication: java.lang.ClassNotFoundException: Didn't find class "com.foxdogstudios.peepers.PeepersApplication" on path /data/app-lib/com.foxdogstudios.peepers-1.apk, /vendor/lib /system/lib </code></pre> </blockquote> <p>It seems that the built apk does not include the class <code>PeepersApplication</code></p>
Video Upload issue in android <p>I am trying to upload an mp4 file from sd card to remote server. The upload is getting sucessfully, but while i am trying to play that file by url using VideoView it is showing "can't play this video ". This issue is happening for only videos which is captured using phone, Suppose if i am uploading a video from watsapp folder everything works fine without any issues. Do i need to do any compression before uploading ? Here is the code which i am using for uploading video</p> <pre><code> try { FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(my url for upload); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("myFile", fileName); video_name = fileName; video_name = fileName.substring(fileName.lastIndexOf("/")+1); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); Log.i("ava", "Initial .available : " + bytesAvailable); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead &gt; 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); serverResponseCode = conn.getResponseCode(); Content = conn.getResponseMessage(); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } </code></pre>
<p>Yes it may occurs because your URL contains white-spaces so you need to just remove space and set </p> <blockquote> <p>%20</p> </blockquote> <p>insted of white-space like :</p> <blockquote> <p>URL url1 = new URL(your_url.trim().replace(" ", "%20"));</p> </blockquote> <p>hope it works for you</p>
Repopulating Scraped Table Data Via Web Source Based on a Cell Input (from a Barcode Scanner) <p>I am scraping the table data from a sports card authentication site (e.g. psacard.com/cert/25819397/) that encapsulates every card in acrylic and has a unique barcode with a web source table import. <a href="https://i.stack.imgur.com/nrEtq.png" rel="nofollow">Card Example</a> I am creating a product csv with the results.</p> <p>Now cards are very time consuming to list because they have many important attributes that all must be typed out, so from that scrape I then map the returned fields to my product csv <a href="https://i.stack.imgur.com/1juRo.png" rel="nofollow">Table Data Returned</a> and then add them together so I have to input as little data as possible. I take the returned brand, year, and player and make a product's imported title "player + year + brand" to import into woocommerce or ebay. I do similar things for the rest of the fields. Delimited text is my comfort zone.</p> <p>What I am trying to figure out is how best to take the rs232 scanner data which automatically enters scanned data as text plus a terminator and populate each line of my product database with data pulled from the scrape.</p> <p>1) Is the Excel web data source manipulable at all with a VBA script, or do I need a purely macro based solution for fetching/scraping the data once a scan inputs a serial number in a cell?</p> <p>2) Is it even possible to trigger such a long chain of events with a scan reliably in Excel?</p> <p>I guess I am stuck conceptually here. I have many possible deep rabbit holes for each segment of the task. I don't know where I should invest my time first. The site does not return JSON or XML with any RESTful request as there is no available API. It's tables or bust which makes me useless programmatically without javascript.</p>
<p>I found the solution, it is here: <a href="https://www.youtube.com/watch?v=ZJ30U0qw850" rel="nofollow">https://www.youtube.com/watch?v=ZJ30U0qw850</a></p> <p>It needs some scripting of the operations, but that is fairly straightforward. The logic is worked out.</p> <p>1) Scan card, which enters integer (barcode) on a predefined cell.</p> <p>2) That cell triggers automatically refreshing web query like the one described in the video.</p> <p>3) A table populated by the web query is called by another table which joins/edits/formats the variable data as a product list row.</p> <p>4) A macro listens for a change in the original cell data to make the next row become the live row for input.</p>
How to check whether app is compatible in all devices or not? <p>I have developed app and tested it in the all the possible devices i have(i.e. on physical devices,genymotion).But i got reviews from client that in some devices it works and in some devices it won't.</p> <p>I have added the <code>minSdkVersion</code> and <code>targetSdkVersion</code> in my <code>AndroidManifest.xml</code> file.<br></p> <p>So,I want to know that is there any tool/software available online to find out that app(which i have developed) is compatible in this list of devices with respective information.</p> <p>Please suggest me other ways to get the info for same.</p> <p>Thanks in Advance.</p>
<p>There is a tool which lets you test your app with multiple virtual and real devices. The link is :</p> <p><a href="https://testobject.com" rel="nofollow">https://testobject.com</a></p>
AngularJS with jquery <p>I am new to angularJS .. previous I use to work with Jquery. </p> <p>So I have question in my mind, can we access variable which are declared in angularJS "<strong>$scope.options</strong>" using jquery.?</p> <pre><code> var hostApp = angular.module('hostApp', []); hostApp.controller('hostController', function ($scope) { $scope.options = [ { value: '1', label: 'hosting1' }, { value: '2', label: 'hosting2' }, { value: '3', label: 'hosting3' } ]; $scope.hostSelected = $scope.options[0]; }); </code></pre>
<p>Yes you can using <strong>$apply</strong></p> <p>HTML:</p> <pre><code>&lt;input type="text" id="txtbox" ng-model="txt" /&gt; &lt;br /&gt; text is : {{ txt }} &lt;br /&gt; &lt;input type="button" id="btnJq" value="Jquery change" /&gt; </code></pre> <p>Script:</p> <pre><code>angular.module("md", []) .controller("crt", function ($scope) { $scope.txt = "text"; }) $(document).ready(function () { $("#btnJq").click(function () { var scope = angular.element($("#txtbox")).scope(); scope.txt = 'Changed'; scope.$apply(); }) }) </code></pre>
Getting Facebook profile picture URL from graph API for Ionic Hybrid Application <p>Facebook graph API tells me I can get a profile picture of a user using</p> <p><a href="http://graph.facebook.com/100001225634061/picture?type=large" rel="nofollow">http://graph.facebook.com/100001225634061/picture?type=large</a></p> <p>which works fine.</p> <p>But If I used the same application in <strong>iOS devices</strong> this link is not working.</p> <p>For Hybrid applications, Graph url is not redirecting in iOS.</p> <p>Any solution for this? Single solution should work on both the devices.</p> <p>Thanks!</p>
<p>Don't use <strong>http</strong>. You can use the <strong>https</strong>.</p> <p><a href="https://graph.facebook.com/100001225634061/picture?type=large" rel="nofollow">https://graph.facebook.com/100001225634061/picture?type=large</a></p>
Laravel routing page not fount error while passing veriable <p>I am new to the Laravel while I reading the documentation I had a problem under routing.. it shows we can pass verifiable like this,</p> <pre><code>Route::get('user/{id}', function ($id) { return 'User '.$id; }); </code></pre> <p>here what is the <code>user</code> is it <code>Controller</code> or <code>veritable</code> name. I tried to pass the verbal like below but it is getting error</p> <p><a href="https://i.stack.imgur.com/U6WKJ.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/U6WKJ.jpg" alt="enter image description here"></a></p> <p>my route code is ,</p> <pre><code>Route::get('/{id}', function ($id) { echo 'ID: '.$id; }); </code></pre>
<p>Your route is correct</p> <pre><code>Route::get('/{id}', function ($id) { echo 'ID: '.$id; }); </code></pre> <p>i have tested it and its working fine</p> <p>Can you check .htaccess file under public folder.</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; &lt;IfModule mod_negotiation.c&gt; Options -MultiViews &lt;/IfModule&gt; RewriteEngine On # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] &lt;/IfModule&gt; </code></pre> <p>Also make sure about laravel project folder name is spelled correctly</p>
Regular expression finding '\n' <p>I'm in the process of making a program to pattern match phone numbers in text.</p> <p>I'm loading this text:</p> <pre><code>(01111-222222)fdf 01111222222 (01111)222222 01111 222222 01111.222222 </code></pre> <p>Into a variable, and using "findall" it's returning this:</p> <pre><code>('(01111-222222)', '(01111', '-', '222222)') ('\n011112', '', '\n', '011112') ('(01111)222222', '(01111)', '', '222222') ('01111 222222', '01111', ' ', '222222') ('01111.222222', '01111', '.', '222222') </code></pre> <p>This is my expression:</p> <pre><code>ex = re.compile(r"""( (\(?0\d{4}\)?)? # Area code (\s*\-*\.*)? # seperator (\(?\d{6}\)?) # Local number )""", re.VERBOSE) </code></pre> <p>I don't understand why the '\n' is being caught. </p> <p>If <code>*</code> in '<code>\\.*</code>' is substituted for by '<code>+</code>', the expression works as I want it. Or if I simply remove <code>*</code>(and being happy to find the two sets of numbers separated by only a single period), the expression works.</p>
<p>The <code>\s</code> matches both <em>horizontal</em> and <em>veritcal</em> whitespace symbols. If you have a <code>re.VERBOSE</code>, you can match a normal space with an escaped space <code>\ </code>. Or, you may exclude <code>\r</code> and <code>\n</code> from <code>\s</code> with <code>[^\S\r\n]</code> to match horizontal whitespace.</p> <p>Use</p> <pre><code>ex = re.compile(r"""( (\(?0\d{4}\)?)? # Area code ([^\S\r\n]*-*\.*)? # seperator ((HERE)) (\(?\d{6}\)?) # Local number )""", re.VERBOSE) </code></pre> <p>See the <a href="https://regex101.com/r/TefKkm/3" rel="nofollow">regex demo</a></p> <p>Also, the <code>-</code> outside a character class does not require escaping.</p>
Angular ng-repeat in select options showing extra space and not selecting default value. <p>I am trying to show a list of years in a select box through angular's <code>ng-repeat</code> but it is showing an empty line before list of years and not showing selected value which should be first year in the list. you can see in code example. any help will be highly appreciated.</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> angular.module('F1FeederApp', ['F1FeederApp.controllers']); angular.module('F1FeederApp.controllers', []). /* Drivers controller */ controller('driversController', function($scope) { $scope.years = getYearRange(); }); /* Year Range Code */ function getYearRange() { var startYear = new Date().getFullYear(); var endYear = 2005; var dateRange = []; while(endYear &lt;= startYear) { dateRange.push(startYear); startYear -= 1 } return dateRange; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app="F1FeederApp"&gt; &lt;div ng-controller="driversController"&gt; &lt;select ng-model="F1s_Selection" class="btn btn-default"&gt; &lt;option ng-repeat="year in years"&gt;{{year}}&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
<p>Use <a href="https://docs.angularjs.org/api/ng/directive/ngOptions" rel="nofollow"><code>ng-options</code></a> instead of <code>ng-repeat</code> it works and it's better.</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>angular.module('F1FeederApp', ['F1FeederApp.controllers']); angular.module('F1FeederApp.controllers', []). /* Drivers controller */ controller('driversController', function($scope) { $scope.years = getYearRange(); }); /* Year Range Code */ function getYearRange() { var startYear = new Date().getFullYear(); var endYear = 2005; var dateRange = []; while(endYear &lt;= startYear) { dateRange.push(startYear); startYear -= 1 } return dateRange; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app="F1FeederApp"&gt; &lt;div ng-controller="driversController"&gt; &lt;select ng-model="F1s_Selection" ng-options="year as year for year in years | orderBy:year track by years " class="btn btn-default"&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
Elseif is not working in Excel Makro (VBA) <p>i have a little problem in my excel macro. </p> <p>Description of the Problem:</p> <p>I want to create a Macro, which hide / unhide special Sheets, if one answer is a Dropdown Menu used.</p> <p>Dropdown Menu:</p> <p>Australian</p> <p>Austria</p> <p>Germany</p> <p>And if one of them choosen e.g, Germany --> the Sheet with Germany should unhide and the sheet with australian and austria should hide.</p> <p>I try to use the ElseIf Command:</p> <pre><code>Sub Choose_Country() If (c2 = "Germany") Then Sheet8.Visible = True Sheet9.Visible = False Sheet10.Visible = False ElseIf (C2 = Australia) Then Sheet8.Visible = False Sheet9.Visible = True Sheet10.Visible = False ElseIf (C2 = Austria) Then Sheet8.Visible = False Sheet9.Visible = False Sheet10.Visible = True End if End sub </code></pre> <p>The Error is, that it doesn't matter what i choose every time the germany sheet is visible and the others not..</p> <p>Any Ideas what my mistake is ?</p> <p>Regards</p>
<p>I think you forgot quite a few "" As @Raph said, select case is way cleaner to look at.</p> <p>Tip: Always use Option Explicit, you would have spotted this one!!!</p> <p>Tip 2 : you may use lcase( ) to compare case insensitive</p> <pre><code>Sub Choose_Country() c2 = something I dare hope :D select case c2 case "Germany" Sheet8.Visible = True Sheet9.Visible = False Sheet10.Visible = False case "Australia" Sheet8.Visible = False Sheet9.Visible = True Sheet10.Visible = False case "Austria" Sheet8.Visible = False Sheet9.Visible = False Sheet10.Visible = True case else msgbox "unknown country" End select End sub </code></pre>
low performance by DBINFO('sqlca.sqlerrd1') of Informix 9.40 <p>After a row was inserted I read the serial of inserted row with DBINFO('sqlca.sqlerrd1'). The select proccess takes a lot of time ( 5 - 10 sec ). For the analyse I switch on the sqexplain before the insert command</p> <pre><code>set explain on; load from x insert into transaction; SELECT distinct dbinfo('sqlca.sqlerrd1') FROM transaction; </code></pre> <p>The output :</p> <pre><code>QUERY: ------ SELECT distinct dbinfo('sqlca.sqlerrd1') FROM transaction Estimated Cost: 353490 Estimated # of Rows Returned: 10 1) cms.transaction: SEQUENTIAL SCAN </code></pre> <p>I perform the update statistics:</p> <pre><code>update statistics medium for table transaction; </code></pre> <p>but this didn't help. Why the SQL-Engine perform the sequential scan? If I search with :</p> <pre><code>SELECT MAX (sernr ) from transaction; </code></pre> <p>(where sernr is serial field ) the SQL-Engine search with index. Here the output:</p> <pre><code>QUERY: ------ SELECT MAX (sernr ) from transaction Estimated Cost: 4 Estimated # of Rows Returned: 1 1) cms.transaction: INDEX PATH (1) Index Keys: sernr (Key-Only) (Aggregate) (Serial, fragments: ALL) </code></pre> <p>What I should to do for increase of performance? </p>
<p>When you use </p> <pre><code>SELECT distinct dbinfo('sqlca.sqlerrd1') FROM transaction; </code></pre> <p>you are in fact reading all the rows in the table <code>transaction</code>, returning the <code>DBINFO('sqlca.sqlerrd1')</code> value in each row. Since the value is always the same, the distinct will only return 1 row.</p> <p>You only want 1 row, so you can use something like this:</p> <pre><code>SELECT DBINFO('sqlca.sqlerrd1') FROM systables WHERE tabid = 1; </code></pre>
JAVA - Storing result set in hash table by grouping data efficiently <p>I'd like to store in a hash table a result set coming from a query execution. The hash table is something like this</p> <pre><code>Map&lt;List&lt;String&gt;,List&lt;Object&gt;&gt; </code></pre> <p>where </p> <pre><code>List&lt;String&gt;, the hash table key, is a subset of the extracted fields Object is a Java object corresponding to a database tuple (all fields) </code></pre> <p>So, first, data have to be grouped in order to create each key and group all the items sharing this key.</p> <p>The pseudo-code related to my current approach is:</p> <pre><code>while(iterate){ while(rs.next){ if(key is empty) // build REFERENCE KEY and delete rs entry else // build key for i-th rs entry and compare it with the REFERENCE key. Eventually, get data and delete rs entry } rs.beforeFirst() } </code></pre> <p>In other words, the result set is iterated many times and each time a new key is created, in order to compare the ramaining result set entries with it. Each time the processed entry is deleted to exit the outer loop.</p> <p>Since the result set is very large (and also each List(Object) ), performance are poor (a very high loading time per key). Appending an <strong>order by</strong> clause to the query (in order to preliminarily group data) doesn't alleviate the problem.</p> <p>Is there a more efficient approach?</p> <p>Thanks everyone.</p> <p>EDIT</p> <pre><code>Input ResultSet --------------------------------------------------------------- | Field1 | Field2 | Field3 | Field4 | Field5 | Field6 | Field7 | --------------------------------------------------------------- | X | A | val1_3 | val1_4 | val1_5 | val1_6 | val1_7 | | X | A | val2_3 | val2_4 | val2_5 | val2_6 | val2_7 | | Y | B | val3_3 | val3_4 | val3_5 | val3_6 | val3_7 | | Z | C | val4_3 | val4_4 | val4_5 | val4_6 | val4_7 | | Y | D | val5_3 | val5_4 | val5_5 | val5_6 | val5_7 | ---------------------------------------------------------------- Key_Fields : [Field1, Field2] Output Map ----------------------------------- | KEY | VALUE | ----------------------------------- | [X,A] | [Object1, Object2] | | [Y,B] | [Object3] | | [Z,C] | [Object4] | | [Y,D] | [Object5] | ----------------------------------- </code></pre> <p>I'm using <code>List&lt;String&gt;</code> for key because another <code>ResultSet</code> can have a <code>Key_Fields</code> of different lenght.</p> <p>Here, my current time-consuming Java code</p> <pre><code>while(itera){ key = new ArrayList&lt;String&gt;(); values = new ArrayList&lt;AbstractClass&gt;(); while(rs.next()){ if(key.isEmpty()){ // build REFERENCE KEY // add first OBJECT to List&lt;AbstractClass&gt; // delete this data from ResultSet } else{ // Build KEY_TO_BE_COMPARED List&lt;String&gt; row_to_be_compared = new ArrayList&lt;String&gt;(); // If this key equals to REFERENCE KEY if(row_to_be_compared.equals(key)){ AbstractClass value_object = new AbstractClass(); ... rs.deleteRow(); } // ORDERBY clause in query ensures that, if keys don't match, then all objects related to REFERENCE KEY have been collected else{ break; } } } rs.beforeFirst(); map.put(key, values); if(!rs.next() || items_loaded==max_hash_size) itera = false; else rs.beforeFirst(); } } </code></pre>
<p>Instead of using List as key. Use a class having List as its instance variable. Override equals very carefully.</p>
Copy multiple image and text things to the Clipboard for pasting into MS Office <p>I have copy text and image into word document at that time image and text store into clipboard that works fine.but i have get clipboard text and image using c# that time only text value get not image path,how to image path also get?</p>
<pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); Image myBitmap; if (Clipboard.ContainsImage()) { myBitmap = Clipboard.GetImage(); pictureBox1.Image = myBitmap; } } } } </code></pre>
Unity : 30fps vs 60fps on 30fps animation <p>I'm testing this on mobile, i have a 30 frame animation with 30 frame rate, i build it to my mobile with in-game target frame rate of 30 and 60. since the animation frame rate would be time base in unity, the animation would be exactly 1 second on both build.</p> <p>This is what i assume would happen : </p> <p>1) on 30fps build, the animation would play 1 frame on each in-game frame, so it would be 1 second.</p> <p>2) on 60fps build, the animation would play 1 frame on every 2 in-game frame, so it would be 1 second as well.</p> <p>My question is, why would the 60fps build look better compare with 30fps build? since the animation would just play 30 frame throughout 1 second.</p> <p>There aren't anything else in the scene, only the animation, so nothing else would distract the feeling of 60fps would look better.</p> <p>hope you all can understand the question, and if anyone have the same feeling, or you can test it yourself to see if you feel the same, feel free to comment, answer or discuss. Thanks.</p>
<p>I think i might have the answer, that's because since the animation would be time base, unity would fill better on empty keyframe in 60fps. example : set a position keyframe on 1st frame, then set another position key frame at 30th frame, unity would effectively play this as a 60 frame rate animation since there are so many empty keyframe.</p> <p>I'm not sure if this is the exact answer, if someone can confirm this or there are no other answer i'll rate this as answer.</p>
Java getting unreported exception <pre><code> public void createDirectory(String path) { try { shellSupport.executeCommand("hadoop fs -mkdir "+path); logger.info("Directory "+path+" created successfully"); } catch(Exception exc) { throw exc; } } </code></pre> <p><strong>Error</strong></p> <blockquote> <p>error: unreported exception Exception; must be caught or declared to be thrown</p> </blockquote> <p>If I remove try catch then code compiles and logger shows the message but directory is not created.</p>
<p>Isn't it enough just to add:</p> <pre><code>public void createDirectory(String path) throws Exception { try { shellSupport.executeCommand("hadoop fs -mkdir "+path); logger.info("Directory "+path+" created successfully"); } catch(Exception exc) { throw exc; } } </code></pre> <p>That is: <code>public void createDirectory(String path) throws Exception</code> to your method?</p>
Passing parameter (directory) to %cd command in ipython notebook <p>I'm trying to pass a parameter (directory) to a %cd command in ipython notebook as below:</p> <pre><code> rootdir = "D:\mydoc" %cd rootdir </code></pre> <p>but i get the following error:</p> <pre><code> [Error 2] The system cannot find the file specified: u'rootdir' D:\mydoc </code></pre> <p>when i'm doing </p> <pre><code> %cd D:\mydoc </code></pre> <p>This obviously works but i want to be able to specify my working directories using parameters...</p> <p>Many thanks who can help me.</p> <p>Best Wishes</p>
<p>You can use <code>$</code> to use the value in a variable.</p> <pre><code>%cd $rootdir </code></pre>
Count visits to a file/image and store to db <p>My application is based on rails <code>4.2.4</code>. My application provides a <code>js</code> file that websites can paste into <code>&lt;head&gt;&lt;/head&gt;</code> and we provide some services to them.</p> <p>I have seen that <strong>Facebook</strong> uses pixels like:</p> <pre><code>&lt;noscript&gt; &lt;img height='1' src='https://www.facebook.com/tr?id=63786861722982&amp;amp;ev=PageView&amp;amp;noscript=1' style='display:none' width='1'&gt; &lt;/noscript&gt; </code></pre> <p>or <strong>Amung.us</strong></p> <pre><code>&lt;script id="_wau4dx"&gt;var _wau = _wau || []; _wau.push(["classic", "2uubkcvnbkfu", "4dx"]); (function() {var s=document.createElement("script"); s.async=true; s.src="//widgets.amung.us/classic.js"; document.getElementsByTagName("head")[0].appendChild(s); })();&lt;/script&gt; </code></pre> <p>To count how many visits that file has. How can I achieve the same thing with <code>javascript</code>?</p>
<p>Instead of serving your JS as a static asset (e.g. file served directly from disk), serve it using a normal controller action. Then add the counting bits in that controller action. </p>
How to plan releases for MS CRM 2016 project <p>We got a couple of enhancements as part of the project on a MS CRM 2016 on prem implementation. The client wants UAT and PRod release after every sprint. </p> <p>Plus, every sprint is of 3 weeks out of which 2 weeks is (coding + SIT testing) and 1 week of UAT, for eg. Sprint 1 will commence in week 1 and UAT will be in Week 3, But Sprint 2 coding will commence in week 3 (when business is testing sprint 1 in UAT)</p> <p>Hence i am facing a challenge of how to plan these releases. whether i will need 2 DEV environments or how to do it in 1 DEV environment only. Kindly help</p>
<p>Normally, we plan releases based on deadlines. And based on that we plan both the required CRM environments, and also, very important, TFS branches.</p> <p>A typical workflow might go through the following stages: DEV -> TEST (UAT) -> Staging -> Production. </p> <p>If you're gonna have concurrent releases where you release Sprint 1, and then Sprint 2, there will be an interim period where Sprint 1 will be in live while still developing Sprint 2. You really need a Staging environment which should mimic production because you might need to fix issues for Sprint 1, which is live, while still developing features for Sprint 2, in other environments. </p> <p>Therefore you normally want to keep those in 2 different environments and TFS branches.</p> <p>So, for example, while developing Sprint 1 you might be in the following situation:</p> <p>Sprint 1</p> <ul> <li>DEV (where you actually develop new features)</li> <li>TEST (where you deploy features which are ready for testing)</li> <li>Staging (nothing there yet)</li> <li>Production (nothing there yet)</li> </ul> <p>While working on Sprint 2 you might have :</p> <ul> <li>DEV (where you develop new Sprint 2 features)</li> <li>TEST (where you test Sprint 2 features ready for testing)</li> <li>Staging (which you leave with Sprint 1 only for potential bug fixes)</li> <li>Production (still with Sprint 1 stuff)</li> </ul> <p>After Sprint 2 release all environments will match, and then start again.</p> <p>That was just one example. Depending on the number of dev teams and releases can get even more complicated.</p>
Projects on Algorithms and Datastructures <p>I have required knowledge about basic data-structures and algorithms. Suggest me some mini-projects so that I can implement Graphs, Hashing etc.I learn't Java Programming.</p>
<p>Implement a(n almost) rectangular board with hexagonal cells which provides a method to tell all the neighbours of a cell when given a cell by {line, col}.</p> <p>Unlike a pure rectangular grid in which a cell have 2,3 or 4 neighbours, a whole hexagonal-cell grid (you know those <a href="https://www.colourbox.com/preview/2154598-honeycomb-grid.jpg" rel="nofollow">honey combs</a>, don't you?) will show cells with 2,3,4,5 or 6 neighbours.</p> <p>Once you've done that, implement the <a href="https://en.wikipedia.org/wiki/A*_search_algorithm" rel="nofollow">'A* search'</a> algorithm on a hexagonal cell map. Then throw in some obstacles and refine. And then put some dangers on the map (turrets, soft soil, etc). </p> <p>If you manage to get some nice graphics in, you may even finish with a <a href="https://en.wikipedia.org/wiki/Tower_defense" rel="nofollow">tower defence</a> game good enough to publish on Android platform and make youself some money.</p>
Text misaligned when the responsive navigation button is clicked <p>I am just testing the Responsive Top Navigation example provided by W3Schools, I've done a minor modification on the internal style sheet so the text <code>Home</code> will move to the center of the menu and it misaligned when I click on the navigation button. </p> <p>Why would this happen and how to fix this ?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; body { margin: 0; } ul.topnav { text-align: center; list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; } ul.topnav li { display: inline-block; text-align: center; } ul.topnav li a { display: inline-block; color: #f2f2f2; text-align: center; text-decoration: none; transition: 0.3s; padding: 14px 16px; font-size: 17px; } ul.topnav li a:hover { background-color: #555; } ul.topnav li.icon { display: none; } @media screen and (max-width: 680px) { ul.topnav li:not(:first-child) { display: none; } ul.topnav li.icon { float: right; display: inline-block; } } @media screen and (max-width: 680px) { ul.topnav.responsive { position: relative; } ul.topnav.responsive li.icon { position: absolute; right: 0; top: 0; } ul.topnav.responsive li { float: none; display: inline; } ul.topnav.responsive li a { display: block; text-align: center; } } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;ul class="topnav" id="myTopnav"&gt; &lt;li&gt;&lt;a class="active" href="#home"&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#news"&gt;News&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#contact"&gt;Contact&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#about"&gt;About&lt;/a&gt; &lt;/li&gt; &lt;li class="icon"&gt; &lt;a href="javascript:void(0);" style="font-size:15px;" onclick="myFunction()"&gt;☰&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div style="padding-left:16px"&gt; &lt;h2&gt;Responsive Topnav Example&lt;/h2&gt; &lt;p&gt;Resize the browser window to see how it works.&lt;/p&gt; &lt;/div&gt; &lt;script&gt; function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; } } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
<p>Like I said in comment, the problem is because your <code>li.icon</code> switch between <code>position: relative</code> to <code>position: absolute</code></p> <p>You have to fix it to <code>position:absolute</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-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; body { margin: 0; } ul.topnav { text-align: center; list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; } ul.topnav li { display: inline-block; text-align: center; } ul.topnav li a { display: inline-block; color: #f2f2f2; text-align: center; text-decoration: none; transition: 0.3s; padding: 14px 16px; font-size: 17px; } ul.topnav li a:hover { background-color: #555; } ul.topnav li.icon { display: none; } @media screen and (max-width: 680px) { ul.topnav li:not(:first-child) { display: none; } ul.topnav li.icon { display: inline-block; position: absolute; right: 0; } } @media screen and (max-width: 680px) { ul.topnav.responsive { position: relative; } ul.topnav.responsive li.icon { position: absolute; right: 0; top: 0; } ul.topnav.responsive li { float: none; display: inline; } ul.topnav.responsive li a { display: block; text-align: center; } } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;ul class="topnav" id="myTopnav"&gt; &lt;li&gt;&lt;a class="active" href="#home"&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#news"&gt;News&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#contact"&gt;Contact&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#about"&gt;About&lt;/a&gt; &lt;/li&gt; &lt;li class="icon"&gt; &lt;a href="javascript:void(0);" style="font-size:15px;" onclick="myFunction()"&gt;☰&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div style="padding-left:16px"&gt; &lt;h2&gt;Responsive Topnav Example&lt;/h2&gt; &lt;p&gt;Resize the browser window to see how it works.&lt;/p&gt; &lt;/div&gt; &lt;script&gt; function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; } } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
How to use the node.js 'request' library with this http request? <p>I was trying to make a simple request to site. it should get html text, but it gets ' '</p> <p>NPM module here: github.com/request/request </p> <p>Code:</p> <pre><code>var fs = require('fs'); var request = require('request'); var options = { url:'https://sample.site/phpLoaders/getInventory/getInventory.php', encoding : 'utf8', gzip : true, forever: true, headers: { 'Host': 'sample.site', 'Connection': 'keep-alive', 'Content-Length': '58', 'Cache-Control': 'max-age=0', 'Accept': '*/*', 'Origin': 'https://csgosell.com', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Referer': 'https://sample.site/', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4', 'Cookie': 'my-cookies from browser' }, form: { stage:'bot', steamId:76561198284997423, hasBonus:false, coins:0 } }; request.post(options, function(error, response, body){ console.log(response.statusCode); if (!error) { fs.writeFileSync('site.html', body); } else{ console.log(error); } } ); </code></pre> <p>Chrome request: <a href="https://i.stack.imgur.com/zKQo5.png" rel="nofollow">https://i.stack.imgur.com/zKQo5.png</a> Nodejs request:<a href="https://i.stack.imgur.com/yH9U3.png" rel="nofollow">https://i.stack.imgur.com/yH9U3.png</a></p> <p>the difference is in headers: :authority:csgosell.com :method:POST :path:/phpLoaders/getInventory/getInventory.php :scheme:https</p> <p>after some googling, I anderstood that it is http2, and tried to put it inow another agent's options, but nothing changed.</p> <pre><code>var spdy = require('spdy'); var agent = spdy.createAgent({ host: 'sample.site', port: 443, spdy: { ssl: true, } }).once('error', function (err) { this.emit(err); }); options.agent = agent; </code></pre>
<p>To answer your question i will copy/paste a part of my code that enable you to receive a post request from your frontend application(angularJS) to your backend application (NodeJS), and another function that enable you to do the inverse send a post request from nodeJS to another application (that might consume it):</p> <p>1) receive a request send from angularJS or whatever inside your nodeJS app</p> <pre><code> //Import the necessary libraries/declare the necessary objects var express = require("express"); var myParser = require("body-parser"); var app = express(); // we will need the following imports for the inverse operation var https = require('https') var querystring = require('querystring') // we need these variables for the post request: var Vorname ; var Name ; var e_mail ; var Strasse ; app.use(myParser.urlencoded({extended : true})); // the post request is send from http://localhost:8080/yourpath app.post("/yourpath", function(request, response ) { // test the post request if (!request.body) return res.sendStatus(400); // fill the variables with the user data Vorname =request.body.Vorname; Name =request.body.Name; e_mail =request.body.e_mail; Strasse =request.body.Strasse; response.status(200).send(request.body.title); }); </code></pre> <p>2) Do the inverse send a POST request from a nodeJS application to another application</p> <pre><code> function sendPostRequest() { // prepare the data that we are going to send to anymotion var jsonData = querystring.stringify({ "Land": "Land", "Vorname": "Vorname", "Name": "Name", "Strasse": Strasse, }); var post_options = { host: 'achref.gassoumi.de', port: '443', method: 'POST', path: '/api/mAPI', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': jsonData.length } }; // request object var post_req = https.request(post_options, function(res) { var result = ''; res.on('data', function (chunk) { result += chunk; console.log(result); }); res.on('end', function () { // show the result in the console : the thrown result in response of our post request console.log(result); }); res.on('error', function (err) { // show possible error while receiving the result of our post request console.log(err); }) }); post_req.on('error', function (err) { // show error if the post request is not succeed console.log(err); }); // post the data post_req.write(jsonData); post_req.end(); // ps : I used a https post request , you could use http if you want but you have to change the imported library and some stuffs in the code } </code></pre> <p>So finally , I hope this answer will helps anyone who is looking on how to get a post request in node JS and how to send a Post request from nodeJS application.</p> <p>For further details about how to receive a post request please read the npm documentation for body-parser library : npm official website documentation</p>
What am I doing wrong with this negative lookahead? Filtering out certain numbers in a regex <p>I have a big piece of code produced by a software. Each instruction has an identifier number and I have to modify only certain numbers:</p> <pre><code>grr.add(new GenericRuleResult(RULEX_RULES.get(String.valueOf(11)), new Result(0,Boolean.FALSE,"ROSSO"))); grr.add(new GenericRuleResult(RULEX_RULES.get(String.valueOf(12)), new Result(0,Boolean.FALSE,"£££"))); etc... </code></pre> <p>Now, I am using SublimeText3 to change rapidly all of the wrong lines with this regex:</p> <pre><code>Of\((11|14|19|20|21|27|28|31)\)\), new Result\( </code></pre> <p>This regex above allowed me to put "ROSSO" (red) in each line containing those numbers. Now I have to put "VERDE" (green) in the remaining lines. My idea was to add a <code>?!</code> in the Regex to look for all of the lines <em>NOT CONTAINING</em> those numbers. </p> <p>From the website <a href="https://regex101.com/" rel="nofollow">Regex101</a> I get in the description of the regex:</p> <pre><code>Of matches the characters Of literally (case sensitive) \( matches the character ( literally (case sensitive) Negative Lookahead (?!11|14|19|20|21|27|28|31) Assert that the Regex below does not match 1st Alternative 11 etc... </code></pre> <p>So why am I not finding the lines containing 12, 13, 14 etc?</p> <p>Edit: the Actual Regex: <code>Of\((?!11|14|19|20|21|27|28|31)\)\), new Result\(</code></p>
<p>Your problem is that you are assuming a negative look ahead changes the cursor position, it does not. </p> <p>That is, a negative lookahead of the form <code>(?!xy)</code> merely verifies that the <em>next</em> two characters are not <code>xy</code>. It does not then swallow two characters from the text. As its name suggests, it merely <em>looks ahead</em> from where you are, without moving ahead!</p> <p>Thus, if you wish to match further things beyond that assertion you must:</p> <ul> <li>negatively assert it is not <code>xy</code>;</li> <li>then consume the two characters for whatever they are;</li> <li>then continue your match.</li> </ul> <p>So try something like:</p> <pre><code>Of\((?!11|14|19|20|21|27|28|31)..\)\), new Result\( </code></pre>
Change <td> Background Color After Validation <p>I have a form inside a table. I want to change the <code>&lt;td&gt;</code> background color after form validation for the error. I manage to do it by inserting an if condition on each <code>&lt;td&gt;</code> style attribute. Is there a short way. </p> <p>For example maybe by using jquery. Below is my style of codes: </p> <pre><code>&lt;td style="&lt;?php echo (!empty($msgError) &amp;&amp; empty($purchase_mode)) ? 'background-color: rgba(244, 67, 54, 0.33);' : ''; ?&gt; "&gt; &lt;input type="checkbox" name="purchase_mode" value="DIRECT"/&gt;Direct &lt;/td&gt; &lt;td style="&lt;?php echo (!empty($msgError) &amp;&amp; empty($purchase_category)) ? 'background-color: rgba(244, 67, 54, 0.33);' : ''; ?&gt; "&gt; &lt;input type="checkbox" name="description" value="SUPPLY"/&gt;SUPPLY &lt;/td&gt; </code></pre> <p>I have tried to use jquery but it will change all the <code>&lt;td&gt;</code> background color on the table: </p> <pre><code>&lt;?php if (empty($purchase_category) || empty($purchase_mode)) { ?&gt; &lt;script&gt; $(document).ready(function(){ $("td").css("background-color", "red"); }); &lt;/script&gt;'; &lt;?php } ?&gt; </code></pre>
<p>You can create an array of string with all the invalid fields name property and then it will take care to set the background color for those fields: </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function ValidateForm(invalidFields){ $("td input").each(function(){ if($.inArray(this.name,invalidFields) &gt;= 0){ $(this).parent().css("background-color","rgba(244, 67, 54, 0.33)"); } }); };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;input type="checkbox" name="purchase_mode" value="DIRECT" /&gt;Direct &lt;/td&gt; &lt;td&gt; &lt;input type="checkbox" name="description" value="SUPPLY" /&gt;SUPPLY &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="button" onclick="ValidateForm(['purchase_mode'])" value="Validate Form"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p>
Where should I put code that I want to always run for each request? <p>Maybe this is more of an ASP.NET MVC question than an Orchard question but I'm relatively new to both and I don't know the answer in either case.</p> <p>ASP.NET MVC applications don't technically have a single point of entry, so where am I supposed to put code that I want to always run each and every time someone visits any page, regardless of layer or origin or permissions? Is there a specific Orchard way of doing this?</p> <p>If it makes a difference, what I'm specifically trying to do at the moment is to restrict the IP range that has access to my website. I want to look at every incoming request and check if the user is either authenticated or has an IP in the allowed range that I configured in my custom settings.</p> <p>I can think of some quick and dirty ways to achieve this like putting the check in <code>Layout</code> and wrap a condition around all of my zones or implement <code>IThemeSelector</code> to switch to a different Theme but I'd like to do it properly.</p>
<p>All what should you do to achieve this, is implementing new <code>IActionFilter</code> or <code>IAuthorizationFilter</code> like the following:</p> <pre class="lang-cs prettyprint-override"><code>public class CheckAccessFilter : FilterProvider, IActionFilter, IAuthorizationFilter { public void OnActionExecuting(ActionExecutingContext filterContext) { // here you can check the incoming request, and how the system will deal with it, // before executing the action } public void OnActionExecuted(ActionExecutedContext filterContext) { } public void OnAuthorization(AuthorizationContext filterContext) { // here you can authorize any request } } </code></pre> <p>But if you want only to authorize based on content items (like: Widgets, Pages, Projections), you can implement <code>IAuthorizationServiceEventHandler</code>:</p> <pre class="lang-cs prettyprint-override"><code>public class IPAuthorizationEventHandler : IAuthorizationServiceEventHandler { public void Checking(CheckAccessContext context) { } public void Adjust(CheckAccessContext context) { } public void Complete(CheckAccessContext context) { } } </code></pre> <p>The best sample you can follow to implement this approach is <code>SecurableContentItemsAuthorizationEventHandler</code>, you can find it in <code>Orchard.ContentPermissions</code> module.</p>
How can I add music player onClick Android <p>I'm making an app in android.</p> <p>I have a button in my app. When I tap the button play, a song starts playing. But now I want my app to play song1 on my first click, on second click song2 and on third click song3 (song1, song2 and song3) are different mp3 files. </p> <p>But I dont know how to archieve this.</p> <p>Thanks in advance</p>
<p>Make a counter variable and a array/list of your music files. on every tap you play the music on index of your counter. after playing them just increase the counter by 1. Done</p>
Wrong response from the webhook: 400 Bad Request <p>I'm recently tried to use webhook to get update from telegram. my program work correctly whit getUpdates(). but when i set webhook i got </p> <blockquote> <p>"Wrong response from the webhook: 400 Bad Request"</p> </blockquote> <p>error when try to check status of webhook by getWebhookInfo method.</p> <p>here is my code: <code>$telegram-&gt;commandsHandler(true)</code> when is used below code in getUpdates mod every thing was fine. <code>$telegram-&gt;commandsHandler(false)</code></p> <p>And is should say i use https and my ssl is ok.</p> <p>This is answer of getWebhookInfo to me.</p> <pre><code>{ "ok": true, "result": { "url": "https://telbit.ir/api/bot/&lt;token&gt;", "has_custom_certificate": false, "pending_update_count": 13, "last_error_date": 1476344420, "last_error_message": "Wrong response from the webhook: 400 Bad Request" } } </code></pre>
<p>I found my answer</p> <p>every things was ok. the error happens because of my framework. </p>
Composer - autoload classes in CodeIgniter outside vendor folder <p>I've been working on setting up a CodeIgniter project with composer. I'm wanting to include <code>php</code> classes stored in files outside the <code>vendor</code> folder - in a <code>shared</code> folder.</p> <p>My directory structure:</p> <pre><code>/ --application/ --shared/ -application/ -class1.php -class2.php -class3.php -base/ -classb1.php --vendor/ --composer.json --composer.lock </code></pre> <p>Looking at the composer <a href="https://getcomposer.org/doc/04-schema.md#autoload" rel="nofollow">documentation</a>, I see there is an <code>autoload</code> property in the root package that I'm trying to use to load the classes in the <code>shared</code> directory. These classes aren't namespaced.</p> <p>My <code>composer.json</code> file is as follows:</p> <pre><code>{ "description" : "The CodeIgniter Application with Composer", "require": { "php": "&gt;=5.3.2", "codeigniter/framework": "3.1.*" }, "require-dev": { "mikey179/vfsStream": "1.1.*" }, "autoload":{ "psr-0":{ "":"shared/application/", "":"shared/base/", "":"shared/data/" } } } </code></pre> <p>My search led me to <a href="http://stackoverflow.com/questions/28253154/how-to-i-use-composer-to-autoload-classes-from-outside-the-vendor">this question</a>, but the classes are still not being loaded. I've ran <code>composer update</code> on the terminal.</p>
<p>Well after looking further, there's a property called <code>classmap</code> (<a href="https://getcomposer.org/doc/04-schema.md#classmap" rel="nofollow">documentation</a>) in the root package.</p> <pre><code>"autoload":{ "classmap":["shared/application/","shared/base/", "shared/data/"] } </code></pre> <p>This loads all the required files in the folders.</p>
cursorboundexception whille displaying listview from content provider <p>somebody pls get me out of this.I am trying to display a list from an sqlite database which worked absolutely fine but dont know what went wrong it showed cant find provider info.I fixed it and then when i am running the code with list_cursor.moveToFirst() it just shows the 1st item in list again and again which proves that it is fetching data....When I use list_cursor.moveToNext() it shows the following exception:PLS HELP ME</p> <pre><code>10-13 15:11:41.017 5337-5337/com.phase3.mascotnew E/AndroidRuntime: FATAL EXCEPTION: main Process: com.phase3.mascotnew, PID: 5337 android.database.CursorIndexOutOfBoundsException: Index 3 requested, with a size of 3 at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426) at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:147) at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:61) at android.database.CursorWrapper.getString(CursorWrapper.java:114) at com.phase3.mascotnew.SelectRecipeActivity$MyCursorAdapter.getView(SelectRecipeActivity.java:145) at android.widget.AbsListView.obtainView(AbsListView.java:2338) at android.widget.ListView.makeAndAddView(ListView.java:1813) at android.widget.ListView.fillDown(ListView.java:698) at android.widget.ListView.fillFromTop(ListView.java:759) at android.widget.ListView.layoutChildren(ListView.java:1646) at android.widget.AbsListView.onLayout(AbsListView.java:2149) at android.view.View.layout(View.java:15140) at android.view.ViewGroup.layout(ViewGroup.java:4867) at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1160) at android.view.View.layout(View.java:15140) at android.view.ViewGroup.layout(ViewGroup.java:4867) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15140) at android.view.ViewGroup.layout(ViewGroup.java:4867) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1888) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1742) at android.widget.LinearLayout.onLayout(LinearLayout.java:1651) at android.view.View.layout(View.java:15140) at android.view.ViewGroup.layout(ViewGroup.java:4867) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15140) at android.view.ViewGroup.layout(ViewGroup.java:4867) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2474) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2180) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6412) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788) at android.view.Choreographer.doCallbacks(Choreographer.java:591) at android.view.Choreographer.doFrame(Choreographer.java:560) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774) at android.os.Handler.handleCallback(Handler.java:808) at android.os.Handler.dispatchMessage(Handler.java:103) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:5299) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645) at dalvik.system.NativeStart.main(Native Method) </code></pre> <p><strong>SelectRecipeActivity.java</strong></p> <pre><code> package com.phase3.mascotnew; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import com.phase3.mascotnew.database.Tables.Recipe; import java.io.File; public class SelectRecipeActivity extends Activity { private ListView mListView = null; private Cursor mCursor = null; private SimpleCursorAdapter adapter; private static final String TAG = "SELECT RECIPE ACTIVITY"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_recipe2); mListView = (ListView) findViewById(R.id.recipe_list); createRecipeSubFolder(); showTableItems(); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { Cursor cursor=(Cursor)mListView.getAdapter().getItem(position); Log.i(TAG, "Fetching item position" + position); String pass_recname = cursor.getString(cursor.getColumnIndex(Recipe.NAME_NIC)); int pass_groupid = (cursor.getInt(cursor.getColumnIndex(Recipe.GROUPID_NIC))); Log.i(TAG, "Fetching data" + " " + pass_recname + " " + pass_groupid); cursor.close(); Intent i = new Intent(SelectRecipeActivity.this, WhatYouNeedActivity.class); i.putExtra("Title", pass_recname); i.putExtra("GroupId", pass_groupid); startActivity(i); Log.i(TAG, "Sending Data"); } }); } @Override protected void onResume() { super.onResume(); showTableItems(); } @Override protected void onPause() { super.onPause(); if(mCursor != null){ mCursor.close(); mCursor = null; } } public void showTableItems() { if (mCursor != null) { mCursor.close(); mCursor = null; } int StatusVal=1; String Status=Recipe.STATUS+"="+ StatusVal; //String selection=Recipe.GROUPID; //String selection = Recipe.GROUPID + " "+ "AND"+" "+Status; mCursor = getContentResolver().query(Recipe.CONTENT_URI, Recipe.PROJECTION_ALL,Status, null, null); if (mCursor == null || mCursor.getCount() == 0) { notifyDataExist(false); return; } notifyDataExist(true); String[] from = {Recipe.NAME_NIC}; int[] to = {R.id.recname_row}; Log.i(TAG, "Setting Adapter"); adapter = new MyCursorAdapter(this, R.layout.list_recipes_row, mCursor, from, to); mListView.setAdapter(adapter); } private void notifyDataExist(boolean exist) { if(exist) { mListView.setVisibility(View.VISIBLE); } else { Log.i(TAG, "Recipe Table has no data"); mListView.setVisibility(View.GONE); } } class MyCursorAdapter extends SimpleCursorAdapter { Activity mActivity = null; int mLayoutId; String[] from = null; int[] to = null; public MyCursorAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to) { super(context, layout, cursor, from, to, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); mActivity = (Activity) context; mLayoutId = layout; this.from = from; this.to = to; } @Override public int getCount() { return mCursor.getCount() + 1; } @Override @TargetApi(15) public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; if (row == null) { row = mActivity.getLayoutInflater().inflate(mLayoutId, null, false); } Cursor list_cursor = getCursor(); list_cursor.moveToPosition(position); list_cursor.moveToNext(); TextView txtSecondCell = (TextView) row.findViewById(R.id.recname_row); String recipename = list_cursor.getString(list_cursor.getColumnIndex(Recipe.NAME_NIC)); txtSecondCell.setText(recipename); Log.i(TAG, "Showing List"); return row; } } private void createRecipeSubFolder(){ Cursor cursor1 = getContentResolver().query(Recipe.CONTENT_URI, Recipe.PROJECTION_ALL, null, null, null); while(cursor1.moveToNext()){ // String path = Environment.getExternalStorageDirectory() // + File.separator + "/MASCOT/" + File.separator // + "/Recipe/" + File.separator + cursor.getString(cursor.getColumnIndex(Recipe.NAME_NIC)); // Log.i("Recipes", cursor.getString(cursor.getColumnIndex(Recipe.NAME_NIC))); File recipeDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MASCOT1/Recipe/" + cursor1.getString(cursor1.getColumnIndex(Recipe.NAME_NIC)) + "/"); if(!recipeDir.exists()) { recipeDir.mkdirs(); Log.i("Recipes Dirs", recipeDir.getName()); } } cursor1.close(); } } </code></pre>
<p>Try this solution </p> <pre><code> @Override @TargetApi(15) public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; if (row == null) { row = mActivity.getLayoutInflater().inflate(mLayoutId, null, false); } Cursor list_cursor = getCursor(); list_cursor.moveToPosition(position); if(!list_cursor.isLast()){ list_cursor.moveToNext(); TextView txtSecondCell = (TextView) row.findViewById(R.id.recname_row); String recipename = list_cursor.getString(list_cursor.getColumnIndex(Recipe.NAME_NIC)); txtSecondCell.setText(recipename); Log.i(TAG, "Showing List"); } return row; } </code></pre>
Automatically generated git commit message with regex <p>I'd like to set up a git alias that would execute git commit with auto generated message like this:</p> <p>"Affected files: [...], [...], [...]."</p> <p>Whereby [...] is a regex match against respective file name.</p> <ul> <li>I want to use it only when updating existing files (no additions, deletions).</li> <li>If regex part is too clunky, I'd be fine with full file names.</li> <li>Having inline comma separated list (as opposed to multi-line) is critical requirement.</li> <li>Not having to touch message in editor is critical requirement. </li> </ul> <p>I am using git bash on windows. My skills with git are very basic (add, commit, push).</p> <p>Thanks.</p>
<p>You can achieve this by placing a <code>commit-msg</code> hook (read: script) in the <code>.git/hook</code> directory of your project.</p> <p>Running <code>git diff --cached --name-status</code> should give you all the information about the [about to be] committed files, which you can parse with <code>awk</code> (or a bunch of <code>grep</code>s and <code>cut</code>s) and then organize it with <code>paste</code>. Putting it all together, your script should look more or less like this:</p> <pre class="lang-sh prettyprint-override"><code>modified_files=`git diff --cached --name-status | awk '$1 == "M" { print $2 }'| paste -d', ' -s` if test "" != "$modified_files" then echo "Affected files: $modified_files" &gt;&gt; $1 fi </code></pre> <p>Note that by default this will still open the editor window, but you could work around it by just running <code>git commit -m ""</code> (or some other message) when you commit.</p> <p><strong>Note:</strong> I tested this with <code>/bin/sh</code> on my Fedora 24 laptop, and it works fine. I'm not sure git bash on Windows has all of these capabilities, but at the very least it should have equivalent facilities. </p> <p><strong>EDIT:</strong><br/> As @torek suggested in the comments, this can be simplified using the <code>--diff-filter</code> option:</p> <pre class="lang-sh prettyprint-override"><code>modified_files=`git diff --cached --diff-filter='M' --name-only | paste -d', ' -s` if test "" != "$modified_files" then echo "Affected files: $modified_files" &gt;&gt; $1 fi </code></pre>
Wit.ai: How to send a message when confidence below a certain level? <p>I'm playing around with the Wit.ai Facebook Messenger Example (<a href="https://github.com/wit-ai/node-wit/blob/master/examples/messenger.js" rel="nofollow">https://github.com/wit-ai/node-wit/blob/master/examples/messenger.js</a>)</p> <p>Is there a way to send a preset response when the user's message is not understood. I was thinking along the lines of some way of stopping the Wit conversation when the confidence is below a certain threshold.</p> <p>Any help greatly appreciated. Thanks.</p>
<p>You can use the Wit API directly and skip the ui all together if you want more fine control.</p> <pre><code>function getIntent(message) { var serviceResult = {}; var url = 'https://api.wit.ai/message?v=20161006&amp;q='+message; var options = { uri: url, qs: {}, method: 'POST', headers: {}, auth: {'bearer': process.env.WIT_TOKEN}, json: true }; request(options, function(error, response, body) { if(!error) { serviceResult.result = "success"; // Check for entities if(body.entities.contact) { serviceResult.entity = body.entities.contact[0].value; serviceResult.entityConfidence = body.entities.contact[0].confidence; } // Check for intent if(body.entities.intent) { serviceResult.intent = body.entities.intent[0].value; serviceResult.intentConfidence = body.entities.intent[0].confidence; } } else { serviceResult.result = "fail"; } }); } </code></pre> <p>Your bot can decide what it wants to do based on the confidence value.</p>
flexbox div goes off screen on small screen <p>Code first:</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>html { display:flex; width:100%; height:100%; } body { display:flex; flex:1; } .container { display:flex; flex:1; overflow-y:auto; flex-direction:column; justify-content:center; align-items:center; } .block1 { justify-content:center; background-color:green; display:flex; width:300px; min-height:150px; } .block2 { background-color:blue; display:flex; min-height:300px; width:500px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="block1"&gt; &lt;img src="https://tse2.mm.bing.net/th?id=OIP.M252f960f4a4f32c22914d8d87623f066o0&amp;pid=15.1"&gt; &lt;/div&gt; &lt;div class="block2"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I have two blocks in a container. I want them centered on the screen. The issue is when the screen height is small, I have a scrollbar that appear but the first block have a part that go offscreen (is invisible)</p> <p>To reproduce, decrease the height of the jsfiddle preview window. You will understand what I mean by going off screen.</p> <p>The expected behavior is to let the scroll bar appear and keep the div visible.</p> <p>I tried by setting flex-shrink to 0 on every element but it isn't working...</p>
<p>You can make use of Flexbox's <code>auto</code> margins.</p> <ol> <li>Remove <code>justify-content: center</code> from <code>.container</code>.</li> <li>Add <code>margin-top: auto</code> to <code>.block1</code>.</li> <li>Add <code>margin-bottom: auto</code> to <code>.block2</code>.</li> </ol> <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>html { display:flex; width:100%; height:100%; } body { display:flex; flex:1; } .container { display:flex; flex:1; overflow-y:auto; flex-direction:column; align-items:center; } .block1 { justify-content:center; background-color:green; display:flex; width:300px; min-height:150px; margin-top: auto; } .block2 { background-color:blue; display:flex; min-height:300px; width:500px; margin-bottom: auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="block1"&gt; &lt;img src="https://tse2.mm.bing.net/th?id=OIP.M252f960f4a4f32c22914d8d87623f066o0&amp;pid=15.1"&gt; &lt;/div&gt; &lt;div class="block2"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
How to find epoch for last month same day? <p>I have below PLSQL code which finds the epoch for last month same day, however it fails when I run it on month end for 31 and 01 days.</p> <pre><code> SET serveroutput ON DECLARE vDay VARCHAR2(30) := '&amp;Enter_current_day'; vDate VARCHAR2(30); vEpoch NUMBER; BEGIN vDate := TO_CHAR(sysdate, 'MM')||'-'||vDay||'-'||TO_CHAR(sysdate, 'YYYY'); vEpoch := (ADD_MONTHS(TO_DATE(vDate, 'MM-DD-YYYY HH24:MI:SS'), -1) - TO_DATE('01/01/1970 00:00:00', 'MM-DD-YYYY HH24:MI:SS')) * 24 * 60 * 60; vDate := TO_DATE(vDate, 'MM-DD-YYYY HH24:MI:SS'); dbms_output.put_line('Current Date: '||to_number(vDay)||' Epoch: '||vEpoch||' Date: '||vDate); END; </code></pre> <p>e.g. if todays date is,</p> <pre><code>A. 30-Sep and if I enter '31' then it should return epoch for the 01-Sep B. 30-Sep and if I enter '01' then it should return epoch for the 01-Sep C. 30-Mar and if I enter '31' then it should return epoch for the 01-Mar D. 30-Mar and if I enter '01' then it should return epoch for the 01-Mar </code></pre>
<p>Maybe something like this would do the trick?</p> <pre><code>DECLARE vday VARCHAR2(30) := '&amp;Enter_current_day'; vdate DATE; vepoch NUMBER; v_today DATE := SYSDATE - 30; BEGIN vdate := to_date(to_char(v_today, 'MM') || '-' || least(to_number(vday), to_number(to_char(last_day(v_today), 'dd'))) || '-' || to_char(v_today, 'YYYY'), 'MM-DD-YYYY'); vepoch := (add_months(vdate, -1) - to_date('01/01/1970 00:00:00', 'MM-DD-YYYY HH24:MI:SS')) * 24 * 60 * 60; dbms_output.put_line('Current Date: ' || to_number(vday) || ' Epoch: ' || vepoch || ' Date: ' || to_char(vdate, 'mm-dd-yyyy')); END; Current Date: 1 Epoch: 1470009600 Date: 09-01-2016 Current Date: 15 Epoch: 1471219200 Date: 09-15-2016 Current Date: 30 Epoch: 1472601600 Date: 09-30-2016 Current Date: 31 Epoch: 1472601600 Date: 09-30-2016 </code></pre> <p>This simply finds the last day of the month returned by the <code>v_today</code> date and compares it to the input <code>vday</code> and picks the lowest value. So, for September, if <code>vday = 31</code>, it would compare 31 with 30 (the last day in September) and output 30.</p> <p>If you're dead-set on returning the first day of the month, then you'd need to change the <code>least</code> section to something like:</p> <pre><code>CASE WHEN to_number(to_char(last_day(v_today), 'dd')) &lt; to_number(vday) THEN '01' ELSE vday END </code></pre> <p>N.B. Note that I've made a few changes to your code to make it more robust - eg. You had <code>vDate := TO_DATE(vDate, 'MM-DD-YYYY HH24:MI:SS');</code> which is a bit daft since you originally had <code>vDate</code> as a string, and by doing that, you're forcing Oracle to implicitly convert the string into a date and then back into a string.</p> <p>Instead, I declared <code>vDate</code> as a date and have output the date in resultant string in the date format you used throughout the rest of the code - this means that it no longer relies on the NLS <code>nls_date_format</code> parameter to decide (this parameter is not necessarily the same for everyone!).</p>
Should I get BluetoothGatt.GATT_SUCCESS also when disconnecting from a device? <p>I am working with custom devices and I am struggling to manage the Bluetooth LE correctly.</p> <p>My only concern is not getting 0 (<code>BluetoothGatt.GATT_SUCCESS</code>) when I read the <code>status</code> value along with value 2 on <code>newState</code> variable (what means <code>BluetoothProfile.STATE_DISCONNECTED</code>) at method <code>onConnectionStateChange</code>. Instead, I get an 8, what can't be tracked in the <code>BluetoothGatt</code> nor <code>BluetoothProfile</code> classes.</p> <p>All connection works fine, I read and write values perfectly. </p> <p><strong>(1)</strong> Is this supposed to be like that? Why do I read an eight?</p> <p>I have seen many <code>status</code> values at my <code>onConnectionStateChange</code> method: 8, 19, 133 etc.</p> <p><strong>(2)</strong> Where can I check this values?</p> <p>Thanks in advanced.</p> <hr> <p><strong>EDIT</strong>: There are many values in the <em>api.h</em> file, we were looking in the wrong place.</p> <p><code>8: 0x08 = GATT CONN TIMEOUT 19: 0x13 = GATT CONN TERMINATE PEER USER 133: 0x85 = GATT_ERROR</code></p>
<p>The int error codes need to be converted to HEX and mapped to the values in the following file:</p> <p><a href="https://android.googlesource.com/platform/external/bluetooth/bluedroid/+/android-5.1.1_r13/stack/include/gatt_api.h" rel="nofollow">https://android.googlesource.com/platform/external/bluetooth/bluedroid/+/android-5.1.1_r13/stack/include/gatt_api.h</a></p> <p>In the cases you mentioned:</p> <pre><code>8 = GATT_INSUF_AUTHORIZATION 19 = GATT_RSP_WRITE 133 = GATT_ERROR </code></pre>
Convert row values into columns using LINQ in c# <p>I have a list as below</p> <pre><code>PillarId Quarter Feature 1 Q12106 France 1 Q12016 Germany 1 Q22016 Italy 1 Q32016 Russia 2 Q22016 India 2 Q32016 USA 3 Q22016 China 3 Q32016 Australia 3 Q32016 New Zeland 3 Q42016 Japan </code></pre> <p>I want convert this into a list which looks like this</p> <pre><code>pillarId Q12016 Q22016 Q32016 Q42016 1 France Italy Russia 1 Germany 2 India USA 3 China Australia Japan 3 New Zeland </code></pre> <p>Can anybody suggest some sample code</p> <p>Thanks</p>
<p>Try this</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace ConsoleApplication16 { class Program { static void Main(string[] args) { DataTable dt = new DataTable(); dt.Columns.Add("PillarId", typeof(int)); dt.Columns.Add("Quarter", typeof(string)); dt.Columns.Add("Feature", typeof(string)); dt.Rows.Add(new object[] {1, "Q12116", "France"}); dt.Rows.Add(new object[] {1, "Q12116", "Germany"}); dt.Rows.Add(new object[] {1, "Q22116", "Italy"}); dt.Rows.Add(new object[] {1, "Q32116", "Russia"}); dt.Rows.Add(new object[] {2, "Q22116", "India"}); dt.Rows.Add(new object[] {2, "Q32116", "USA"}); dt.Rows.Add(new object[] {3, "Q22116", "China"}); dt.Rows.Add(new object[] {3, "Q32116", "Austrailia"}); dt.Rows.Add(new object[] {3, "Q32116", "New Zeland"}); dt.Rows.Add(new object[] {3, "Q42116", "Japan"}); string[] uniqueQuarters = dt.AsEnumerable().Select(x =&gt; x.Field&lt;string&gt;("Quarter")).Distinct().ToArray(); var groups = dt.AsEnumerable() .GroupBy(x =&gt; x.Field&lt;int&gt;("PillarId")).Select(x =&gt; x.GroupBy(y =&gt; y.Field&lt;string&gt;("Quarter")).Select(z =&gt; new { id = x.Key, quarter = z.Key, feature = z.Select((a,i) =&gt; new { feature = a.Field&lt;string&gt;("Feature"), index = i}).ToList()}).ToList()).ToList(); DataTable pivot = new DataTable(); pivot.Columns.Add("PillarId", typeof(int)); foreach (string quarter in uniqueQuarters) { pivot.Columns.Add(quarter, typeof(string)); } foreach (var group in groups) { int maxNewRows = group.Select(x =&gt; x.feature.Count()).Max(); for (int index = 0; index &lt; maxNewRows; index++) { DataRow newRow = pivot.Rows.Add(); foreach (var row in group) { newRow["PillarId"] = row.id; newRow[row.quarter] = row.feature.Skip(index) == null || !row.feature.Skip(index).Any() ? "" : row.feature.Skip(index).First().feature; } } } } } } </code></pre> <p><a href="https://i.stack.imgur.com/fmgHw.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/fmgHw.jpg" alt="enter image description here"></a></p>
Ionic / AngularJS key not accessible in ng-repeat <p>I am trying to access the <code>{{key}}</code> from an <code>ng-repeat</code> from a controller using <strong>Ionic 1</strong>. The <code>{{key}}</code> that is generated as text is different from the <code>{{key}}</code> I am receiving at the controller, not sure why this is.</p> <p>What I want to do is find the div id which should be dynamically generated using the <code>id = "historyHeader_{{key}}"</code> and need to receive it using <code>ng-click="loadInlineHistory({{key}})"</code></p> <p><strong>Controller:</strong></p> <pre><code>$scope.loadInlineHistory = function (dateLoaded) { var textS = $("#historyHeader_"+dateLoaded).text(); } </code></pre> <p><strong>View</strong></p> <pre><code>&lt;ion-list&gt; &lt;div ng-repeat="(key, value) in history | groupBy: 'date'"" style="background:#fff;padding:0.4em"&gt; &lt;div class="item item-divider"&gt; &lt;span style="min-height: 100%" id="historyHeader_{{key}}"&gt; {{key}}&lt;/span&gt; &lt;/div&gt; &lt;div style="width: 100%"&gt; &lt;div class="row" ng-repeat="hist in value"&gt; &lt;div ng-click="testRepeatx()"&gt; &lt;div class="row"&gt; &lt;div class="col col-50" align="left"&gt;3 laterals &lt;/div&gt; &lt;div class="col col-50" align="left" style="color:#999"&gt;{{hist.reps}} calories&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row" &gt; &lt;button class="button button-block button-balanced" ng-click="loadInlineHistory({{key}})"&gt; &lt;i class="ion-plus"&gt;&lt;/i&gt;&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/ion-list&gt; </code></pre>
<p>Just remove the curly brackets from the <code>ng-click</code> function call.</p> <pre><code>&lt;div class="row" &gt; &lt;button class="button button-block button-balanced" ng-click="loadInlineHistory(key)"&gt; &lt;i class="ion-plus"&gt;&lt;/i&gt;&lt;/button&gt; &lt;/div&gt; </code></pre>
Page redirect on clicking of "Cancel" button of a confirm dialouge <p>Please look at the code snippet - </p> <pre><code>&lt;form action="post" onsubmit="return confirm('Are You Sure?')"&gt; &lt;a id="saveBtn" class="btnClass"&gt;Save&lt;a/&gt; &lt;/form&gt; </code></pre> <p>When I click on the 'Save' and then Click on the "<strong>Ok</strong>" button of confirm popup the form get submitted. If I click "<strong>Cancel</strong>" the form is not submitted and the I left on the current page. Is it possible if I click "<strong>Cancel</strong>" button then the page redirected to other page?</p>
<p>You should probably not use the <code>onsubmit</code> attribute, go with the unobtrusive event listener approach for better readability and maintainability.</p> <p>Something like this should show the general idea and you can update it with your own redirect link:</p> <pre><code>var submitLink = document.getElementById('saveBtn'), myForm = document.getElementById('myForm'); submitLink.addEventListener('click', function(e) { if (confirm('Are You Sure?')) { myForm.submit(); } else { e.preventDefault(); window.location = 'http://google.com'; // redirect to your own URL here } }); </code></pre> <p>This relies on the form and anchor having <code>id</code> attributes:</p> <pre><code>&lt;form action="post" id="myForm"&gt; &lt;a href="#" id="saveBtn" class="btnClass"&gt;Save&lt;a/&gt; &lt;/form&gt; </code></pre>
NSIS: Change the text "Execute:*******" to custom text <p>I'm very new to NSIS and created a script to install all my programs in a chained fashion. The script works very well but I would like to change the text in the highlighted box to show the name of the program being installed. For example, if the installer is installing Acrobat Reader, it should say "Installing: Adobe Acrobat Reader".</p> <p><em>Here is a screenshot:</em> <img src="https://i.stack.imgur.com/U9q16.png" alt="Image"></p> <pre><code> ; Script generated by the HM NIS Edit Script Wizard. ; HM NIS Edit Wizard helper defines !define PRODUCT_NAME "Deployment" !define PRODUCT_VERSION "1.0" !define PRODUCT_PUBLISHER "NoNe" ; MUI 1.67 compatible ------ !include "MUI.nsh" ; MUI Settings !define MUI_ABORTWARNING !define MUI_ICON "${NSISDIR}\Contrib\Graphics\Icons\modern-install.ico" ; Welcome page ;!insertmacro MUI_PAGE_WELCOME ; License page ;!insertmacro MUI_PAGE_LICENSE "..\..\..\path\to\licence\YourSoftwareLicence.txt" ; Instfiles page !insertmacro MUI_PAGE_INSTFILES ; Finish page ;!insertmacro MUI_PAGE_FINISH ; Language files !insertmacro MUI_LANGUAGE "English" ; MUI end ------ Name "${PRODUCT_NAME} ${PRODUCT_VERSION}" OutFile "Deploy.exe" InstallDir "$TEMP" ShowInstDetails show Section -SETTINGS SetOutPath "$TEMP" SetOverwrite on SectionEnd Section "Adobe Acrobat Reader XI" SEC01 ;Should display "Installing: Acrobat Reader" when installing this section File "E:\Applications\AdbeRdr11002_en_US.exe" ExecWait "$TEMP\AdbeRdr11002_en_US.exe /msi EULA_ACCEPT=YES /qn" SectionEnd Section "Mozilla Firefox" SEC02 ;Should display "Installing: Mozilla Firefox" when installing this section File "E:\Applications\Firefox4901.exe" ExecWait "$TEMP\Firefox.exe -ms" SectionEnd </code></pre> <p>Is there a way to do this?</p> <p>Thanks in advance... :)</p>
<p>You can use instruction <strong>DetailPrint "Installing: Adobe Acrobat Reader"</strong> </p> <p>to add the string "Installing: Adobe Acrobat Reader" to the details view of the installer.</p> <p>But next command (in your script) will overwrite this text (e.g. "Extracting file ...") so you may use <strong>SetDetailsPrint</strong> none|listonly|textonly|both|lastused command to set where the output is applied:</p> <pre><code>SetDetailsPrint both DetailPrint "Installing: Adobe Acrobat Reader" SetDetailsPrint listonly ... Extract all your files here while "Installing: Adobe Acrobat Reader" is displayed ... SetDetailsPrint both </code></pre>
Azure Blob Storage returns 404 on PUT <p>I created new blob storage; set CORS to allow all (*) origins; created new container (dev); set container access policy to "Container". Now when I'm trying to upload file (file.txt) to my container I get 404 ResourceNotFound "The specified resource does not exist." response. I make following request from Postman:</p> <pre><code>PUT /dev/file.txt HTTP/1.1 Host: mystorageaccount.blob.core.windows.net x-ms-blob-type: BlockBlob x-ms-date: Thu, 13 Oct 2016 09:00:00 GMT x-ms-version: 2015-02-21 x-ms-blob-content-type: text/plain </code></pre> <p>What might be a problem?</p>
<blockquote> <p>set container access policy to "Container"</p> </blockquote> <p>Setting container access policy to <code>Container</code> will only work for read operations. For write operations, the requests need to be authenticated. </p> <p>For authentication, you would need to create an <code>Authorization</code> header as described here: <a href="https://msdn.microsoft.com/en-us/library/azure/dd179428.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/azure/dd179428.aspx</a>.</p> <p>An alternative to that is to make use of <code>Shared Access Signature (SAS)</code>. What you need to do is create a <code>SAS Token</code> with at least <code>Write</code> permission and create a SAS URL with that token (which is your blob url + SAS token). Please see this link for more details about Shared Access Signature: <a href="https://azure.microsoft.com/en-in/documentation/articles/storage-dotnet-shared-access-signature-part-1/" rel="nofollow">https://azure.microsoft.com/en-in/documentation/articles/storage-dotnet-shared-access-signature-part-1/</a>.</p>
Instrumental test for Realm database gives "Call 'Realm.init(Context)' before creating Realmconfiguration" even though I call it <p>For my Android application I use the Realm mobile database. I want to write tests for this, and the best way I found of testing was using instrumental tests. </p> <p>This is the constructor of my database class:</p> <pre><code>public Database(Context context) { this.context = context.getApplicationContext(); Realm.init(context); RealmConfiguration realmConfig = new RealmConfiguration.Builder() .name("com.arnowouter.badger.realmdatabase") // TODO: 4/10/2016 check if encryptable .build(); realm = Realm.getInstance(realmConfig); } </code></pre> <p>As you can see, Realm.init(context) is called. But when I run this test:</p> <pre><code>@RunWith(AndroidJUnit4.class) @MediumTest public class DatabaseTest { Database database; Context context; @Before public void setupDatabase() { context = InstrumentationRegistry.getContext(); database = new Database(context); } } </code></pre> <p>I get this error:</p> <pre><code>java.lang.IllegalStateException: Call `Realm.init(Context)` before creating a RealmConfiguration at io.realm.RealmConfiguration$Builder.&lt;init&gt;(RealmConfiguration.java:399) at io.realm.RealmConfiguration$Builder.&lt;init&gt;(RealmConfiguration.java:394) at com.arnowouter.badger.Database.Database.&lt;init&gt;(Database.java:38) at com.arnowouter.badger.DatabaseTest.setupDatabase(DatabaseTest.java:27) at java.lang.reflect.Method.invoke(Native Method) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runners.Suite.runChild(Suite.java:128) at org.junit.runners.Suite.runChild(Suite.java:27) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at org.junit.runner.JUnitCore.run(JUnitCore.java:115) at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59) at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1970) </code></pre>
<p>Considering the fact that the Context stored in Realm is the application configuration like this</p> <pre><code>// Thread pool for all async operations (Query &amp; transaction) volatile static Context applicationContext; </code></pre> <p>Which is initialized like this</p> <pre><code>public static synchronized void init(Context context) { if (BaseRealm.applicationContext == null) { if (context == null) { throw new IllegalArgumentException("Non-null context required."); } RealmCore.loadLibrary(context); //... BaseRealm.applicationContext = context.getApplicationContext(); } } </code></pre> <p>This means that the <code>context</code> you give it returns <code>null</code> for <code>context.getApplicationContext()</code>.</p> <p>Unfortunately, apparently the instrumentation's context returns <code>null</code> for <code>getFilesDir()</code>, so we need to obtain an application or an activity context.</p> <p>I'd probably just set application in a static variable, and use that.</p> <pre><code>public class CustomApplication extends Application { private static CustomApplication INSTANCE; public static CustomApplication get() { return INSTANCE; } @Override public void onCreate() { if(INSTANCE == null) { INSTANCE = this; } } } </code></pre> <p>And in manifest:</p> <pre><code>&lt;application name=".CustomApplication" </code></pre> <p>That way you can do:</p> <pre><code>@RunWith(AndroidJUnit4.class) @MediumTest public class DatabaseTest { Database database; Context context; @Before public void setupDatabase() { Realm.init(CustomApplication.get()); context = InstrumentationRegistry.getContext(); database = new Database(context); } } </code></pre>
Meteor error: Could not locate the bindings file <p>I have respond from meteor: "Error: Could not locate the bindings file." and then it shows places searched for file - in one of them file exist - look attached picture <a href="https://i.stack.imgur.com/10yFW.png" rel="nofollow">screen showing sought file exist in searched localisation</a> . I tried several remedy from this site but I'm bit confuse working with cmd. So, please explain to me like I'm 5 what and where I could change to make it work. I have to add meteor application originally was made on iOS and I'm on windows. Problems started when I'm trying to add package accounts-password and then run application. </p>
<p>In the net are lots of advices what to do and I did everything I found but none sad to do "meteor update" and only this works for me. So thumbs up, please. reason was most likely: creation of the app on older version of the meteor. That worked fine most of the time but adding accounts-password course it couldn't find bcrypt. Simply "meteor update" solved problem. </p>
SPARQL to encompass all sub-properties of a property <p>I want all Wikidata items that have ended, so I wrote this:</p> <pre><code>?item wdt:P582 ?endtime. </code></pre> <p>Problem: it does not include items that have been "abolished".<br> <a href="https://www.wikidata.org/wiki/Property:P576" rel="nofollow">abolished</a> is a subproperty of <a href="https://www.wikidata.org/wiki/Property:P582" rel="nofollow">end time</a>.</p> <p><strong>QUESTION</strong>: How to encompass all subproperties? </p> <hr> <p>Current query that does not include subproperties:</p> <pre><code>SELECT ?item ?endtime WHERE { ?item p:P31/ps:P31/wdt:P279* wd:Q3917681. # Embassies... ?item wdt:P582 ?endtime. # ... that have ended } </code></pre> <p>I could do a UNION with all known sub-properies, but new sub-properties may appear in the future.</p>
<p>If Wikidata includes subproperty relationships, you just need: </p> <pre><code>?p rdf:SubPropertyOf* wdt:P582 . ?item ?p ?endtime. </code></pre>
Google Cloud Project charges for download <p>I am getting charged for service cloud-storage/BandwidthDownloadAmerica as mentioned here: <a href="https://cloud.google.com/storage/pricing#network-pricing" rel="nofollow">https://cloud.google.com/storage/pricing#network-pricing</a></p> <p>Though, my google cloud storage bucket location, big-query dataset location and the machine where I am downloading are same as 'EU'. As per my opinion, the download from storage to machine should be considered as Ingress.</p> <p>My process includes: 1. Exporting from big-query dataset to cloud storage bucket. 2. Composing the file pieces to single file. 3. Downloading the composed file.</p> <p>I believe the charge mentioned in billing under:</p> <blockquote> <p>com.google.cloud/services/cloud-storage/BandwidthDownloadAmerica Download US EMEA</p> </blockquote> <p>is for the step no. 3</p> <p>Is there some setting that might have missed.</p> <p>My project configuration is set to [default].</p> <p>Any guidance is welcome. As we are new to the Google Cloud system.</p> <p>Please let me know.</p>
<p>EMEA stands for "Europe, Middle East, and Africa", so BandwidthDownloadAmerica does indeed include EU. So it seems correct that you incur these charges.</p> <p>(Granted, the naming is not great here, we're working to fix that)</p>
d3js v4: Add nodes to force-directed graph <p>I would like to render a <strong>force-directed graph in d3js v4</strong> and provide a function for <strong>dynamically adding new nodes and links</strong> to the simulation. My first attempt (see below) still has some major issues:</p> <ul> <li>Already existing nodes and links seem to be ignored by the force simulation after adding a link</li> <li>The bindings between simulation nodes and links and their SVG counterparts somehow doesn't work</li> </ul> <p>I think I know all the examples (e.g.,<a href="http://bl.ocks.org/ericcoopey/6c602d7cb14b25c179a4" rel="nofollow"> [1</a>,<a href="http://bl.ocks.org/mbostock/1062288" rel="nofollow">2]</a>) demonstrating similar functionality for v3, but I would like to do it with v4.</p> <p>Thanks for your help!</p> <p><strong>index.html</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;D3 Test&lt;/title&gt; &lt;script type="text/javascript" src="js/d3.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/graph.js"&gt;&lt;/script&gt; &lt;style type="text/css"&gt; .links line { stroke: #aaa; } .nodes circle { pointer-events: all; stroke: none; stroke-width: 40px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="chart-container" style="max-width: 1000px;"&gt;&lt;/div&gt; &lt;button class="expand"&gt;Expand graph&lt;/button&gt; &lt;script type="text/javascript"&gt; //sample graph dataset var graph = { "nodes": [ {"id": "A"}, {"id": "B"}, {"id": "C"}, {"id": "D"}, {"id": "E"}, {"id": "F"} ], "links": [ {"source": "B", "target": "A"}, {"source": "C", "target": "A"}, {"source": "D", "target": "A"}, {"source": "D", "target": "C"}, {"source": "E", "target": "A"}, {"source": "F", "target": "A"} ] } //graph container var targetElement = document.querySelector('.chart-container'); var graph = new Graph(targetElement, graph); d3.selectAll('button.expand').on('click', function (){ var nodes = [ {"id": "G", "group": 1} ]; var links = [ {"source": "F", "target": "G", "value": 1} ]; graph.expandGraph(links, nodes); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>graph.js</strong></p> <pre><code>var Graph = function(targetElement, graph) { var self = this, width = targetElement.offsetWidth, height = width / 2, svg = d3.select(targetElement).append('svg') .attr("width", width) .attr("height", height), simulation = d3.forceSimulation() .force("link", d3.forceLink().id(function(d) { return d.id; })) .force("charge", d3.forceManyBody()) .force("center", d3.forceCenter(width / 2, height / 2)), link = svg.append("g") .attr("class", "links") .selectAll("line"), node = svg.append("g") .attr("class", "nodes") .selectAll("circle"), update = function() { // Redefine and restart simulation simulation.nodes(graph.nodes) .on("tick", ticked); simulation.force("link") .links(graph.links); // Update links link = link.data(graph.links); // Enter links link = link.enter().append("line"); // Exit any old links link.exit().remove(); // Update the nodes node = node.data(graph.nodes); // Enter any new nodes node = node.enter().append("circle") .attr("r", 5) .call(d3.drag() .on("start", dragstarted) .on("drag", dragged) .on("end", dragended)); // Exit any old nodes node.exit().remove(); function ticked() { link .attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); } }, dragstarted = function(d) { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; }, dragged = function(d) { d.fx = d3.event.x; d.fy = d3.event.y; }, dragended = function(d) { if (!d3.event.active) simulation.alphaTarget(0); d.fx = null; d.fy = null; }, expandGraph = function(links, nodes) { for (var i=0; i &lt; nodes.length; i++) { console.log('adding node', nodes[i]); graph.nodes.push(nodes[i]); } for (var i=0; i &lt; links.length; i++) { console.log('adding link', links[i]); graph.links.push(links[i]); } update(); }; // Public functions this.expandGraph = expandGraph; update(); }; </code></pre>
<p>You forgot to <code>merge()</code> your nodes. I have updated your code quickly:</p> <p><strong>graph.js</strong></p> <pre><code>var Graph = function(targetElement, graph) { var self = this, width = targetElement.offsetWidth, height = width / 2, svg = d3.select(targetElement).append('svg') .attr("width", width) .attr("height", height), simulation = d3.forceSimulation() .force("link", d3.forceLink().id(function(d) { return d.id; })) .force("charge", d3.forceManyBody()) .force("center", d3.forceCenter(width / 2, height / 2)), linkGroup = svg.append("g") .attr("class", "links"), nodeGroup = svg.append("g") .attr("class", "nodes"), update = function() { // Redefine and restart simulation simulation.nodes(graph.nodes) .on("tick", ticked); simulation.force("link") .links(graph.links); // Update links link = linkGroup .selectAll("line") .data(graph.links); // Enter links linkEnter = link .enter().append("line"); link = linkEnter .merge(link); // Exit any old links link.exit().remove(); // Update the nodes node = nodeGroup.selectAll("circle").data(graph.nodes); // Enter any new nodes nodeEnter = node.enter().append("circle") .attr("r", 5) .call(d3.drag() .on("start", dragstarted) .on("drag", dragged) .on("end", dragended)); node = nodeEnter.merge(node); // Exit any old nodes node.exit().remove(); function ticked() { link .attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); } }, dragstarted = function(d) { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; }, dragged = function(d) { d.fx = d3.event.x; d.fy = d3.event.y; }, dragended = function(d) { if (!d3.event.active) simulation.alphaTarget(0); d.fx = null; d.fy = null; }, expandGraph = function(links, nodes) { for (var i=0; i &lt; nodes.length; i++) { console.log('adding node', nodes[i]); graph.nodes.push(nodes[i]); } for (var i=0; i &lt; links.length; i++) { console.log('adding link', links[i]); graph.links.push(links[i]); } update(); }; // Public functions this.expandGraph = expandGraph; update(); }; </code></pre> <p>Actually I don't understand this new function 100%, but you always need to merge your new links and nodes (i.e. <code>linkEnter</code> and <code>nodeEnter</code>) with your existing graph. If you don't do this, your old Graph kind of dies...</p> <p>Mike Bostock made an example how to use <code>merge</code> here: <a href="https://bl.ocks.org/mbostock/3808218" rel="nofollow">https://bl.ocks.org/mbostock/3808218</a></p> <p>I hope i was able to help. FFoDWindow</p> <p>PS: This is my first answer on Stackoverflow, so if there are any issues, please tell me :-)</p>
How to Replace special Character in Unix Command <p>My source data contains special characters not in readable format. Can anyone help on the below :</p> <p><a href="https://i.stack.imgur.com/sY3ZC.png" rel="nofollow">Source data:</a></p> <p><a href="https://i.stack.imgur.com/2bVpw.png" rel="nofollow"><img src="https://i.stack.imgur.com/2bVpw.png" alt="ascii values"></a></p> <p>Commands Tryed: sed 's/../t/g' test.txt > test2.txt</p>
<p>you can use <code>tr</code> to keep only printable characters:</p> <pre><code>tr -cd "[:print:]" &lt;test.txt &gt; test2.txt </code></pre> <p>Uses <code>tr</code> delete option on non-printable (print criteria negated by <code>-c</code> option)</p> <p>If you want to <em>replace</em> those special chars by something else (ex: X):</p> <pre><code>tr -c "[:print:]" "X" &lt;test.txt &gt; test2.txt </code></pre> <p>With <code>sed</code>, you could try that to replace non-printable by <code>X</code>:</p> <pre><code>sed -r 's/[^[:print:]]/X/g' text.txt &gt; test2.txt </code></pre> <p>it works on some but fails on chars >127 (maybe because the one I tried is printable as ▒ !) on my machine whereas <code>tr</code> works perfectly.</p> <p>inline examples (printf to generate special chars + filter + od to show bytes):</p> <pre><code>$ printf "\x01ABC\x05\xff\xe0" | od -c 0000000 001 A B C 005 377 340 0000007 $ printf "\x01ABC\x05\xff\xe0" | sed "s/[^[:print:]]//g" | od -c 0000000 A B C 377 340 0000005 $ printf "\x01ABC\x05\xff\xe0" | tr -cd "[:print:]" | od -c 0000000 A B C 0000003 </code></pre>
Why is my angular-ui-tour not finding the steps of my detached tour? <p>I'm using <a href="http://benmarch.github.io/angular-ui-tour/#/docs" rel="nofollow">angular-ui-tour</a> to enable my project to have multiple tours within the same DOM, because is has a detached tour option which I need to do so.</p> <p>My dependencies (relevant for this issue): </p> <ul> <li>angular 1.5.7</li> <li>bootstrap ^3.3.6</li> <li>angular-bootstrap ^2.0.0</li> <li>angular-ui-tour ^0.6.2 </li> </ul> <p>I can initialize the tour with the according config, but when I check for steps, no steps are found.</p> <p>When I try to start the tour, the error confirms this: 'No step.'-error. What am I missing here?</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>angular.module('myApp',['bm.uiTour']).run(['uiTourService', function(uiTourService) { //setup the tour uiTourService.createDetachedTour('general', { name: 'general', backdrop: true, debug: true }); //testing var uitour = uiTourService.getTourByName('general'); console.log(uitour); // Object {_name: undefined, initialized: true} //test tour steps console.log(uitour._getSteps()); // [] //test tour start uitour.start().then(function(data) { //tour start succeeded }, function(error) { //tour start failed console.log(error); // No steps. }); } ]);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body ui-tour&gt; &lt;div tour-step tour-step-belongs-to="general" tour-step-order="1" tour-step-title="step 1" tour-step-content="this is step 1"&gt; &lt;/div&gt; &lt;div tour-step tour-step-belongs-to="general" tour-step-order="2" tour-step-title="step 2" tour-step-content="this is step 2"&gt; &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
<p>I've managed to resolve this question. Apparently this is a known bug of <a href="https://github.com/benmarch/angular-ui-tour" rel="nofollow">angular-ui-tour</a> and will be fixed in the next patch.</p> <p>For more information about this question, I can refer you to the <a href="https://github.com/benmarch/angular-ui-tour/issues/90" rel="nofollow">issue on the GitHub</a>.</p> <p>For now, you can resolve the issue by making the following change in the angular-ui-tour tourStep directive:</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>//Add step to tour (old) scope.tourStep = step; scope.tour = scope.tour || ctrl; //Add step to tour (new) scope.tourStep = step; scope.tour = ctrl;</code></pre> </div> </div> </p>
Is it secure to pass the DB query to AzureML as a global parameter? <p>When using AzureMLBatchExecution activity in Azure Data Factory, is it secure to pass the DB query as a global parameter to the AzureML web service? </p>
<p>When you talk about "secure", are you worried about secure transmission between AML and ADF, or secure storage of your DB query information? For the former, all communication between these two services will be done with HTTPS. For the latter, our production storage has its strict access control. Besides, we only log the count of the global parameters and never the values. I believe it's secure to pass your DB query as a global parameter to the AzureML web service.</p>
SwitchPreference dependency on two other switch preferences <p>I have three <code>switchpreferences</code> in my app (say, switch1, switch2 and switch3). What I want to achieve is whenever switch1 <code>AND</code> switch2 are set to <code>false</code>, switch3 must also be set to <code>false</code> automatically. If either of switch1 or switch2 is set to <code>true</code>, switch3 should also be <code>true</code>. How can I achieve that??</p>
<p>Implement onCheckChangedListener for switch1 and switch2 and add the below statement in your onCheckChanged() callback method.</p> <pre><code>switch3.setChecked(switch1.isChecked() || switch2.isChecked()) </code></pre>
UnHandled Exception while dynamically adding TextBox <p>I am trying to dynamically add textbox onclick of button. Below is my code. I am able to add one textbox, but while adding next textbox after completing all code <code>UnHandled exception</code> is thrown. I don't know from where it is being thrown. </p> <pre><code>protected override void LoadViewState(object savedState) { base.LoadViewState(savedState); controlidlist = (List&lt;string&gt;)ViewState["controlidlist"]; if(controlidlist != null) { foreach (string Id in controlidlist) { i++; TextBox tb = new TextBox(); tb.ID = Id; System.Web.UI.LiteralControl lineBreak = new System.Web.UI.LiteralControl(); UpdatePanel1.ContentTemplateContainer.Controls.Add(tb); UpdatePanel1.ContentTemplateContainer.Controls.Add(lineBreak); } } else { controlidlist = new List&lt;string&gt;(); } } </code></pre> <p>ButtonClick Event:</p> <pre><code>protected void Button_Click1(object sender, EventArgs e) { try { i++; TextBox tB = new TextBox(); tB.ID = "textBox_" + i; System.Web.UI.LiteralControl lineBreak = new System.Web.UI.LiteralControl("&lt;br&gt;"); UpdatePanel1.ContentTemplateContainer.Controls.Add(tb); UpdatePanel1.ContentTemplateContainer.Controls.Add(lineBreak); ViewState["controlidlist"] = controlidlist; controlidlist.Add(tb.ID); UpdatePanel1.DataBind(); } catch(Exception ex) { } } </code></pre> <p>After completely executing above code below exception is thrown in Global.asax.</p> <p>Error:</p> <blockquote> <p>{"Exception of type 'System.Web.HttpUnhandledException' was thrown."}</p> </blockquote> <p>global.asax</p> <pre><code>void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs Exception exception = Server.GetLastError() as HttpUnhandledException; if (exception != null &amp;&amp; exception.InnerException is ProductNotFoundException) { } } </code></pre> <p><strong>This may be simple, but I am very new to this</strong></p>
<p>You can try below code for adding dynamic <code>TextBox</code> with line break:</p> <pre><code>TextBox t = new TextBox(); t.ID = "textBox_" + i; ViewState["controlidlist"] = controlidlist; controlidlist.Add(tb.ID); UpdatePanel1.ContentTemplateContainer.Controls.Add(t); Literal lit = new Literal() { Mode=LiteralMode.PassThrough, Text="&lt;br/&gt;" }; UpdatePanel1.ContentTemplateContainer.Controls.Add(lit); </code></pre> <p>Hope it will solves your issue.</p> <p>Thanks</p>
Setting up a worker thread to continuously check a bool value of an object <p>I am running this code in a form, but when i start it, it freezes. This is because <strong>while</strong> keeps the other code from running. I want to setup a separate worker thread for this while task. However i do not know how to set up a worker thread for this specific task.</p> <pre><code> public void startGame(Form sender) // Form that is being send is an mdiContainer { View view = new View(); Controller game = new Controller(view); view.MdiParent = sender; //Here i tell the other form it's parent is sender view.Visible = true; //problem code while (true) //This loop is supposed to keep checking if the game has ended and if it did, close the form view. { if(game.gameOver == true) { view.Close(); break; } } } </code></pre>
<p>Getting multi-threading right is not an easy task and should only be done if really necessary.</p> <p>I have an alternative suggestion:</p> <p>Your Controller <code>game</code> raises an event when the game is over:</p> <pre><code>class Controller { ... public event EventHandler GameFinished; private bool gameOver; public bool GameOver { get { return gameOver; } set { gameOver = value; if (gameOver) GameFinished?.Invoke(this, new EventArgs()); } } } </code></pre> <p>The class containing <code>startGame</code> adds a handler to this event and closes the view when the event has been raised:</p> <pre><code>View view = new View(); Controller game = new Controller(view); ... game.GameFinished += (sender, e) =&gt; { view.Close(); } </code></pre>
SQl sum items conditionally <p>I have the below code. It counts 1 if it is certain work and 0 if it is other work. I need a way to count 0.5 if it is a third work. I have tried this and it always seems to count in whole numbers. Is there a way to do this using SQL? I have searched and cannot find such a way to calculate some items as 0.5. This is going to help with production totals in a access database</p> <pre><code>SELECT TOP 1000 [Type of Work], COUNT(case when [Type of Work] IN ('LEP Decisions', 'Creditable Coverage', 'Pends','Demographics', 'Consents','POA','PCP','Housing Verifications', 'LEP Cases') then 1 else Null END)as count ,[User ID] FROM [Medicare_Enrollment].[dbo].[Sample] group by [Type of Work], [User ID] </code></pre>
<pre><code>SELECT TOP 1000 [Type of Work], SUM(case when [Type of Work] IN ('LEP Decisions','Creditable Coverage','Pends','Demographics','Consents','POA','PCP','Housing Verifications','LEP Cases') then 1 WHEN [Type of Work] IN ('') -- Put your work list THEN 0.5 else 0 END)as count ,[User ID] FROM [Medicare_Enrollment].[dbo].[Sample] group by [Type of Work], [User ID] </code></pre>
PHP: sleep() for particular line of code <p>is it possible to use sleep() (or some other function) to wait before execution?</p> <p>I have for example:</p> <pre><code>&lt;div&gt;bla bla&lt;/div&gt; &lt;?php $a echo $a; ?&gt; some divs and html &lt;?php $b echo $b; ?&gt; </code></pre> <p>How to execute the first php script say 5 sec after the page has loaded but to show everything else as the page loads? If I use sleep() before the first php it will delay the whole page from loading.</p>
<p>Yes, you can use <code>sleep()</code> to delay execution, but since the output is usually buffered and isn't sent to the browser until the script has finished the result isn't what you're after.</p> <p>If you do a <code>flush()</code> and <code>ob_flush()</code> right after calling <code>sleep()</code> the output buffer is flushed and sent to the browser.</p> <p>See <a href="http://php.net/manual/en/function.ob-flush.php" rel="nofollow">http://php.net/manual/en/function.ob-flush.php</a></p>
Join results from two MySQL tables <p>I have two MySQL tables from which i can't get joined results.</p> <p>The first one is just a list of companies and their names:</p> <pre><code>companies: ____________________________ companyid | companyname | 1 comp1 2 comp2 </code></pre> <p>The second one is the list of user roles:</p> <pre><code>roles: _____________________________________________________ roleid | uid | role | companyid | suspended | 1 1 dir 1 0 2 1 manag 2 0 </code></pre> <p>I want to get a result that would look like:</p> <pre><code>_______________________ companyname | role | comp1 dir comp2 manag </code></pre> <p>My query below returns nothing...</p> <pre><code>SELECT companies.companyid, roles.role FROM companies INNER JOIN roles ON roles.companyid=companies.companyname where (uid = 1 and suspended = 0) </code></pre>
<p>Check you joining condition.</p> <p>Try this,</p> <pre><code>select a.companyname,b.role from companies a, roles b where a.companyid=b.companyid and (b.uid = 1 and b.suspended &lt;&gt; 0); </code></pre>
"Unknown Host" - Connecting to PostgreSQL database in SQL Shell (Windows) <p>I've previously been using PostgreSQL in Ubuntu using:</p> <pre><code>$sudo -i -u postgres </code></pre> <p>to access postgres through the terminal to create a role and database. And then able to log in and make changes using:</p> <pre><code>$sudo -u [dbname] psql </code></pre> <p>However now I need to use PostgreSQL with LabVIEW so I've had to download PostgreSQL on a Windows PC. I can access the database through Pgadmin and have created a database but when I go into SQL shell it comes up with:</p> <pre><code>Server [localhost]: Database [postgres]: Port [5432]: Username [postgres]: </code></pre> <p>I'm not sure if this has anything to do with roles, as I haven't created one for the windows database. But I can't even get past the above to create a role or make any changes in the command prompt.</p> <p>When I type my computer host name, it says </p> <pre><code> psql: could not translate host name "Lisa" to address: Unknown host </code></pre> <p>It says I am connected on PgAdmin and I am able to create databases and tables through the interface, but I can't figure out how to access it in the SQL Shell (psql).</p>
<p>Entered server as localhost IP.</p> <pre><code> Server [localhost]: 127.0.0.1 Database [localhost]: [dbname] Port [5432]: 5432 Username [postgres]: [username] </code></pre>
Android RecyclerView - scrolling changes items <p>I have a recyclerview with linear layout manager and it contains different items. one of the items have a button that hides or display the nested layout of this items. </p> <p>So I added something like 10 rows of the specific type, and when I click on specific item, it's nested layout is displayed, but I see that another item display it's own nested layout. Second try was to click on some button and scrolling, the nested layout was shown on a different items.</p> <p>As you can see from the code, I tried to call the method - notifyDataSetChanged(), but it doesn't help. I know that there is expanded recycler view, but In my case I want to solve it without change the whole code.. </p> <p>The layout:</p> <pre><code>&lt;RelativeLayout android:layout_height="wrap_content" android:layout_width="wrap_content" &gt; &lt;TextView android:id = "@+id/tv" android:layout_height="wrap_content" android:layout_width = "wrap_content" android:text = "click on the button" /&gt; &lt;Button android:id = "@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" android:layout_toRightOf="@+id/tv" /&gt; &lt;RelativeLayout android:id = "@+id/nested" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tv" android:visibility="gone" &gt; &lt;TextView android:id = "@+id/tv1" android:layout_height="wrap_content" android:layout_width = "wrap_content" android:text = "click on the button" /&gt; &lt;/RelativeLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p>The code in the adapter (onBind)</p> <pre><code>@Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { int type = getItemViewType(position); ViewType viewType = ViewType.values()[type]; try { switch (viewType) { case VIEW1: // code for view 1 break; case VIEW2: final ViewHolder viewHolder = (ViewHolder) holder; viewHolder.tv.setText("TV1"); viewHolder.btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { viewHolder.nestedLayout.setVisibility(!isVisible ? View.VISIBLE : View.GONE ); viewHolder.isVisible = !viewHolder.isVisible; // notifyDataSetChanged(); } }); break; } } catch (Exception e) { e.printStackTrace(); Log.d("ChatListAdapter","chat list adapter ioexception" + e.getMessage()); } } </code></pre>
<p>You have to set the visibility state for each view (each call to onBindViewHolder). I guess what happens for you is that you set the visibility for a view that is later recycled and have the visibility set. </p>
Is it necessary for MQTT client to have same key, cert as used by MQTT broker for TLS? <p>I am using node.js mosca MQTT broker and node.js mqtt package for implementing mqtt client.</p> <p><a href="https://github.com/mcollina/mosca" rel="nofollow">https://github.com/mcollina/mosca</a></p> <p><a href="https://www.npmjs.com/package/mqtt" rel="nofollow">https://www.npmjs.com/package/mqtt</a></p> <p>I want to implement MQTT over TLS. Suppose the mosca MQTT broker uses tls-cert.pem and tls-key.pem, is it necessary for the mqtt client to use the same cert and key to be able to connect to this MQTT broker?</p> <p>The mosca MQTT broker was run as a stand-alone using the command below;</p> <p><code>mosca --key ./tls-key.pem --cert ./tls-cert.pem --http-port 3000 --http-bundle --http-static ./ | pino</code></p> <p>When a web browser running HTTPS talks to a web server running HTTPS, there is no need for the web browser to know the cert and key. I wonder if this applies to mqtt.</p>
<p>For a basic secure connection the client only needs to know the CA cert used to sign the brokers certificate. It uses this to prove to it's self that the broker is who it claims to be.</p> <p>If you are using self signed certificate (which I'm guessing you are) then the CA certificate is the same as the broker certificate, so both the client and the broker will have the same certificate.</p> <p>Web browsers have a built in list of CA certificates which cover most of the public CA's that issue certificates.</p> <p>NO BODY should ever have access to the private key apart from the broker.</p>
Java is taking a class from the wrong path <p>I have 2 projects: project1 and project2 and the class <code>Class1</code> in both projects but there are differences between these classes.</p> <p>I'm trying to use Project1.Class1 in a XHTML file but sometimes it takes <code>Project2.Class1</code>.</p> <p>I have already checked every import in my classes and everything seems to be alright. Does anyone know why Eclipse is taking the wrong path?. </p>
<p>It is not a problem with java. If you have 2 java classes with same name and package structure, the class which is first seen in class path will be loaded in to the memory. The other class will be omitted as per the class loading policy.</p> <p>If you want use only one class, Keep that class alone in the classpath and remove the other one. </p>
How to position a toast in Nougat's multi-window mode? <p>While using Nougat's new multi-window mode, I noticed that a <code>Toast</code> will be displayed over another app if my own app is in the top window in portrait mode.</p> <p><a href="https://i.stack.imgur.com/E6Y3z.png" rel="nofollow"><img src="https://i.stack.imgur.com/E6Y3z.png" alt="enter image description here"></a></p> <p>This is ... not good at all. So I tried positioning my <code>Toast</code> following <a href="http://stackoverflow.com/a/2507069/5015207">this answer</a> to <strong>"How to change position of Toast in Android?"</strong></p> <pre><code>toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); </code></pre> <p>Unfortunately the <code>Gravity</code> seems to be interpreted as "gravity for the screen" not "gravity for my window". </p> <p>How to get a <code>Toast</code> displayed somewhere near the bottom of my window and centered horizontally?</p> <p><a href="https://i.stack.imgur.com/spaaN.png" rel="nofollow"><img src="https://i.stack.imgur.com/spaaN.png" alt="enter image description here"></a></p>
<p>I suspect this is the intended behaviour. Beyond there not being any straightforward way to achieve what you desire, according to the <a href="https://material.google.com/components/snackbars-toasts.html" rel="nofollow">Material Design Guidelines</a> Toasts are used primarily to convey system messages and should appear at the bottom of the screen. </p> <p>My guess would be that any system messages should pertain to the device as a whole, and are not necessarily application specific, so this consistent behaviour makes sense. That said, I can see why this behaviour is undesirable, because the Toast ends up taking up practically 25% of the screen on one of the applications... however, regardless of the position of the Toast it will be gobbling up that screen real estate, whether it's on your application or the one below.</p> <p>If you really wanted to implement a workaround, here is the implementation for offsetting the Toast vertically. A slight variation should achieve landscape mode, but it's a bit more finnicky.</p> <pre><code>View root = findViewById(R.id.root_main); int[] xy = new int[2]; root.getLocationOnScreen(xy); DisplayMetrics displayMetrics = new DisplayMetrics(); WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(displayMetrics); int devHeight = displayMetrics.heightPixels; int viewHeight = root.getHeight(); Toast toast = Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG); int yOffset = Math.abs(xy[1] - devHeight + viewHeight) + toast.getYOffset(); toast.setGravity(Gravity.BOTTOM, 0, yOffset); toast.show(); </code></pre>
Prioritizing recursive crawl in Storm Crawler <p>When crawling the world wide web, I would want to give my crawler an initial seed list of URLs - and would expect my crawler to automatically 'discover' new seed URLs from internet during it's crawling.</p> <p>I see such option in Apach Nutch (see topN parameter in <a href="https://wiki.apache.org/nutch/bin/nutch%20generate" rel="nofollow">generate command of nutch</a>). Is there any such option in <a href="https://github.com/DigitalPebble/storm-crawler" rel="nofollow">Storm Crawler</a> as well?</p>
<p>StormCrawler can handle recursive crawls, and the way URLs are prioritized depends on the backend used for storing the URLs.</p> <p>For instance the <a href="https://github.com/DigitalPebble/storm-crawler/tree/master/external/elasticsearch" rel="nofollow">Elasticsearch module</a> can be used for that, see the README for a short tutorial and the <a href="https://github.com/DigitalPebble/storm-crawler/blob/master/external/elasticsearch/es-conf.yaml" rel="nofollow">sample config file</a>, where by default the spouts will sort URLs based on their nextFetchDate (**.sort.field*).</p> <p>In Nutch, the -topN argument only specifies the max number of URLs to put in the next segment (based on the scores provided by whichever scoring plugin is used). With StormCrawler we don't really need an equivalent as things are not processed by batches, the crawl runs continuously.</p>
Chart.js: Chart not resizing in iframe <p>I am trying to show multiple diagrams/charts at the same time using chart.js. For my setup, I have one <strong>chart.html</strong> file which displays the diagram and a <strong>split.html</strong> file which creates multiple iframes (2 so far) and loads the <strong>chart.html</strong> in them. When opening the <strong>chart.html</strong> directly, the resizing works, but when loaded in iframe it doesn't. I could only imagine the error at chart.js since the sizing itself is already weird. It orients on the next "higher" element (div with fixed 100% width and height in my case) and setting width or height directly on the canvas doesnt change anything, see code below.</p> <p><strong>chart.html</strong>:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script src="./node_modules/chart.js/dist/Chart.bundle.js"&gt;&lt;/script&gt; &lt;script src="./node_modules/jquery/dist/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="./js/diagram.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="container" style="width:100%; height:100%;"&gt; &lt;canvas id="diagram"&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p></p> <p><strong>split.html</strong>:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="./css/splitter.css" /&gt; &lt;script src="./node_modules/jquery/dist/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="./js/splitter.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="content"&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p></p> <p><strong>diagram.js</strong>:</p> <pre><code>$(document).ready(function() { var ctx = document.getElementById("diagram"); var myChart = new Chart(ctx, { type: 'line', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: /** excluded (unimportance) **/ }, options: { responsive: true, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); // Resize chart $(window).resize(function() { console.log("resize works!"); if(myChart) myChart.update(); }); }); </code></pre> <p><strong>splitter.js</strong>:</p> <pre><code>$(document).ready(function () { const splits = 2; switch (splits) { case 2: $("#content").append( $('&lt;iframe /&gt;') .attr("id", "frame1") .attr("src", "./chart.html") .addClass("width50 height100") ); $("#content").append( $('&lt;iframe /&gt;') .attr("id", "frame2") .attr("src", "./chart.html") .addClass("width50 height100 left50") ); break; } }); </code></pre> <p><strong>splitter.css</strong>:</p> <pre><code>iframe { position: fixed; border: none; margin: 0; padding: 0; } .width100 { width: 100%; } .height100 { height: 100%; } .width50 { width: 50%; } .height50 { height: 50%; } .left50 { left: 50%; } .top50 { top: 50%; } </code></pre>
<p>Change iframes to divs with modifiing your splitter.js:</p> <pre><code>$(document).ready(function () { const splits = 2; for(var i = 0; i &lt; splits;i++){ var chartContainer = $('&lt;div id="frame' + (i + 1) + '"&gt;&lt;/div&gt;').appendTo("#content"); var canvas = $('&lt;canvas class="diagram"&gt;').appendTo(chartContainer); if(i === 0) chartContainer.addClass('width50 height100'); else chartContainer.addClass('width50 height100 left50'); } }); </code></pre> <p>It will add two divs to the content element instead of iframes and also put the canvases into the divs. Than change your diagram.js to foreach over the canvases and make them work as a chart:</p> <pre><code>$('canvas.diagram').each(function(){ var ctx = $(this); var myChart = new Chart(ctx, { //here comes the chart configuration... }); }); </code></pre> <p>Change your css to align the two div next to each other with</p> <pre><code>.width50 { width: 50%; display: inline-block; } </code></pre> <p>So the charts are now inside block elements and because of they're set to be responsive if you resize the window they will be resized automatically based on their parent elements' width (so you can remove the resizing part from your script too)</p>
Android autoTesting with Cucumber and Espresso <p>I have a problem with Cucumber, I can't start tests, all the time I have the same problem, and have no idea how to fix it.</p> <p>When I run tests I got this message:</p> <pre><code>Started running tests Test running failed: Instrumentation run failed due to 'cucumber.runtime.CucumberException' Empty test suite. </code></pre> <p>My build.gradle</p> <pre><code>android { .... sourceSets { androidTest { assets.srcDirs = ['src/androidTest/assets'] } } } dependencies {... //Testing testCompile 'junit:junit:4.12' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0' androidTestCompile 'com.android.support.test:testing-support-lib:0.1' androidTestCompile('info.cukes:cucumber-android:1.2.4') { exclude module: 'cucumber-jvm-deps' exclude module: 'guava' } androidTestCompile 'info.cukes:cucumber-jvm-deps:1.0.3' </code></pre> <p>Cucumber Runner: </p> <pre><code>CucumberOptions(features = "features/Test.feature") public class CucumberInstrumentationRunner extends MonitoringInstrumentation { private final CucumberInstrumentationCore instrumentationCore = new CucumberInstrumentationCore(this); @Override public void onCreate(final Bundle bundle) { super.onCreate(bundle); instrumentationCore.create(bundle); start(); } @Override public void onStart() { waitForIdleSync(); instrumentationCore.start(); } } </code></pre> <p>Test.feature</p> <pre><code>Scenario: Пользователь пытается авторизоваться используя неверные логин и пароль Given I've launched "com.example.activities.LoginActivity" When User 'User@User.com' singIn with password 'wrongPassword' Then Check message about incorrect password </code></pre> <p>and LoginActivitySteps</p> <pre><code>public class LoginActivitySteps extends InstrumentationTestCase { // ViewInteractions private final ViewInteraction mEmailEdt = onView(withId(R.id.edt_email)); private final ViewInteraction mPassEdt = onView(withId(R.id.edt_pass)); private final ViewInteraction mLoginBtn = onView(withId(R.id.button_login)); private Activity currentActivity; @Given("^I've launched \"([^\"]*)\"$") public void I_ve_launched_(String activityClassName) throws Throwable { String targetPackage = getInstrumentation().getTargetContext().getPackageName(); Class&lt;? extends Activity&gt; activityClass = (Class&lt;? extends Activity&gt;) Class.forName(activityClassName); currentActivity = launchActivity(targetPackage, activityClass, null); } @When("^User '(.+)' singIn with password '(.+)'$") public void userLogin(String login, String password) { mEmailEdt.perform(clearText()); mPassEdt.perform(clearText()); mEmailEdt.perform(ViewActions.typeText(login)); mPassEdt.perform(ViewActions.typeText(password)); mLoginBtn.perform(ViewActions.click()); } @Then("^Check message about incorrect password") public void checkTextOnScreen() { onView(withText("Wrong pass")).check(matches(isDisplayed())); } </code></pre>
<p>I think you're missing some <code>build.gradle</code> configuration parts like:</p> <pre><code> testApplicationId "cucumber.cukeulator.test" testInstrumentationRunner "cucumber.cukeulator.test.Instrumentation" </code></pre> <p>Check this <code>Cucumber</code> example <code>build.gradle</code> configuration content: <a href="https://github.com/cucumber/cucumber-jvm/blob/master/examples/android/android-studio/Cukeulator/app/build.gradle" rel="nofollow">https://github.com/cucumber/cucumber-jvm/blob/master/examples/android/android-studio/Cukeulator/app/build.gradle</a></p> <p>Hope it will help</p>
Recompile, relink, vertex shader in shader program <p>I have in place a system for detecting changes made to my shader files. When a shader is changes, let's say the vertex shader, I want to compile that one and replace it with the old version (while <strong>not</strong> changing the input/output of the shader and thus reusing the VAO, VBO, etc).</p> <pre><code>std::pair&lt;bool, std::string&gt; Shader::recompile() { std::string vertex_src = load_shader_source(vertex_filepath); glDetachShader(gl_program, vertex_shader); // gl_program is a GLuint for the shader program glDeleteShader(vertex_shader); vertex_shader = glCreateShader(GL_VERTEX_SHADER); auto raw_str = vertex_src.c_str(); glShaderSource(vertex_shader, 1, &amp;raw_str, NULL); glCompileShader(vertex_shader); GLint vertex_shader_status; glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &amp;vertex_shader_status); GLint fragment_shader_status = 1; if (vertex_shader_status == 1) { glAttachShader(gl_program, vertex_shader); // glLinkProgram(gl_program); // Logging - mostly irrelevant to the question GLint is_linked = 0; glGetProgramiv(gl_program, GL_LINK_STATUS, &amp;is_linked); SDL_Log("Shader relinking is success: %i", is_linked == GL_TRUE); std::string err_log = ""; GLint max_log_lng = 0; glGetProgramiv(gl_program, GL_INFO_LOG_LENGTH, &amp;max_log_lng); err_log.reserve(max_log_lng); glGetProgramInfoLog(gl_program, max_log_lng, NULL, (char *) err_log.c_str()); SDL_Log("%s", err_log.c_str()); return {true, ""}; } </code></pre> <p>The result when using this approach is that nothing changes, but when I link the program (inside the if-statement) it goes all away. I am assuming this is because the linking changes all the bindings and thus makes the existing ones invalid, resulting in nothing being rendered at all.</p> <p>So, is this even possible to hotswap the a specific shader like this in a shader program?</p>
<p>Linking does not invalidate any attribute bindings since they are part of the VAO state and not of the program. There are two things that could happpen when relinking the program:</p> <ul> <li>The index of an attribute might change. This can be prevented by either fixing them in both shaders (<code>layout (location=...)</code>) or by fixing them between compile and load (<code>glBindAttribLocation​</code>). The same thing might also happen for uniforms and can be handled in the same way.</li> <li>The values of uniforms are lost. This can not simply be prevented, but setting them in each frame should fix the problem.</li> </ul>
Bouncing Slide Menu with Jquery <p>I'm new to Jquery and fairly new to HTML/CSS, but because I'm the type that learns through hands-on experience, I've been building a practice website while I learn new things, and have been experimenting with elements I'd like to eventually implement on a genuine site.</p> <p>I've been trying to build a proper slide menu that activates when the cursor is hovered over the menu items. I've managed to get the menus to slide out, but if I move my cursor down into the slid-out menu, the whole thing starts bouncing! I've tried utilizing .stop() but then it flashes!</p> <p>I've found questions on here and other sites from people with very similar (if not identical) issues, but I think I'm not understanding any of the answers that worked for them. I need visuals, and answers like "insert an if () {} statement" confuses me because I'm not sure where to put it. If I go by what my source material instructs me to do (put a check/if statement in the bottom function) it just seems to break the code and then the menus don't even slide out.</p> <p>It has been very frustrating, and when I get too frustrated (like after six hours) I can't think as well about a solution, so if someone could help me find errors in my code or give me a fairly detailed explanation of what I could do to fix this bouncing problem, and how it started, I would really appreciate it.</p> <p>I've attached the JQ, HTML, &amp; CSS. Thanks in advance.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $('.dropdown').hover( function() { $(this).children(".sub-menu").slideDown(200); }, function() { $(this).children(".sub-menu").slideUp(200); } ); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>nav { background-color: #000000; padding:10px 0; text-align:center; } nav li { margin: 10px; padding: 0 10px; display: inline; } nav ul { list-style-type:none; margin:0; padding:0; } nav a { font-size: 30px; height: 35px; line-height: 30px; color: #ffffff; text-decoration: none; } nav a:hover, nav a:focus, nav a:active { color: #ff0000; } nav ul li { display:inline-block; position:relative; } nav li ul { background-color:#000000; position:absolute; left:0; top:50px; width:200px; } nav li li a { position:relative; font-size:25px; margin:0; padding:0; display:block; } ul.sub-menu { display:none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=""&gt;&lt;b&gt;Home&lt;/b&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Inspiration&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt;&lt;a href=""&gt;Find&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href=""&gt;Ebooks&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;PDFs&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;News&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt;&lt;a href=""&gt;Contact Us&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href=""&gt;E-mail List&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Contact Us&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="dropdown"&gt;&lt;a href=""&gt;Extras&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href=""&gt;Coming Soon&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt;</code></pre> </div> </div> </p>
<p>You have a space between your <code>&lt;li&gt;</code> elements and the dropdown menu (<a href="https://jsfiddle.net/8g48k77c/" rel="nofollow">You can see it here</a>). Just remove / move it.</p> <p>I did </p> <pre><code>nav { [...] // padding: 10px 0; padding: 0; } nav li { [...] // padding: 0 10px; padding: 10px; } </code></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>$(document).ready(function() { $('.dropdown').hover( function() { $(this).children(".sub-menu").slideDown(200); }, function() { $(this).children(".sub-menu").slideUp(200); } ); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>nav { background-color: #000000; padding: 0; text-align:center; } nav li { margin: 10px; padding: 10px; display: inline; } nav ul { list-style-type:none; margin:0; padding:0; } nav a { font-size: 30px; height: 35px; line-height: 30px; color: #ffffff; text-decoration: none; } nav a:hover, nav a:focus, nav a:active { color: #ff0000; } nav ul li { display:inline-block; position:relative; } nav li ul { background-color:#000000; position:absolute; left:0; top:50px; width:200px; } nav li li a { position:relative; font-size:25px; margin:0; padding:0; display:block; } ul.sub-menu { display:none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=""&gt;&lt;b&gt;Home&lt;/b&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Inspiration&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt;&lt;a href=""&gt;Find&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href=""&gt;Ebooks&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;PDFs&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;News&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt;&lt;a href=""&gt;Contact Us&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href=""&gt;E-mail List&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Contact Us&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="dropdown"&gt;&lt;a href=""&gt;Extras&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href=""&gt;Coming Soon&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt;</code></pre> </div> </div> </p>
Parse dates and create time series from .csv <p>I am using a simple csv file which contains data on calory intake. It has 4 columns: <code>cal</code>, <code>day</code>, <code>month</code>, year. It looks like this:</p> <pre><code>cal month year day 3668.4333 1 2002 10 3652.2498 1 2002 11 3647.8662 1 2002 12 3646.6843 1 2002 13 ... 3661.9414 2 2003 14 # data types cal float64 month int64 year int64 day int64 </code></pre> <p>I am trying to do some simple time series analysis. I hence would like to parse <code>month</code>, <code>year</code>, and <code>day</code> to a single column. I tried the following using <code>pandas</code>:</p> <pre><code>import pandas as pd from pandas import Series, DataFrame, Panel data = pd.read_csv('time_series_calories.csv', header=0, pars_dates=['day', 'month', 'year']], date_parser=True, infer_datetime_format=True) </code></pre> <p>My questions are: (1) How do I parse the data and (2) define the data type of the new column? I know there are quite a few other similar questions and answers (see e.g. <a href="http://stackoverflow.com/questions/23797491/parse-dates-in-pandas">here</a>, <a href="http://stackoverflow.com/questions/34146679/python-pandas-csv-parsing">here</a> and <a href="http://stackoverflow.com/questions/30864676/pandas-parse-dates-from-csv">here</a>) - but I can't make it work so far.</p>
<p>You can use parameter <code>parse_dates</code> where define column names in <code>list</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>:</p> <pre><code>import pandas as pd import numpy as np import io temp=u"""cal,month,year,day 3668.4333,1,2002,10 3652.2498,1,2002,11 3647.8662,1,2002,12 3646.6843,1,2002,13 3661.9414,2,2003,14""" #after testing replace io.StringIO(temp) to filename df = pd.read_csv(io.StringIO(temp), parse_dates=[['year','month','day']]) print (df) year_month_day cal 0 2002-01-10 3668.4333 1 2002-01-11 3652.2498 2 2002-01-12 3647.8662 3 2002-01-13 3646.6843 4 2003-02-14 3661.9414 print (df.dtypes) year_month_day datetime64[ns] cal float64 dtype: object </code></pre> <p>Then you can rename column:</p> <pre><code>df.rename(columns={'year_month_day':'date'}, inplace=True) print (df) date cal 0 2002-01-10 3668.4333 1 2002-01-11 3652.2498 2 2002-01-12 3647.8662 3 2002-01-13 3646.6843 4 2003-02-14 3661.9414 </code></pre> <p>Or better is pass <code>dictionary</code> with new column name to <code>parse_dates</code>:</p> <pre><code>df = pd.read_csv(io.StringIO(temp), parse_dates={'dates': ['year','month','day']}) print (df) dates cal 0 2002-01-10 3668.4333 1 2002-01-11 3652.2498 2 2002-01-12 3647.8662 3 2002-01-13 3646.6843 4 2003-02-14 3661.9414 </code></pre>
VSTS SonarQube cannot find TRX file <p>I am using Visual Studio Team Services to carry out an automated build, and using SonarQube to display Code Quality, Coverage, etc. I am also using a privately hosted build agent.</p> <p>The build steps all work successfully with data being processed and populated through to SonarQube which is great. However, no code coverage is being displayed in SonarQube. After looking through the logs in VSTS I found that SonarQube is looking for the .trx file (which contains code coverage) in a different directory to the one that VSTS publishes the .trx file to.</p> <p>So when VSTS builds the solution it creates the test results file here: C:\agent_work\3\s\TestResults</p> <p>But SonarQube is trying to use test results from here: C:\agent_work\3\TestResults</p> <p>On the build server, if I manually copy the .trx file into the correct location and then run the build again, the code coverage all works fine and processes through to SonarQube. So the issue is definitely the mismatch of the locations where the .trx is published and where it is to be picked up form. </p> <p>I can't find a way of changing the publish location, or the SonarQube source location. </p> <p>Please help!</p>
<p>This is a known issue, and will be fixed by the next release. See: <a href="https://jira.sonarsource.com/browse/SONARMSBRU-262" rel="nofollow">https://jira.sonarsource.com/browse/SONARMSBRU-262</a>.</p> <p>We just announced the RC versions of the products that have this fix, you can give them a try. See <a href="https://groups.google.com/forum/?utm_medium=email&amp;utm_source=footer#!msg/sonarqube/5eVMAp8JqUg/lpNz9yAdAQAJ" rel="nofollow">this thread</a>.</p>
How can I schedule tasks to CPUs? <p>I have some tasks defined as Docker containers, each one will consume one full CPU whilst it runs.</p> <p>Id like to run them as cost efficiently as possible so that VMs are only active when the tasks are running.</p> <p>Whats the best way to do this on Google Cloud Platform?</p> <p>It seems Kuberenetes and other cluster managers assume you will be running some service, and have spare capacity in your cluster to schedule the containers.</p> <p>Is there any program or system that I can use to define my tasks, and then start/stop VMs on a schedule to run those tasks?</p> <p>I think the best way is to just use the GCP/Docker APIs and script it myself?</p>
<p>You're right, all the major cloud container services provide you a cluster for running containers - <a href="https://cloud.google.com/container-engine/" rel="nofollow">GCP Container Engine</a>, <a href="https://aws.amazon.com/documentation/ecs/" rel="nofollow">EC2 Container Service</a>, and <a href="https://azure.microsoft.com/en-us/services/container-service/" rel="nofollow">Azure Container Service</a>. </p> <p>In all those cases, the compute is charged by the VMs in the cluster, so you'll pay while the VMs are running. If you have an occasional workload you'll need to script creating or starting the VMs before running your containers, and stopping or deleting them when you're done.</p> <p>An exception is <a href="https://www.joyent.com/triton" rel="nofollow">Joyent's cloud</a>, which let's you run Docker containers and <a href="https://www.joyent.com/pricing" rel="nofollow">charges per container</a> - that could fit your scenario.</p> <p><em>Disclaimer - I don't work for Google, Amazon, Microsoft or Joyent. Or Samsung.</em></p>
Why in C# is implicit casting from T to T[] not included? <p>I'm curious as to why we cannot consume the following method:</p> <pre><code>void Foo(Bar[] items); </code></pre> <p>With:</p> <pre><code>Foo(new Bar()); </code></pre> <p>It would compile and work if the method signature included params</p> <pre><code>void Foo(params Bar[] items); </code></pre> <p>I'm sure there are obvious (to some) reasons, I cannot think of any. </p> <p>EDIT: I understand how the params keyword works - maybe not completely at a low level. I am asking why do we need the keyword params, what are the reasons preventing this implicit cast by default? Granted, this can just be considered a feature request for more syntactic sugar. It may also be expensive for the compiler to include this by default and the cost-benefit isn't there. If so, that's my answer. Maybe my idol Mr. Lippert has a logical reason or can simply say; not possible. Until then, my curiosity get's the better of me.</p>
<p>Since the <code>params</code> keyword creates an array of <code>Bar</code> which is filled by the compiler with your single instance of <code>Bar</code>. If you define an <code>array of Bar</code> by your self then the compiler thinks "Ok, this is not my concern. The programmer will take care to provide the needed type when calling the function"</p>
Javascript change function triggers tagname <p>I have working HTML and Javascript code but only for one <code>select</code> tag. And the issue is that I need it to cover all <code>select</code> tags I have in HTML. So colors in all options should be changed according to its <code>value</code> while selecting them.</p> <pre class="lang-html prettyprint-override"><code>Some text &lt;select&gt; &lt;option value='red'&gt;wrong option&lt;/option&gt; &lt;option value='green'&gt;right option&lt;/option&gt; &lt;option value='red'&gt;wrong option&lt;/option&gt; &lt;/select&gt; some text.&lt;br&gt; Some text &lt;select&gt; &lt;option value='green'&gt;right option&lt;/option&gt; &lt;option value='red'&gt;wrong option&lt;/option&gt; &lt;option value='red'&gt;wrong option&lt;/option&gt; &lt;/select&gt; some text.&lt;br&gt; Some text &lt;select&gt; &lt;option value='red'&gt;wrong option&lt;/option&gt; &lt;option value='red'&gt;wrong option&lt;/option&gt; &lt;option value='green'&gt;right option&lt;/option&gt; &lt;/select&gt; some text. </code></pre> <p>That is only for first element in the <code>select</code> array.</p> <pre><code>var select = document.getElementsByTagName('select'); select[0].onchange = function() { for(var i = 0; i &lt; select[0].options.length; i++) { if(i == select[0].selectedIndex) { select[0].style.color = this.value; } else { select[0].options[i].style.color = 'black'; } } } </code></pre>
<p>You're specifically targeting the first <code>select</code> element with <code>select[0]</code>. If you want to apply this to <em>all</em> of them, you'll need a loop:</p> <pre><code>for (var i = 0; i &lt; select.length; i++) { select[i].onchange = function() { ... } } </code></pre>
XML column compare in SQl server 2005 <p>I want to compare two XML columns with multiple rows in SQL Server 2005.</p> <p>Table structure is as below</p> <pre><code>CREATE TABLE [dbo].[UpdationLog]( [LogID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL, [CustID] [int] NOT NULL, [OldValue] [xml] NOT NULL, [NewValue] [xml] NOT NULL, CONSTRAINT [PK_UpdationLog] PRIMARY KEY CLUSTERED ( [LogID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO INSERT INTO [dbo].[UpdationLog] VALUES (1526,'&lt;ccm CustID="1526" CustName="Teja" Address="Bangalore"/&gt;','&lt;ccm CustID="1526" CustName="Tejas" Address="Bengaluru"/&gt;'), (1245,'&lt;ccm CustID="1245" CustName="Abhi" Address="Andhra"/&gt;','&lt;ccm CustID="1245" CustName="Abhilash" Address="Andra Pradesh"/&gt;'), (1145,'&lt;ccm CustID="1145" CustName="Abhi" Address="Assam"/&gt;','&lt;ccm CustID="1145" CustName="Abhinandan" Address="Assam"/&gt;') </code></pre> <p>I want to compare XML column <code>OldValue</code> and <code>NewValue</code> and display updated records.</p> <p>Desired Output</p> <pre><code>|-------|-------------|---------------|------------ |CustID | Attribute | OldValue | NewValue |-------|-------------|---------------|--------- |1526 | CustName | Teja | Tejas |1526 | Address | Bangalore | Bengaluru |1245 | CustName | Abhi | Abhilash |1245 | Address | Andhra | Andra Pradesh |1145 | CustName | Abhi | Abhinandan </code></pre> <p><a href="http://sqlfiddle.com/#!3/cb0b3/1" rel="nofollow">http://sqlfiddle.com/#!3/cb0b3/1</a></p>
<p>Here is one way. Not sure this is the ideal method but should get what you are looking for </p> <pre><code>SELECT CustID, Attribute, Max(CASE WHEN iden = 'old' THEN val END) AS OldValue, Max(CASE WHEN iden = 'new' THEN val END) AS NewValue FROM (SELECT o.value('@CustID', 'int') AS CustID, o.value('@CustName', 'varchar(50)') AS CustName, o.value('@Address', 'varchar(500)') AS Address, 'old' AS iden FROM UpdationLog CROSS apply [OldValue].nodes('ccm') a(o) UNION ALL SELECT n.value('@CustID', 'int') AS CustID, n.value('@CustName', 'varchar(50)') AS CustName, n.value('@Address', 'varchar(500)') AS Address, 'new' AS iden FROM UpdationLog CROSS apply [NewValue].nodes('ccm') b(n)) a CROSS apply (SELECT CustName, 'CustName' UNION ALL SELECT Address, 'Address') tc (val, Attribute) GROUP BY CustID, Attribute </code></pre>
Removing unwanted users from assignee list <p>I have a fairly vanilla JIRA cloud instance with 5 developers, however when assigning an issue, using the box to search for a user, I see what appears to be spam users in my list.</p> <p>How do I remove these users? They do not show in the /admin/users section, as active or inactive users. </p> <p><a href="https://i.stack.imgur.com/jBx22.png" rel="nofollow"><img src="https://i.stack.imgur.com/jBx22.png" alt="Screenshot of assignees"></a></p>
<p>The first point to check is within the <a href="https://confluence.atlassian.com/adminjiraserver071/managing-project-permissions-802592442.html" rel="nofollow">project permissions</a> (Toolgear->Projects->select project->Permissions). Since your users appears in the Assignee dropdown on the issue page, the user must be a member of the "Assignable User" permission.</p> <p>As you will be see from the project permission page (which is really just displaying permissions from the underlying permission scheme), the Assignable User permission is potentially composed of specific groups of users, project roles, or a few other options. You'll need to follow the trail of options selected there to figure out where the users are coming from.</p> <p>For example, if the permissions include project roles, you can see those from another tab in the project section (the tab will be either "Roles" or "Users and roles", depending on your JIRA version).</p> <p>If that permission instead includes some specific hardcoded groups from the user directory, you would need to edit the permission scheme directly to remove or change it. (Be aware that the permission scheme could be used by multiple projects, so you'd also need to make sure that your changes did not impact those projects, or else duplicate the permission scheme so that you have a unique copy for your own project.)</p> <p>A useful blog post providing a high-level overview of JIRA permissions is <a href="http://blog.tempo.io/2015/jira-best-practices-jira-permissions/" rel="nofollow">here</a>.</p> <p>As for why you cannot find the phantom users in the User Manager: this is puzzling, but if you confirm that the Assignable Users permission was incorrectly scoped and you fix it, maybe this question will become moot.</p> <p>I have never personally seen a case where users in the Assignee dialog could not be found in the user directory, but perhaps there is some sort of caching issue. In this scenario, I recommend <a href="https://confluence.atlassian.com/adminjiraserver071/synchronizing-data-from-external-directories-802592362.html" rel="nofollow">re-syncing your presumed LDAP directory connection</a> to make sure it is up-to-date, and then checking to see if the problem recurs once the sync is complete.</p>
Conditional code for each build phase <p>I'm building a project from commandline with:</p> <pre><code>xcodebuild -project ABC.xcodeproj -xcconfig ABC.xcconfig -target "All" -configuration Release </code></pre> <p><strong>How to have a few lines of codes that differ from one build phase to another?</strong></p> <p>e.g. is it possible to have something like this in <code>ABC.cpp</code>:</p> <pre><code>#if TARGET == VST2 MyFunction(); // this will be compiled if and only if we are in VST2 build phase #endif </code></pre> <p>If so, how and where to define <code>TARGET</code> and <code>VST2</code>? In the code itself (in which file?) or in the XCode GUI? (in which menu?)</p> <hr> <p>This is how the project looks like, and you can see the "build phases" of target "All":</p> <p><a href="https://i.stack.imgur.com/d7tAC.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/d7tAC.jpg" alt="enter image description here"></a></p>
<p>The solution is to select the relevant target in XCode, go in <em>Build Settings</em>, and then search for <em>Preprocessor macros</em>, and then add a name, like <code>VST2</code> for each Debug, Release, Tracer.</p> <p>Then in the code, it's possible to do:</p> <pre><code>#ifdef VST2 ... #endif </code></pre>
Android SQLite long value being retrieved/cast as an int value <p>I have an <code>INTEGER</code> column in my database table and have saved the value of <code>1476355625598</code> to it (by updating an existing row).</p> <p>When I immediately check the value by doing a query, I get the same, correct, value of <code>1476355625598</code> returned.</p> <p>However, when my IntentService later retrieves the value, it is getting the value of <code>-1113124226</code> returned.</p> <p>I've done a check and <code>-1113124226</code> is the same value as if you'd called <code>(int)1476355625598</code>.</p> <p>I've added debugging output to all my lines of code that modify this column, and can confirm that I have no other database operations that are updating the value.</p> <p>So it seems something is casting my long to an int... Any ideas how/why this could be happening?</p> <p>NB - The value I'm saving is a timestamp (millis format), which is preferable to saving it in a String format.</p> <p><strong>UPDATE</strong></p> <p>Because my database is accessible via a content provider, I've added a content observer to my MyApplication class. It does not report any other updates of the table in question.</p> <p><strong>UPDATE #2</strong></p> <p>Issue now solved. See comment...</p>
<p>The OP find his error before I have the time to write this but I will still post it to close it. OP can add his own if he want (no hard feeling ;) ) (This will prevent others to spam later to get some rep point...)</p> <p>As excepted, the problem was coming from the retrieving of the value from the cursor. Even if the value is store into an INTEGER, this column can hold a <code>long</code> so on the cursor, we need to get the value using the <code>getLong(int)</code> or <code>getLong(String)</code> methods. If not, JAVA will truncate the value as excepted.</p> <p>In the question, the getter is not present but the OP post and answer on an other POST : <a href="http://stackoverflow.com/a/40008872/1617737">http://stackoverflow.com/a/40008872/1617737</a></p> <p>This show how he duplicate a cursor. This was were he used <code>getInt</code> instead of <code>getLong</code> for NUMERIC SqliteType.</p>
Android: How to modify a WebView created in main activity from another activity <p>I have created a Webview in my Main Activity and I load the relevant html file. When I hit the settings icon, I launch another activity(SettingsActivity), I want to be able to alter the WebView from the SettingsActivity.</p> <p>Eg. in my SettingsActivity I would like to change the font size or do whatever to it:</p> <pre><code>MainActivity mActivity= new MainActivity(); mActivity.myWebView.getSettings().setDefaultFontSize(8); </code></pre> <p>In this case I got a null pointer exception. So how do I access/pass the webView data created in my activity to another.</p> <p>Thanks, Matt</p>
<p>In your case you should run <code>startActivityForResult()</code> when starting <code>SettingsActivity</code> and send bundled changes data via return <code>Intent</code> with result. Read official <a href="https://developer.android.com/training/basics/intents/result.html" rel="nofollow">docs</a> that cover two-way communication between activities.</p>