input
stringlengths
51
42.3k
output
stringlengths
18
55k
double quotas appearing after json output in PHP array to JSON <p>I have read a question answer at </p> <p><a href="http://stackoverflow.com/questions/11012695/php-array-to-json-how-to-get-rid-of-some-double-quotes">PHP Array to json, how to get rid of some double quotes?</a></p> <p>I have same issue but my code is little different so I unable to ride of rid of some double quotes.</p> <p>My code : </p> <pre><code>$features = array(); $geojson = array( 'type' =&gt; 'FeatureCollection', 'features' =&gt; $features ); while($row = mysqli_fetch_assoc($result)) { $type = $row['type']; if($type == 'Point') { //$output = ; $feature = array( 'type' =&gt; 'Feature', 'properties' =&gt; array( 'score' =&gt; "", 'fid' =&gt; "" //Other fields here, end without a comma ), 'geometry' =&gt; array( 'type' =&gt; $type, 'coordinates' =&gt; array($row['lat'], $row['lng']) ) ); } else { //$output = '['.$row['more_info'].']'; $feature = array( 'type' =&gt; 'Feature', 'properties' =&gt; array( 'score' =&gt; "", 'fid' =&gt; "" //Other fields here, end without a comma ), 'geometry' =&gt; array( 'type' =&gt; $type, 'coordinates' =&gt; array('['.$row['more_info'].']') ) ); } array_push($geojson['features'], $feature); }; mysqli_close($conn); echo $newgeojson = json_encode($geojson, JSON_NUMERIC_CHECK); </code></pre> <p>array Output before convert to json (json_encode):</p> <pre><code>Array ( [type] =&gt; FeatureCollection [features] =&gt; Array ( [0] =&gt; Array ( [type] =&gt; Feature [properties] =&gt; Array ( [score] =&gt; [fid] =&gt; ) [geometry] =&gt; Array ( [type] =&gt; Point [coordinates] =&gt; Array ( [0] =&gt; 88.388786315918 [1] =&gt; 22.551879205144 ) ) ) [1] =&gt; Array ( [type] =&gt; Feature [properties] =&gt; Array ( [score] =&gt; [fid] =&gt; ) [geometry] =&gt; Array ( [type] =&gt; Polygon [coordinates] =&gt; Array ( [0] =&gt; [[88.41796875, 22.568048815726],[88.41796875, 22.572804222704],[88.41796875, 22.577876475976],[88.428955078125, 22.578114233267],[88.428955078125, 22.573121244003],[88.428611755371, 22.568048815726],[88.41796875, 22.568048815726]] ) ) ) ) ) </code></pre> <p>Output I am getting after json_encode</p> <pre><code>{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"score":"","fid":""},"geometry":{"type":"Point","coordinates":[88.388786315918,22.551879205144]}},{"type":"Feature","properties":{"score":"","fid":""},"geometry":{"type":"Polygon","coordinates":["[[88.41796875, 22.568048815726],[88.41796875, 22.572804222704],[88.41796875, 22.577876475976],[88.428955078125, 22.578114233267],[88.428955078125, 22.573121244003],[88.428611755371, 22.568048815726],[88.41796875, 22.568048815726]]"]}}]} </code></pre> <p>As you can see the coordinates coming with " ".</p> <pre><code>"[[88.41796875, 22.568048815726],[88.41796875, 22.572804222704],[88.41796875, 22.577876475976],[88.428955078125, 22.578114233267],[88.428955078125, 22.573121244003],[88.428611755371, 22.568048815726],[88.41796875, 22.568048815726]]" </code></pre> <p>I do not want that double quote start and end of multi coordinates.</p> <p>Please guide / suggest me how can I ride of those double quote.</p>
<p>@Simba - Thank you for guide me. Your guides help me to get exact result</p> <pre><code>$output = json_decode('['.$row['more_info'].']'); $feature = array( 'type' =&gt; 'Feature', 'properties' =&gt; array( 'score' =&gt; "", 'fid' =&gt; "" //Other fields here, end without a comma ), 'geometry' =&gt; array( 'type' =&gt; $type, 'coordinates' =&gt; array($output) ) ); </code></pre>
Using ServiceStack OrmLite to delete rows with condition in other table <p>I have the following tables in the database:</p> <pre><code>Table C Table B Table A ------- ------- ------- Id Id Id BId AId </code></pre> <p>The BId column is a foreign key to TableB. AId is a foreign key to TableA. I want to delete all rows from Table C that is connected to a row in TableA. The following SQL (used in SQL Management Studio) does the trick:</p> <pre><code>DELETE [ns].[TableC] FROM [ns].[TableC] c JOIN [ns].[TableB] b ON c.[BId] = b.[Id] WHERE b.[AId] = 530 GO </code></pre> <p>I tried using the following code:</p> <pre><code>var query = connection.From&lt;TableC&gt;() .Join&lt;TableC, TableB&gt;((c, b) =&gt; c.BId == b.Id) .Where&lt;TableB&gt;(b =&gt; b.AId == 530); connection.Delete&lt;TableC&gt;(query); </code></pre> <p>But this results in an exception and from calling GetLastSql() I get:</p> <pre><code>DELETE FROM "ns"."TableC" WHERE ("ns"."TableB"."AId" = @0) </code></pre> <p>How can I use ServiceStack OrmLite to accomplish this delete?</p>
<p>Support for DELETE TABLE JOINS were just recently added to OrmLite and is available from v4.5.1 that's now <a href="https://github.com/ServiceStack/ServiceStack/wiki/MyGet" rel="nofollow">available on MyGet</a>.</p>
How to style dialog button in NativeScript? <p>My alerts and dialog buttons are white in color after i have upgraded my NativeScript version to the latest one. Please help me retrieve its original black color...</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var dialogs = require("ui/dialogs"); dialogs.alert({ title: "Be Aware", message: "Make sure you receive money from the customer before you REDEEM.", okButtonText: "Customer Paid" }).then(function () { console.log("Dialog closed!"); });</code></pre> </div> </div> </p> <p><a href="https://i.stack.imgur.com/QHgP3.png" rel="nofollow">Customer Paid button is white</a></p>
<p>The solution was found in the comments.</p> <p>The problem was linked to a <code>CSS</code> property generated for an other button.</p> <p>This property was also affecting the button in the modal.</p> <p><strong>Solution</strong></p> <p>Use another class/id/selector for the modal's button</p> <p><em>OR</em></p> <p>Use the same selector than the other button and change the values inside the <code>CSS</code></p>
get dictionary contains in list if key and value exists <p>How to get complete dictionary data inside lists. but first I need to check them if key and value is exists and paired.</p> <pre><code>test = [{'a': 'hello' , 'b': 'world', 'c': 1}, {'a': 'crawler', 'b': 'space', 'c': 5}, {'a': 'jhon' , 'b': 'doe' , 'c': 8}] </code></pre> <p>when I try to make it conditional like this</p> <pre><code>if any((d['c'] is 8) for d in test): </code></pre> <p>the value is True or False, But I want the result be an dictionary like</p> <pre><code>{'a': 'jhon', 'b': 'doe', 'c': 8} </code></pre> <p>same as if I do</p> <pre><code>if any((d['a'] is 'crawler') for d in test): </code></pre> <p>the results is:</p> <pre><code>{'a': 'crawler', 'b': 'space', 'c': 5} </code></pre> <p>Thanks before.</p>
<p>Use comprehension:</p> <pre><code>data = [{'a': 'hello' , 'b': 'world', 'c': 1}, {'a': 'crawler', 'b': 'space', 'c': 5}, {'a': 'jhon' , 'b': 'doe' , 'c': 8}] print([d for d in data if d["c"] == 8]) # [{'c': 8, 'a': 'jhon', 'b': 'doe'}] </code></pre>
Excel - sum numbers in each cell, that matches the pattern <p>I have a table for capacity management, that contains information about teams working on project in time. I would like to be able to create a new table, that would basically tell me, which team is overloaded. I guess example would explain it better:</p> <p>Here is simplified table 1</p> <p><a href="https://i.stack.imgur.com/ctrPW.png" rel="nofollow"><img src="https://i.stack.imgur.com/ctrPW.png" alt="enter image description here"></a></p> <p>The number indicates how many resources is needed from the team on given day</p> <p>Here is the second table, that I need</p> <p><a href="https://i.stack.imgur.com/ROhtA.png" rel="nofollow"><img src="https://i.stack.imgur.com/ROhtA.png" alt="enter image description here"></a></p> <p>The numbers in columns is sum of all numbers for the team for the specific day across all projects.</p> <p>Is this somehow possible? Thanks for any advice!</p>
<p>Create a summary table with the dates in the column headers and the team names in the row headers. Then you can use a SumProduct() formula to calculate the totals per team and date. Refer to the screenshot below.</p> <p>The formula in cell B13 is</p> <pre><code>=SUMPRODUCT(($B$1:$H$1=B$12)*($A$2:$A$8=$A13)*$B$2:$H$8) </code></pre> <p>Copy across and down. The summary table can be on a different sheet. Just make sure that you get the references right and pay attention to the placements of the $ signs.</p> <p><a href="https://i.stack.imgur.com/5wsuN.png" rel="nofollow"><img src="https://i.stack.imgur.com/5wsuN.png" alt="enter image description here"></a></p>
Swift UITableViewCell subview do not register tap <p><strong>Background:</strong> I'm making a calendar and for that I'm combining a UITableView and a UICollectionViews. The UITableView is holding month cells. Each month UITableViewCell is holding a UICollectionView with UICollectionViewCell days.</p> <p><strong>Problem:</strong> The UICollectionViewCells aren't clickable. I can fix this by calling self.bringSubviewToFront(self.collectionView) in the month UITableViewCell. However this makes the UITableView not scroll because the collectionView is now top view.</p> <p>So, I can either choose between be able to scroll the UITableView or be able to click the UICollectionView.</p> <p><strong>What I tried:</strong> I tried to capture the click before it happens and bring the collectionView to front and then put it back again. Not a good solution though:</p> <pre><code>//In UITableViewCell class //UIGestureRecognizerDelegate //Bring collectionView to front before tap override func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -&gt; Bool { self.bringSubviewToFront(self.collectionView) return true } //UIScrollViewDelegate //Bring collectionView to back again func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { self.sendSubviewToBack(self.collectionView) //Do stuff } </code></pre> <p><strong>Question:</strong> How can I achieve to both be able to scroll and have the UICollectionView clickable without bringing back and forward the view between taps? Is there a way to have the UICollectionView in front and still make the UITableView scrollable?</p> <p><a href="https://i.stack.imgur.com/ZoLZA.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZoLZA.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/EaG1C.png" rel="nofollow"><img src="https://i.stack.imgur.com/EaG1C.png" alt="enter image description here"></a></p>
<p>Nested UIScrollView with same scroll directions is against Apple's Human Interface Guidelines and your app might even get rejected for this so try disabling the scroll of your UICollectionView.</p> <p>Hope this helps.</p>
How to call another key from ng-repeat source <p>Pardon me if the question sounds weird. Suppose I have the following object:</p> <pre><code>// For example purposes, pretend that link gets pushed to $scope.links 5 times. var link = { name: "name", description: "description", members: [{ memname: "member name" }], active: true } $scope.links.push(link); </code></pre> <p>...and I used $scope.links as follows</p> <pre><code>&lt;li ng-repeat="item in links"&gt; &lt;li ng-repeat = "member in item.members"&gt; ... &lt;/li&gt; &lt;/li&gt; </code></pre> <p>...and inside the list with <code>member in item.members</code>, I want to use <code>link.active</code> for <code>ng-show</code>. Is it possible to do so?</p> <p>Something like:</p> <p><code>&lt;li ng-repeat="member in item.members" ng-show="item.active"&gt;</code>.</p> <p>Please advise.</p> <p>Thank you.</p>
<p>Created Snippet for you .</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 myCtrl($scope) { $scope.links = [{ 'name': "name", 'description': "description", 'members': [{ 'memname': "member name" },{ 'memname': "member name 2" }], 'active': true },{ 'name': "name 2", 'description': "description", 'members': [{ 'memname': "member name" },{ 'memname': "member name 2" }], 'active': false }] //$scope.links.push(link); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app ng-controller="myCtrl"&gt; &lt;ul&gt; &lt;li ng-repeat="item in links" ng-show="item.active == true"&gt; {{item.name}} &lt;ul &gt; &lt;li ng-repeat = "member in item.members" &gt; {{member.memname}} &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Hope this will help you.</p>
Use debounce in setTimeout <p>I'm trying to implement <code>debounce</code> from underscore library within <code>setTimeout</code>. </p> <pre><code>setInterval(function() { setTimeout(function(){ _.debounce(function() { console.log('debounce'); }, 500); }, 1000); }, 100); </code></pre> <p>Basically, <code>console.log('debounce')</code> should be called once in 500ms but it seems there's no output at all in the console.</p> <p>JS Bin for testing: <a href="http://jsbin.com/beqisuruwu/edit?js,output" rel="nofollow">http://jsbin.com/beqisuruwu/edit?js,output</a></p> <p>Thanks in advance.</p>
<p>Are you sure you need function after setTimeout? Because _.debounce is a function itself. I am not sure either )) but code below works for me:setInterval(function() { setTimeout( _.debounce(function() { console.log('debounce'); }, 500) , 1000); }, 100);</p>
i need to schedule 2 tasks at diffrent times <p>i try to schedule 2 tasks, the first need to done everyday - to check birthdays, the second task need to be only if today is the first day of the month..</p> <p>i tried to make 1 schedule that will done everyday at 8:00 am , and when its done to check if its the first day of month.</p> <p>if its true make the method of the second task.</p> <p>my problem is that the method starts every time that onCreate() done &amp; its the first day t the month, so if i open the app 10 times at the 1/10/16 , the method will happen 10 times, instead of 1 time.</p> <p><strong>my code:</strong></p> <p>onCreate()</p> <pre><code>startTimers(); </code></pre> <p>startTimers method:</p> <pre><code> private void startTimers() { d = new Date(); d.setTime(System.currentTimeMillis()); d.setHours(8); d.setMinutes(0); d.setSeconds(0); timer = new Timer(); timerTask = new TimerTask() { @Override public void run() { if(d.getDate() == 1){ // TODO: 19/10/2016 find good if that will make it work only 1 time per month.. saveSalariesBeforeStartNewMonth(); resetSumOfMinutes(); Log.d("TAG","Started new Month good luck!@#!@"); } checkBirthdays(); } }; timer.schedule(timerTask,d.getTime(),1000*60*60*24);//every day at 8:00 at morining.. } </code></pre> <p>Thank for helpers.</p>
<p>Try to store a simple boolean to the <code>SharedPreferences</code> after successfully scheduling so that before you call <code>startTimers()</code> just check with the stored value. Sth like:</p> <pre><code>public void onCreate(){ if (!isScheduledAlready()) { startTimers(); } } public boolean isScheduledAlready(){ SharedPreferences prefs = getPrefs().getPreferences(); return prefs.getBoolean("schedule_keys", false); } public void setSchedule(boolean scheduled) { SharedPreferences prefs = getPrefs().getPreferences(); prefs.edit().putBoolean("schedule_keys", scheduled).apply(); } </code></pre> <p>Also I'm not sure if in your situation you might want to tweak the value when the month change? If then you can just need add more a bit more conditions I guess.</p>
Angular 2 - Waiting for boolean to be true before executing service <p>I have an navigation menu that uses ng2-page-scroll module. </p> <p>I scroll trough page using hashtag links.</p> <p>The problem is that if i work cross routes, the data takes some time to load, so the service normally scrolls to my section, than the whole data loads, and the section of interest will not be on screen fold anymore, so the user needs to manully scroll to get to the section of interst. This makes the whole menu useless.</p> <p>So I'm using EventEmitter in all sections, to set bools in the "scrollable" page, all good... </p> <p>But i don't know how to wait for the <code>allDataLoaded</code> boolean to turn true. </p> <p>I tried to use promises</p> <p>This is how my code looks so far. </p> <p><strong>HTML of navigation menu component</strong></p> <pre><code>&lt;a [routerLink]="['']" [queryParams]="{ scrollTo: '#home' }"&gt; &lt;a [routerLink]="['']" [queryParams]="{ scrollTo: '#contact' }"&gt; &lt;a [routerLink]="['']" [queryParams]="{ scrollTo: '#about' }"&gt; </code></pre> <p><strong>HTML of component using root segment</strong></p> <pre><code>&lt;componentOne (dataLoadedEvent)="homeLoaded = true; checkIfDataLoaded()"&gt;&lt;/componentOne&gt; </code></pre> <p><strong>TS of component using root segment</strong></p> <pre><code>homeLoaded: boolean = false; contactLoaded: boolean = false; aboutLoaded: boolean = false; allDataLoaded: boolean = false; ngOnInit() { // other code here this.route.queryParams.forEach((params: Params) =&gt; { if (params['scrollTo']) { this.checkIfDataLoaded().then(() =&gt; { this.scrollToSection(params['scrollTo']); }); } }); } checkIfDataLoaded() { if (this.homeLoaded &amp;&amp; this.contactLoaded &amp;&amp; this.aboutLoaded) { //this.allDataLoaded = true; return new Promise((resolve, reject) =&gt; { resolve(true); }); } } </code></pre> <p>As Günter Zöchbauer answered here ( <a href="http://stackoverflow.com/a/40126194/3264998">http://stackoverflow.com/a/40126194/3264998</a> ) for another questoin, the code will break with <code>TypeError: Cannot read property 'then' of undefined</code></p> <p><strong>TL;DR</strong> What is the proper way to use promises when waiting for a bool to turn true/false?</p>
<p>The problem is in your code, in particular in <code>checkIfDataLoaded()</code> method and not because you're working with booleans.</p> <p>It obviously throws an error when the inner condition resolves to false because then the method returns <code>undefined</code> and therefore calling <code>undefined.then(...</code> raises an error.</p> <p>Of course, I don't know what exactly <code>checkIfDataLoaded()</code> should do but if you want to chain <code>.then()</code> to its result then it <strong>always</strong> has to return a <code>Promise</code>.</p> <p>Maybe something along these lines:</p> <pre><code>checkIfDataLoaded() { return new Promise((resolve, reject) =&gt; { if (this.homeLoaded &amp;&amp; this.contactLoaded &amp;&amp; this.aboutLoaded) { // Whatever logic goes here resolve(true); } else { resolve(false); } }); } </code></pre> <p>This way <code>checkIfDataLoaded()</code> always returns <code>Promise</code> while its internals can do whatever you need.</p>
How to successfully complete this INSERT JOIN WHERE SQL statement? <p>I am looking to insert into table community_players the community_id and player_id from respective tables; 'communities' and 'users' where the following conditions are met:</p> <p>users.user_email AND communities.admin = 'steve.downs@gmail.com' AND communities.code = 'HX99F9'</p> <p>This is what I have so far....</p> <p><code>INSERT INTO TABLE community_players (community_id, player_id) FROM TABLE communities JOIN TABLE users ON id WHERE users.user_email = 'steve.downs@gmail.com' AND communities.admin = 'steve.downs@gmail.com' AND communities.code = 'HX99f9'</code></p> <p>These are the 3 tables in question:</p> <p><code>users id | user_email | user_password | user_name</code></p> <p><code>communities id | name | code | admin</code></p> <p><code>community_players community_id | player_id</code></p>
<p>Should be something like:</p> <p><code>INSERT INTO community_players (community_id, player_id) (SELECT communities.community_id, users.user_id FROM TABLE communities JOIN TABLE users ON id WHERE users.user_email = 'steve.downs@gmail.com' AND communities.admin = 'steve.downs@gmail.com' AND communities.code = 'HX99f9'</code> )`</p> <p>But its hard to say, without knowing the database schemas of the tables communities and users. Which sounds particular weird is the <code>JOIN TABLE users ON id</code> part ... this will only work, if the communities table has a field which holds the user id (which might be uncommon in that use case).</p>
How to set Actions in aws java sdk for iot rule? <p>I am trying to create a rule using the aws sdk for java (not the standalone aws iot java sdk).</p> <p>So far I have done these</p> <pre><code>public class Application extends Controller { static AWSIotClient awsIotClient; private static void init() { AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider().getCredentials(); } catch (Exception e) { throw new AmazonClientException( "Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (~/.aws/credentials), and is in valid format.", e); } awsIotClient = new AWSIotClient(credentials); Region usEast1 = Region.getRegion(Regions.US_EAST_1); awsIotClient.setRegion(usEast1); Logger.info("Creds init"); } public static Result index() { init(); CreateTopicRuleRequest another_test = new CreateTopicRuleRequest(); another_test.setRuleName("test"); TopicRulePayload topicRulePayload = new TopicRulePayload(); topicRulePayload.setDescription("A test rule"); topicRulePayload.setSql("SELECT state.reported.turbineStatus FROM '$aws/things/turbine1/shadow/update/accepted' WHERE state.reported.turbineStatus=true"); topicRulePayload.setActions(); // stuck here another_test.setTopicRulePayload(topicRulePayload); CreateTopicRuleResult test = awsIotClient.createTopicRule(another_test); return ok(index.render("iot")); } } </code></pre> <p>In the code above, I am stuck at the part <code>topicRulePayload.setActions();</code></p> <p>How can I set actions to it? I looked over its source code and found out that it is using collections.</p>
<p>I finally got it working for me</p> <pre><code>public static Result index() { init(); CreateTopicRuleRequest another_test = new CreateTopicRuleRequest(); another_test.setRuleName("test"); TopicRulePayload topicRulePayload = new TopicRulePayload(); topicRulePayload.setDescription("A test rule"); topicRulePayload.setSql("SELECT state.reported.turbineStatus FROM '$aws/things/turbine1/shadow/update/accepted' WHERE state.reported.turbineStatus=true"); ArrayList&lt;Action&gt; actionList = new ArrayList(); Action action = new Action(); S3Action s3 = new S3Action(); s3.setRoleArn("arn:aws:iam::442759113924:role/sushant"); s3.setBucketName("bajra-iot-test"); s3.setKey("bajra-iot-test"); action.setS3(s3); actionList.add(action); topicRulePayload.setActions(actionList); another_test.setTopicRulePayload(topicRulePayload); CreateTopicRuleResult test = awsIotClient.createTopicRule(another_test); return ok(index.render("iot")); } </code></pre>
Angularfire2 redirect after login <p>i'm using ionic 2 rc0 and angular 2 and i just added angularfire2 to use firebse auth. </p> <p>I have all configured and tested (I just see my user logged in the firebase console) but i want to redirect to other page after login.</p> <p>My code for login:</p> <pre><code>registerUserWithGoogle() { console.log('Google'); this.af.auth.login(); } </code></pre> <p>My firebase config is:</p> <pre><code>export const myFirebaseAuthConfig = { provider: AuthProviders.Google, method: AuthMethods.Redirect }; </code></pre> <p>So there is a way to redirect after the method login()?</p>
<p>AngularFire2 has <code>FirebaseAuth</code>, to which you can subscribe to auth state changes </p> <p>This is recommended way to handle user auth, because you will subscribe to changes in the auth state, other methods might not work as expected, like when user refreshes the page user object might not exist.</p> <pre><code>import { FirebaseAuth } from 'angularfire2'; @Component({ templateUrl: 'app.html' }) export class AppComponent { constructor(public auth: FirebaseAuth) { } ngOnInit() { this.auth.subscribe(user =&gt; { if (user) { // go to home page } else { // go to login page } }); } } </code></pre> <p><strong>Note:</strong> You don't need to subscribe on every page. Only subscribe in <code>AppComponent</code> or your app specific root component.</p>
Find report file outside of Application.StartupPath or bin folder <p>My Crystal Report is located outside of <code>Application.StartupPath</code> and the bin folder - in a tree folder:</p> <pre><code>MainFolder - CrystalReport_here_which_is_Sales_report.rpt bin 'folder - DebugFolder - inside debug folder is the application startup </code></pre> <p>I used this code but it cannot locate the file - How can I resolve this?</p> <pre><code>rpt.Load(Application.StartupPath &amp; "\Sales_Report.rpt") </code></pre>
<p>You can solve your problem with a relative path (code in vb.net) :</p> <pre><code>Dim CRPath as String = System.IO.Path.GetDirectoryName(Application.StartupPath) &amp; "\..\..\MainFolder\" rpt.Load(CRPath &amp; "Sales_Report.rpt") </code></pre>
S3 client.GetObject behaviour if read beyond fileSize <p>I need to read a file from S3 in blocks. I am using the following code : </p> <pre><code>GetObjectRequest request = new GetObjectRequest(bucketName, filePath); rangeObjectRequest.setRange(startOffset, startOffset + length - 1); S3Object objectPortion = s3Client.getObject(request); S3ObjectInputStream stream = objectPortion.getObjectContent(); byte[] outputBuffer = ByteStreams.toByteArray(stream); </code></pre> <p>I wish to know what will happen if the range which I give is not in the bounds of the file, for eg. , if the file size is 2MB and I set the range to be fetched as startOffset = 3MB, length = 1MB will I get an exception or will it simply return a stream with 0 bytes.</p> <p>I understand I could have checked this myself but I currently dont have access to S3.</p>
<p>The underlying API returns an error, so the library should throw an <a href="http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/AmazonServiceException.html" rel="nofollow">exception</a> with an <a href="http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/AmazonServiceException.html#getErrorCode--" rel="nofollow">ErrorCode</a> of <code>InvalidRange</code>. </p> <p>Here's the raw response from the API itself for request for bytes 80-90 of a 66 byte object. XML formatted for readability.</p> <pre><code>HTTP/1.1 416 Requested Range Not Satisfiable x-amz-request-id: xxx x-amz-id-2: xxx Content-Type: application/xml Transfer-Encoding: chunked Date: Wed, 19 Oct 2016 19:44:36 GMT Server: AmazonS3 &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Error&gt; &lt;Code&gt;InvalidRange&lt;/Code&gt; &lt;Message&gt;The requested range is not satisfiable&lt;/Message&gt; &lt;RangeRequested&gt;bytes=80-90&lt;/RangeRequested &lt;ActualObjectSize&gt;66&lt;/ActualObjectSize&gt; &lt;RequestId&gt;xxx&lt;/RequestId&gt; &lt;HostId&gt;xxx&lt;/HostId&gt; &lt;/Error&gt; </code></pre>
How can I highlight the text In the textbox? <p>The code for text area.</p> <pre><code>&lt;div&gt; &lt;textarea id="ta" onpaste="functionFind(event)"&gt;&lt;/textarea&gt; &lt;/div&gt; </code></pre> <p>The function that will be executed</p> <pre><code>function functionFind(pasteEvent) { var textareacont = (pasteEvent.originalEvent || pasteEvent).clipboardData.getData("text/html"); var tofindword = prompt("Enter the word to find"); if(textareacont.includes(tofindword )) { //What code do I write here so that all the word that matches "tofindword" gets highlighted in the same textbox only } } </code></pre> <p>The function will be executed once we paste something into the textbox and all the matching words should get highlighted in the same textbox only. </p>
<p>You can't actually render markup inside a textarea. However, you can fake it by </p> <ul> <li>carefully positioning a div behind the textarea</li> <li>Keep the div's inner HTML same as of textarea</li> <li>Add your highlight markup to the div</li> </ul> <p>For example: </p> <pre><code>&lt;div class="container"&gt; &lt;div class="backdrop"&gt; &lt;div class="highlights"&gt; &lt;mark&gt;This&lt;/mark&gt; demo shows how to highlight bits of text within a textarea. &lt;mark&gt;Alright&lt;/mark&gt;, that's a lie. &lt;mark&gt;You&lt;/mark&gt; can't actually render markup inside a textarea. &lt;mark&gt;However&lt;/mark&gt;, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there. &lt;mark&gt;JavaScript&lt;/mark&gt; takes care of syncing the content and scroll position from the textarea to the div, so everything lines up nicely. &lt;mark&gt;Hit&lt;/mark&gt; the toggle button to peek behind the curtain. &lt;mark&gt;And&lt;/mark&gt; feel free to edit this text. &lt;mark&gt;All&lt;/mark&gt; capitalized words will be highlighted. &lt;/div&gt; &lt;/div&gt; &lt;textarea&gt; This demo shows how to highlight bits of text within a textarea. Alright, that's a lie. You can't actually render markup inside a textarea. However, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there. JavaScript takes care of syncing the content and scroll position from the textarea to the div, so everything lines up nicely. Hit the toggle button to peek behind the curtain. And feel free to edit this text. All capitalized words will be highlighted.&lt;/textarea&gt; &lt;/div&gt; </code></pre> <p>And style the mark tag</p> <pre><code>mark { border-radius: 3px; color: transparent; background-color: #b1d5e5; } </code></pre> <p>For your requirement,</p> <ul> <li>Add css for mark tag</li> <li>Add a div behind your text area.</li> <li>while 'onpaste' in textarea, copy the content of text area into div's innerHTML</li> <li>Search for the text from the prompt in the div and add mark tag for it</li> </ul> <p>Refer the <a href="https://codepen.io/lonekorean/pen/gaLEMR" rel="nofollow">codepen</a> link for details</p>
fill input fields with json data then sent to the printer <p>i want to fill input fields with data from json and then sent it to the printer and then again to fill inputs from last row -1 in db then sent to the printer and then last row -2 then print it etc.. I have managed to return the json data from last n insered rows from database depending on the printmultiple value</p> <p>The html</p> <pre><code>&lt;div id="printableArea"&gt; &lt;div align="center"&gt; &lt;input type="text" name="barcode2" id="barcode2" required readonly &gt; &lt;input type="text" name="barcodecountry" id="barcodecountry" &gt; &lt;input type="text" name="barcodecountry" id="barcodecountry2" &gt; &lt;br&gt; &lt;div id="print"&gt; &lt;/div&gt; &lt;label id="idbar"&gt;id.:&lt;/label&gt;&lt;input type="text" name="barcodesurname" id="barcodesurname" required readonly&gt; &lt;br&gt; &lt;br&gt; &lt;label id="pricebar"&gt;price:&lt;/label&gt;&lt;input type="text" name="barcodename" id="barcodename" required readonly&gt; &lt;input type="text" name="barcodecountry" id="barcodecountry3"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>printablearea is the div that inputs are filled and i am sending for printing to printer</p> <p>In my Js file </p> <pre><code>$(document).ready(function() { $('form').submit(function(event) { $('.form-group').removeClass('has-error'); // remove the error class $('.help-block').remove(); // remove the error text var formData = { 'surname' : $('input[name=surname]').val(), 'name' : $('input[name=name]').val(), 'telephone' : $("#telephone").val(), 'mail' : $("#mail").val(), 'barcode' : $("#barcode").val(), 'customid' : $("#customid").val(), 'ticketprice' : $("#ticketprice").val(), 'seat' : $("#seat").val(), 'printmultiple' :$("#printmultiple").val() }; $.ajax({ type : 'POST', url : 'process2.php', data : formData, dataType : 'json', from the server encode : true }) .done(function(data) { console.log(data); if ( ! data.success) { if (data.errors.surname) { $('#surname-group').addClass('has-error'); $('#surname-group').append('&lt;div class="help-block"&gt;' + data.errors.surname + '&lt;/div&gt;'); } else if (data.errors.name) { $('#name-group').addClass('has-error'); $('#name-group').append('&lt;div class="help-block"&gt;' + data.errors.name + '&lt;/div&gt;'); } } else { $.each(data.added, function (i,it){ $('#printableArea').append(data.added[i]); }); for(i=0; i&lt;data.added[13]; i++){ $('#barcodecountry2').val(data.added[1]); $('#barcodesurname').val(data.added[0]); $('#barcodename').val(data.added[4]); $('#barcode2').val(data.added[2]); $("#print").barcode( document.getElementById("barcode2").value, "code128" ); $('#printableArea').print(); } $('form').append('&lt;div class="alert alert-success"&gt;' + data.message + '&lt;/div&gt;'); } }) .fail(function(data) { console.log(data); }); event.preventDefault(); }); }); </code></pre> <p>I want the returned data from json to fill the inputs for example the first 5 elements of json to be filled then print then next 5 then print . I have added code for printing depending on printmultiple value but only prints tha last row n times </p> <p>below i add returned json data : <code>Object { 0: "7784", 1: "2016-10-18 23:16:01.000000", 2: "16221458721646", 3: "2016-10-19", 4: "8", 5: "normal", 6: null, 7: "admin", 8: "DASDSADAS", 9: "7884", 18 more… }</code> </p>
<p>i have found the solution </p> <pre><code> for(i=0; i&lt;data.added[0].printmultiple; i++){ $('#barcodecountry2').val(data.added[i].signintime); $('#barcodesurname').val(data.added[i].customid); //get id $('#barcodename').val(data.added[i].ticketprice); $('#barcode2').val(data.added[i].barcode); $("#print").barcode( //div id print document.getElementById("barcode2").value,// Value barcode (dependent on the type of barcode) "code128" // type (string) ); </code></pre>
How to remove a swift 2 array element is not at index <p>How to remove a swift 2 array element is not at index</p> <p><a href="https://i.stack.imgur.com/zzCzW.png" rel="nofollow">picture</a></p> <p><a href="https://i.stack.imgur.com/p58Vf.png" rel="nofollow">picture</a></p>
<p>First of all please post the code rather than screenshots. Nobody who is willing to help is also willing to retype the code for testing.</p> <p>The index variable <code>i</code> in the loop is a <code>Storable</code> object, not an <code>Int</code> index, that's exactly what the error message says.</p> <p>Using <code>enumerate</code> you get the index and the object</p> <pre><code>for (i, storable) in fridge.enumerate { if storable.days ... { fridge.removeAtIndex(i) } } </code></pre> <p>But be aware that you certainly will run into the next problem if you are removing items from the object you are enumerating just now.</p>
Fatal error: Function name must be a string with Anonymous function <p>I am finding myself in a bit of a problem. I have two anonymous functions and one calls the other. But when the function <code>$fCompleteDate</code> is called within the function <code>$fFindAndCreateDate</code> </p> <p>I get the fatal error of: </p> <blockquote> <p>Function name must be a string.</p> </blockquote> <p>The function <code>$fFindAndCreateDate</code> is called later on in the script.</p> <p>I have literally no idea what the problem is.</p> <pre><code>$fCompleteDate = function($sDate) { $sDate = str_replace('/', '-', $sDate); return str_repeat('01-', max(0, 2 - substr_count($sDate, '-'))) . $sDate; }; $fFindAndCreateDate = function($aStruct) { $aDateStructNames = array('', 'Remark', 'Formatted', 'Extra'); foreach($aDateStructNames as $sDateStructName) { echo $fCompleteDate('2001'); echo 'a : '. $fCompleteDate($aStruct['startDate'.$sDateStructName]); echo 'b : '. $fCompleteDate($aStruct['endDate'.$sDateStructName]); } }; </code></pre>
<p>I see that you use Anonymous functions so I updated my answer.</p> <p>You need to specify that the second function use the first one like this:</p> <pre><code>$fFindAndCreateDate = function($aStruct) use ($fCompleteDate) { .... } </code></pre>
creating a login page but button click doesn't show any data or error messages <p><strong>when i click on the submit button it doesn't show any error and does not respond with any message.after a click it only reload itself and doesn't show any data. please reply me with the error.</strong></p> <pre><code>&lt;?php $server="localhost"; $username="root"; $password="admin007#"; $dbname="demo"; $con=new mysqli($server,$username,$password,$dbname); if(!$con) { die('error connecting to the database'); } if(isset($_POST['login'])){ $a=mysqli_real_escape_string($con, $_POST['user']); $b=mysqli_real_escape_string($con, $_POST['pass']); $sql="SELECT * FROM login WHERE username='$a' AND password='$b'"; $result=mysqli_query($con, $sql); $check=mysqli_num_rows($result); if($check&gt;0){ echo "you are logged in"; } else { echo "Error"; } } ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;tr&gt; &lt;td&gt;Username:&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="user" value=""/&gt;&lt;/td&gt; &lt;/tr&gt;&lt;br /&gt;&lt;br /&gt; &lt;tr&gt; Password: &lt;td&gt;&lt;input type="password" name="pass" value=""/&gt;&lt;/td&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr align="center"&gt;&lt;td colspan="2"&gt;&lt;input type="submit" name="login" value="Log In"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>There is a <code>&lt;form&gt;</code> Tag missing</p> <pre><code>&lt;body&gt; &lt;form action="#" method="post"&gt; &lt;tr&gt; &lt;td&gt;Username:&lt;/td&gt; &lt;td&gt; &lt;input type="text" name="user" value="" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;br /&gt; &lt;br /&gt; &lt;tr&gt; Password: &lt;td&gt; &lt;input type="password" name="pass" value="" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;br /&gt; &lt;tr align="center"&gt; &lt;td colspan="2"&gt; &lt;input type="submit" name="login" value="Log In" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/form&gt; &lt;/body&gt; </code></pre>
Getting only 10 rows in Solr Cassandra search <p>I am working on Datastax Cassandra with Apache Solr for multiple partial search. Issue is, everytime I am getting only 10 rows even once I am doing count(*) query, I am able to check there are 1300 rows belong to particular query.</p> <pre><code>nandan@cqlsh:testo&gt; select id from empo where solr_query = 'isd:9*'; id -------------------------------------- 5ee5fca6-6f48-11e6-8b77-86f30ca893d3 27e3e3bc-6f48-11e6-8b77-86f30ca893d3 f3156e76-6f47-11e6-8b77-86f30ca893d3 f315ac74-6f47-11e6-8b77-86f30ca893d3 f315bc82-6f47-11e6-8b77-86f30ca893d3 27e3058c-6f48-11e6-8b77-86f30ca893d3 4016eee4-6f47-11e6-8b77-86f30ca893d3 1bd33e34-6f47-11e6-8b77-86f30ca893d3 8f0a9168-6f47-11e6-8b77-86f30ca893d3 6669cc42-6f47-11e6-8b77-86f30ca893d3 (10 rows) </code></pre> <p>After searching few links, I make changes into solrconfig.xml file. and changes are as below. </p> <pre><code>&lt;requestHandler class="solr.SearchHandler" default="true" name="search"&gt; &lt;!-- default values for query parameters can be specified, these will be overridden by parameters in the request --&gt; &lt;lst name="defaults"&gt; &lt;int name="rows"&gt;1000000&lt;/int&gt; &lt;/lst&gt; &lt;!-- SearchHandler for CQL Solr queries: this handler doesn't support any additional components, only default parameters --&gt; &lt;requestHandler class="com.datastax.bdp.search.solr.handler.component.CqlSearchHandler" name="solr_query"&gt; &lt;lst name="defaults"&gt; &lt;int name="rows"&gt;1000000&lt;/int&gt; &lt;/lst&gt; &lt;/requestHandler&gt; </code></pre> <p>But still I am getting same issue. Please let me know what will be the solution for this. Thanks.</p>
<p>I don't think it should be managed from the schema. The query has a <code>rows</code> and a <code>start</code> parameter. Use those: rows defines the max number of items to return, start defines the first item in the list to return:</p> <pre><code>q=isd:9*&amp;rows=22&amp;start=17&amp;wt=json </code></pre> <p><code>isd:9*</code> returns all items where isd starts with 9.</p> <p><code>start=17</code> says begin at the 18th item in the list.</p> <p><code>rows=22</code> returns 22 items, from 18 to 40.</p>
Regarding word search error (Encoding error Java) <p>I have a list of french words where I am trying to search in my database. The words are "thé Mariage frères", "thé Lipton" etc. While I am reading my file in java, it shows the words as "thé Lipton", "thé Mariage frères". It fails to get the correct words. I don't know how to correct my errors.</p> <p>Help me, please!!!</p>
<p>You file is in one encoding (maybe latin1/iso-8859-1) and you're reading your file in another encoding.</p> <p>See if this port helps <a href="http://stackoverflow.com/questions/12096844/how-to-read-a-file-in-java-with-specific-character-encoding">How to read a file in Java with specific character encoding?</a></p>
Custom tableview cell multiple rows <p><a href="https://i.stack.imgur.com/jVspI.png" rel="nofollow"><img src="https://i.stack.imgur.com/jVspI.png" alt="This is samole image"></a> This is my json data. Here it is Restaurant name coming one and line name coming 2 some times line name coming more then how to print the data in custom cell.please. help me</p> <pre><code> "currency": "$", "state": "sale", "total": 243.1, "name": "a1238", "restaurant_name": "\"Food Court\" Biergarten", "date": "2016-10-16 07:52:07", "table_no": null, "so_id": 238, "lines": [ { "line_status": "pending", "line_id": 2536, "line_price": 1, "line_qty": 1, "line_name": "Käse" }, { "line_status": "pending", "line_id": 2579, "line_price": 7.8, "line_qty": 2, "line_name": "3 Musketiere (3x verschiedene Hefe 0,3l)" }, </code></pre>
<p>Use your restaurant array for section</p> <pre><code>numberOfSectionsInTableView{} </code></pre> <p>and your <code>"lines": [{}]</code> array for</p> <pre><code>numberOfRowsInSection{} </code></pre> <p>You may get better idea from code mentioned below</p> <pre><code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number restaurant count return [restaurantArray count]; } </code></pre> <p>and for multiple rows considering you have restaurant as object:</p> <pre><code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of lines count. return [objRestaurant.Lines count]; } </code></pre>
400 Bad Request with spring REST <p>I have spring rest service such this</p> <pre><code>@RequestMapping(method = RequestMethod.POST, path = "/getdata", consumes = {"multipart/form-data"}, produces = MediaType.APPLICATION_JSON) public @ResponseBody Result getBarcode(@RequestParam("text") String sl, @RequestParam("imageFile") MultipartFile file) { ... some logic return new Result(text, message, !processingError); } </code></pre> <p>When i call this from <strong>http</strong> form it works fine and return <strong>json text</strong>. But when i trying to call this from java code</p> <pre><code>RestTemplate restTemplate = new RestTemplate(); MultiValueMap&lt;String, Object&gt; map = new LinkedMultiValueMap&lt;&gt;(); map.add("text", "123"); map.add("imageFile", new File("...path to file...")); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); headers.setAccept(MediaType.parseMediaTypes("application/json,text/html,application/xhtml+xml,application/xml")); HttpEntity&lt;MultiValueMap&lt;String, Object&gt;&gt; requestEntity = new HttpEntity&lt;&gt;(map, headers); ResponseEntity&lt;BcResult&gt; response = restTemplate.exchange("http://localhost:8080/getdata", HttpMethod.POST, requestEntity, BcResult.class); </code></pre> <p>Then i am getting <strong>400 Bad request error</strong>. Can`t figure out what is wrong with this code...</p>
<p>Set your file like this.</p> <pre><code> map.add("imageFile", new FileSystemResource(new File("...path to file..."))); </code></pre> <p>or like this</p> <pre><code>map.add("imageFile", new ClassPathResource("...path to file...")); </code></pre>
Lock-free programming: reordering and memory order semantics <p>I am trying to find my feet in lock-free programming. Having read different explanations for memory ordering semantics, I would like to clear up what possible reordering may happen. As far as I understood, instructions may be reordered by the compiler (due to optimization when the program is compiled) and CPU (at runtime?). </p> <p>For the relaxed semantics <a href="http://en.cppreference.com/w/cpp/atomic/memory_order" rel="nofollow">cpp reference</a> provides the following example:</p> <pre class="lang-cpp prettyprint-override"><code>// Thread 1: r1 = y.load(memory_order_relaxed); // A x.store(r1, memory_order_relaxed); // B // Thread 2: r2 = x.load(memory_order_relaxed); // C y.store(42, memory_order_relaxed); // D </code></pre> <p>It is said that with x and y initially zero the code is allowed to produce r1 == r2 == 42 because, although A is sequenced-before B within thread 1 and C is sequenced before D within thread 2, nothing prevents D from appearing before A in the modification order of y, and B from appearing before C in the modification order of x. How could that happen? Does it imply that C and D get reordered, so the execution order would be DABC? Is it allowed to reorder A and B? </p> <p>For the acquire-release semantics there is the following sample code:</p> <pre class="lang-cpp prettyprint-override"><code>std::atomic&lt;std::string*&gt; ptr; int data; void producer() { std::string* p = new std::string("Hello"); data = 42; ptr.store(p, std::memory_order_release); } void consumer() { std::string* p2; while (!(p2 = ptr.load(std::memory_order_acquire))) ; assert(*p2 == "Hello"); // never fires assert(data == 42); // never fires } </code></pre> <p>I'm wondering what if we used relaxed memory order instead of acquire? I guess, the value of <code>data</code> could be read before <code>p2 = ptr.load(std::memory_order_relaxed)</code>, but what about <code>p2</code>?</p> <p>Finally, why it is fine to use relaxed memory order in this case?</p> <pre class="lang-cpp prettyprint-override"><code>template&lt;typename T&gt; class stack { std::atomic&lt;node&lt;T&gt;*&gt; head; public: void push(const T&amp; data) { node&lt;T&gt;* new_node = new node&lt;T&gt;(data); // put the current value of head into new_node-&gt;next new_node-&gt;next = head.load(std::memory_order_relaxed); // now make new_node the new head, but if the head // is no longer what's stored in new_node-&gt;next // (some other thread must have inserted a node just now) // then put that new head into new_node-&gt;next and try again while(!head.compare_exchange_weak(new_node-&gt;next, new_node, std::memory_order_release, std::memory_order_relaxed)) ; // the body of the loop is empty } }; </code></pre> <p>I mean both <code>head.load(std::memory_order_relaxed)</code> and <code>head.compare_exchange_weak(new_node-&gt;next, new_node, std::memory_order_release, std::memory_order_relaxed)</code>.</p> <p>To summarize all the above, my question is essentially when do I have to care about potential reordering and when I don't?</p>
<p>For #1, compiler may issue the store to y before the load from x (there are no dependencies), and even if it doesn't, the load from x can be delayed at cpu/memory level.</p> <p>For #2, p2 would be nonzero, but neither *p2 nor data would necessarily have a meaningful value. </p> <p>For #3 there is only one act of publishing non-atomic stores made by this thread, and it is a release</p> <p>You should always care about reordering, or, better, not assume any order: neither C++ nor hardware executes code top to bottom, they only respect dependencies. </p>
Optimization of an algorithm using apply inestead of two fors in R <p>I've got a following problem:</p> <p>I want to reorganise my table from:</p> <pre><code>df &lt;- data.frame(A=c(1,0,1), B=c(1,0,1), C=c(0,1,1)) A B C x 1 1 0 y 0 0 1 z 1 1 1 </code></pre> <p>Into a frame:</p> <pre><code> AB AC BC x 1 0 0 y 0 0 0 z 1 1 1 </code></pre> <p>By using a conjunction of each column.</p> <p>I can do it by using two for functions, but it is really time consuming on "big data" and I'm looking for an optimisation function. I find out that <code>apply</code> can be useful in that case, but I have no idea how can I use it in that case. </p> <p>Can someone give me a hint, how to solve above problem? </p>
<p>This will work using a combination of lapply and dplyr. It makes a list of the product of the columns, which is then bound into a single dataframe.</p> <pre><code>library(dplyr) lapply(1:(ncol(df)-1), function(n){ out &lt;- df[,n] * df names(out) &lt;- paste0(names(df)[n] ,names(df)) out %&gt;% select(c((n+1):ncol(df))) }) %&gt;% bind_cols() </code></pre>
why is cassandra not getting connected to server? <p>I have installed cassandra and worked on it. It worked properly. Now, it is showing as-</p> <p><code>localhost/&lt;&gt; is in use by another process. Change listen_address:storage_port in cassandra.yaml to values that do not conflict with other services Fatal configuration error; unable to start server. See log for stacktrace. INFO 09:17:02 Announcing shutdown INFO 09:17:02 Compacted 4 sstables to [./../data/data/system/local-7ad54392bcdd35a684174e047860b377/system-local-ka-33,]. 6,485 bytes to 5,751 (~88% of original) in 223ms = 0.024595MB/s. 4 total partitions merged to 1. Partition merge counts were {4:1, } INFO 09:17:04 Waiting for messaging service to quiesce user@inblrlt-user:~/dev/Cassandra/apache-cassandra-2.1.7/bin$ ./cqlsh Connection error: ('Unable to connect to any servers', {'127.0.0.1': OperationTimedOut('errors=None, last_host=None',)})</code></p> <p>How to change my server address so that the issue is cleared?</p>
<p>Your localhost is already in use. Follow the following steps-</p> <p><code>$ jps</code></p> <p>You see some processes running. For example:</p> <p><code>9107 Jps 1112 CassandraDaemon</code></p> <p>Then kill the <code>CassandraDaemon</code> process by the process id you see after executing <code>jps</code>. In my example, here process id <code>1112</code> for <code>CassandraDaemon</code>. </p> <p><code>$ kill -9 1112</code></p> <p>Then check processes again after a while-</p> <p><code>$ jps</code></p> <p>You will see <code>CassandraDaemon</code> will no longer be available.</p> <p><code>9170 Jps</code></p> <p>Then remove your <code>saved_caches</code> and <code>commilog</code> and start <code>cassandra</code> again.</p> <p>If you want to change the <strong>listen_address</strong> from <strong>localhost</strong> to any private ip or public ip, you need to make the following changes:</p> <ol> <li>change <strong>seeds:</strong> at cassandra.yaml</li> <li>change <strong>listen_address:</strong> at cassandra.yaml</li> <li>change <strong>rpc_address:</strong> at cassandra.yaml</li> <li>set <code>JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=&lt;place_your_ip_here&gt;"</code> at cassandra-env.sh</li> </ol>
NetworkX: how to properly create a dictionary of edge lengths? <p>Say I have a regular grid network made of <code>10x10</code> nodes which I create like this:</p> <pre><code>import networkx as nx from pylab import * import matplotlib.pyplot as plt %pylab inline ncols=10 N=10 #Nodes per side G=nx.grid_2d_graph(N,N) labels = dict( ((i,j), i + (N-1-j) * N ) for i, j in G.nodes() ) nx.relabel_nodes(G,labels,False) inds=labels.keys() vals=labels.values() inds=[(N-j-1,N-i-1) for i,j in inds] posk=dict(zip(vals,inds)) nx.draw_networkx(G, pos=posk, with_labels=True, node_size = 150, node_color='blue',font_size=10) plt.axis('off') plt.title('Grid') plt.show() </code></pre> <p>Now say I want to create a dictionary which stores, for each edge, its length. This is the intended outcome:</p> <pre><code>d={(0,1): 3.4, (0,2): 1.7, ...} </code></pre> <p>And this is how I try to get to that point:</p> <pre><code>from math import sqrt lengths={G.edges(): math.sqrt((x-a)**2 + (y-b)**2) for (x,y),(a,b) in G.edges()} </code></pre> <p>But there clearly is something wrong as I get the following error message:</p> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-7-c73c212f0d7f&gt; in &lt;module&gt;() 2 from math import sqrt 3 ----&gt; 4 lengths={G.edges(): math.sqrt((x-a)**2 + (y-b)**2) for (x,y),(a,b) in G.edges()} 5 6 &lt;ipython-input-7-c73c212f0d7f&gt; in &lt;dictcomp&gt;(***failed resolving arguments***) 2 from math import sqrt 3 ----&gt; 4 lengths={G.edges(): math.sqrt((x-a)**2 + (y-b)**2) for (x,y),(a,b) in G.edges()} 5 6 TypeError: 'int' object is not iterable </code></pre> <p><strong>What am I missing?</strong></p>
<p>There is a lot going wrong in the last line, first and foremost that G.edges() is an iterator and not a valid dictionary key, and secondly, that G.edges() really just yields the edges, not the positions of the nodes.</p> <p>This is what you want instead: </p> <pre><code>lengths = dict() for source, target in G.edges(): x1, y1 = posk[source] x2, y2 = posk[target] lengths[(source, target)] = math.sqrt((x2-x1)**2 + (y2-y1)**2) </code></pre>
How to fix element p size <p>I'm working in one html/js apps similar to powerpoint, so the apps leave you create slider and show them in any type of screen (they are big screen but with not that many pixel, example one screen make 128x90 [px], the screen make 2x1 [metters])</p> <p>At the creation process the people can choose different font sizes in px (11, 12, 14 .... 100), at this moment i add text and the parent element have this css</p> <pre><code>.text-show{ color: #FFFFFF; margin-bottom: 10px; font-size: 11px !important; font-family: Arial; font-weight: lighter !important; line-height: 1 !important; } </code></pre> <p>And others css (i working in someone project and one old dev add to many parent and css).</p> <p>My problem is that when i add text, for example </p> <pre><code>&lt;p&gt; some text &lt;span style="font-size: 11px"&gt;other text&lt;/span&gt;&lt;/p&gt; </code></pre> <p>At the creator part i get for the size of ‘p‘ this ‘SOMEx12px‘, but in the end result i get ‘SOMEx12.66px‘</p> <p>And because i'm working with not to many pixel, the 0.66px variation is visible (i had other element, so is more the sum other this little diff that make the problem).</p> <p>So my question is way and how i can fix this problem, i verify the css and i can not find any weird.</p> <p>For test it, i use the same browser to create the slider and to see it, the screen have the same browser too. </p>
<p>You have try to use a Normalize.css file? the browser some time add part of code that you don't need, maybe something like <code>p{font-size:110%}</code> or <code>spam{font-size:110%}</code> Also could be that are inside your normalize part.</p>
Timer.start() unexpectedly? <pre><code>private void PlayerClockInPanelControl_Load(object sender, EventArgs e) { InitializedMouseDownEvent(); } private void InitializedMouseDownEvent() { aTimer = new System.Timers.Timer(); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); aTimer.Interval = 2000; aTimer.Enabled = true; } private void OnTimedEvent(object source, ElapsedEventArgs e) { this.ShowErrorMessage("Hello"); aTimer.Stop(); } private void picturebox_MouseDown(object sender, EventArgs e) { aTimer.Start(); } private void picturebox_MouseUp(object sender, EventArgs e) { aTimer.Stop(); } </code></pre> <p>My idea was, the timer should start only when <code>MouseDown</code> event is fired but now once the form loads, it displays "Hello" every second. As mentioned in the code there is only <code>aTimer.Start()</code> being called during <code>MouseDown</code> event. May I know what's wrong?</p>
<p>You get this behaviour because there is no difference between <code>timer.Start()</code> and <code>timer.Enabled = true</code> (and also <code>timer.Stop()</code> and <code>timer.Enabled = false</code>). For this reason if you call <code>timer.Enabled = tru</code>e in your <code>formLoad</code> you start the timer.<br> For more information check <a href="https://msdn.microsoft.com/en-us/library/system.windows.forms.timer.enabled.aspx" rel="nofollow">this MDSN page</a></p>
Rest API automation using Rest Assured framework for dot net <p>I have used rest-assured framework for rest api automation testing using JAVA But now I have to develop automation code using dot net. Can I use the same framework for dot net also? If can't, please suggest some frameworks for rest api automation testing?</p>
<p>Yes, you can test .Net REST api using a java framework. You are simplt testing the operations and the responses to those operations, the language of the testing framework can be anything you desire.</p>
Even/Odd Numbers in Arm <p>I am trying to write an ARM program that counts the number of odd numbers written in a .txt file and sums the amount of even numbers.</p> <p>I understand that the least significant binary digit(Z Bit) signifies whether a number is odd or even. </p> <p>My question is which instruction(s) can I use to get this done, and also how can I create an "if" statement that compares the values?</p> <p>Basically what I want to do is compare the number using something like:</p> <pre><code>@condition "if number from file is even" add r4,r1,r4 @condition "if number from file is odd" add r5,r5,#1 </code></pre> <p>I just need a little help with the syntax for the conditions</p> <p>Thanks</p>
<p>The Z bit is a condition code bit which is true if the value the conditions codes were set from is "Zero". You can set the condition codes with (for example):</p> <pre><code>tst r1,#1 </code></pre> <p>Then the Z bit will be set if the number is even, and clear if it is odd. You can then use conditional execution to control the additions:</p> <pre><code>addeq r4,r1,r4 addne r5,r5,#1 </code></pre>
git remove directory with special char ( symbol) in it <p>got this directories:</p> <ul> <li>main%F0java </li> <li>main%F0res</li> </ul> <p>created for any reason (i guess android studio is to blame) and committed it on a rush. the fact is thath %F0 is the  symbol so when i go to commit/remove via terminal/source tree i always fail.</p> <p>I tried:</p> <p>git rm -rf *java</p> <p>but got </p> <p>fatal: pathspec 'main%F0java' did not match any files</p> <p>I just started to pull out my (few) hair. Anyway around this mess ? I'm on a mac btw</p> <p>Thanks</p>
<p>removing and committing via the console (not with sourcetree) seemed to work. thanks to Issam</p>
Can't bind to 'control' since it isn't a known property of (myComponent) <p>this is my app.module.ts</p> <pre><code>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; // import { CountryDetailsComponent} from './country-detail.component'; // import { LandingPageComponent} from './landing-page.component'; import { routing } from './app.routing' import { TypeaheadModule } from 'ng2-bootstrap/components/typeahead'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { TabsModule } from 'ng2-bootstrap/ng2-bootstrap'; import { CollapseModule } from 'ng2-bootstrap/ng2-bootstrap'; import { AlertModule } from 'ng2-bootstrap/ng2-bootstrap'; @NgModule({ imports: [ BrowserModule, HttpModule, routing, FormsModule, ReactiveFormsModule, TypeaheadModule, TabsModule, CollapseModule, AlertModule], declarations: [ AppComponent ], providers: [], bootstrap: [ AppComponent ] }) export class AppModule { } </code></pre> <p>I have this angular2 components:</p> <p>import {ErrorMessagesComponent} from '../error-messages.component'; import {ValidationComponent} from '../validation.component'; import {GasType} from "../gas-type";</p> <pre><code>export class CountryDetailsComponent extends LoadingPage implements OnInit { countryName: string; productionForm: FormGroup; .. } </code></pre> <p>and</p> <pre><code>import { Component, Input } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { ValidationComponent } from './validation.component'; @Component({ selector: 'error-messages', template: `&lt;div style="color:#E82C0C; margin: 6px 0;" *ngIf="errorMessage !== null"&gt;{{errorMessage}}&lt;/div&gt;` }) export class ErrorMessagesComponent { @Input() control: FormControl; constructor() { } </code></pre> <p>and template <code>country-details.component.html</code>:</p> <pre><code> &lt;div class="col-lg-10 "&gt; &lt;input class="price-format form-control" type="text" [formControl]="productionForm.controls.priceFormat" [(ngModel)]="productionConfig.priceFormat" id="inputPriceFormat" name="priceFormat"&gt; &lt;error-messages [control]="productionForm.controls.priceFormat"&gt;&lt;/error-messages&gt; &lt;/div&gt; </code></pre> <p>but i get this error:</p> <pre><code>Can't bind to 'control' since it isn't a known property of 'error-messages'. 1. If 'error-messages' is an Angular component and it has 'control' input, then verify that it is part of this module. 2. If 'error-messages' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("nputPriceFormat" name="priceFormat"&gt; &lt;error-messages [ERROR -&gt;][control]="productionForm.controls.priceFormat"&gt;&lt;/error-messages&gt; &lt;/div&gt; "): b@43:36 </code></pre> <p>how should i fix this?</p>
<p>The component needs to be registered with an <code>@NgModule()</code></p> <pre><code>declarations: [ AppComponent, ErrorMessageComponent ], </code></pre>
How to filter data without repeat values in mongodb with java <p>I'm trying to get data from mongoDB without repeat values. I want to filter following data</p> <pre><code>{"page":"www.abc.com","impressions":1,"position":144} {"page":"www.abc.com","impressions":1,"position":8} {"page":"www.xyz.com","impressions":7,"position":4} {"page":"www.pqr.com","impressions":1,"position":7} {"page":"www.abc.com","impressions":1,"position":19} </code></pre> <p>to filter as following. any idea how should I do that ?</p> <pre><code>{"page":"www.xyz.com","impressions":7,"position":4} {"page":"www.pqr.com","impressions":1,"position":7} </code></pre>
<p>You should be able to run an aggregation pipeline that groups the documents by the <code>page</code> field using the <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/group/" rel="nofollow"><code>$group</code></a></strong> pipeline operator, get a count of the documents using the <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sum/#grp._S_sum" rel="nofollow"><code>$sum</code></a></strong> operator and retain the other two fields using the <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/first/#grp._S_first" rel="nofollow"><code>$first</code></a></strong> (or <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/last/#grp._S_last" rel="nofollow"><code>$last</code></a></strong>) operator.</p> <p>The preceding pipeline after the <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/group/" rel="nofollow"><code>$group</code></a></strong> should be able to filter the grouped documents on the count field, i.e. filter out the duplicates from the result. Use the <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/match/#pipe._S_match" rel="nofollow"><code>$match</code></a></strong> pipeline operator for such query.</p> <p>A final cosmetic pipeline would involve the <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/project/#pipe._S_project" rel="nofollow"><code>$project</code></a></strong> stage which reshapes each document in the stream, include, exclude or rename fields, inject computed fields, create sub-document fields, using mathematical expressions, dates, strings and/or logical (comparison, boolean, control) expressions.</p> <p>Run this aggregation pipeline to get the desired result:</p> <pre><code>db.collection.aggregate([ { "$group": { "_id": "$page", "count": { "$sum": 1 }, "impressions": { "$first": "$impressions" }, "position": { "$first": "$position" } } }, { "$match": { "count": 1 } }, { "$project": { "_id": 0, "page": "$_id", "impressions": 1, "position": 1 } } ]) </code></pre>
How to use Glide with dagger2 <p>I am developing a music application. I want to load artist's image from LastFM so i do this this way 1. I created a class <code>ArtistImageLoader extends BaseGlideUrlLoader</code>. 2. In the <code>getUrl</code> method i used retrofit2 to get the artist's image url from LastFM via <a href="http://www.last.fm/api/show/album.getInfo" rel="nofollow">getArtistInfo</a> method. </p> <p>My problem is i didn't know how to inject the service of retrofit to make the request in <code>ArtistImageLoader</code>. I did this way but i got a NOP exception. <code>lastFmService</code> wasn't be not injected.</p> <pre><code>// GlideModule glide.register(MLocalArtist.class, InputStream.class, new ArtistImageLoader.Factory()); // Use it in onCreate method of ArtistsFragment DaggerLastFmComponent.builder().activityModule(new ActivityModule(getActivity())) .netComponent(getNetComponent()) .build().inject(this); // use this code in onBindViewHolder method of artists recycler adapter Glide.with(getContext()) .from(MLocalArtist.class) .load(localArtist) .into(localArtistViewHolder.ivArtwork); </code></pre> <p><strong>ArtistImageLoader</strong></p> <pre><code>public class ArtistImageLoader extends BaseGlideUrlLoader&lt;MLocalArtist&gt; { @Inject LastfmService lastfmService; public ArtistImageLoader(Context context) { super(context); } @Override protected String getUrl(MLocalArtist model, int width, int height) { Call&lt;List&lt;MArtist&gt;&gt; call = lastfmService.getArtistInfo(model.artistName); try { List&lt;MArtist&gt; artists = call.execute().body(); if (artists != null &amp;&amp; artists.size() &gt; 0) { Timber.e(artists.get(0).toString()); } } catch (IOException e) { e.printStackTrace(); } return null; } public static class Factory implements ModelLoaderFactory&lt;MLocalArtist, InputStream&gt; { @Override public ModelLoader&lt;MLocalArtist, InputStream&gt; build(Context context, GenericLoaderFactory factories) { return new ArtistImageLoader(context); } @Override public void teardown() { } } } </code></pre> <p>Can you help me to do it? Thank you so much!</p> <p><strong>Glide Version</strong>: 3.7.0</p> <p><strong>Integration libraries</strong>: OkHttp3 + Dagger2</p> <p><strong>Device/Android Version</strong>: Android Emulator + Asus zenfone 5</p> <p><strong>EDIT 1</strong> </p> <p>ActivityComponent.java</p> <pre><code>@PerActivity @Component(dependencies = AppComponent.class, modules = ActivityModule.class) public interface ActivityComponent { Context context(); } </code></pre> <p>AppComponent.java</p> <pre><code>@Singleton @Component(modules = AppModule.class) public interface AppComponent { App app(); } </code></pre> <p>NetComponent.java</p> <pre><code>@Singleton @Component(modules = {NetModule.class, AppModule.class}) public interface NetComponent { @Named("chartSoundCloud") Retrofit getSoundcloudChartRetrofit(); @Named("searchSoundCloud") Retrofit getSoundcloudSearchRetrofit(); @Named("lastFM") Retrofit getLastFmRetrofit(); } </code></pre> <p>LastFmComponent.java</p> <pre><code>@PerActivity @Component(dependencies = NetComponent.class, modules = {LastFmModule.class, ActivityModule.class}) public interface LastFmComponent extends ActivityComponent { void inject(ArtistsFragment artistsFragment); } </code></pre> <p>ActivityModule.java</p> <pre><code>@Module public class ActivityModule { private final Context mContext; public ActivityModule(Context mContext) { this.mContext = mContext; } @Provides @PerActivity Context provideActivityContext() { return mContext; } } </code></pre> <p>AppModule.java</p> <pre><code>@Module public class AppModule { private App app; public AppModule(App app){ this.app = app; } @Singleton @Provides App provideApplication() { return app; } @Singleton @Provides @Named("applicationContext") Context provideApplicationContext(){ return app; } } </code></pre> <p>LastFmModule.java</p> <pre><code>@Module public class LastFmModule { @Provides @PerActivity LastfmService provideLastFmService(@Named("lastFM") Retrofit retrofit) { return retrofit.create(LastfmService.class); } } </code></pre> <p>NetModule.java</p> <pre><code>@Module public class NetModule { static final int DISK_CACHE_SIZE = (int) MEGABYTES.toBytes(50); @Provides @Singleton Cache provideOkHttpCache(@Named("applicationContext") Context application) { Cache cache = new Cache(application.getCacheDir(), DISK_CACHE_SIZE); return cache; } @Provides @Singleton ScdClientIdInterceptor provideScdClientIdInterceptor() { return new ScdClientIdInterceptor(); } @Provides @Singleton LastFMInterceptor provideLastFmInterceptor() { return new LastFMInterceptor(); } @Provides @Singleton HttpLoggingInterceptor provideHttpLoggingInterceptor() { return new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY); } @Provides @Singleton @Named("soundcloud-Http") OkHttpClient provideOkHttpSoundCloudClient(Cache cache, ScdClientIdInterceptor clientIdInterceptor, HttpLoggingInterceptor httpLoggingInterceptor) { return createOkHttpClient(cache, clientIdInterceptor, httpLoggingInterceptor); } @Provides @Singleton @Named("lastFM-Http") OkHttpClient provideOkHttpLastFmClient(Cache cache, LastFMInterceptor clientIdInterceptor, HttpLoggingInterceptor httpLoggingInterceptor) { return createOkHttpClient(cache, clientIdInterceptor, httpLoggingInterceptor); } private OkHttpClient createOkHttpClient(Cache cache, Interceptor clientIdInterceptor, HttpLoggingInterceptor httpLoggingInterceptor) { OkHttpClient okHttpClient = new OkHttpClient.Builder() .cache(cache) .addInterceptor(clientIdInterceptor) .addInterceptor(httpLoggingInterceptor) .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .build(); return okHttpClient; } @Provides @Singleton Gson provideGson() { return GsonFactory.create(); } @Provides @Singleton @Named("searchSoundCloud") Retrofit provideSearchSoundCloudRetrofit(Gson gson, @Named("soundcloud-Http") OkHttpClient okHttpClient) { Retrofit searchRetrofit = new Retrofit.Builder() .baseUrl(Constants.BASE_SOUNDCLOUD_API_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); return searchRetrofit; } @Provides @Singleton @Named("chartSoundCloud") Retrofit provideChartSoundCloudRetrofit(Gson gson, @Named("soundcloud-Http") OkHttpClient okHttpClient) { Retrofit chartRetrofit = new Retrofit.Builder() .baseUrl(Constants.BASE_SOUNDCLOUD_API_V2_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); return chartRetrofit; } @Provides @Singleton @Named("lastFM") Retrofit provideLastFmRetrofit(Gson gson, @Named("lastFM-Http") OkHttpClient okHttpClient) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constants.LASTFM_API_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); return retrofit; } } </code></pre>
<p>My assumption is that your ArtistImageLoader is defined in an separate class. The reason for the your problem is the way dagger works. It only injects fields annotated with <code>@Inject</code> on the class you specified as parameter of the inject method. Therefore nothing inside your <code>ArtistImageLoader</code> annotated with <code>@Inject</code> will be injected, but only the annotated fields, which are defined inside your <code>ArtistsFragment</code>.</p> <p>I would recommend to define an LastfmService field with the <code>@Inject</code> annotation in your fragment and pass the instance to your Glide LoaderFactory. The factory can provide it to the instances of the loader. It's not the nicest solution, but since you can't directly pass it to the instances this seems to viable workaround.</p> <p>Another approach would be to build your dependency tree inside your custom <code>Application</code>. This allows you access the dependencies from anywhere without being dependent on the activity lifecycle. </p>
Get the size of heap and stack per process in linux <p>I wanted to know the size of heap and stack per process in linux. Is there any way to find it?</p> <p>I found out that sbrk(0) will give me the end of heap. But how can I find the start of heap to get the heap size?</p> <p>Also on stack size is there any way to find the start of stack and current stack pointer address per process through any library calls or system calls?</p>
<p>On Linux, you can read <code>/proc/[PID]/maps</code> and find <code>[heap]</code> and <code>[stack]</code> entries.</p> <p>But for the GLIBC heap implementations usually used on Linux, the "heap" consists of both memory obtained via <code>sbrk()</code> that shows up in the <code>/proc/[PID]/maps</code> file as <code>[heap]</code> <em>and</em> memory obtained via <code>mmap()</code> - see <a href="http://stackoverflow.com/questions/30542428/malloc-does-it-use-brk-or-mmap">this quesiton</a>. So the "size" of the heap is going to be very hard to determine with certainty.</p> <p>And the region labelled <code>[stack]</code> in the <code>maps</code> file is the stack for the main thread only. Multithreaded processes will have multiple stacks, one for each thread. And they will show up in the <code>maps</code> file as anonymous memory - maybe. The application can control the memory used for a thread's stack via the use of <code>pthread_attr_setstack()</code> and set it to <em>any</em> memory the application might use.</p>
Cassandra stopped working after nodetool repair <p>After running "nodetool repair" command cassandra node gone down and did not start again.</p> <pre><code>INFO [main] 2016-10-19 12:44:50,244 ColumnFamilyStore.java:405 - Initializing system_schema.aggregates INFO [main] 2016-10-19 12:44:50,247 ColumnFamilyStore.java:405 - Initializing system_schema.indexes INFO [main] 2016-10-19 12:44:50,248 ViewManager.java:139 - Not submitting build tasks for views in keyspace system_schema as storage service is not initialized </code></pre> <p>Cassandra version 3.7</p>
<p>Turned on the node and it's fine. It took too long to start (more than 30 minutes).</p> <pre><code>INFO [main] 2016-10-19 15:32:48,348 ColumnFamilyStore.java:405 - Initializing system_schema.indexes INFO [main] 2016-10-19 15:32:48,354 ViewManager.java:139 - Not submitting build tasks for views in keyspace system_schema as storage service is not initialized INFO [main] 2016-10-19 16:07:36,529 ColumnFamilyStore.java:405 - Initializing system_distributed.parent_repair_history INFO [main] 2016-10-19 16:07:36,546 ColumnFamilyStore.java:405 - Initializing system_distributed.repair_history </code></pre> <p>Now I'm trying to figure out why it is so slow.</p>
Setup node https server using SSL certificate from GoDaddy <p>Earlier i used a self signed certificate and created a https server on node js using</p> <pre><code>var privateKey = fs.readFileSync( 'key.pem' ); var certificate = fs.readFileSync( 'cert.pem' ); var app = express(); https.createServer({ key: privateKey, cert: certificate, passphrase:'abc123' }, app).listen(1111); </code></pre> <p>I have now purchased and verified an SSL certificate from GoDaddy.I have downloaded the SSL certificate from GoDaddy and got 2 files :</p> <p>1) d752ec439hdwudbdh7.crt:</p> <p>-----BEGIN CERTIFICATE-----</p> <p>........</p> <p>-----END CERTIFICATE-----</p> <p>2)gd-bundle-g2-g1.crt:</p> <p>-----BEGIN CERTIFICATE-----</p> <p>........</p> <p>-----END CERTIFICATE-----</p> <p>-----BEGIN CERTIFICATE-----</p> <p>........</p> <p>-----END CERTIFICATE-----</p> <p>-----BEGIN CERTIFICATE-----</p> <p>........</p> <p>-----END CERTIFICATE-----</p> <p>What files are these and how do i configure these files to use with https.createServer</p>
<p><code>d752ec439hdwudbdh7.crt</code> is your site's certificate generated by GoDaddy. It corresponds to your <code>cert.pem</code> file. As the format of the file provided by GoDaddy is actually PEM (base64 encoded data beginning with the <code>----BEGIN</code> text), you can use it as it is without having to convert formats.</p> <p><code>gd-bundle-g2-g1.crt</code> is the set of certificates (one or more intermediate certificates and optionally, a root certificate) that is used to verify trust. This chain of certificates is what browsers and other user agents use to determine if the certificate was granted by GoDaddy, and if GoDaddy is someone they trust. You will need to use the <code>ca</code> option in <code>https.createServer</code> and specify the path to this file. Again, the file format is what is expected by node/ express and you can just rename it to something sensible and use it like this:</p> <pre><code>var privateKey = fs.readFileSync( 'key.pem' ); var certificate = fs.readFileSync( 'cert.pem' ); var caBundle = fs.readFileSync( 'ca.pem' ); var app = express(); https.createServer({ key: privateKey, cert: certificate, ca: caBundle, passphrase:'abc123' }, app).listen(1111); </code></pre> <p>Once done, I'd recommend checking your site against an online scanner like <a href="https://www.ssllabs.com/ssltest/index.html" rel="nofollow">SSL Labs Server test</a> to ensure that your site does not show any certificate related errors. It'd also be good to fix any other misconfiguration reported there.</p>
How to alert when last cat show full image? <p>How to alert when last cat show full image ?</p> <p>When you click <code>Click HERE</code> cat image will slide, i want to apply my code for alert when display last cat full image (in this cast when click 3 time)</p> <p>But please do not to count click. because i have to use in difference screen size.</p> <p><a href="https://jsfiddle.net/vncxfx0s/5/" rel="nofollow">https://jsfiddle.net/vncxfx0s/5/</a></p> <pre><code> &lt;div style="cursor: pointer;" id="move-left" onclick="left_fn(-222)"&gt; Click HERE &lt;/div&gt; &lt;div style=" width: 455px; overflow: hidden; "&gt; &lt;ul style=" width: 2000em; transition: transform 200ms ease-in-out; transform: translate3d(0px, 0px, 0px); margin-left: -10px; padding: 0;" id="cat-ul"&gt; &lt;li style=" display: inline-table; "&gt; &lt;img src="http://i.imgur.com/w3abdeV.jpg"&gt; &lt;/li&gt; &lt;li style=" display: inline-table; "&gt; &lt;img src="http://i.imgur.com/w3abdeV.jpg"&gt; &lt;/li&gt; &lt;li style=" display: inline-table; "&gt; &lt;img src="http://i.imgur.com/w3abdeV.jpg"&gt; &lt;/li&gt; &lt;li style=" display: inline-table; "&gt; &lt;img src="http://i.imgur.com/w3abdeV.jpg"&gt; &lt;/li&gt; &lt;li style=" display: inline-table; "&gt; &lt;img src="http://i.imgur.com/w3abdeV.jpg"&gt; &lt;/li&gt; &lt;li style=" display: inline-table; "&gt; &lt;img src="http://i.imgur.com/w3abdeV.jpg"&gt; &lt;/li&gt; &lt;li style=" display: inline-table; "&gt; &lt;img src="http://i.imgur.com/w3abdeV.jpg"&gt; &lt;/li&gt; &lt;li style=" display: inline-table; "&gt; &lt;img src="http://i.imgur.com/w3abdeV.jpg"&gt; &lt;/li&gt; &lt;li style=" display: inline-table; "&gt; &lt;img src="http://i.imgur.com/Wc9bszd.jpg"&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;script&gt; function left_fn(value) { document.getElementById("cat-ul").style.transform = "translate3d("+value+"px, 0px, 0px)"; var x = (value + 222); var y = (value - 222); document.getElementById('move-left').setAttribute('onclick','left_fn('+y+')') } &lt;/script&gt; </code></pre>
<p>One solution is to use jQuery and Viewport-plugin. The plugin ads couple of new pseudo selectors. For example you can check any element is inside or outside of viewport. A little snippet:</p> <pre><code>if($("#lastChild").is(":in-viewport")) { alert("hhh"); } </code></pre> <p>See here for more informations: <a href="https://www.appelsiini.net/projects/viewport" rel="nofollow">https://www.appelsiini.net/projects/viewport</a></p> <p>I've edited a working fiddle with the viewport plugin: <a href="https://jsfiddle.net/manumanfred/vncxfx0s/8/" rel="nofollow">https://jsfiddle.net/manumanfred/vncxfx0s/8/</a></p>
.bashrc function with arguments <p>I often use the following command to merge PDFs:</p> <pre><code>gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=output_name.pdf /location/of/plots/*.pdf </code></pre> <p>I tried setting up an equivalent function in my .bashrc file:</p> <pre><code>function(){ gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=$1 $2 } </code></pre> <p>Now, <code>$ function output.pdf input.pdf</code> only takes one input. How can I change that? Ideally I'd like to be able to pass <code>*.pdf</code> as input.</p>
<p>The following function works fine for me:</p> <pre><code>pdf_merge() { output=$1 shift gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="$output" "$@" } </code></pre>
What kind of iterators supports random access but not contiguous storage in C++? <p>I saw that there is a new iterator since C++17,below listed by a screenshot in cppreference. I was a lot confused. What kind of iterators is random access but not contiguous storage in C++?? otherwise, the ContiguousIterator is not powerful than RandomAccessIterator ? right?</p> <p><a href="https://i.stack.imgur.com/xRS2F.png" rel="nofollow">enter image description here</a></p> <p>and then the link here:</p> <p><a href="http://en.cppreference.com/w/cpp/iterator" rel="nofollow">enter link description here</a></p>
<p>One non-contiguous container with random-access iterators is <a href="http://en.cppreference.com/w/cpp/container/deque" rel="nofollow"><code>std::deque</code></a>. Quoting the cppreference site:</p> <blockquote> <p>As opposed to <code>std::vector</code>, the elements of a deque are not stored contiguously: typical implementations use a sequence of individually allocated fixed-size arrays.</p> <p>The complexity (efficiency) of common operations on deques is as follows:</p> <ul> <li>Random access - constant <em>O(1)</em></li> <li>Insertion or removal of elements at the end or beginning - constant <em>O(1)</em></li> <li>Insertion or removal of elements - linear <em>O(n)</em></li> </ul> </blockquote>
Why cant I format date to d-m-Y using CakePHP's accessor <p>I got a problem with accessor on single record/get.</p> <p>I have date record with value '2015-10-10'.</p> <pre><code> //PatientsController.php $record = $patients-&gt;find()-&gt;first(); debug($record-&gt;dob);die; //would print 19-10-2016 (today's date) </code></pre> <p>In My Entity/Patient.php protected function _getDob( $dob ) { $time = new Time( $dob ); return $time->i18nFormat('dd-MM-YYY'); }</p> <p>If I change <code>$time-&gt;i18nFormat('dd-MM-YYY');</code> to <code>$time-&gt;i18nFormat('YYY-MM-dd');</code> it would show '2015-10-10', which is correct but not the format I want.</p> <p>The question is, why? </p> <p>For now, I'm using custom finder and formatResults and change the format to d-m-y</p> <pre><code> public function findPatients($query, $options) { return $query-&gt;formatResults(function($results) { return $results-&gt;map(function($row) { $tgl = new Time( $row['dob'] ); $row['dob'] = $tgl-&gt;i18nFormat('dd-MM-YYY'); return $row; }); }); } </code></pre> <p>Still wonder why cant it be formatted in accessor.</p>
<p>You may be putting <strong>dd-MM-YYY</strong> it should be <strong>dd-MM-yyyy</strong> Then your code should be </p> <pre><code>public function findPatients($query, $options) { return $query-&gt;formatResults(function($results) { return $results-&gt;map(function($row) { $tgl = new Time( $row['dob'] ); $row['dob'] = $tgl-&gt;i18nFormat('dd-MM-yyyy'); return $row; }); }); } </code></pre> <p>Here is the <a href="http://book.cakephp.org/3.0/en/core-libraries/time.html#Cake%5CI18n%5CTime::i18nFormat" rel="nofollow">Official Doc</a></p>
Error: You have written a subquery that can return more than one field without using the EXIST reserved word <p>I get the following error when I run the query.</p> <blockquote> <p>You have written a subquery that can return more that one field without using the EXIST reserved word in the main query's FROM clause. Revise the SELECT statement of the subquery to request only one field.</p> </blockquote> <p>This is my select statement:</p> <pre><code>sql = "SELECT (SELECT * FROM Data WHERE ProductDate = '" + yesterday + "' "+"AND EndTime &gt; '" + endTime + "'), " + "(SELECT * FROM Data WHERE ProductDate = '" + todayDate + "' " + "AND EndTime = '" + endTime + "')"; </code></pre> <p>The objective is to query both select statements into one query. How do I do that?</p>
<p>You could use <code>UNION</code>:</p> <pre><code>sql = "SELECT * FROM (" + " SELECT * FROM Data WHERE ProductDate = '" + yesterday + "' AND EndTime &gt; '" + endTime + "' " + " UNION" + " SELECT * FROM Data WHERE ProductDate = '" + todayDate + "' AND EndTime = '" + endTime + "' " + ")"; </code></pre> <p>Or better, shorter and simpler with a WHERE on two OR-ed conditions:</p> <pre><code>sql = "SELECT * FROM Data " + "WHERE (ProductDate = '" + yesterday + "' AND EndTime &gt; '" + endTime + "')" + "OR (ProductDate = '" + todayDate + "' AND EndTime = '" + endTime + "')"; </code></pre> <p>And as others have said: look into <strong>parameterized queries</strong>, because sooner or later one of the values may be injected with all kinds of horror. E.g. see this answer for that: <a href="http://stackoverflow.com/a/7505842/1220550">http://stackoverflow.com/a/7505842/1220550</a>.</p> <p>One final thing: the usage of <code>endTime</code> seems strange combined with both dates as you did. But that is for you to know or decide, and not the topic of this question.</p>
Codeigniter DB escape and like <p>I use CI 3, and I have a problem using escape and like clause. Here is my code :</p> <pre><code>$where = '(a.title LIKE \'%'. $this-&gt;db-&gt;escape($name) .'%\' OR agi.senior_artist LIKE \'%'. $this-&gt;db-&gt;escape($name) .'%\')' </code></pre> <p>The problem is <code>$this-&gt;db-&gt;espace</code> add quotes to the string, so I got an error. It works without the escape, and only <code>$name</code> but I prefer to espace the data.</p> <p>Is there a native solution ? </p>
<p>You need to use</p> <pre><code>$this-&gt;db-&gt;escape_like_str() </code></pre> <p>instead</p> <pre><code>$this-&gt;db-&gt;escape() </code></pre> <p>when you use LIKE conditions</p> <p><a href="https://www.codeigniter.com/userguide3/database/queries.html" rel="nofollow">Read more</a></p>
Redirection in reactjs <p>I have a problem which i couldn't solve it for a while. I have mvc application which will render a login page upon successful login i have to redirect to a particular page.</p> <p>The login authentication is done by Api controller which will give me a json bit on successful authentication.I have a question on how to do redirection on successful login.I am using ecmascript 5 specs. I have not inherited layout in my login form and all the components and routes are in scripts registered in layout page.This login is kind of temporary page and below is the jsx code for login.Timely help will be appreciated</p> <pre><code>var MyInput = React.createClass({ //onchange event handleChange: function (e) { this.props.onChange(e.target.value); $("#diverror span").removeClass('alert'); $("#diverror span").removeClass('alert-danger'); }, componentDidMount: function () { if (this.props.onComponentMounted) { this.props.onComponentMounted(this);//register this input in the form } }, render: function () { var inputField; inputField = &lt;input type={this.props.type} value={this.props.value} ref={this.props.name} name={this.props.name} className='form-control' onChange={this.handleChange} /&gt; return ( &lt;div className="form-group"&gt; &lt;label htmlFor={this.props.htmlFor}&gt;{this.props.label}&lt;/label&gt; {inputField} &lt;/div&gt; ); } </code></pre> <p>});</p> <pre><code>var Router = ReactRouter; var Route = ReactRouter.Route; var Routes = ReactRouter.Routes; var Navigation = ReactRouter.Navigation; var History = ReactRouter.History; var LoginForm = React.createClass({ mixins: [History], mixins: [Navigation], //get initial state enent getInitialState: function () { return { EnterpriseId: '', Password: 'ALWTempReplatform', } }, //handle change full name onChangeEnterpriseId: function (value) { this.setState({ EnterpriseId: value }); }, //handle chnage email onChangePassword: function (value) { this.setState({ Password: value }); }, // submit function handleSubmit: function (e) { e.preventDefault(); enterpriseId = this.state.EnterpriseId; this.serverRequest = $.ajax({ //url: this.props.urlPost, url: '/api/LoginApi/Login', dataType: 'json', cache: false, data: enterpriseId, data: { enterpriseId: enterpriseId }, success: function (data) { //Will clear form here this.setState({ EnterpriseId: '', Password:'' }); if (data == 0) { history.pushState({}, '', '/') window.location.reload() } else { $("#diverror span").text("Access Denied"); $("#diverror span").addClass('alert'); $("#diverror span").addClass('alert-danger'); } }.bind(this), error: function (e) { console.log(e); //alert('Error! Please try again'); } }); }, render : function(){ //Render form return( &lt;form name="loginForm" noValidate onSubmit={this.handleSubmit}&gt; &lt;div className="container"&gt; &lt;div className="row"&gt; &lt;div className="col-md-3"&gt;&lt;/div&gt; &lt;div className="col-md-6 divformbtncontainer"&gt; &lt;div className="formcontroldiv"&gt; &lt;MyInput type={'text'} value={this.state.EnterpriseId} label= {'Enterprise Id'} name={'EnterpriseId'} htmlFor={'EnterpriseId'} onChange={this.onChangeEnterpriseId} /&gt; &lt;MyInput type={'password'} value={this.state.Password} label={'Password'} name={'Password'} htmlFor={'Password'} onChange={this.onChangePassword} /&gt; &lt;button type="submit" className="btn btn-primary btn-signin"&gt;SIGN IN&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className="col-md-3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div className="row"&gt; &lt;div className="col-md-3"&gt;&lt;/div&gt; &lt;div id="diverror" className="col-md-6 error"&gt; &lt;span&gt;&lt;/span&gt; &lt;/div&gt; &lt;div className="col-md-3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; ); } }); //Render react component into the page ReactDOM.render(&lt;LoginForm /&gt;, document.getElementById('divLoginForm')); </code></pre>
<p>So basically you just add the router to the class through context, e.g.:</p> <pre><code>... contextTypes: { router: React.PropTypes.object.isRequired } ... </code></pre> <p>and then if the condition is correct</p> <pre><code>if (successCondition) { this.context.router.push('stateName'); } </code></pre> <p>you use the router to redirect to a new state.</p> <p>Hope this helps.</p> <hr> <p><strong>UPDATE</strong></p> <pre><code>var React = React; // &lt;-- add Reach to the application var Router = ReactRouter; var Route = ReactRouter.Route; var Routes = ReactRouter.Routes; var Navigation = ReactRouter.Navigation; var History = ReactRouter.History; var LoginForm = React.createClass({ mixins: [History], mixins: [Navigation], // --&gt; Add the router into the context contextTypes: { router: React.PropTypes.object.isRequired } ... if (data == 0) { this.context.router.push('stateName'); // --&gt; push the new state if successful } else ... </code></pre> <p>I have added the necessary bits to your provided example. I noticed you don't have React defined or maybe it's a problem with adding the bits to the wrong places. Hope this helps.</p>
I have a fragment that resets and displays a blank page instead of the views <p>I have a side drawer for navigation between my different fragments, find code below.</p> <pre><code> public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_dash) { FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction(); xfragmentTransaction.replace(R.id.containerView,new dashFragment()).commit(); } else if (id == R.id.nav_profile) { FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.containerView,new profileFragment()).commit(); } else if (id == R.id.nav_notify) { FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction(); xfragmentTransaction.replace(R.id.containerView,new notiFragments()).commit(); } else if (id == R.id.nav_contacts) { FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction(); xfragmentTransaction.replace(R.id.containerView,new contactsFragment()).commit(); } else if (id == R.id.signout) { startActivity(new Intent(this,loginActivity.class)); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } </code></pre> <p>The issue i am having is that when i leave the initial fragment which is the dashFragment and visit another fragment, like the profileFragment and the return back to the dashFragment, the dashFragment displays a blank page instead of showing my buttons and other items. Below is the code for my dashFragment.</p> <pre><code>public class dashFragment extends Fragment { public static TabLayout tabLayout; public static ViewPager viewPager; private List&lt;Fragment&gt; fragmentList = new ArrayList&lt;&gt;(); private List&lt;String&gt; titleList = new ArrayList&lt;&gt;(); @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View x = inflater.inflate(R.layout.tablayout, null); tabLayout = (TabLayout) x.findViewById(R.id.tabs); viewPager = (ViewPager) x.findViewById(R.id.viewpager); fragmentList = new ArrayList&lt;&gt;(); prepareDataResource(); titleList(); topLevel rta = new topLevel(getFragmentManager(),fragmentList,titleList); viewPager.setAdapter(rta); viewPager.setOffscreenPageLimit(10); tabLayout.setupWithViewPager(viewPager); setTabIcons(); return x; } private void prepareDataResource() { fragmentList.add(new homeFragment()); fragmentList.add(new resultsFragment()); } private void titleList() { titleList.add("Home"); titleList.add("Results"); } private void setTabIcons() { tabLayout.getTabAt(0).setIcon(R.drawable.home_tab); tabLayout.getTabAt(1).setIcon(R.drawable.results_tab); } } </code></pre>
<p>You need to add addToBackStack() method.</p> <p>i.e</p> <p>FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.root_view,new TimeChanging()).<strong>addToBackStack</strong>(new TimeChanging().getClass().getName()).commit();</p> <p>And when you load your first fragment just don't replace add a fragment for HOME or default.</p> <p><strong><em>And to clear Back Stack,use:</em></strong></p> <p>public void clearBackStack(){</p> <pre><code> FragmentManager manager = getSupportFragmentManager(); Log.i("Fragment Count", String.valueOf(manager.getBackStackEntryCount())); if (manager.getBackStackEntryCount() &gt; 0) { FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0); manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE); } } </code></pre>
Need to match the repeated words and replace it with a new one using regex <p>I was trying to match a pattern from the below line in linux,</p> <pre><code>$(menu_no),ini_question3.vox,inv_question3.vox,inv_question3.vox,ini_question3.vox,to_question3.vox </code></pre> <p>From the above line i need to find the repeated word and replace the repetition with some other word,</p> <p>Ex: Here the repeated word is inv_question3.vox,inv_question3.vox i need this to be changed to inv_question3.vox,end.vox</p> <p>I was trying to do a find and replace in vim editor using the below command, but it didn't work,</p> <pre><code>:s/\(inv_question*.vox\),\(inv_question*.vox\)/\1,end.vox/g </code></pre>
<p>I'm not sure what you want to replace, but if you want to match duplicate string <code>inv_question3.vox</code>, you can try:</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>let string = '$(menu_no),ini_question3.vox,inv_question3.vox,inv_question3.vox,ini_question3.vox,to_question3.vox'; let result = string.replace(/(inv_question\d\.vox\,){2,}/, '$1,end.vox,'); console.log(result)</code></pre> </div> </div> </p> <ul> <li><code>\d</code>: only 1 number.</li> <li><code>{2,}</code>: 2 or more times</li> </ul> <p>Then, replacing with <code>$1,end.vox,</code> with <code>$1</code> is <code>inv_question3.vox</code></p>
nested ng-repeat that one depend on the other <p>I have an issue with angular, I want to use two nested ng-repeat in a data table where the first get the data, and the second get the name of field to be retrieved from the data (retrieved in the first ng-repeat) <br> here is what I tried to do with code :<br></p> <pre class="lang-js prettyprint-override"><code>&lt;table md-table flex-order-gt-sm &gt; &lt;thead md-head&gt; &lt;tr md-row &gt; //1st : get the name of fields, not a problem &lt;th md-column ng-repeat="field in fields"&gt;{{item.name}}&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody md-body&gt; &lt;tr md-row ng-repeat="item in items"&gt; &lt;td md-cell ng-repeat="field in fields" &gt; //here is the problem I want to get the item that it's field name is field {{item.{{field}} }}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p> for example if fields contain :{'a','b','c'}<br> and items contains {'a':'1','b':'2','c':'3'};<br> I want for example for the 1st iteration of {{item.{{field}} }} to return 1</p>
<p>use <code>toString()</code> to retireve the scope data in an scope object.</p> <pre><code>&lt;tr md-row ng-repeat="item in items"&gt; &lt;td md-cell ng-repeat="field in fields" &gt; {{item[field.toString()]}} &lt;/td&gt; &lt;/tr&gt; </code></pre> <p><a href="https://plnkr.co/edit/NDcmPG7RFvpNTtv8p4Y2?p=preview" rel="nofollow">HEre is the plunker</a></p>
retrieving multiple JSON files with jquery <p>I want to retrieve data from multiple json files.I am able to append data to the table from one of the json file. But when I wanted to pull the data from multiple json files it wont work. My code is:</p> <pre><code>var uri = 'sharepointmodel.json'; var uri2 = 'navisioncustomer.json'; function find(sharepointmodel) { var info = $('#KUNDE').val() $("#loader").show(); $.getJSON(uri).done(function (data) { var item = data.filter(function (obj) { return obj.name === info || obj.ID === info; })[0]; if (typeof item ==='undefined'){ alert("Ukendt navn eller ID"); } else if (typeof item !== 'undefined' || item !== null) { $("table.table").append("&lt;tr&gt;&lt;td&gt; " + item.name + item.url + "&lt;/td&gt;&lt;/tr&gt;"); } }).fail(function (jqXHR, textStatus, err) { $('#ERROR').text('Kan ikke oprette forbindelse til serveren!'); }).always(function (){ $("#loader").hide(); }); } function find(navisioncustomer) { var info2 = $('#KUNDE').val() $("#loader").show(); $.getJSON(uri2).done(function (data) { var item = data.filter(function (obj) { return obj.name === info2 || obj.ID === info2; })[0]; if (typeof item ==='undefined'){ alert("Ukendt navn eller ID"); } else if (typeof item !== 'undefined' || item !== null){ $("table.table2").append("&lt;tr&gt;&lt;td&gt; " + item.name + item.phone + "&lt;/td&gt;&lt;/tr&gt;"); } }).fail(function (jqXHR, textStatus, err) { $('#ERROR').text('Kan ikke oprette forbindelse til serveren!'); }).always(function (){ $("#loader").hide(); }); } </code></pre>
<p>Both of your function names are same, find(). That's why just one function is getting called and your data is getting appended from only one file.</p> <p>Either have different function names or have one function and pass uri variable to it e.g.</p> <pre><code> function find(json_uri) { var info = $('#KUNDE').val() $("#loader").show(); $.getJSON(json_uri).done(function(data) { var item = data.filter(function(obj) { return obj.name === info || obj.ID === info; })[0]; if (typeof item === 'undefined') { alert("Ukendt navn eller ID"); } else if (typeof item !== 'undefined' || item !== null) { $("table.table").append("&lt;tr&gt;&lt;td&gt; " + item.name + item.url + "&lt;/td&gt;&lt;/tr&gt;"); } }).fail(function(jqXHR, textStatus, err) { $('#ERROR').text('Kan ikke oprette forbindelse til serveren!'); }).always(function() { $("#loader").hide(); }); } </code></pre> <p>To append data to both you will have to make two calls</p> <pre><code>find(uri); fin(uri2); </code></pre>
Frequency tables by groups with weighted data in R <p>I wish to calculate two kind of frequency tables by groups with weighted data. </p> <p>You can generate reproducible data with the following code :</p> <pre><code>Data &lt;- data.frame( country = sample(c("France", "USA", "UK"), 100, replace = TRUE), migrant = sample(c("Native", "Foreign-born"), 100, replace = TRUE), gender = sample (c("men", "women"), 100, replace = TRUE), wgt = sample(100), year = sample(2006:2007) ) </code></pre> <p>Firstly, I try to calculate a frequency table of migrant status (Native VS Foreign-born) by country and year. I wrote the following code using the packages <code>questionr</code> and <code>plyr</code> : </p> <pre><code>db2006 &lt;- subset (Data, year == 2006) db2007 &lt;- subset (Data, year == 2007) result2006 &lt;- as.data.frame(cprop(wtd.table(db2006$migrant, db2006$country, weights=db2006$wgt),total=FALSE)) result2007 &lt;- as.data.frame(cprop(wtd.table(db2007$migrant, db2007$country, weights=db2007$wgt),total=FALSE)) result2006&lt;-rename (result2006, c(Freq = "y2006")) result2007&lt;-rename (result2007, c(Freq = "y2007")) result &lt;- merge(result2006, result2007, by = c("Var1","Var2")) </code></pre> <p>In my real database, I have 10 years so it takes times to apply this code for all the years. Does anyone know a faster way to do it ?</p> <p>I also wish to calculate the share of women and men among migrant status by country and year. I am looking for something like :</p> <pre><code>Var1 Var2 Var3 y2006 y2007 Foreign born France men 52 55 Foreign born France women 48 45 Native France men 51 52 Native France women 49 48 Foreign born UK men 60 65 Foreign born UK women 40 35 Native UK men 48 50 Native UK women 52 50 </code></pre> <p>Does anyone have an idea of how I can get these results?</p>
<p>You could do this by: making a function with the code you've already written; using <code>lapply</code> to iterate that function over all years in your data; then using <code>Reduce</code> and <code>merge</code> to collapse the resulting list into one data frame. Like this:</p> <pre><code># let's make your code into a function called 'tallyho' tallyho &lt;- function(yr, data) { require(dplyr) require(questionr) DF &lt;- filter(data, year == yr) result &lt;- with(DF, as.data.frame(cprop(wtd.table(migrant, country, weights = wgt), total = FALSE))) # rename the last column by year names(result)[length(names(result))] &lt;- sprintf("y%s", year) return(result) } # now iterate that function over all years in your original data set, then # use Reduce and merge to collapse the resulting list into a data frame NewData &lt;- lapply(unique(Data$year), function(x) tallyho(x, Data)) %&gt;% Reduce(function(...) merge(..., all=T), .) </code></pre>
python @property not overwrite class attribute <p>I'm confused with the class attribute. I understand that Python interpreter will search attr inside <code>cls.__dict_</code> (object attribute) first, If the attribute doesn't exists, it will looking for at class attributes. But in that case I dont know why the result below return None</p> <pre><code>class A(object): __attr = None @property def attr(self): return self.__attr class B(A): __attr = 1 c = B() print(c.attr) # None </code></pre>
<p>This isn't about <code>property</code>, but about the behaviour of attributes prefixed with <code>__</code>. This triggers name mangling, which is almost never what you want and behaves unexpectedly in an inheritance scenario. Don't use it.</p>
Random crash on capturing image on lower android versions <p>In my application i capture image from camera, on marshmallow it works fine, but on lower version it gives random crash. Sometimes it works fine, sometimes it not . Here is code which i am using in my app</p> <pre><code> String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String photoName = "Image_" + timeStamp + ".jpg"; String imageFile = new File(extStorageDirectory, photoName); Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) { // Create the File where the photo should go try { SingleTon.getInstance().imageFile.createNewFile(); } catch (IOException ex) { // Error occurred while creating the File ex.printStackTrace(); } // Continue only if the File was successfully created if ( SingleTon.getInstance().imageFile != null) { Log.e("Check1 ", SingleTon.getInstance().imageFile+";"); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(SingleTon.getInstance().imageFile)); ((Activity)context).startActivityForResult(takePictureIntent, Constant.CAMERA_PIC_REQUEST); } } </code></pre> <p>onActivity Result I am doing this :</p> <pre><code> Uri imagePathUri = Uri.parse(SingleTon.getInstance().imageFile.getPath()); String picturePath = compressImage(context, imagePathUri); </code></pre> <p>For compressing image </p> <pre><code> public static String compressImage(Context context, Uri imageUri) { String filePath = getRealPathFromURI(context, imageUri); Bitmap scaledBitmap = null; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile(filePath,options); int actualHeight = options.outHeight;//2988 int actualWidth = options.outWidth; //5312 float maxHeight = 1200.0f; float maxWidth = 1200.0f; /*float maxHeight = 816.0f; float maxWidth = 612.0f;*/ float imgRatio = actualWidth / actualHeight; float maxRatio = maxWidth / maxHeight; if (actualHeight &gt; maxHeight || actualWidth &gt; maxWidth) { if (imgRatio &lt; maxRatio) { imgRatio = maxHeight / actualHeight; actualWidth = (int) (imgRatio * actualWidth); actualHeight = (int) maxHeight; } else if (imgRatio &gt; maxRatio) { imgRatio = maxWidth / actualWidth; actualHeight = (int) (imgRatio * actualHeight); actualWidth = (int) maxWidth; } else { actualHeight = (int) maxHeight; actualWidth = (int) maxWidth; } } options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight); options.inJustDecodeBounds = false; options.inDither = false; options.inPurgeable = true; options.inInputShareable = true; options.inTempStorage = new byte[16*1024]; try{ bmp = BitmapFactory.decodeFile(filePath,options); } catch(OutOfMemoryError exception){ exception.printStackTrace(); } try{ scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888); } catch(OutOfMemoryError exception){ exception.printStackTrace(); } float ratioX = actualWidth / (float) options.outWidth; float ratioY = actualHeight / (float)options.outHeight; float middleX = actualWidth / 2.0f; float middleY = actualHeight / 2.0f; Matrix scaleMatrix = new Matrix(); scaleMatrix.setScale(ratioX, ratioY, middleX, middleY); Canvas canvas = new Canvas(scaledBitmap); canvas.setMatrix(scaleMatrix); canvas.drawBitmap(bmp, middleX - bmp.getWidth()/2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG)); ExifInterface exif; try { exif = new ExifInterface(filePath); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0); Log.d("EXIF", "Exif: " + orientation); Matrix matrix = new Matrix(); if (orientation == 6 || orientation == 0) { matrix.postRotate(90); Log.d("EXIF", "Exif: " + orientation); } else if (orientation == 3) { matrix.postRotate(180); Log.d("EXIF", "Exif: " + orientation); } else if (orientation == 8) { matrix.postRotate(270); Log.d("EXIF", "Exif: " + orientation); } scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true); } catch (IOException e) { e.printStackTrace(); } FileOutputStream out = null; String filename = getFilename(); try { out = new FileOutputStream(filename); scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); } catch (FileNotFoundException e) { e.printStackTrace(); } return filename; } </code></pre> <p>Kindly suggest what is wrong here. I need picture path(compressed and rotated). Sometimes it works perfectly fine and other times on saving image it goes back to app and restart calling activity.</p>
<blockquote> <p>This is because app gets restarted and its path gets null value because path is set only when i open camera</p> </blockquote> <p>Most likely, your process is being terminated while it is in the background. <a href="https://developer.android.com/guide/components/processes-and-threads.html#Lifecycle" rel="nofollow">This is perfectly normal behavior</a>. You will also have similar symptoms if the user rotates the screen. </p> <p>Save your path in the saved instance state <code>Bundle</code> via <code>onSaveInstanceState()</code>. Restore it from the saved instance state <code>Bundle</code> in <code>onCreate()</code> or <code>onRestoreInstanceState()</code>. Then, you will have your path when control returns to you via <code>onActivityResult()</code>. <a href="https://github.com/commonsguy/cw-omnibus/tree/master/Camera/FileProvider" rel="nofollow">This sample app</a> demonstrates the process, specifically with <code>ACTION_IMAGE_CAPTURE</code>.</p>
Decompile unity coroutine(ienumerator) correctly <p>I'm creating game with unity, I found my old game that project was deleted, and wanna get full C# code from there. I've used ILSpy to decompile to get it, everything was decompiled fine except coroutine(ienumerator). It decompile like C__Iterator, not correctly.(I've tried this with current project. Not decompile correctly) I think it's because of Iterator Block..Is there any tool that decompile it correctly? Is there any way to decompile coroutine(ienumerator) correctly?</p>
<p>No, there is no application that will decompile correctly the <code>IEnumerator</code> because this statement is syntactic sugar. This means that when the compiler find an iterator block it transalte the block iterator in something more complex that the disassembler is not able to reconstruct in the original way.</p>
How to disable location service programmatically in iOS? <p>I have the following:</p> <pre><code>class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate { ... let locationManager = CLLocationManager() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -&gt; Bool { if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.allowsBackgroundLocationUpdates = true locationManager.distanceFilter = 3000.0 locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print("my location: \(locations.first?.coordinate)") locationManager.stopUpdatingLocation() locationManager.delegate = nil } } </code></pre> <p>But even when the app is turned off i see the location service icon in status bar:</p> <p><a href="https://i.stack.imgur.com/MCuVq.png" rel="nofollow"><img src="https://i.stack.imgur.com/MCuVq.png" alt="enter image description here"></a></p> <p>I wonder if there is a way to disable it programmatically. Thanks in advance!</p>
<p>In your plist file, you must make sure the location row is <code>Privacy - LocationWhenInUseUsageDescription</code> not <code>Privacy - LocationAlwaysUsageDescription</code> </p>
Problems with focus() in an input radio in Firefox <p>I have discovered a problem in Firefox when you try to make focus in an input radio. It doesn't make focus in the input, unless you previously use tab to focus on the input before. After that it works correctly. Does anyone know how to solve it? Thank 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-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; Radio Button: &lt;input type="radio" id="myRadio"&gt; &lt;p&gt;Click the buttons below to give focus and/or remove focus from the radio button.&lt;/p&gt; &lt;button type="button" onclick="getFocus()"&gt;Get focus&lt;/button&gt; &lt;button type="button" onclick="loseFocus()"&gt;Lose focus&lt;/button&gt; &lt;script&gt; function getFocus() { document.getElementById("myRadio").focus(); } function loseFocus() { document.getElementById("myRadio").blur(); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
<p>It is working for me in Firefox (v47.0 and v47.0.1). The only thing is not highlighting it... But if you add some CSS like the following, you will see how it is working fine:</p> <p><code>input#myRadio:focus { outline: 7px solid yellow; }</code></p>
How to handle exception like download failed or invalid URL link or internet failure using TDownLoadURL? <p>I have an VCL app containing an object TDownloadUrl (VCL.ExtActns) used to download applications, my question is how to handle any kind of exception that restrict to download [for example:- like download failed or invalid URL link or internet failure or url not reachable or internet not available] using TDownLoadURL?.</p> <p>Thanks in advance</p>
<p><code>TDownloadURL</code> only defines 2 error messages, which are both declared in the <code>Vcl.Consts</code> unit:</p> <ul> <li><p><code>SUrlMonDllMissing</code>, which is raised when the Win32 <a href="https://msdn.microsoft.com/en-us/library/ms775123.aspx" rel="nofollow"><code>URLDownloadToFile()</code></a> function cannot be accessed at runtime.</p></li> <li><p><code>SErrorDownloadingURL</code>, which is raised when <code>URLDownloadToFile()</code> fails for any reason. Unfortunately, there is no way to differentiate <em>why</em> <code>URLDownloadToFile()</code> fails (although the <code>OnProgress</code> event may provide information about what it was doing just before the failure occurred).</p></li> </ul> <p>The error messages are resource strings and thus can be localized, so they could potentially be in any language, not just English. And they are raised using the general <code>SysUtils.Exception</code> class itself, not any derived types. However, you can use them for substring matching, at least:</p> <pre><code>uses ..., Vcl.ExtActns, Vcl.Consts, System.StrUtils; try DownloadURL1.Filename := ...; DownloadURL1.URL := ...; DownloadURL1.Execute; except on E: Exception do begin if StartsText(SUrlMonDllMissing, E.Message) then ... else if StartsText(SErrorDownloadingURL, E.Message) then ... else ... end; end; </code></pre> <p>If you need more detailed error information, you might try calling <code>URLDownloadToFile()</code> directly, as it returns an <code>HRESULT</code> value. However, be careful by the following gotcha in the documentation:</p> <blockquote> <p>URLDownloadToFile returns S_OK even if the file cannot be created and the download is canceled. If the szFileName parameter contains a file path, ensure that the destination directory exists before calling URLDownloadToFile. For best control over the download and its progress, an IBindStatusCallback interface is recommended.</p> </blockquote> <p>If that does not solve your issue, then you should use a different HTTP client API/library to perform the download, such as the HTTP client in Indy, ICS, Synapse, WinInet/WinHTTP, libCURL, etc.</p>
Hosted static website in AWS <p>I need help with AWS Host to website. </p> <p>I hosted my static site following the AWS recomendations. (using S3-bucket, Route-S3).</p> <p>However, in my site after my domain is appears ".s3-website-sa-east-1.amazonaws.com". How to do for not appears this after my domain?</p>
<p>You need to create an Amazon route53 entry as detailed here:</p> <p><a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/website-hosting-custom-domain-walkthrough.html#root-domain-walkthrough-switch-to-route53-as-dnsprovider" rel="nofollow">http://docs.aws.amazon.com/AmazonS3/latest/dev/website-hosting-custom-domain-walkthrough.html#root-domain-walkthrough-switch-to-route53-as-dnsprovider</a></p>
IF Statement in eBay API <p>I have a PHP code to use eBay API to get 5 results by keyword. </p> <p>I want to add an IF condition to show a headline <code>&lt;h2&gt;List of products&lt;/h2&gt;</code> only if there are results.</p> <pre><code> // Check to see if the request was successful, else print an error if ($resp-&gt;ack == "Success") { $results = ''; // If the response was loaded, parse it and build links foreach($resp-&gt;searchResult-&gt;item as $item) { $pic = $item-&gt;galleryPlusPictureURL; $link = $item-&gt;viewItemURL; $title = $item-&gt;title; $price = $item-&gt;sellingStatus-&gt;currentPrice; // For each SearchResultItem node, build a link and append it to $results $results .= "&lt;tr&gt;&lt;td style=\"text-align: center;\"&gt;&lt;img width=\"300\" src=\"$pic\"&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;a href=\"$link\" rel=\"nofollow\"&gt;$title&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td style=\"text-align: right;\"&gt;".$price." &amp;euro;&amp;nbsp;&amp;nbsp;&lt;div&gt;&lt;a href=\"$link\" rel=\"nofollow\"&gt;&lt;p class=\"bux\"&gt;&gt; Offer&lt;/p&gt;&lt;/a&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;"; } } // If the response does not indicate 'Success,' print an error else { $results = "&lt;h3&gt;Oops! The request was not successful. Make sure you are using a valid "; $results .= "AppID for the Production environment.&lt;/h3&gt;"; } echo "&lt;table&gt;".$results."&lt;/table&gt;"; </code></pre> <p>How do I edit the code above in order to show <code>&lt;h2&gt;List of products&lt;/h2&gt;</code> only if there is at least one result otherwise show nothing?</p>
<pre><code>// Check to see if the request was successful, else print an error if ($resp-&gt;ack == "Success") { $results = ''; // If the response was loaded, parse it and build links foreach($resp-&gt;searchResult-&gt;item as $item) { $pic = $item-&gt;galleryPlusPictureURL; $link = $item-&gt;viewItemURL; $title = $item-&gt;title; $price = $item-&gt;sellingStatus-&gt;currentPrice; // For each SearchResultItem node, build a link and append it to $results $results .= "&lt;tr&gt;&lt;td style=\"text-align: center;\"&gt;&lt;img width=\"300\" src=\"$pic\"&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;a href=\"$link\" rel=\"nofollow\"&gt;$title&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td style=\"text-align: right;\"&gt;".$price." &amp;euro;&amp;nbsp;&amp;nbsp;&lt;div&gt;&lt;a href=\"$link\" rel=\"nofollow\"&gt;&lt;p class=\"bux\"&gt;&gt; Offer&lt;/p&gt;&lt;/a&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;"; } if ( ! empty($results) ) $results = '&lt;h2&gt;List of products&lt;/h2&gt;'. $results; } // If the response does not indicate 'Success,' print an error else { $results = "&lt;h3&gt;Oops! The request was not successful. Make sure you are using a valid "; $results .= "AppID for the Production environment.&lt;/h3&gt;"; } echo "&lt;table&gt;".$results."&lt;/table&gt;"; </code></pre>
Smarty Template date_format gives unpredictable results <p>I am passing a timestamp into a Smarty Template, and using <code>date_format</code> gives unpredictable results. Here's an example template that demonstrates the problem most elegantly:</p> <pre><code>{"1456602208"} {"1456602208"|date_format} {"1432808316"} {"1432808316"|date_format} </code></pre> <p>The output of this template:</p> <pre><code>1456602208 Oct 19, 2208 1432808316 May 28, 2015 </code></pre> <p>The second date is correctly formatted. The first one, however, should be </p> <pre><code>Feb 27, 2016 </code></pre> <p>Why is this?</p>
<p>The best way to avoid this is to cast to <code>int</code> the timestamp. Now it's a numeric <code>string</code>.</p> <p>Smarty did some changes in 2.6.10 to use all numeric input values as timestamp, but before was not always the case. </p> <p>As I can see the first timestamp ends in <code>2208</code> and also the year returned for that timestamp is <code>2208</code>, so I think smarty think it's not a timestamp, but a date formatted somehow.</p> <p>See more <a href="http://www.smarty.net/docsv2/en/language.modifier.date.format.tpl" rel="nofollow">here (smarty doc)</a> </p>
Count blanks row by row <p>I need an auto-expanding formula to count blank cells in each row, as long as there are values in <code>B</code>. I've tried <code>=ARRAYFORMULA(IF(ISBLANK(B2:B),IFERROR(1/0),COUNTBLANK(E2:2)))</code> and thereby managed the expansion, but it keeps counting <code>E2:2</code> and not the actual row the array expands to.</p> <p><a href="https://i.stack.imgur.com/klDni.png" rel="nofollow"><img src="https://i.stack.imgur.com/klDni.png" alt=""></a></p>
<p>Try something like this</p> <pre><code>=ArrayFormula(IF(LEN(B2:B100),MMULT(N(ISBLANK(B2:100)), TRANSPOSE(column(B2:2)^0)),)) </code></pre> <p>Change range to suit. </p>
File path when working with One Drive for Buisiness <p>I have a MS Word Add-In that works with a file located in the local synchronized area of One Drive for Business.</p> <p>I create the file at C:..\OneDrive..\MyDir\File.docx Some point later I create a FileInfo object:</p> <pre><code>var file = new FileInfo(doc.FullName); </code></pre> <p>This works fine when I debug. However when I run the code normally, doc.FullName is the web path <a href="https://..-my.sharepoint.com/personal/../MyDir/File.docx" rel="nofollow">https://..-my.sharepoint.com/personal/../MyDir/File.docx</a> Which breaks the FileInfo object.</p> <p>Why would MS Word return the uri instead of the local file path? and why is MS Word inconsistent when debugging my add-in? and any thoughts on whether I can code around this?</p> <p>-- Edit --</p> <p>There are three behaviours:</p> <ol> <li><p>Run Winword.exe (doc.FullName = <a href="http://[OneDrive]" rel="nofollow">http://[OneDrive]</a>)</p></li> <li><p>Run Winword.exe and attach to process in Visual Studio (doc.FullName = <a href="http://[OneDrive]" rel="nofollow">http://[OneDrive]</a>)</p></li> <li><p>Press F5 in Visual Sudio to debug (doc.FullName = C:..\OneDrive..) </p></li> </ol>
<p>Word can open both local files and cloud files. When the latest OneDrive sync client is installed and you open a local file that's sync'd to the cloud, Word will discover its cloud URL and prefer using that, because it lights up cloud-based features like coauthoring. If it's possible for your plugin to be tweaked to support cloud-only files that don't have a local copy, then that solution will probably work for OneDrive-sync'd file as well.</p>
How to make expandable div to show first element and toggle rest <p>I have few sections on my webpage with different type of news stories. Some with images, some without (just text). I want be able to display the first paragraph or first div of each story and then on click toggle the whole content of the div (story). </p> <p>I've found this bit of code on CSS Tricks website:</p> <pre><code>var news = 2; hidenews = "- Hide news archive"; shownews = "+ Show news archive"; $(".archive").html( shownews ); $(".news:not(:lt("+news+"))").hide(); $(".archive").click(function (e) { e.preventDefault(); if ($(".news:eq("+news+")").is(":hidden")) { $(".news:hidden").show(); $(".archive").html( hidenews ); } else { $(".news:not(:lt("+news+"))").hide(); $(".archive").html( shownews ); } }); &lt;div class="news"&gt;First news&lt;/div&gt; &lt;div class="news"&gt;Second news&lt;/div&gt; &lt;div class="news"&gt;Third news&lt;/div&gt; &lt;a class="archive" href="#"&gt;&lt;/a&gt; </code></pre> <p>It works great, but only with one div. With multiple ones on the page when I click show button it opens all the divs. </p> <p>Can anyone help me to edit the code so only one story opens on click not all of them, please?</p>
<p>You need to have <code>toggle</code> button for each element.</p> <pre><code>//Hide all content $('.content').hide(); $('.archive').click(function(){ //Get content DIV var content = $(this).parent('.news').find('.content'); //Content toggle content.toggle(); //Show / Hide adjusted $(this).text(content.is(":visible") ? 'Hide' : 'Show'); }); </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.content').hide(); $('.archive').click(function(){ var content = $(this).parent('.news').find('.content'); content.toggle(); $(this).text(content.is(":visible") ? 'Hide' : '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;div class="news"&gt;First news &lt;div class="content"&gt;First news Content&lt;/div&gt; &lt;a class="archive" href="#"&gt;Show&lt;/a&gt; &lt;/div&gt; &lt;div class="news"&gt;Second news &lt;div class="content"&gt;Second news Content&lt;/div&gt; &lt;a class="archive" href="#"&gt;Show&lt;/a&gt; &lt;/div&gt; &lt;div class="news"&gt;Third news &lt;div class="content"&gt;Third news Content&lt;/div&gt; &lt;a class="archive" href="#"&gt;Show&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
Facing crash in samsung galaxy note 7 <p>Facing crash on galaxy note 7</p> <p><code>Caused by android.database.sqlite.SQLiteCantOpenDatabaseException: unable to open database file (code 2062): , while compiling: PRAGMA journal_mode ################################################################# Error Code : 2062 (SQLITE_CANTOPEN_EMFILE) Caused By : Application has opened two many files. Maximum of available file descriptors in one process is 1024 in default. (unable to open database file (code 2062): , while compiling: PRAGMA journal_mode) #################################################################</code></p>
<p>You have opened too many files.</p> <p>Your code forgets to close all its database objects, or other files.</p>
for /f %%I was unexpected at this time <p>I'm trying to write a script to copy the latest file. I got this command from the net:</p> <pre><code>FOR /F "delims=|" %%I IN ('DIR "X:\Dirs\*.rar" /B /O:D') DO SET NewestFile=%%I copy "%NewestFile%" "J:\Personal\Gastos\dirs" </code></pre> <p>It outputs an error:</p> <blockquote> <p>%%I was unexpected at this time.</p> </blockquote> <p>Does anyone know why that happens and how to correct it?</p> <p>Thanks</p> <p>Jeraisel</p>
<p>Try this in a batch file:</p> <pre class="lang-bat prettyprint-override"><code>@ECHO OFF (SET SrcDir=X:\Dirs) IF /I "%CD%" NEQ "%SrcDir%" PUSHD "%SrcDir%" SET "NewestFile=" FOR /F "DELIMS=" %%I IN ('DIR/B/OD *.rar') DO SET "NewestFile=%%I" IF DEFINED NewestFile (IF EXIST "J:\Personal\Gastos\dirs\" ( COPY "%NewestFile%" "J:\Personal\Gastos\dirs")) </code></pre>
How to set ios App push notfication sound with custom tone in Objective C? <p>In My App I need notification other than default, how it possible? I have try many code but i didn't get success. Notification send from Php.</p>
<p>When you are sending a payload of pushnotification. You have to mention sound file name. </p> <p>What ever sound you want to play, you have to add that file in project directory. Mention this file name on payload of push notification. Your sound is playing when push notification is receive. </p> <pre><code>{ "aps" : { "alert" : "Message received from Bob" "sound" : "give your file name like as opening.mp4" }, } </code></pre> <p>Feedback me it is working or not?</p>
Find a Twitter mention using Regex in Java (with a twist) <p>I need to create a regex pattern to find mentions in a class called Tweets. In this case, the valid characters after the '@' are: (A-Z or a-z), digits, underscore ("_"), or hyphen ("-"). The difference with classic Twitter usernames is that pattern should allow @--- or @___ or @00000, but also, when the char before '@' or after the name is not in the valid character list it should return the mention as valid (so not only white-spaces). </p> <p>Strings like:</p> <p>$$$$$@john$$$$$$ or %%%%@john%%% </p> <p>should find @john as a valid mention since % isn't a valid name. </p> <p>@@@@@john@@@@@ should also return @john.</p> <p>Using <a href="http://regexr.com/" rel="nofollow">http://regexr.com/</a> I created this pattern:</p> <p><code>@[a-zA-Z0-9_-]*</code> </p> <p>which in the mentioned page passes most requirements except @@@@john@@@ and richard@gmail.com which should ignore (since it has richard before) but instead turns into @gmail.</p> <p>After that I improved this pattern</p> <p><code>(?&lt;=^|(?&lt;=[^a-zA-Z0-9-_\\.]))@[A-Za-z0-9_-]+</code></p> <p>Tested in the same page (and also this one to verify results: <a href="http://myregexp.com/signedJar.html" rel="nofollow">http://myregexp.com/signedJar.html</a>) Not sure why this page shows results that my code doesn't. I include my Java implementation just in case:</p> <pre><code>Set&lt;String&gt; users = new HashSet&lt;&gt;(); // to avoid repeated mentions for (Tweet t: tweets){ String line = t.getText(); String pattern = "(?&lt;=^|(?&lt;=[^a-zA-Z0-9-_\\.]))@[A-Za-z0-9_-]+"; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(line); if (m.find()){ users.add(m.group().toLowerCase()); } </code></pre> <p>And these are my test cases (all should return a mention except last two):</p> <pre><code>@tony $$@yahoo$$ john @john john @joules- @john-cassidy %%@jake%% @@@jake@@@ dude$@jake$$ $$$@jack$$$ @@@jake@@@ @john4 @jake2$ @johN3 @rock-smith @John @gmail.com //should not return but does: wrong richard@mit.edu //should not find and it doesn't: good </code></pre> <p>From what I understand this: <strong>(?&lt;=^|(?&lt;=[^a-zA-Z0-9-<em>\.]))</strong> is the *lookbehind* and I'm lacking the *lookahead* (not sure how to lookahead AFTER the valid chars) and cant understand the explanation about lookahead at <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">http://www.regular-expressions.info/lookaround.html</a> to allow these chars: <strong>[A-Za-z0-9</em>-]</strong> but not the rest (to ignore the match @gmail.com and avoid @gmail as return) .</p> <p>Thanks in advance for your help. I have just 6 months in Java so this is the second time I use Regex and this feels like a complex one.</p>
<p>Adding positive lookahead to the end of original regex should help:</p> <p>(?&lt;=^|(?&lt;=[^a-zA-Z0-9-<em>\.]))@[A-Za-z0-9</em>-]+<strong>(?=[^a-zA-Z0-9-_\.])</strong></p>
Why do I get a multilevel array? <p>I need an array with a list of names so I simply get them from the database, but when I printed the array I noticed it stores every name into a seperate array. Why is that, and how can I just store them in one?</p> <p>My code:</p> <pre><code>&lt;? // Product names $producten = "SELECT `naam` FROM `producten`"; $productencon = $conn-&gt;query($producten); $productencr = array(); while ($productencr[] = $productencon-&gt;fetch_array()); echo '&lt;pre&gt;'; print_r($productencr); echo '&lt;/pre&gt;'; ?&gt; </code></pre> <p>The output of that printed array is this:</p> <p><a href="https://i.stack.imgur.com/bkPHe.png" rel="nofollow"><img src="https://i.stack.imgur.com/bkPHe.png" alt="enter image description here"></a></p>
<p>Because <code>fetch_array</code> will return both the assoc name of the column and the numeric index.</p> <p>If you want only the name of the column you should use: <code>fetch_assoc</code> or if you want only numeric you should use <code>fetch_row</code></p> <p><code>fetch_array</code> is a combination of both <code>fetch_assoc</code> and <code>fetch_row</code></p> <p>If you want to keep <code>fetch_array</code> you can also specify as first param the result type. Default is <code>MYSQLI_BOTH</code>.</p> <p>You check more here: <a href="http://php.net/manual/en/mysqli-result.fetch-array.php" rel="nofollow">http://php.net/manual/en/mysqli-result.fetch-array.php</a></p>
Do I need to extend FirebaseInstanceIdService to subscribe to FCM Topics? <p>I want to manage topic subscription from the client (android app). I am currently doing it at activity onCreate(). I am wondering if the right way is to subscribe / unsubscribe at InstanceIdService::onTokenRefresh() or at any time convenient (on button click, etc).</p> <p><strong>In short, if I manage topic subscription at the client side (no server), do I still have to bother with InstanceIdService?</strong></p> <p>Different sources of documentation provide different take on Firebase Cloud Messaging (FCM) topic subscription. Some mention InstanceIdService, some not. Here they are:</p> <ol> <li>Firebase Guide on <a href="https://firebase.google.com/docs/notifications/android/console-topics">Send Topic Messages with Firebase Console</a></li> </ol> <p>It does not mention InstanceIdService when talking about topic subscriptions.</p> <blockquote> <p>Once you've completed the setup tasks, you can add client code to subscribe to a topic and then handle messages sent to the topic.</p> <p>Client apps can subscribe to any existing topic, or they can create a new topic. When a client app subscribes to a new topic name (one that does not already exist for your Firebase project), a new topic of that name is created in FCM and any client can subsequently subscribe to it.</p> <p>To subscribe to a topic, the client app calls Firebase Cloud Messaging subscribeToTopic() with the FCM topic name:</p> </blockquote> <pre><code>FirebaseMessaging.getInstance().subscribeToTopic("news"); </code></pre> <ol start="2"> <li><a href="https://codelabs.developers.google.com/codelabs/firebase-android/#8">Firebase Android Codelab</a></li> </ol> <blockquote> <p>The class MyFirebaseInstanceIdService will be a service used to handle FCM logic. This service is used to alert the application when a new InstanceID token is generated, and to retrieve the generated token.</p> <p>Modify it to extend FirebaseInstanceIdService and override the onTokenRefresh method to subscribe to a topic. Use the following code to update the onTokenRefresh method in MyFirebaseInstanceIdService to look like this:</p> </blockquote> <pre><code>public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService { private static final String TAG = "MyFirebaseIIDService"; private static final String FRIENDLY_ENGAGE_TOPIC = "friendly_engage"; /** * The Application's current Instance ID token is no longer valid * and thus a new one must be requested. */ @Override public void onTokenRefresh() { // If you need to handle the generation of a token, initially or // after a refresh this is where you should do that. String token = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "FCM Token: " + token); // Once a token is generated, we subscribe to topic. FirebaseMessaging.getInstance() .subscribeToTopic(FRIENDLY_ENGAGE_TOPIC); } } </code></pre> <ol start="3"> <li><a href="https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MainActivity.java">Firebase quickstart project on github</a></li> </ol> <p>It uses InstanceIdService, but topic subscription does not happen there. It is done simply in client as part of button click in an activity:</p> <pre><code>Button subscribeButton = (Button) findViewById(R.id.subscribeButton); subscribeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // [START subscribe_topics] FirebaseMessaging.getInstance().subscribeToTopic("news"); // [END subscribe_topics] // Log and toast String msg = getString(R.string.msg_subscribed); Log.d(TAG, msg); Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } }); </code></pre> <p>The comment at InstanceIdService code suggests to manager subscription <code>onTokenRefresh()</code></p> <pre><code>@Override public void onTokenRefresh() { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // Instance ID token to your app server. sendRegistrationToServer(refreshedToken); } </code></pre>
<p>As you already know, <code>FirebaseInstanceId</code> is probably a singleton class, where you retrieve your registration token. So I think the <code>subscribeToTopic()</code> method, since only the name of the topic is passed, you can presume that it already calls an instance of the <code>FirebaseInstanceId</code> itself or then just send in a request towards the FCM servers with the corresponding registration token and the topic it should be subscribed to.</p> <p><strong>Long story short</strong>, I don't think it's a requirement for you to extend the <code>FirebaseInstanceIdService</code> to call <code>subscribeToTopic()</code>, however, I think it's essential because (<em>as described in the <a href="https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceIdService" rel="nofollow">docs</a></em>) it is the:</p> <blockquote> <p>Base class to handle Firebase Instance ID token refresh events.</p> </blockquote> <hr> <p>For your other inquiries.</p> <blockquote> <p><em>I want to manage topic subscription from the client (Android app). I am currently doing it at activity <code>onCreate()</code>. I am wondering if the right way is to subscribe / unsubscribe at <code>InstanceIdService::onTokenRefresh()</code> or at any time convenient (on button click, etc)?</em></p> </blockquote> <p>I think doing it in <code>onCreate()</code> is okay. If you see my answer <a href="http://stackoverflow.com/a/40055267/4625829">here</a>, @FrankvanPuffelen mentioned:</p> <blockquote> <p>subscribing to topics on app start is fine.</p> </blockquote> <p>However, I think it's also good to add in a <code>subscribeToTopic()</code> call in <code>onTokenRefresh()</code>, so that as soon as a new token is provided for the app instance, you'll immediately subscribe it accordingly.</p> <p><strong>Note</strong> that behavior I'm thinking here is that when a registration token is invalidated, it's subscription is also lost and that adding <code>subscribeToTopic()</code> in <code>onRefreshToken()</code> will immediately re-subscribe them for you (<em>of course this still depends in your implementation on which topic you want to subscribe it</em>).</p>
Create object with code in VB6 <p>i have a program in Visual Basic 6, and i need create a button in my program with code.</p> <p>I write this code:</p> <pre><code>private sub Pulso_click() dim boton as CommandButton set boton = new CommandButton boton.width = 100 boton.height = 30 boton.caption = "MiBoton" End Sub </code></pre> <p>but don't run. i have "El uso de la palabra clave New no es valido", in english "keyword New use invalid".</p> <p>This run in Visual Basic 6</p> <p>Where is the problem??? Thanks</p>
<p>This code works for me</p> <pre><code> Option Explicit ' Dim WithEvents Cmd1 As CommandButton ' Private Sub Form_Load() Set Cmd1 = Controls.Add("vb.commandbutton", "Cmd1") Cmd1.Width = 2000 Cmd1.Top = Me.Height / 2 - Cmd1.Height / 2 - 100 Cmd1.Left = Me.Width / 2 - Cmd1.Width / 2 - 100 Cmd1.Caption = "Dynamic Button" Cmd1.Visible = True End Sub ' Private Sub Cmd1_click() MsgBox "I have been Created Dynamically at Run-time", _ , "Dynamic Controls" End Sub ' </code></pre> <p><a href="https://i.stack.imgur.com/AHJuy.png" rel="nofollow"><img src="https://i.stack.imgur.com/AHJuy.png" alt="enter image description here"></a></p> <p>Works with no problems for me, I hope this code works for you, You can also use indexes create one command button and set the index to zero then on form load or whenever you want it to show </p> <pre><code>Load Command1(1) Command1(1).Caption = "command2" Command1(1).Left = Command1(0).Left + Command1(0).Width Command1(1).Top = Command1(0).Top Command1(1).Visible = True </code></pre> <p>You get the point, good luck, I use indexes myself lots of times when I have a bunch of controls it's loads faster this way, enjoy.</p>
PowerShell winforms Tab selected index changed event <p>I have designed the GUI using WinForms in PowerShell as follows</p> <pre><code>Add-Type -Assembly 'System.Windows.Forms' $form = New-Object Windows.Forms.Form $TabControl = New-Object System.Windows.Forms.TabControl $tabPage1 = New-Object System.Windows.Forms.TabPage $tabPage1.Name = "Tab1" $tabPage1.Text = "Tab1" $tabPage1.Width = 500 $tabPage1.Height = 500 $tabPage2 = New-Object System.Windows.Forms.TabPage $tabPage2.Name = "Tab2" $tabPage2.Text = "Tab2" $tabPage2.Width = 500 $tabPage2.Height = 500 $TabControl.TabPages.Add($tabPage1) $TabControl.TabPages.Add($tabPage2) $TabControl.SelectedIndexChanged($TabControl_SelectedIndexChanged) $TabControl_SelectedIndexChanged { ({$selectedTab = $TabControl.SelectedTab; [System.Windows.Forms.MessageBox]::Show($selectedTab)}) } $form.Controls.Add($TabControl) </code></pre> <p>I would like to handle the selectedindex changed event but I couldn't, I got the following error with the above code</p> <p><code>Method invocation failed because [System.Windows.Forms.TabControl] does not contain a method named 'SelectedIndexChanged'.</code> so can some one help me</p>
<p>Figured it out this is how I need to add the event</p> <p>instead of this</p> <pre><code>TabControl.SelectedIndexChanged($TabControl_SelectedIndexChanged) $TabControl_SelectedIndexChanged { ({$selectedTab = $TabControl.SelectedTab; [System.Windows.Forms.MessageBox]::Show($selectedTab)}) } $TabControl.Add_SelectedIndexChanged({ $selectedTab = $TabControl.SelectedTab [System.Windows.Forms.MessageBox]::Show($selectedTab.TabIndex) }) </code></pre>
Eclipse library jar files in Android studio <p><a href="https://i.stack.imgur.com/K0c8H.png" rel="nofollow">image here</a></p> <p>In the picture you can see the libs folder and it contans two sub folders and a jar file named unity classes. I want to merge this project with my android studio project so in this case i want to copy my eclipse project java files, res folder and libs and everything. I copied everything in my android studio project but confused that how to copy libs folder from eclipse to android studio. I know that there is a compile ' ' option in build.gradle but what to write their? I am a newbie so please tell me what to do? I just want these libs folder to be written in android studio</p>
<p>I found the answer finally. Its simple and i just have to add this line</p> <pre><code>dependencies { compile fileTree(dir: 'libs', include: '*.jar') } </code></pre>
Pandas Create Column with Groupby and Sum with additional condition <p>I'm trying to add a new column in pandas DataFrame after grouping and with additional conditions </p> <pre><code>df = pd.DataFrame({ 'A' :[4,5,7,8,2,3,5,2,1,1,4,4,2,4,5,1,3,9,7,9], 'B' :[9,5,7,8,3,3,5,2,1,1,4,4,2,4,5,1,3,5,7,9], 'C' :[9,5,7,8,3,3,5,2,1,1,4,4,2,4,5,1,3,5,7,9], 'D' :[1,0,1,0,1,1,0,0,1,1,0,0,0,1,1,1,0,0,1,0] }) df1 = df.groupby(['A', 'B'], as_index=False).transform('sum') df1 = df.join(df.groupby(['A'])['C'].sum(), on='A', rsuffix='_inward') df1 </code></pre> <p>In above query it is able to sum and give output but how do I add condition for <code>df['D'] == 1</code></p> <p>Expected output </p> <pre><code> A B C D C_inward 0 4 9 9 1 13 2 7 7 7 1 14 4 2 3 3 1 3 5 3 3 3 1 3 8 1 1 1 1 3 9 1 1 1 1 3 13 4 4 4 1 13 14 5 5 5 1 5 15 1 1 1 1 3 18 7 7 7 1 14 </code></pre>
<p>You can add <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p> <pre><code>mask = df['D'] == 1 df1 = df[mask].join(df[mask].groupby(['A'])['C'].sum(), on='A', rsuffix='_inward') print (df1) A B C D C_inward 0 4 9 9 1 13 2 7 7 7 1 14 4 2 3 3 1 3 5 3 3 3 1 3 8 1 1 1 1 3 9 1 1 1 1 3 13 4 4 4 1 13 14 5 5 5 1 5 15 1 1 1 1 3 18 7 7 7 1 14 </code></pre>
Can someone explaint what this code do? <p>I'm trying to figure out what this code but no luck. I need some explanations</p> <pre><code>signed char c = '0'; for(; c &gt; 0; c++); printf("%d", c); </code></pre> <p>output is -128, when I change the sign to "less then" output is 48, why?</p>
<p><a href="http://www.asciitable.com/" rel="nofollow">http://www.asciitable.com/</a></p> <p>The character <code>'0'</code> has the numerical value 48.</p> <p>You count this up until your value is below 0 so in a <code>signed char</code> that happens on overflow to -128. edit:(this is undefined behavior, but the common result, this doesn't mean it happens every time, this means DON'T DO IT)</p> <p>If you evaluate with less than 0 then 48 is not less 0 so you don't count up c.</p> <p>And as kerrek pointed out, you have undefined behavior because you produce an overflow on a signed variable.</p>
How to check key value is exist in an array using PHP <p>I need one help. I need to check some key value is exist in an array using PHP. I am explaining my code below.</p> <pre><code>$comment = json_encode(array(array('day_id' =&gt; '1', 'comment' =&gt; 'vodka0'),array('day_id' =&gt; '', 'comment' =&gt; ''), array('day_id' =&gt; '3', 'comment' =&gt; 'vodka3'),array('day_id'=&gt;'4','comment'=&gt;'hytt'))); $arrComment = json_decode($comment, true); </code></pre> <p>Here i need to check some <code>day_id</code> key has value or all <code>day_id</code> key has blank value.Please help.</p>
<p>Use <a href="http://php.net/manual/en/function.array-column.php" rel="nofollow"><code>array_column</code></a> and <a href="http://php.net/manual/en/function.array-filter.php" rel="nofollow"><code>array_filter</code></a> to check this:</p> <pre><code>// extract all day_id columns $dayId = array_column($arrComment, 'day_id'); // filter the empty values $filtered = array_filter($dayId); if (empty($filtered)) { echo "All Day Ids are empty."; } else { echo "Some or all of them have some value."; } </code></pre>
How to change viewBox to center an element in svg <p>I have a svg map which contains a bunch of circles, on click on a circle I want to make the circle the center of the canvas. I am using <strong>RaphaelJS</strong> to work with svg.</p> <p>I have tried <code>paper.setViewBox(width / 2 - cx, height / 2 - cy, width, height, true)</code>, where <em>cx</em> and <em>xy</em> are the coordinates of the selected circle in my svg file, but it doesn't work.</p>
<p>Your calculations look wrong to me. I would expect it to be:</p> <pre><code>paper.setViewBox(cx - width / 2, cy - height / 2, width, height, true) </code></pre>
Method with same name and different return type is achieved in c# but not in java <p>I am new to JAVA environment, am facing issue while trying to implement method with same name and different return type. In C# I have used method hiding concept to achieve this. Is there any better way to implement the same in JAVA. Please find the code snippet for reference. Please advise me in this</p> <p>C#:</p> <pre><code>class Shape { public int Width { get; set; } public int Height { get; set; } public void Print() { Console.WriteLine("Base class is called"); } } class Table: Shape { public int m_tableHeight; public int m_tableWidth; public string m_modle; public Table(int tableWidth, int tableHeight,string modle) { m_tableHeight = tableHeight; m_tableWidth = tableWidth; m_modle = modle; } public new string Print() { return m_modle; } } </code></pre> <p>JAVA:</p> <pre><code>public class Shape { public int getWidth()throws Exception{ return getWidth(); } public void setWidth(int value)throws Exception{ setWidth(value); } public int getHeight()throws Exception{ return getHeight(); } public void setHeight(int value)throws Exception{ setHeight(value); } public void Print()throws Exception{ System.out.println("Base class is called"); } } public class Table extends Shape { public int m_tableHeight; public int m_tableWidth; public String m_modle; public Table(int tableWidth,int tableHeight,String modle)throws Exception{ m_tableHeight=tableHeight; m_tableWidth=tableWidth; m_modle=modle; } //Throws error as return type is incompatible with shape.print() public String Print()throws Exception{ return m_modle; } } </code></pre>
<p>In Java methods are identified by there method descriptor: the method descriptor consists of class and method name as well as the type of the method parameters, but the return type is not part of the method descriptor!</p> <p>So in Java you can not have two methods with same name, same parameters (but different return type) in one class. (Of course on method can override an other method and narrow* the return type, but this is overriding not overloading)</p> <p><em>(* you can only narrow them (override a method that returns Number with an Method that returns Double) but you can not change them and you can not override a method that return void with an method that return something else)</em></p>
Execute shell script from scala aplication <p>I want to execute the sh file from scala application, Lets say i have createPassword.sh file , I need to invoke this sh file from scala application and get the output back.</p> <p>How can i achieve through scala application ?</p>
<p>This should do the trick if the script is in the current working directory (otherwise specify the full path of the script)</p> <pre><code>import sys.process._ val result = "./createPassword.sh" !! </code></pre> <p><code>result</code> is then a String containing the standard output (and standard error)</p> <p>EDIT: If you want to use <code>ProcessBuillder</code> from Java SE7, you can also use this in scala:</p> <pre><code> import java.io.{BufferedReader, InputStreamReader} val p = new ProcessBuilder("/bin/bash","createPassword.sh") val p2 = p.start() val br = new BufferedReader(new InputStreamReader(p2.getInputStream())) var line:String = "" while ({line = br.readLine(); line!= null}) { println(line) } </code></pre>
how to load a component programatically to one div in angular 2 <p>i am very new to angular 2, i have some set of dynamically created divs i want to load per-defined components to those div based on user selection. i tried many blogs to load component dynamically but none of them are clear and simple. </p> <p>what i'am expecting is to know how to load one component to a div on click of a button.</p> <p>for example</p> <pre><code>@Component({ selector: 'container', template: `&lt;div id="container"&gt;// need to place the component here on click of a button //&lt;/div&gt;` }) </code></pre> <p>if anybody can provide a plunker or solution is highly appreciated</p>
<p>Define a html component using # inside template</p> <pre><code>&lt;div #container &gt;&lt;/div&gt; </code></pre> <p>Now you can access this container inside the component class</p> <pre><code>this.container.innerHTML="YOUR CONTENT"; </code></pre>
How to mock Spring Message Resource inside another Mock class with Mockito? <p>In my test when I assert de exception message I'm getting <code>null</code></p> <p>I'm not getting mock the message inside Service.... :(</p> <p>I have:</p> <p>My test:</p> <pre><code>@RunWith(MockitoJUnitRunner.class) public class ServiceImplTest { @InjectMocks private ServiceImpl service; @Mock private Message message; public static final String REQUIRED_FIELD = "required.field"; @Before public void setUp() { when(message.getMessage(eq(REQUIRED_FIELD), any(List.class))).thenReturn(REQUIRED_FIELD); System.out.println(message.getMessage(REQUIRED_FIELD, new ArrayList())); } @Test(expected = MyException.class) public void testCancel_shouldValidCancellation_and_ThrowTicketException_with_RequiredFieldMessage() { try { Object object = //... new object service.do(object); } catch (Exception e) { assertEquals(REQUIRED_FIELD, e.getMessage()); // &lt;-- e.getMessage return null!!! } } } </code></pre> <p>My service:</p> <pre><code>@Service public class ServiceImpl implements Service { @Autowired Message message; @Override public Object do(Object object) { if(object.getSomeAttribute() == null)) { throw new MyException(message.getMessage("required.field", "attribute")); } //doSomething... return something; } } </code></pre> <p>In the <code>setUp()</code> of test the <code>printLn()</code> prints <code>required.field</code> but I can't use <code>message</code> of <code>Service</code>!!</p> <p>Can someone help me?</p>
<p>It is hard tell for sure, without knowledge about the interface of <code>Message</code>, but it is easy to spot that you configure mock object to stub method with signature <code>getMessage(String, List)</code>:</p> <pre><code>when(message.getMessage(eq(REQUIRED_FIELD), any(List.class))).thenReturn(REQUIRED_FIELD); </code></pre> <p>However, <code>ServiceImpl</code> uses <code>getMessage(String, String)</code>. The default value which is returned by mock in this case is <code>null</code>. You have to configure mock object properly.</p>
XMPPError: bad-request - modify error create new user using smack library 4.1.8 and openfire <p>i have been developing a chat application using smack client library 4.1.8 and xmpp server(openfire server) but while trying to create new user using Accountmanger class it raises and exception "XMPPError: bad-request - modify"</p> <pre><code>XMPPTCPConnectionConfiguration conf = XMPPTCPConnectionConfiguration.builder() .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled) .setHost("127.0.0.1") .setDebuggerEnabled(true) .setPort(5222) .setSendPresence(true) .setServiceName("127.0.0.1") .build(); AbstractXMPPConnection conn2 = new XMPPTCPConnection(conf); //conn2.login(); conn2.connect(); AccountManager accountManager = AccountManager.getInstance(conn2); if (accountManager.supportsAccountCreation()) { accountManager.sensitiveOperationOverInsecureConnection(true); accountManager.createAccount("qidus", "123456"); conn2.login("qidus", "123456"); } } catch (SmackException | IOException | XMPPException e) { e.printStackTrace(); } </code></pre> <p>and the exception is this</p> <pre><code>04:01:41 AM SENT (0): &lt;iq to='127.0.0.1' id='aYej1-3' type='get'&gt;&lt;query xmlns='jabber:iq:register'&gt;&lt;/query&gt;&lt;/iq&gt; </code></pre> <p>04:01:41 AM RECV (0): </p> <pre><code>org.jivesoftware.smack.XMPPException$XMPPErrorException: XMPPError: bad-request - modify at org.jivesoftware.smack.XMPPException$XMPPErrorException.ifHasErrorThenThrow(XMPPException.java:135) at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:232) at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:213) at org.jivesoftware.smackx.iqregister.AccountManager.getRegistrationInfo(AccountManager.java:332) at org.jivesoftware.smackx.iqregister.AccountManager.supportsAccountCreation(AccountManager.java:144) at chat.Chat$1.run(Chat.java:46) </code></pre>
<p>You need to set properly Service Name. You can chek your serviceName in Openfire through admin panel (127.0.0.1:9090) it's in first page in middle of the page, look for "Server Name" after login.</p> <p>By default it's your machine name.</p> <p>However your code will run just once: 2nd time AccountManger will throw an exception due to already registered user.</p>
redirect .htaccess - remove last part of url <p>I need redirect url like: <strong>www.domain.com/xx/yy/itinerar</strong> to <strong>www.domain.com/xx/yy</strong>. The value of yy can be various. I have </p> <pre><code>RewriteCond %{REQUEST_URI} (.*)itinerar </code></pre> <p>but i have trouble with RewriteRule.</p>
<p>You can use this redirect rule:</p> <pre><code>RewriteEngine On RewriteRule ^(.*)/itinerar/?$ /$1 [L,NC,R=301] </code></pre>
LNK2001 with Cmake static library <p>I am struggling to link to a static library created with CMake in another Visual C++ project. I am getting LNK2001 unresolved symbol errors for all the symbols in the library. Forgot to link with the library? I really don't think I have, as I have specified it as an absolute path and verified that if I change the name I get an error that it can't find the library - so it's definitely looking at it.</p> <p>I used DUMPBIN to look at the symbol names and they seem different to what VC++ is looking for, e.g.</p> <p>(in static library)</p> <pre><code>??0Matrix@NEWMAT@@QAE@HH@Z (public: __thiscall NEWMAT::Matrix::Matrix(int,int)) </code></pre> <p>(unresolved symbol)</p> <pre><code>public: __cdecl NEWMAT::Matrix::Matrix(int,int)" (??0Matrix@NEWMAT@@QEAA@HH@Z) </code></pre> <p>note QAE vs QEAA in the decoration, also the library has __thiscall whereas the compiler is looking for __cdecl</p> <p>It looks like the calling convention might be the issue, but why would it be different, and is there a compiler switch to make it consistent?</p> <p>I have gone through the project properties and tried to make all compiler options the same but to no avail. Unfortunately I'm not a VC++ expert so it is probably something very simple, but anyone able to help?</p>
<p>Ok, I have apparently fixed this although I'm confused by the error I got. It seems the CMake library was targeting x86, not x64. I discovered this when I tried to link to a different library in the same group which then reported an error about inconsistent machine types. Having fixed CMake to do a x64 build I notice that the calling convention is now as expected and I have no unresolved symbols.</p> <p>Just a bit unclear why I didn't get the machine type error on the first library but such is life.</p>
How to pause and stop SKScene without having performance issues? <p>I am writing a program using Swift3 in Xcode. I am using SpriteKit and SKScene in my program. As you know, there is a predefined update function that always runs (even when the view changed) in gamescene.sks.</p> <p>I know that "self.scene.view.paused = YES;" does not work for update functions that are always called.</p> <p>Is there any way to pause and stop SKScene and its update function?</p>
<p>Apples DemoBot is always a good project to check out. </p> <p>The best way to pause your game is to create a world node and pause that node instead of pausing the skView.</p> <pre><code>let worldNode = SKNode() </code></pre> <p>add it in didMoveToView in your GameScene.</p> <pre><code>addChild(worldNode) </code></pre> <p>Than add all the nodes (or SKActions) that you want paused to the worldNode</p> <pre><code>worldNode.addChild(SOMENODE) worldNode.addChild(SOMENODE2) </code></pre> <p>Than in your pause method you say </p> <pre><code>worldNode.isPaused = true physicsWorld.speed = 0 </code></pre> <p>and in your resume method you say </p> <pre><code>worldNode.isPaused = false physicsWorld.speed = 1 </code></pre> <p>Than for the update method you can exit early if the worlNode is paused</p> <pre><code>override func update(_ currentTime: TimeInterval) { guard !worldNode.isPaused else { return } // rest of your code } </code></pre> <p>Hope this helps.</p>
Angularjs - ng-change and $scope.$watch fires only once <p></p> <p>I have tried both ng-change as well as $watch on the model. However, it fires exactly once. Either when the first character of the input is entered. Or when the last character is deleted. For example, when I enter the first number, the function is called correctly. When I continue typing other numbers into the input, the function isn't called. Like when the input is "1234", it fires when 1 is typed into the input. But when 2 and 3 and 4 are entered, it does not get fired. </p> <p>Same thing happens while deleting. When 4,3,2 are deleted, the event doesn't get fired. When 1 is deleted, it gets fired. </p> <p>I did search the forum before asking. However, I was not able to find any meaningful answer. Does it have anything to $digest lifecycle? </p>
<p>It will be helpful, if you elaborate your question further more.</p> <p>Basically this scenario working fine. </p> <pre><code>&lt;div ng-controller="test"&gt; &lt;input ng-model="a" ng-change="check()" /&gt; &lt;/div&gt; </code></pre> <p>JS code</p> <pre><code>angular.module("myApp", []) .controller('test', ['$scope', function($scope){ $scope.check = function(){ alert('it changes'); } }]); &lt;div ng-controller="test"&gt; &lt;input ng-model="a" ng-change="check()" /&gt; &lt;/div&gt; </code></pre>
How to show total rate in SQL? <p>I need item wise total amount from below table (quired data) in SQL. How to achieve this? please suggest me- NB: Please see the attached file, I am unable to paste it correctly.</p> <p><a href="https://i.stack.imgur.com/nbnFX.png" rel="nofollow"><img src="https://i.stack.imgur.com/nbnFX.png" alt="enter image description here"></a></p>
<p>Use window functions:</p> <pre><code>select t.*, sum(totalamount) over (partition by itemid) as totalamountsum from t; </code></pre>
Button submit's value not transmitted in POST <p>I am using Yii2 and I want to create comment functionality on post using Pjax widget. The comment windows displays all the existing comments for the post adding an edit button to the ones that belongs to the connected user in order to permit changes. Under this list of comments,there is a form including a textarea and a submit button to allow comment creation. Each time the user click on an already existing comment 's edit button, a form is displayed to allow update. </p> <p><strong>How all this actually runs and the trouble I meet:</strong></p> <ul> <li><p>I can update an existing comment an infinite number of times, and it is what I want.</p></li> <li><p>If, just after refreshing the view post page, I enter a new comment, it is correctly submitted. But <strong>I cannot enter an other one and I want to be able to post more than one</strong>. The second time, it appears that the POST contains the content of the comment but nothing regarding the submit button. Thus I cannot recognize which button has been clicked. </p></li> <li><p>The same thing happens after I have changed an existing comment i.e. <strong>I cannot create a new comment</strong> for the same reason – nothing about the submit button in the POST.</p></li> </ul> <p><strong>My question</strong></p> <p>How comes the submit button is transmitted in the POST only if it is the first one used and it is the first time it is used after a refresh of the page?</p> <p><strong>Here are the relevant code parts</strong></p> <p><strong>1-Controller</strong></p> <pre><code>/** * display a post *@param integer $id * * return a view */ public function actionView ($id){ $post = $this-&gt;findModel($id); $comment=$this-&gt;manageComment($post); return $this-&gt;render('view', [ 'post_model' =&gt; $post, 'comment_model' =&gt; $comment, ]); } /* * deals with the post according to the submit value * if submitted and return the comment under treatment * otherwise – not submitted – return a new comment * *@param $post the post that holds the comments * * return a Comment model */ protected function manageComment($post) { $comment=new Comment; if(isset($_POST['Comment']) ) { switch ($_POST['Submit']) { case 'create': $comment-&gt;attributes=$_POST['Comment']; if($post-&gt;addComment($comment,false)) { //la création a réussi if($comment-&gt;status==Comment::STATUS_PENDING) Yii::$app-&gt;session-&gt;setFlash('success', Yii::t('app','Thank you for your comment. Your comment will be visible once it is approved.')); //on renouvelle le commentaire pour éviter d'avoir //un bouton update (mise à jour) return new Comment; } break; case 'update': $comment=Comment:: find() -&gt;where(['id' =&gt; $_POST['Comment']['id']]) -&gt;one(); if($comment-&gt;attributes=$_POST['Comment']){ if($post-&gt;addComment($comment,true)) { //update successful if($comment-&gt;status==Comment::STATUS_PENDING) {Yii::$app-&gt;session-&gt;setFlash('success', Yii::t('app','Thank you for your comment. Your comment will be visible once it is approved.'));} $comment= new Comment; return $comment; } else { //la mise à jour a échoué $comment= new Comment; return $comment; } }else{echo'load failed'; exit();} break; case 'edit': // echo $_POST['Comment']['id']; exit(); $comment-&gt;id = $_POST['Comment']['id']; return $comment; break; default: } } //creation successful return $comment; } </code></pre> <p><strong>2-In Post view</strong></p> <pre><code>&lt;!--comment_model is passed by PostController--&gt; &lt;?= $this-&gt;render('@app/views/comment/_create-form', ['model' =&gt; $comment_model, 'post' =&gt; $post_model]); ?&gt; </code></pre> <p><strong>3 - the _create-form view</strong></p> <pre><code> &lt;div class="comment-form"&gt; &lt;?php Pjax::begin([ ]);?&gt; &lt;!-- this bloc must be part of the Pjax in order for the new comment to appear immediately --&gt; &lt;div class="comment"&gt; &lt;h4 &gt;&lt;?= Yii::t('app','Comments by users')?&gt;&lt;/h4&gt; &lt;div class="comments"&gt; &lt;?php $comments= Comment::find() -&gt;where (['post_id' =&gt; $post-&gt;id ]) -&gt;andWhere(['status' =&gt; true]) -&gt;all(); foreach($comments as $com){ $identity= User::findIdentity($com-&gt;user_id); $firstname=$identity-&gt;firstname; familyname=$identity-&gt;familyname; $date= Utils::formatTimestamp($com-&gt;created_at); $txt1 = Yii::t('app','Posted by '); $txt2 = Yii::t('app',' on '); $text_header =$txt1. $firstname.' '.$familyname.$txt2.$date; //here we check that $model-&gt;id is defined an equal to $com-&gt;id //to include edition form if (isset($model-&gt;id) &amp;&amp; ($model-&gt;id == $com-&gt;id) )// { // echo Yii::$app-&gt;user-&gt;identity-&gt;id. ' '.$com-&gt;user_id; exit(); echo $this-&gt;render( '_one-comment',(['com' =&gt; $com, 'text_header' =&gt; $text_header, 'submit_btn' =&gt; false, 'with_edit_form' =&gt; true])); } else { $submit_btn=false; if (Yii::$app-&gt;user-&gt;identity-&gt;id == $com-&gt;user_id) $submit_btn=true; else $submit_btn=false; echo $this-&gt;render('_one-comment',(['com' =&gt; $com, 'text_header' =&gt; $text_header, 'submit_btn' =&gt; $submit_btn,'with_edit_form' =&gt; false])); } }?&gt; &lt;/div&gt; &lt;!--this div should be between Pjax::begin and Pjax::end otheswise it is not refreshed--&gt; &lt;div id="system-messages" &gt; &lt;?php foreach (Yii::$app-&gt;session-&gt;getAllFlashes() as $type =&gt; $message): ?&gt; &lt;?php if (in_array($type, ['failure','success', 'danger', 'warning', 'info'])): ?&gt; &lt;?= Alert::widget([ 'options' =&gt; ['class' =&gt; ' alert-dismissible alert-'.$type], 'body' =&gt; $message ]) ?&gt; &lt;?php endif ?&gt; &lt;?php endforeach ?&gt; &lt;/div&gt; &lt;?php $form = ActiveForm::begin([ 'options' =&gt; ['data' =&gt; ['pjax' =&gt; true]],//'id' =&gt; 'content-form' // more ActiveForm options ]); ?&gt; &lt;?= $form-&gt;field($model, 'content') -&gt;label('Postez un nouveau commentaire') -&gt;textarea(['rows' =&gt; 6]) ?&gt; &lt;?= Html::submitButton('Create comment', ['content' =&gt; 'edit','name' =&gt;'Submit','value' =&gt; 'create']) ?&gt; &lt;?php ActiveForm::end();?&gt; &lt;/div&gt; &lt;?php Pjax::end() ?&gt; &lt;/div&gt; </code></pre> <p><strong>4 - the _one-comment view</strong></p> <pre><code>&lt;div class="one-comment"&gt; &lt;div class="comment-header"&gt; &lt;?php echo $text_header;?&gt; &lt;/div&gt; &lt;div class="comment-text"&gt; &lt;?php echo $com-&gt;content;?&gt; &lt;/div&gt; &lt;div class="comment-submit"&gt; &lt;?php if ($with_edit_form) { // echo "with edit ".$com-&gt;id; exit(); echo $this-&gt;render('_update-one-comment',(['com' =&gt;$com])); } else { if($submit_btn){ $form = ActiveForm::begin([ 'options' =&gt; [ 'data' =&gt; ['pjax' =&gt; true]],//'name' =&gt; 'one','id' =&gt; 'com-form-'.$com-&gt;id, // more ActiveForm options ]); ?&gt; &lt;?= $form-&gt;field($com, 'id')-&gt;hiddenInput()-&gt;label(false);?&gt; &lt;div class="form-group"&gt; &lt;?= Html::submitButton('', [ 'class' =&gt; 'glyphicon glyphicon-pencil sub-btn', 'content' =&gt; 'edit', 'name' =&gt;'Submit','value' =&gt; 'edit']) ?&gt; &lt;/div&gt; &lt;?php ActiveForm::end(); } }?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>5 the _update-one-comment form</strong> <pre><code> //echo 'dans update-one-comment';print_r($com-&gt;toArray()); exit(); $form = ActiveForm::begin([ 'options' =&gt; [ 'data' =&gt; ['pjax' =&gt; true]],//'name' =&gt; 'edit-one','id' =&gt; 'edit-com-form-'.$com-&gt;id, // more ActiveForm options ]); ?&gt; &lt;?= $form-&gt;field($com, 'id')-&gt;hiddenInput()-&gt;label(false);?&gt; &lt;?= $form-&gt;field($com, 'created_at')-&gt;hiddenInput()-&gt;label(false);?&gt; &lt;?= $form-&gt;field($com, 'updated_at')-&gt;hiddenInput()-&gt;label(false);?&gt; &lt;?= $form-&gt;field($com, 'content') -&gt;label('Mise à jour commentaire') -&gt;textarea(['rows' =&gt; 6]) ?&gt; &lt;div class="form-group"&gt; &lt;?= Html::submitButton($com-&gt;isNewRecord ? Yii::t('app', 'Create comment') : Yii::t('app', 'Update comment'), ['class' =&gt; $com-&gt;isNewRecord ? 'btn btn-success' : 'btn btn-primary','name' =&gt;'Submit','value' =&gt; 'update']) ?&gt; &lt;/div&gt; &lt;?php ActiveForm::end(); ?&gt; </code></pre> <p><strong>6- the Post model 's addComment()</strong></p> <pre><code> public function addComment($comment, $up=false) { if(Yii::$app-&gt;params['commentNeedApproval']) {$comment-&gt;status=Comment::STATUS_PENDING;} else {$comment-&gt;status=Comment::STATUS_APPROVED;} $comment-&gt;post_id=$this-&gt;id; $comment-&gt;user_id=Yii::$app-&gt;user-&gt;identity-&gt;id; if($up){ $test=$comment-&gt;update(); if($test) {//($comment-&gt;save(false)){ Yii::$app-&gt;session-&gt;setFlash('success',Yii::t( 'app','The comment has been succesfully updated.')); return true; } Yii::$app-&gt;session-&gt;setFlash('failure',Yii::t( 'app','The comment could not be updatded.')); } else { //création if($comment-&gt;save()){ Yii::$app-&gt;session-&gt;setFlash('success', Yii::t('app','The comment has been succesfully recorded.')); return true; } Yii::$app-&gt;session-&gt;setFlash('failure', Yii::t('app',$up.false.'The comment could not be recorded.')); } return false; } </code></pre>
<p>Why are you counting on the submit button name / value to figure out what you need to do? </p> <p>$_POST['Comment']['id'] is a much better indicator of what needs to done. If it is there update otherwise create. </p> <p>Also make sure the model does not allow editing of comments posted by others.</p> <p>The model should not set flash messages, that is a job for the controller.</p> <p>"I can update an existing comment an infinite number of times." of course you can, from what you told us there is nothing that would say you should not be able to. And you are not checking to prevent that.</p>
How do I connect to VMware from another PC? <p>I am facing an issue with my VMware and Ubuntu PC. Scenario: I have a Windows 8.1 PC (IP: 192.168.1.10) and installed VM ware on this Window PC and installed Centos 7 on the VM ware (IP: 192.168.163.127). Also, I have another PC installed with Ubuntu 15.10 (IP: 192.168.1.12). I need to ping or connect to the Centos on the VM ware from my Ubuntu PC. I am using VMware workstation 12 Pro. How do I can do this? Is this possible? Please, anybody, help me.</p>
<p>By using NAT it is quite possible. For further information about how you can configure your NAT and Bridge please take a look at following links: <a href="https://pubs.vmware.com/workstation-12/index.jsp?topic=%2Fcom.vmware.ws.using.doc%2FGUID-D05850F8-E850-4086-A735-5C84C72D007C.html" rel="nofollow">https://pubs.vmware.com/workstation-12/index.jsp?topic=%2Fcom.vmware.ws.using.doc%2FGUID-D05850F8-E850-4086-A735-5C84C72D007C.html</a> <a href="https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&amp;cmd=displayKC&amp;externalId=1018697" rel="nofollow">https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&amp;cmd=displayKC&amp;externalId=1018697</a> <a href="http://serverfault.com/questions/229860/vmware-networking-mode-nat-or-bridged">http://serverfault.com/questions/229860/vmware-networking-mode-nat-or-bridged</a></p> <p>I hope it helps you.</p>
Normailized Dtabase schema of quiz in php <p>I am little confusing for building schema of quiz</p> <p>In this i have to upload many questions and having four options each option contains textbox and corresponding checkbox that denotes for right answer. if admin select one ceckbox that could be right answer.</p> <p>Note:- In some cases i have uploaded many option 6 to 7 and answers might be 2 or 3 are correct and admin will click on many checkboxes</p> <p><a href="https://i.stack.imgur.com/W4eAd.png" rel="nofollow"><img src="https://i.stack.imgur.com/W4eAd.png" alt="enter image description here"></a> </p> <p>Can anyone helping in schema </p>
<p>This seems fairly straight forward. You just have three tables, one for quizzes, one for questions and one for answers. Something like this:</p> <p>Quizzes</p> <pre><code>+----+-------------+-----------------+ | id | name | description | +----+-------------+-----------------+ | 1 | Sample Quiz | An example quiz | +----+-------------+-----------------+ </code></pre> <p>Questions</p> <pre><code>+----+---------+------------+ | id | quiz_id | question | +----+---------+------------+ | 1 | 1 | Question 1 | +----+---------+------------+ </code></pre> <p>Answers</p> <pre><code>+----+-------------+----------+------------+ | id | question_id | answer | is_correct | +----+-------------+----------+------------+ | 1 | 1 | Answer 1 | 0 | | 2 | 1 | Answer 2 | 1 | | 3 | 1 | Answer 3 | 0 | | 4 | 1 | Answer 4 | 0 | +----+-------------+----------+------------+ </code></pre> <p>This schema will support as many quizzes as you need, each with any number of questions and each question can have any number of answers.</p>
Android marshmallow after granting permission through Appop Denial error for SYSTEM_ALERT_WINDOW permission <p>Hi i am trying to get SYSTEM_ALERT_WINDOW permission i have added <code>&lt;uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /&gt;</code> in my manifest file. Now when i install the release build, it asks for permission and everything works as expected in marshmallow. But when i install it from playstore it automatically grants me SYSTEM_ALERT_WINDOW permission, but when i try to start a System overlay service, it is giving me error. </p> <p><code>W/ActivityManager: Appop Denial: Accessing service ComponentInfo{packagename/packagename.classname} from pid=6189, uid=10289 requires appop SYSTEM_ALERT_WINDOW</code></p> <p>But when i checked facebook chathead it was working without asking me permissions.</p> <p>How do i check for appop denial permissions?</p>
<p>It may not be asking for the permissions if already allowed please check as below:</p> <p>No permissions have been granted if you go to <strong>Settings > Apps > "Your app" > Permissions.</strong></p> <p>You should uninstall clear app data and uninstall it completely, then install via playstore.</p> <p>If you don't want to do implement the new system yet then you can reduce your target sdk version to 22 to get the old permission system. You can still compile with sdk version 23 though.</p> <p>Thanks</p>
NewtonSoft JsonConvert SerializeObject Dictionary of Object Escape Chars <p>I'm having some trouble using the JsonConvert.SerializeObject method concerning escape chars in WCF. My web method returns a Stream as follows:</p> <pre><code> return new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(myObject))); </code></pre> <p>This works fine apart from one of the properties of myObject is a Dictionary of <code>&lt;string, object&gt;</code>. All of the simple types serialize correctly, however when I try and add my custom class as a value I get the type returned instead of the data. On realising this comes from the serialiser calling .ToString on my custom class I've tried overriding it with:</p> <pre><code>public override string ToString() { return JsonConvert.SerializeObject(this); } </code></pre> <p>However the returned data now includes escape chars</p> <pre><code>{ "my_dictionary": { "elem_1": "{\"Prop1\":null,\"Prop2\":3}", "elem_2": "{\"Prop1\":null,\"Prop2\":3}", "int_property" : 123 } } </code></pre> <p>Any ideas on how I could avoid my custom class being escaped in this way and returned as an array?</p> <p>Thanks in advance, Matt</p>
<p>I use JavaScriptSerializer (just replace "Object" with your custom class)</p> <pre><code>using System.Web.Script.Serialization; List&lt;Object&gt; list = new List&lt;Object&gt;(); JavaScriptSerializer jss = new JavaScriptSerializer(); string res = jss.Serialize(list); </code></pre> <p>and get this format with "res" value:</p> <pre><code>[{"IdEmpresa":1,"Nombre":"Test","URL":"http:/localhost:8080/","Activo":true},IdEmpresa":2,"Nombre":"Test2,","URL":"http://localhost:8081/","Activo":true}] </code></pre>
generating new line for each loop bash <p>I have this problem about bash output i need to write code that would output: </p> <pre><code>1 22 333 </code></pre> <p>using loops so far i have this code: </p> <pre><code>First loop.... for ((i=1; i&lt;=1; i=i+1)) do echo $i done #Second loop.... for ((i=1; i&lt;=2; i++)) do for ((j=2; j&lt;=2; j++)) do echo -n $j done done #Third loop..... for ((i=1; i&lt;=2; i++)) do for ((j=2; j&lt;=2; j++)) do echo -e $j done done </code></pre> <p>Problem is it outputs third loop inside the second like </p> <pre><code>1 223 33 </code></pre> <p>Thanks for any help.</p>
<p>A simple nested for loop is be sufficient to do what you want:</p> <p>CODE:</p> <pre><code>for ((i=1; i&lt;=5; i++)) do for((j=1; j&lt;=$i; j++)) do echo -n $i done echo done </code></pre> <p>OUTPUT:</p> <pre><code>1 22 333 4444 55555 </code></pre>
multiple commands in git alias is not working <p>I have the following code in my <code>.gitconfig</code> file:</p> <pre><code>[alias] john = "!f(){ git branch -r | grep -v '\-&gt;' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done; git fetch --all; git pull --all; };f" </code></pre> <p>Which is basically creating an <code>alias</code> for pulling every branch on the remote server. But is constantly trowing an error. Can someone help me understand what is going wrong, I've tried dissecting the command, but I can't find what is going wrong.</p>
<p>You need to escape embedded double quotes with backslashes. For instance:</p> <pre><code>[alias] next = "!f() { id=$(git rev-list --reverse --ancestry-path ..master | head -1); test -n \"$id\" &amp;&amp; git checkout $id || echo 'no more commits'; }; f" </code></pre> <p>(which I actually have commented out since hardcoding <code>master</code> is bogus: this is a leftover from <a href="http://stackoverflow.com/a/38541028/1256452">this answer</a>).</p> <p>You can also wrap long lines with backslash-newline:</p> <pre><code> next = "!f() { \ id=$(git rev-list --reverse --ancestry-path ..master | head -1); \ test -n \"$id\" &amp;&amp; git checkout $id || echo 'no more commits'; }; f" </code></pre> <p>(untested, but should work).</p> <p>All that said, this is wrong:</p> <blockquote> <p>Which is basically creating an alias for pulling every branch on the remote server.</p> </blockquote> <p>Your sample alias attempts to create a new local branch for each remote-tracking branch (which is fine as far as it goes, but not possible in full generality, e.g., if you have both <code>refs/remotes/origin/zorg</code> and <code>refs/remotes/evil/zorg</code>, you cannot have local branch <code>zorg</code> track both remote-tracking branches). (For scripting purposes, it's better to use <code>git for-each-ref</code> here, but the existing loop should work well enough for your purposes.)</p> <p>But, then you run <code>git fetch --all</code>, which means <em>fetch from all remotes</em> (<code>fetch</code> defaults to fetching from the "current" remote, which is pretty loosely defined as "the current branch's remote, or <code>origin</code> if the current branch has no remote set). Once the fetch finishes, you run <code>git pull --all</code>, which passes <code>--all</code> to <code>git fetch</code> again, then attempts to merge (or rebase) the current branch based on its configured <code>remote</code> and <code>merge</code> settings.</p> <p>This therefore updates at most <em>one</em> of the branches you created in the <code>while</code> loop.</p> <p>To merge-or-rebase each local branch, you need to loop over the local branches (again, preferably using <code>git for-each-ref</code>).</p>
How would i change my program so that the colours are specific and not random? <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;style&gt; #myDiv { height: 200px; width: 200px; background-color: salmon; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="myDiv"&gt;&lt;/div&gt; &lt;script&gt; function setColor() { var x = '0123456789ABCDEF'; var y = '#'; var i; for (i = 0; i &lt; 6; i++) { y = y + x[Math.round(Math.random() * 15)]; } document.getElementById("myDiv").style.backgroundColor = y; } var myVar = setInterval(function() { setColor() }, 1000); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>I need the code to change to specific colors not randomly. Please tell me how I would do that. i have just started programming with javascript,html and css so my programming language is not very high. but i am quick to learn and understand</p>
<p>A modified version of your code:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style&gt; #myDiv { height: 200px; width: 200px; background-color: black; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="myDiv"&gt;&lt;/div&gt; &lt;script&gt; //global variable (acts as a dynamic index for array) var i=0; function setColor(){ //specific colors var y = ["red", "blue", "yellow", "green"]; //at end of array, start at beginning again if (i === (y.length+1)*1000) i = 0; //each time setColor is called, i is incremented by 1000 i += 1000; //colors in array accessed. document.getElementById("myDiv").style.backgroundColor=y[i/1000 - 1]; } //setColor() called after each 1000 milliseconds var myVar = setInterval(function(){setColor()}, 1000); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
angular2 input value bind from another input with ngmodel directive <p>Consider i have two inputs like the below</p> <pre><code>&lt;input [(ngModel)]="value1" type="number"&gt; &lt;input [(ngModel)]="value2" type="number"&gt; </code></pre> <p>the value2 should be updated when i type any number in value1.</p> <p>I tried something like below</p> <pre><code>&lt;input [ngModel]="value1" (ngModelChange)="value2=value1*value2" type="number"&gt; &lt;input [(ngModel)]="value2" type="number"&gt; </code></pre> <p>but the [value2=value1*value2] updates the value1 with the value2 data </p>
<p>Try <code>change</code> event instead of <code>ngModelChange</code> as below :</p> <pre><code>&lt;input [(ngModel)]="value1" (change)="value2=value1*value2" type="number"&gt; &lt;input [(ngModel)]="value2" type="number"&gt; </code></pre>
User authentication failing after upgrading to 3.2.1 <p>I just upgraded my app from Grails 3.2.0 to <strong>3.2.1</strong> due to some problems and the user authentication started failing. I'm using Grails Spring Security Core plugin version <strong>3.1.1</strong>.</p> <p>I'm getting the following exception:</p> <pre><code>org.springframework.security.authentication.InternalAuthenticationServiceException: Cannot cast object 'User(email:user@example.com)' with class 'com.test.User' to class 'com.test.User' at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:126) at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144) at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94) at grails.plugin.springsecurity.web.authentication.GrailsUsernamePasswordAuthenticationFilter.attemptAuthentication(GrailsUsernamePasswordAuthenticationFilter.groovy:53) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) Caused by: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'User(email:user@example.com)' with class 'com.test.User' to class 'com.test.User' at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnSAM(DefaultTypeTransformation.java:405) at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnNumber(DefaultTypeTransformation.java:319) at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:232) at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.castToType(ScriptBytecodeAdapter.java:603) at com.test.User.findWhere(User.groovy) at com.test.User$findWhere.call(Unknown Source) at grails.plugin.springsecurity.userdetails.GormUserDetailsService.$tt__loadUserByUsername(GormUserDetailsService.groovy:60) at grails.plugin.springsecurity.userdetails.GormUserDetailsService$_loadUserByUsername_closure1.doCall(GormUserDetailsService.groovy) </code></pre> <p>This is only failing when we deploy it on Apache Tomcat (using <strong>8.5.6</strong>) but it is working fine on development with <code>grails run-app</code>.</p> <p>Here are the modified dependencies in <code>build.gradle</code> (rest configuration is same as generated by create-app):</p> <pre><code>// "compile" changed to "provided" provided "org.springframework.boot:spring-boot-starter-tomcat" compile "org.grails.plugins:spring-security-core:3.1.1" compile "org.grails.plugins:asynchronous-mail:2.0.0.RC4" compile "org.mongodb:bson:3.3.0" compile "org.codehaus.groovy.modules.http-builder:http-builder:0.7.1" runtime "mysql:mysql-connector-java:5.1.39" // https://github.com/spring-projects/spring-boot/issues/6761 runtime "com.google.code.gson:gson:2.5" // Commented this to avoid issue (https://github.com/grails/grails-core/issues/10196) //provided "org.codehaus.groovy:groovy-ant" </code></pre> <p>The same setup was working in the Grails 3.2.0.</p> <p>Any idea about this exception?</p>
<p>Seems to be an issue with Grails 3.2.1 itself. Issue tracked <a href="https://github.com/grails/grails-core/issues/10244" rel="nofollow">grails/grails-core#10244</a>.</p> <p>Workaround is to override <code>limitScanningToApplication</code> in your <code>grails-app/init/PACKAGE/Application.groovy</code></p> <pre><code>import grails.boot.GrailsApp import grails.boot.config.GrailsAutoConfiguration class Application extends GrailsAutoConfiguration { static void main(String[] args) { GrailsApp.run(Application, args) } @Override boolean limitScanningToApplication() { return false } } </code></pre>
Cant parse date to D3 line graph <p>I want to create a line graph like below fiddle, <a href="http://jsfiddle.net/wRDXt/2/" rel="nofollow">http://jsfiddle.net/wRDXt/2/</a></p> <p>Here the date is used as <code>new Date(2013, 17, 1)</code>.</p> <p>I have json contents as follows,</p> <pre><code>[{ "_id": "bb68d8a2-8778-4c85-8616-ed1e96a61ea6", "FLAG": "public", "STATUS": "active", "DESCRIPTION": "df", "DATE_TIME": "04-10-2016 16:39:39", "TOKEN": "bge2jb", "LAST_UPDATED": "Tue Oct 04 16:39:39 IST 2016" }, { "_id": "556ae8ad-7291-4303-a9e4-618a82694600", "FLAG": "public", "STATUS": "active", "DESCRIPTION": "d", "DATE_TIME": "04-10-2016 16:52:20", "TOKEN": "16l4jal", "LAST_UPDATED": "Tue Oct 04 16:52:20 IST 2016" }, { "_id": "98db36ba-392d-4df2-ac6c-820eaf582a11", "FLAG": "public", "STATUS": "active", "DESCRIPTION": "uyk", "DATE_TIME": "07-10-2016 12:13:10", "TOKEN": "dfl5ja", "LAST_UPDATED": "Fri Oct 07 12:13:10 IST 2016" }] </code></pre> <p>My date format, which came from api call is like <code>07-10-2016 12:13:10</code> or <code>Fri Oct 07 12:13:10 IST 2016</code>.</p> <p>If I pass this date, I am getting following error in console,</p> <pre><code>Uncaught TypeError: minDate.getDate is not a function </code></pre> <p>How do I pass my date to this and get the graph.</p> <p>My fiddle is <a href="http://jsfiddle.net/wRDXt/190/" rel="nofollow">http://jsfiddle.net/wRDXt/190/</a></p>
<p>The <code>date</code> in your <code>dataset</code> is not a date-object, but a string. Therefore it does not have a <code>getDate()</code>-function and you get the error you get. </p> <p>To fix this, right after you have declared your dataset, loop through all entries in the dataset and redefine <code>date</code> by parsing the <code>date</code>-string:</p> <pre><code>dataset.forEach(function(d) { d.date = d3.time.format("%d-%m-%Y %H:%M:%S").parse(d.date); }); </code></pre> <p>See fiddle: <a href="http://jsfiddle.net/wRDXt/204/" rel="nofollow">http://jsfiddle.net/wRDXt/204/</a></p> <p><a href="https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Formatting.md" rel="nofollow">Reference for <code>d3.time.format</code></a></p>
xcopy: did "/d" find newer file? <p>xcopy allows for the use of the parameter /d to "copy all Source files that are newer than existing Destination files" (<a href="https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/xcopy.mspx?mfr=true" rel="nofollow">https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/xcopy.mspx?mfr=true</a>).</p> <p>My question is: Is there a way to find out afterwards if any files were actually found and copied? The errorlevel returned is 0, no matter if any copy action did take place at all.</p> <p>Thing is: I want to use a batch script as preparation for automated testing. It looks in some exchange directory, and copies the content to the testing environment if it finds newer files. If no newer files are found, testing would be obsolete and should be skipped.</p> <p>Of course i might implement a different test step to compare if there are newer files, and please feel free to tell me if that would be best practice anyway. But to me it seemed somehow neat to cover it in one step, since I call xcopy anyway.</p> <p>Thanks in advance,</p> <p>Florian</p>
<pre><code>FOR /f %%a IN ('XCOPY /d /l ..\* .') DO SET /a numcopied=%%a </code></pre> <p>executed <strong>before</strong> you perform you actual <code>xcopy /d</code> will set <code>numcopied</code> to the number of files to be copied.</p> <p>Note that I used the directories <code>..</code> and <code>.</code> here for testing - you'd need to substitute your dirnames.</p>
how to replace a column of a data frame with several columns alternatively? <p>I have a data frame like this </p> <pre><code>X &lt;- matrix(rexp(30, rate=.1), ncol=5) Y &lt;- matrix(rexp(6, rate=.1), ncol=1) mydata &lt;- data.frame(cbind(Y,X)) </code></pre> <p>Now I want to change the third column of X with each of the columns of Xm </p> <pre><code>Xm &lt;- matrix(rexp(60, rate=.1), ncol=10) </code></pre> <p>and do a linear regression and save the sd of X3. If I want to do it manually I do </p> <pre><code>X[ , 3] &lt;- Xm[ , 1] mydata &lt;- data.frame(cbind(Y,X)) fit1 = lm(Y~.,data=mydata) </code></pre> <p>then </p> <pre><code>X[ , 3] &lt;- Xm[ , 2] mydata &lt;- data.frame(cbind(Y,X)) fit2 = lm(Y~.,data=mydata) </code></pre> <p>then </p> <pre><code>X[ , 3] &lt;- Xm[ , 3] mydata &lt;- data.frame(cbind(Y,X)) fit3 = lm(Y~.,data=mydata) . . . etc. </code></pre> <p>however, if I do it manually it takes so long and not efficient. Is there anyone who can help me to make it more automatic?</p>
<p>You can do it in loop </p> <p>like </p> <pre><code>res=lapply(1:ncol(Xm),function(i){ mydata[[3]] &lt;- Xm[ , i] # change 3-rd column of mydata om i-th colomn of Xm lm(Y~.,data=mydata) }) </code></pre> <p>where <code>res</code> - list of your lm models</p> <p>If you want to save only X3 std you can do it in such way </p> <pre><code>res2=lapply(1:ncol(Xm),function(i){ mydata[[3]] &lt;- Xm[ , i] summary(lm(Y~.,data=mydata))$coefficients["X3","Std. Error"] }) </code></pre> <p>but in your example they all <code>NaN</code></p>
node.js multipart/form-data local file upload to api <p>I want to upload a file to a restful api service from my javascript application. It should use a local path like "c:/folder/test.png" and upload to something like "localhost/uploads", is there a easy approch, I am a little lost coming to the upload part and have tryed searching around, but didn't find any that matched my case, and I have tryed this code below:</p> <pre><code> var request = require('request'); var url = "http://localhost/uploads"; var req = request.post(url, function (err, resp, body) { if (err) { console.log('Error!'); } else { console.log('URL: ' + body); } }); var form = req.form(); form.append('file', fs.createReadStream("C:/kristian/Devbeasts-small.png")); </code></pre> <p>this code gives me the error: Error: Cannot find module 'request'</p> <p>It requires a multipart form-data.</p>
<p>You need to use <a href="https://github.com/felixge/node-formidable" rel="nofollow">https://github.com/felixge/node-formidable</a> It work fast to upload files</p>