问:
Displaying static content with angular2
Please forgive the newbie question; I'm just starting out with angular2. I've made it through the angular heroes demo and understand how components work, how to connect data to html, etc.

But what if I have a piece of static html that I want to display conditionally (i.e. on some pages and not others)? Do I need to create a full component, with all the imports and exports, even if there's no data model to hook it to? If not, how do I go about doing this? In angular 1, I'd just create a directive and call it, but angular2 has moved everything to components.an

Update
Created a component called WelcomeComponent (welcome.component.ts) and an html file (we're trying to keep all html separate in templates rather than mixing in with component code.) I registered my component in app.component.ts.

Here's the contents of welcome.component.ts:

```<code>import { Component } from '@angular/core';

@Component({
    selector: 'welcome',
    templateUrl: './welcome.component.html'
})

export class WelcomeComponent{}
</code>```

Here's welcome.component.html:

```<code><!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
    <div class="container">
        <h1>Hello, world!</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed et tincidunt mi, sed porttitor justo. Donec in vehicula arcu. Sed lobortis massa in sodales feugiat. Morbi in metus tristique, volutpat nisl ut, blandit odio. Ut elit ipsum, euismod ut suscipit interdum, tristique in velit. Quisque vestibulum elementum aliquam.</p>
        <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p>
    </div>
</div>
</code>```

Here's app.module.ts:

```<code>import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { HttpModule }    from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
// Imports for loading & configuring the in-memory web api
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService }  from './in-memory-data.service';
import { AppComponent }         from './app.component';
import { FavoritesComponent }   from './favorites.component';
import { ItemsComponent }      from './items.component';
import { ItemDetailComponent }  from './item-detail.component';
import {ItemSearchComponent} from './item-search.component';
import { ItemService }          from './item.service';
import {WelcomeComponent} from './welcome.component';
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    InMemoryWebApiModule.forRoot(InMemoryDataService),
    AppRoutingModule
  ],
  declarations: [
    AppComponent,
    FavoritesComponent,
    ItemDetailComponent,
    ItemSearchComponent,
    ItemsComponent,
    WelcomeComponent
  ],
  providers: [ ItemService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
</code>```

And here's how I'm trying to call it in my index.html file:

```<code><welcome></welcome>

  <div class="container">
    <my-app></my-app>
    <my-favorites></my-favorites>
    <hr>

    <footer>
      <p>© 2016 Company, Inc.</p>
    </footer>
  </div> <!-- /container -->
</code>```

Note that the my-favorites component is defined exactly the same way, and the contents of that component do display correctly. What am I missing?

答:
Use a component to display the static HTML.  Start by creating a new folder in your project to hold the component.  Then create the component, which will look something like this:

```<code>import { Component } from '@angular/core'
@Component(
   selector: 'my-content',  /* this is the name that will be used in the markup */
   template: `<div>Some static content</div>`
)
export class MyContentComponent{}
</code>```

You will then need to register this component in your app.module in the declarations section.  Now you can add the selector to any component that needs to display the static content:

```<code><div>
   <my-content></my-content>
</div>
</code>```

When you want to conditionally display the content, you can add *ngIf="showContent" to the component element ('showContent' needs to exist as a property on the hosting component).

```<code><div>
   <my-content *ngIf="showContent"></my-content>
</div>
</code>```

Update:

The root component of your app is AppComponent defined in markup as <my-app>.  All additional components need to be nested in the templates under that level.  Move the mark up from your index.html to app.component.html and it should work.

Index.html:

```<code><my-app></my-app>
</code>```

app.component.html:

```<code>  <welcome></welcome>
  <div class="container">
    <!-- current contents of app.component.html -->
    <my-favorites></my-favorites>
    <hr>

    <footer>
      <p>© 2016 Company, Inc.</p>
    </footer>
  </div> <!-- /container -->
</code>```

Title: Displaying static content with angular2

Body:
Please forgive the newbie question; I'm just starting out with angular2. I've made it through the angular heroes demo and understand how components work, how to connect data to html, etc.

But what if I have a piece of static html that I want to display conditionally (i.e. on some pages and not others)? Do I need to create a full component, with all the imports and exports, even if there's no data model to hook it to? If not, how do I go about doing this? In angular 1, I'd just create a directive and call it, but angular2 has moved everything to components.an

Update
Created a component called WelcomeComponent (welcome.component.ts) and an html file (we're trying to keep all html separate in templates rather than mixing in with component code.) I registered my component in app.component.ts.

Here's the contents of welcome.component.ts:

import { Component } from '@angular/core';

@Component({
    selector: 'welcome',
    templateUrl: './welcome.component.html'
})

export class WelcomeComponent{}

Here's welcome.component.html:

Hello, world!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed et tincidunt mi, sed porttitor justo. Donec in vehicula arcu. Sed lobortis massa in sodales feugiat. Morbi in metus tristique, volutpat nisl ut, blandit odio. Ut elit ipsum, euismod ut suscipit interdum, tristique in velit. Quisque vestibulum elementum aliquam.

Learn more »

Here's app.module.ts:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { HttpModule }    from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
// Imports for loading & configuring the in-memory web api
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService }  from './in-memory-data.service';
import { AppComponent }         from './app.component';
import { FavoritesComponent }   from './favorites.component';
import { ItemsComponent }      from './items.component';
import { ItemDetailComponent }  from './item-detail.component';
import {ItemSearchComponent} from './item-search.component';
import { ItemService }          from './item.service';
import {WelcomeComponent} from './welcome.component';
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    InMemoryWebApiModule.forRoot(InMemoryDataService),
    AppRoutingModule
  ],
  declarations: [
    AppComponent,
    FavoritesComponent,
    ItemDetailComponent,
    ItemSearchComponent,
    ItemsComponent,
    WelcomeComponent
  ],
  providers: [ ItemService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

And here's how I'm trying to call it in my index.html file:

<welcome></welcome>

    <my-app></my-app>
    <my-favorites></my-favorites>

© 2016 Company, Inc.

Note that the my-favorites component is defined exactly the same way, and the contents of that component do display correctly. What am I missing?

Body:
Use a component to display the static HTML.  Start by creating a new folder in your project to hold the component.  Then create the component, which will look something like this:

import { Component } from '@angular/core'
@Component(
   selector: 'my-content',  /* this is the name that will be used in the markup */
   template: `<div>Some static content</div>`
)
export class MyContentComponent{}

You will then need to register this component in your app.module in the declarations section.  Now you can add the selector to any component that needs to display the static content:

<div>
   <my-content></my-content>
</div>

When you want to conditionally display the content, you can add *ngIf="showContent" to the component element ('showContent' needs to exist as a property on the hosting component).

<div>
   <my-content *ngIf="showContent"></my-content>
</div>

Update:

The root component of your app is AppComponent defined in markup as <my-app>.  All additional components need to be nested in the templates under that level.  Move the mark up from your index.html to app.component.html and it should work.

Index.html:

<my-app></my-app>

app.component.html:

  <welcome></welcome>
  <div class="container">
    <!-- current contents of app.component.html -->
    <my-favorites></my-favorites>
    <hr>

    <footer>
      <p>&copy; 2016 Company, Inc.</p>
    </footer>
  </div> <!-- /container -->


来源: stackexchange

问:
numbers not allowed (0-9) - Regex Expression in javascript
I want a regex pattern which will allow me any chars, but it will not allow (0-9) numbers?</p>

答:
Like this: ^[^0-9]+$

Explanation:

^ matches the beginning of the string

[^...] matches anything that isn't inside

0-9 means any character between 0 and 9

+ matches one or more of the previous thing

$ matches the end of the string

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
multi-master in cosmosdb/documentdb
How can I set up multiple write regions in cosmosdb so that I do not need to combine query results of two or more different regions in my application layer? From this documentation, it seems like cosmosdb global distribution is global replication with one writer and multiple read secondarys, not true multi-master. https://learn.microsoft.com/en-us/azure/documentdb/documentdb-multi-region-writers</p>

答:
The referenced article states how to implement multi-master in Cosmosdb, while explicitly stating that it is not a multi-master database.

There are ways to "simulate" multi-master scenarios by configuring the consistency level (e.g. session) which will allow callers to see their local copy without having it written to the write region. You can find the details of the various levels here: https://learn.microsoft.com/en-us/azure/cosmos-db/consistency-levels.

Aside from that, consider if you truly need multi-master by working with the consistency levels, considering what acceptable latency is, etc. There are few scenarios that can't tolerate latency, particularly when you have adequate tools to provide a user experience that approximates a local write master. There is no such thing as real-time when remote networks are involved ;)

ContentLicense: CC BY-SA 3.0

Title: multi-master in cosmosdb/documentdb


问:
How to not error on cmdlets that are missing
I have a lot of powershell scripts so I created a custom logging Powershell module with a couple of cmdlets. The problem is that we have had trouble getting all of the users to download and put the custom module in their PSModulePath.

Ideally I'd like the script to continue silently and not show any errors if the cmdlet cannot be found, but I haven't found a good way to do it. Right now we get messages like this:

```<code>C:> foo-bar
foo-bar : The term 'foo-bar' is not recognized as the name of a cmdlet, function, script file, or operable program...
</code>```

Setting ErrorActionPreference will suppress the message, but it also suppresses all other error messages which isn't desirable.

I could write a custom function in every script that checks to see if the module is loading before calling the custom cmdlets, but it seems like there should be a better way to do it.

答:
You can use try/catch in a different way to suppress that. Since it is not a cmdlet, -erroraction won't work directly. So you can try like this:

```<code>try
{
    foo-bar
}
catch [Management.Automation.RuntimeException]
{

}
</code>```

Body:
I have a lot of powershell scripts so I created a custom logging Powershell module with a couple of cmdlets. The problem is that we have had trouble getting all of the users to download and put the custom module in their PSModulePath.

Ideally I'd like the script to continue silently and not show any errors if the cmdlet cannot be found, but I haven't found a good way to do it. Right now we get messages like this:

C:> foo-bar
foo-bar : The term 'foo-bar' is not recognized as the name of a cmdlet, function, script file, or operable program...

Setting ErrorActionPreference will suppress the message, but it also suppresses all other error messages which isn't desirable.

I could write a custom function in every script that checks to see if the module is loading before calling the custom cmdlets, but it seems like there should be a better way to do it.

Body:
You can use try/catch in a different way to suppress that. Since it is not a cmdlet, -erroraction won't work directly. So you can try like this:

try
{
    foo-bar
}
catch [Management.Automation.RuntimeException]
{

}


问:
How might I find the largest number contained in a JavaScript array?
I have a simple JavaScript Array object containing a few numbers.

```<code>[267, 306, 108]
</code>```

Is there a function that would find the largest number in this array?

答:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

const inputArray = [ 1, 3, 4, 9, 16, 2, 20, 18];
const maxNumber = Math.max(...inputArray);
console.log(maxNumber);```

Body:
I have a simple JavaScript Array object containing a few numbers.

[267, 306, 108]

Is there a function that would find the largest number in this array?


问:
FireFox Driver not working with Selenium
WHAT I HAVE DONE SO FAR:

I have included selenium as dependency in build.gradle. It looks like

```<code>dependencies {

    testCompile group: 'junit', name: 'junit', version: '4.11'
    testCompile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1'

}
</code>```

And in my test class I have included a small code as below.

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
import org.junit.Test;
import static org.junit.Assert.*;

public class TestClass {
    @Test
    public void Test1(){

            System.setProperty("webdriver.gecko.driver", "/Users/xyz/Downloads/geckodriver");
            DesiredCapabilities capabilities=DesiredCapabilities.firefox();
            capabilities.setCapability("marionette", true);
            WebDriver driver = new FirefoxDriver(capabilities);
            driver.get("http://www.google.com");
            driver.close();
            driver.quit();
    }
}
</code>```

And I have created a Testng instance to run the test case in intellij.

PROBLEM I AM FACING

After I execute the test. I get the following error.

```<code>org.openqa.selenium.WebDriverException: failed to lookup address information: nodename nor servname provided, or not known
</code>```

I am not sure how should i go about debugging it.

答:
Check path when you setProperty

System.setProperty("webdriver.gecko.driver",
  "D:\workspacess\src\config\geckodriver.exe");             WebDriver driver
  = new FirefoxDriver();

Body:
WHAT I HAVE DONE SO FAR:

I have included selenium as dependency in build.gradle. It looks like

dependencies {

    testCompile group: 'junit', name: 'junit', version: '4.11'
    testCompile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1'

}

And in my test class I have included a small code as below.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
import org.junit.Test;
import static org.junit.Assert.*;

public class TestClass {
    @Test
    public void Test1(){

            System.setProperty("webdriver.gecko.driver", "/Users/xyz/Downloads/geckodriver");
            DesiredCapabilities capabilities=DesiredCapabilities.firefox();
            capabilities.setCapability("marionette", true);
            WebDriver driver = new FirefoxDriver(capabilities);
            driver.get("http://www.google.com");
            driver.close();
            driver.quit();
    }
}

And I have created a Testng instance to run the test case in intellij.

PROBLEM I AM FACING

After I execute the test. I get the following error.

org.openqa.selenium.WebDriverException: failed to lookup address information: nodename nor servname provided, or not known

I am not sure how should i go about debugging it.


问:
Error run react-scripts start: event.js 182
I cloned a project in bitbucket, and when I run npm start, I received an error:

```<code> events.js:182
      throw er; // Unhandled 'error' event
      ^

Error: watch /var/www/html/eoffice-chat-web/public ENOSPC
    at exports._errnoException (util.js:1026:11)
    at FSWatcher.start (fs.js:1371:19)
    at Object.fs.watch (fs.js:1397:11)
    at createFsWatchInstance (/var/www/html/eoffice-chat-web/node_modules/chokidar/lib/nodefs-handler.js:37:15)
    at setFsWatchListener (/var/www/html/eoffice-chat-web/node_modules/chokidar/lib/nodefs-handler.js:80:15)
    at FSWatcher.NodeFsHandler._watchWithNodeFs (/var/www/html/eoffice-chat-web/node_modules/chokidar/lib/nodefs-handler.js:228:14)
    at FSWatcher.NodeFsHandler._handleDir (/var/www/html/eoffice-chat-web/node_modules/chokidar/lib/nodefs-handler.js:407:19)
    at FSWatcher.<anonymous> (/var/www/html/eoffice-chat-web/node_modules/chokidar/lib/nodefs-handler.js:455:19)
    at FSWatcher.<anonymous> (/var/www/html/eoffice-chat-web/node_modules/chokidar/lib/nodefs-handler.js:460:16)
    at FSReqWrap.oncomplete (fs.js:153:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! eoffice-chat-web@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the eoffice-chat-web@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/tom/.npm/_logs/2017-06-06T09_07_59_232Z-debug.log
</code>```

Please help me fix it! Thank you.

答: The ENOSPC part of your error means that there is no space on the drive where it is running. Check to make sure you have enough space free on that partition.

Body:
I cloned a project in bitbucket, and when I run npm start, I received an error:

 events.js:182
      throw er; // Unhandled 'error' event
      ^

Error: watch /var/www/html/eoffice-chat-web/public ENOSPC
    at exports._errnoException (util.js:1026:11)
    at FSWatcher.start (fs.js:1371:19)
    at Object.fs.watch (fs.js:1397:11)
    at createFsWatchInstance (/var/www/html/eoffice-chat-web/node_modules/chokidar/lib/nodefs-handler.js:37:15)
    at setFsWatchListener (/var/www/html/eoffice-chat-web/node_modules/chokidar/lib/nodefs-handler.js:80:15)
    at FSWatcher.NodeFsHandler._watchWithNodeFs (/var/www/html/eoffice-chat-web/node_modules/chokidar/lib/nodefs-handler.js:228:14)
    at FSWatcher.NodeFsHandler._handleDir (/var/www/html/eoffice-chat-web/node_modules/chokidar/lib/nodefs-handler.js:407:19)
    at FSWatcher.<anonymous> (/var/www/html/eoffice-chat-web/node_modules/chokidar/lib/nodefs-handler.js:455:19)
    at FSWatcher.<anonymous> (/var/www/html/eoffice-chat-web/node_modules/chokidar/lib/nodefs-handler.js:460:16)
    at FSReqWrap.oncomplete (fs.js:153:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! eoffice-chat-web@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the eoffice-chat-web@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/tom/.npm/_logs/2017-06-06T09_07_59_232Z-debug.log

Please help me fix it! Thank you.


问:
C# String.IsNullOrEmpty Javascript equivalent
I want to try to do string call equivalent to the C# String.IsNullOrEmpty(string) in javascript. I looked online assuming that there was a simple call to make, but I could not find one.

For now I am using a if(string === "" || string === null) statement to cover it, but I would rather use a predefined method (I keep getting some instances that slip by for some reason)

What is the closest javascript (or jquery if then have one) call that would be equal?

答:
you can say it by logic </p>

<p>Let say you have a variable name a strVal, to check if is null or empty </p>

```<code>if (typeof (strVal) == 'string' && strVal.length > 0)
{
// is has a value and it is not null  :)
}
else
{
//it is null or empty :(
}
</code>```

Body:
you can say it by logic

Let say you have a variable name a strVal, to check if is null or empty

if (typeof (strVal) == 'string' && strVal.length > 0)
{
// is has a value and it is not null  :)
}
else
{
//it is null or empty :(
}


问:
$location.hash() breaking my function
I'm very close to finishing up my page, and I ran into this odd bug.

When I use ng-include, the pages load fine, but they resume scrolling from the previous position, so they don't start at the top with every click.

I resorted to using anchor scroll, but it doesn't work properly. I have to click the link again, for it to load the contents, and if I click the same link again, it offsets the page to some weird position.

This is my code in the controller:

```<code>    $scope.toPage = function (index, id) {
    $scope.missiveIndex = index;
    $scope.contentsDown();
    $location.hash(id);
};
</code>```

and this is the HTML part:

```<code><article id="{{articles.ids}}" class="stories-anim" ng-repeat="articles in stories" ng-hide="!isMissiveSlideIndex($index)" ng-include="articles.content" [autoscroll]>
</article>
</code>```

the id is passed in via ng-click="ng-click="toPage($index, button.ids);"

is there a way to put the location.hash in the [onload] expression and autoscroll that way?

thanks

答:
Probably the anchor scroll didn't work because the content of the page was not fully loaded when it was called.

You can solve that by using a timeout.

```<code>$timeout(function() {
  $anchorScroll();
},500);
</code>```

Title: $location.hash() breaking my function

Body:
I'm very close to finishing up my page, and I ran into this odd bug.

When I use ng-include, the pages load fine, but they resume scrolling from the previous position, so they don't start at the top with every click.

I resorted to using anchor scroll, but it doesn't work properly. I have to click the link again, for it to load the contents, and if I click the same link again, it offsets the page to some weird position.

This is my code in the controller:

    $scope.toPage = function (index, id) {
    $scope.missiveIndex = index;
    $scope.contentsDown();
    $location.hash(id);
};

and this is the HTML part:

the id is passed in via ng-click="ng-click="toPage($index, button.ids);"

is there a way to put the location.hash in the [onload] expression and autoscroll that way?

thanks

Body:
Probably the anchor scroll didn't work because the content of the page was not fully loaded when it was called.

You can solve that by using a timeout.

$timeout(function() {
  $anchorScroll();
},500);


问:
Count all word including numbers in a php string
To count words in a php string usually we can use str_word_count but I think not always a good solution

good example:

```<code>$var ="Hello world!";
echo str_word_count($str);
print_r(str_word_count($str, 1));
</code>```

-->output

```<code>   2
   Array ( [0] => Hello [1] => world )
</code>```

bad example:

```<code>$var ="The example number 2 is a bad example it will not
count numbers  and punctuations !!";
</code>```

-->output:

```<code>  14
  Array ( [0] => The [1] => example [2] => number [3] => is [4] => a
  [5] => bad [6] => example [7] => it [8] => will [9] => not
  [10] => count [11] => numbers [12] => and [13] => punctuations )
</code>```

Is there a good predefined function to do this properly or do I have to use preg_match() ?

答:
You may also use the below code it's working for me.

```<code>    function get_num_of_words($string) {
        $string = preg_replace('/\s+/', ' ', trim($string));
        $words = explode(" ", $string);
        return count($words);
    }

    $string="php string word count in simple way";
    echo $count=get_num_of_words($string);
</code>```

The result will be 7

Body:
To count words in a php string usually we can use str_word_count but I think not always a good solution

good example:

$var ="Hello world!";
echo str_word_count($str);
print_r(str_word_count($str, 1));

-->output

   2
   Array ( [0] => Hello [1] => world )

bad example:

$var ="The example number 2 is a bad example it will not
count numbers  and punctuations !!";

-->output:

  14
  Array ( [0] => The [1] => example [2] => number [3] => is [4] => a
  [5] => bad [6] => example [7] => it [8] => will [9] => not
  [10] => count [11] => numbers [12] => and [13] => punctuations )

Is there a good predefined function to do this properly or do I have to use preg_match() ?

Body:
You may also use the below code it's working for me.

    function get_num_of_words($string) {
        $string = preg_replace('/\s+/', ' ', trim($string));
        $words = explode(" ", $string);
        return count($words);
    }

    $string="php string word count in simple way";
    echo $count=get_num_of_words($string);

The result will be 7


问:
cancel canvas animation by adding eventListener
I am trying to reset my rectangle animation from the starting point when I resize the browser, the code is like this:

```<code>/*from basic setup*/
canvas = document.getElementById("myCanvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx = canvas.getContext("2d");

/*the "resize" event and the reset function should be triggered */
window.addEventListener("resize",function(){
     canvas.height = window.innerHeight;
     canvas.width = window.innerWidth;
     //cancelAnimationFrame(timeID)
     //theRect();
});

/*drawing the rectangle*/
var x = 0,y = canvas.height - 100,w = 100, h = 100,dx=1;

function theRect(){
 ctx.fillStyle = "lightblue";
 ctx.fillRect(x,y,w,h)
 x+=dx;
 if(x+w>canvas.width/2 || x<0){
    dx=-dx;
 }
}

/*start animation*/

function animate(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    theRect();
    requestAnimationFrame(animate);

}
//var timeID = requestAnimationFrame(animate)

animate();
</code>```

I was thinking if each time the browser resized, the rectangle has to be reset to the starting point asctx.fillRect(0,canvas.height-100,100,100)and continue its animation.

So my original approach to solve this is using cancelAnimationFrame()this method to kill the animation first and calling this function again within my eventlistener so each time the event was fired, the animation will stop and run again.

but cancellAnimationFrame()function requires the target animation timeID, and there is no way to track this timeID inside my animate()function since if I am calling var timeID = requestionAnimationFrame(animate)it will come to huge lag spikes on my browser

just the more I want to modify to more I become to loss with this, so my questions are:

1, is this wise to use cancelAnimationFrame here as the first step to reset my animation?

2, is there any other good way to achieve this "reset" purpose?

Could someone please help me with this? thanks in advance.

答:
The code posted does seem to get confused and cause the rectangle to hang and quiver in place for reasons I never fully understood. Addressing two issues largely resolved the problem.

Queuing lengthy calculations from a resize handler can reduce system overhead. A simple timer (say 100ms) can be used to delay starting the reaction required.

All parameters for the animation need to be recalculated after window resize.

Note that using window.innerHeight and window.innerWidth for the canvas size causes display of scroll bars. One cause is that the effect of body element padding and margins puts the animation outside the view port. I didn't take this further and subtracted 20px from the values for demonstration purposes only.

This working example is shown as HTML source because it uses the whole viewport:

```<code><!DOCTYPE html><html><head><meta charset="utf-8">
    <title>animation question</title>
</head>
<body>
    <canvas id="myCanvas"></canvas>
<script>

/*from basic setup*/
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var delayTimer = 0;
var animateTimer = 0;

function sizeCanvas() { // demonstration
    canvas.height = window.innerHeight -20;
    canvas.width = window.innerWidth -20;
}
sizeCanvas();  // initialize

/* monitor "resize" event */

window.addEventListener("resize",function(){
     clearTimeout( delayTimer);
     if( animateTimer) {
         cancelAnimationFrame( animateTimer);
         animateTimer = 0;
     }
     delayTimer = setTimeout( resizeCanvas, 100);
});

function resizeCanvas() {
    delayTimer = 0;
    sizeCanvas();
    x = 0; y = canvas.height - 100;
    animate(); // restart
}

/*drawing the rectangle*/
var x = 0,y = canvas.height - 100,w = 100, h = 100,dx=2;

function theRect(){
 ctx.fillStyle = "lightblue";
 ctx.fillRect(x,y,w,h)
 x+=dx;
 if(x+w>canvas.width/2 || x<0){
    dx=-dx;
 }
}

/*start animation*/

function animate(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    theRect();
    animateTimer = requestAnimationFrame(animate);
}
animate();

</script>
</body>
</html>
</code>```

So in answer to your questions:

using cancelAnimationFrame is a good way of cleanly stopping the current animation, as long as it is started again.

It is not absolutely required as part of the solution if you are willing to leave the animation running. A solution taking this approach may still need to halt animation by testing if the resize timer is running inside animate and didn't seem to be a any clearer so I haven't posted the code. (I encountered no noticeable overhead from recording the requestId returned from requestAnimationFrame.)

Body:
I am trying to reset my rectangle animation from the starting point when I resize the browser, the code is like this:

/*from basic setup*/
canvas = document.getElementById("myCanvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx = canvas.getContext("2d");

/*the "resize" event and the reset function should be triggered */
window.addEventListener("resize",function(){
     canvas.height = window.innerHeight;
     canvas.width = window.innerWidth;
     //cancelAnimationFrame(timeID)
     //theRect();
});

/*drawing the rectangle*/
var x = 0,y = canvas.height - 100,w = 100, h = 100,dx=1;

function theRect(){
 ctx.fillStyle = "lightblue";
 ctx.fillRect(x,y,w,h)
 x+=dx;
 if(x+w>canvas.width/2 || x<0){
    dx=-dx;
 }
}

/*start animation*/

function animate(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    theRect();
    requestAnimationFrame(animate);

}
//var timeID = requestAnimationFrame(animate)

animate();

I was thinking if each time the browser resized, the rectangle has to be reset to the starting point asctx.fillRect(0,canvas.height-100,100,100)and continue its animation.

So my original approach to solve this is using cancelAnimationFrame()this method to kill the animation first and calling this function again within my eventlistener so each time the event was fired, the animation will stop and run again.

but cancellAnimationFrame()function requires the target animation timeID, and there is no way to track this timeID inside my animate()function since if I am calling var timeID = requestionAnimationFrame(animate)it will come to huge lag spikes on my browser

just the more I want to modify to more I become to loss with this, so my questions are:

1, is this wise to use cancelAnimationFrame here as the first step to reset my animation?

2, is there any other good way to achieve this "reset" purpose?

Could someone please help me with this? thanks in advance.

Body:
The code posted does seem to get confused and cause the rectangle to hang and quiver in place for reasons I never fully understood. Addressing two issues largely resolved the problem.

Queuing lengthy calculations from a resize handler can reduce system overhead. A simple timer (say 100ms) can be used to delay starting the reaction required.

All parameters for the animation need to be recalculated after window resize.

Note that using window.innerHeight and window.innerWidth for the canvas size causes display of scroll bars. One cause is that the effect of body element padding and margins puts the animation outside the view port. I didn't take this further and subtracted 20px from the values for demonstration purposes only.

This working example is shown as HTML source because it uses the whole viewport:

<!DOCTYPE html><html><head><meta charset="utf-8">
    <title>animation question</title>
</head>
<body>
    <canvas id="myCanvas"></canvas>
<script>

/*from basic setup*/
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var delayTimer = 0;
var animateTimer = 0;

function sizeCanvas() { // demonstration
    canvas.height = window.innerHeight -20;
    canvas.width = window.innerWidth -20;
}
sizeCanvas();  // initialize

/* monitor "resize" event */

window.addEventListener("resize",function(){
     clearTimeout( delayTimer);
     if( animateTimer) {
         cancelAnimationFrame( animateTimer);
         animateTimer = 0;
     }
     delayTimer = setTimeout( resizeCanvas, 100);
});

function resizeCanvas() {
    delayTimer = 0;
    sizeCanvas();
    x = 0; y = canvas.height - 100;
    animate(); // restart
}

/*drawing the rectangle*/
var x = 0,y = canvas.height - 100,w = 100, h = 100,dx=2;

function theRect(){
 ctx.fillStyle = "lightblue";
 ctx.fillRect(x,y,w,h)
 x+=dx;
 if(x+w>canvas.width/2 || x<0){
    dx=-dx;
 }
}

/*start animation*/

function animate(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    theRect();
    animateTimer = requestAnimationFrame(animate);
}
animate();

</script>
</body>
</html>

So in answer to your questions:

using cancelAnimationFrame is a good way of cleanly stopping the current animation, as long as it is started again.

It is not absolutely required as part of the solution if you are willing to leave the animation running. A solution taking this approach may still need to halt animation by testing if the resize timer is running inside animate and didn't seem to be a any clearer so I haven't posted the code. (I encountered no noticeable overhead from recording the requestId returned from requestAnimationFrame.)


问:
Use numpy with Cython
I want to create .so file from python and execute the .so file in C.
To do it I used cython to convert .pyx to .so

```<code>## print_me.pyx
cimport numpy as cnp
import  numpy as np
cimport cython
cpdef public char* print_me(f):
    # I know this numpy line does nothing
    cdef cnp.ndarray[cnp.complex128_t, ndim=3] a = np.zeros((3,3,3), dtype=np.complex128)
    return f
</code>```

Then I used setup.py to actually convert .pyx to .so

```<code>## setup.py
from distutils.core import setup
from Cython.Build import cythonize
import numpy as np

setup(
    ext_modules=cythonize("print_me.pyx"),
    include_dirs=[np.get_include()]
)
</code>```

By running the following command line, I was able to create .so file

```<code>python setup.py build_ext --inplace
</code>```

When I tried to run so file using the following C code, I got a Segmentation Fault.

```<code>/* toloadso.c */
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <time.h>
#include <python2.7/Python.h>

int main(void)
{
    // define function
    void *handle;
    char* (*print_me)(PyObject*);
    char *error;

    PyObject* filename = PyString_FromString("hello");

    // load so file
    handle = dlopen("./print_me.so", RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "%s\n", dlerror());
        exit(EXIT_FAILURE);
    }
    dlerror();

    // get function handler from so file
    print_me = (char* (*)(PyObject*))dlsym(handle, "print_me");

    // check if handler got error
    error = dlerror();
    if (error != NULL) {
        fprintf(stderr, "%s\n", error);
        exit(EXIT_FAILURE);
    }

    // execute loaded function
    printf("%s\n", (char*)(*print_me)(filename));
    dlclose(handle);
    exit(EXIT_SUCCESS);
}
</code>```

I compiled this .c file with following command:

```<code>gcc -fPIC -I/usr/include/ -o toloadso toloadso.c -lpython2.7 -ldl
(It compiled without error or warning)
</code>```

When I tried to run this code, I got a segmentation Fault

```<code>[root@localhost ~]# ./toloadso
Segmentation fault
</code>```

If I comment out the following line in print_me.pyx

```<code>cdef cnp.ndarray[cnp.complex128_t, ndim=3] a = np.zeros((3,3,3), dtype=np.complex128)
</code>```

My C code runs without error, but once I uncomment this line, it does not work.
I think that trying to use numpy in cython generates an error somehow.

How can I fix it??
I thank you so much for your reply

答:
Thank you for your help first. I could get something useful information, even though that could not directly solve my problem.

By referring to others advice,
rather than calling print_me function from .so file, I decided to call directly from C. This is what I did.

```<code># print_me.pyx
import  numpy as np
cimport numpy as np

np.import_array()

cdef public char* print_me(f):
    cdef int[2][4] ll = [[1, 2, 3, 4], [5,6,7,8]]
    cdef np.ndarray[np.int_t, ndim=2] nll = np.zeros((4, 6), dtype=np.int)
    print nll
    nll += 1
    print nll
    return f + str(ll[1][0])
</code>```

This is my .c file

```<code>// main.c
#include <python2.7/Python.h>
#include "print_me.h"

int main()
{
    // initialize python
    Py_Initialize();
    PyObject* filename = PyString_FromString("hello");
    initsquare_number();
    //initprint_me();

    // call python-oriented function
    printf("%s\n", print_me(filename));

    // finalize python
    Py_Finalize();
    return 0;
}
</code>```

I compiled then as follows

```<code># to generate print_me.c and print_me.h
cython print_me.pyx

# to build main.c and print_me.c into main.o and print_me.o
cc -c main.c print_me.c -I/usr/include/python2.7 -I/usr/lib64/python2.7/site-packages/numpy/core/include

# to linke .o files
cc -lpython2.7 -ldl main.o print_me.o -o main

# execute main
./main
</code>```

This results the following

```<code>[[0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]]
[[1 1 1 1 1 1]
 [1 1 1 1 1 1]
 [1 1 1 1 1 1]
 [1 1 1 1 1 1]]
hello5
</code>```

Thank you for all of your help again!! :)

Title: Use numpy with Cython

Body:
I want to create .so file from python and execute the .so file in C.
To do it I used cython to convert .pyx to .so

## print_me.pyx
cimport numpy as cnp
import  numpy as np
cimport cython
cpdef public char* print_me(f):
    # I know this numpy line does nothing
    cdef cnp.ndarray[cnp.complex128_t, ndim=3] a = np.zeros((3,3,3), dtype=np.complex128)
    return f

Then I used setup.py to actually convert .pyx to .so

## setup.py
from distutils.core import setup
from Cython.Build import cythonize
import numpy as np

setup(
    ext_modules=cythonize("print_me.pyx"),
    include_dirs=[np.get_include()]
)

By running the following command line, I was able to create .so file

python setup.py build_ext --inplace

When I tried to run so file using the following C code, I got a Segmentation Fault.

/* toloadso.c */
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <time.h>
#include <python2.7/Python.h>

int main(void)
{
    // define function
    void *handle;
    char* (*print_me)(PyObject*);
    char *error;

    PyObject* filename = PyString_FromString("hello");

    // load so file
    handle = dlopen("./print_me.so", RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "%s\n", dlerror());
        exit(EXIT_FAILURE);
    }
    dlerror();

    // get function handler from so file
    print_me = (char* (*)(PyObject*))dlsym(handle, "print_me");

    // check if handler got error
    error = dlerror();
    if (error != NULL) {
        fprintf(stderr, "%s\n", error);
        exit(EXIT_FAILURE);
    }

    // execute loaded function
    printf("%s\n", (char*)(*print_me)(filename));
    dlclose(handle);
    exit(EXIT_SUCCESS);
}

I compiled this .c file with following command:

gcc -fPIC -I/usr/include/ -o toloadso toloadso.c -lpython2.7 -ldl
(It compiled without error or warning)

When I tried to run this code, I got a segmentation Fault

[root@localhost ~]# ./toloadso
Segmentation fault

If I comment out the following line in print_me.pyx

cdef cnp.ndarray[cnp.complex128_t, ndim=3] a = np.zeros((3,3,3), dtype=np.complex128)

My C code runs without error, but once I uncomment this line, it does not work.
I think that trying to use numpy in cython generates an error somehow.

How can I fix it??
I thank you so much for your reply

Body:
Thank you for your help first. I could get something useful information, even though that could not directly solve my problem.

By referring to others advice,
rather than calling print_me function from .so file, I decided to call directly from C. This is what I did.

# print_me.pyx
import  numpy as np
cimport numpy as np

np.import_array()

cdef public char* print_me(f):
    cdef int[2][4] ll = [[1, 2, 3, 4], [5,6,7,8]]
    cdef np.ndarray[np.int_t, ndim=2] nll = np.zeros((4, 6), dtype=np.int)
    print nll
    nll += 1
    print nll
    return f + str(ll[1][0])

This is my .c file

// main.c
#include <python2.7/Python.h>
#include "print_me.h"

int main()
{
    // initialize python
    Py_Initialize();
    PyObject* filename = PyString_FromString("hello");
    initsquare_number();
    //initprint_me();

    // call python-oriented function
    printf("%s\n", print_me(filename));

    // finalize python
    Py_Finalize();
    return 0;
}

I compiled then as follows

# to generate print_me.c and print_me.h
cython print_me.pyx

# to build main.c and print_me.c into main.o and print_me.o
cc -c main.c print_me.c -I/usr/include/python2.7 -I/usr/lib64/python2.7/site-packages/numpy/core/include

# to linke .o files
cc -lpython2.7 -ldl main.o print_me.o -o main

# execute main
./main

This results the following

[[0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]]
[[1 1 1 1 1 1]
 [1 1 1 1 1 1]
 [1 1 1 1 1 1]
 [1 1 1 1 1 1]]
hello5

Thank you for all of your help again!! :)


问:
SSRS 2005 - Running Group Count
How do you you display the running GROUP count via SSRS 2005?

I have a report that has n groups where the source data must remain anonymous and I want that number in the header of the group...

So instead of the name in the group header like such...

Employee - John Smith

Employee - Mary Swain

...

Employee - Ahmad Sal

I want...

Employee #1

Employee #2

...

Employee #n

Thanks!!!

答:
=RunningValue(Fields!Employee.Value, CountDistinct, Nothing)

Voila!

Title: SSRS 2005 - Running Group Count


问:
force swagger to ask for basic http authentication with springfox
I have web service that secure with spring security with basic http authentication.
when i was document it with swagger using springfox-swagger2 library
how can i force  swagger ui to ask for user name password</p>

答:
I am not sure why do you want to do that?
If you don't want to expose certain api's in swagger, use a PathSelector. If you don't want everyone to see your Api's, host your swagger ui on a specific server and share the details as per need. Not sure why you would want to add a http authentication.</p>


问:
Why do I keep getting this message but the SQL syntax is working
I have a problem: I keep getting this message shown below, but the add button is working (meaning it is adding data to the database).

The error below appears every time I press the add button. I updated the code. This is now the showlist function.

Code:

```<code>void Showlist()
{
    string sql = "SELECT studentnumber AS 'Student Number', lastname AS 'Last Name', firstname AS 'First Name', middlename AS 'Middle Name', picture AS 'Picture', course AS 'Course', year AS 'Year', section AS 'Section', partylist AS 'Partylist', information AS 'Information', position 'Position', election 'Election', FROM candidates";
    MySqlDataAdapter adapter = new MySqlDataAdapter(sql, conn);
    DataSet ds = new DataSet();
    adapter.Fill(ds, "candidates");
    dataGridView1.DataSource = ds;
    dataGridView1.DataMember = "candidates";
}
</code>```

答:
There is an additional , in the select statement just before From .

change the sql select line as :-

```<code>string sql = "SELECT studentnumber AS 'Student Number', lastname AS 'Last Name', firstname AS 'First Name', middlename AS 'Middle Name', picture AS 'Picture', course AS 'Course', year AS 'Year', section AS 'Section', partylist AS 'Partylist', information AS 'Information' , position 'Position', election 'Election' FROM candidates";
</code>```

Body:
I have a problem: I keep getting this message shown below, but the add button is working (meaning it is adding data to the database).

The error below appears every time I press the add button. I updated the code. This is now the showlist function.

Code:

void Showlist()
{
    string sql = "SELECT studentnumber AS 'Student Number', lastname AS 'Last Name', firstname AS 'First Name', middlename AS 'Middle Name', picture AS 'Picture', course AS 'Course', year AS 'Year', section AS 'Section', partylist AS 'Partylist', information AS 'Information', position 'Position', election 'Election', FROM candidates";
    MySqlDataAdapter adapter = new MySqlDataAdapter(sql, conn);
    DataSet ds = new DataSet();
    adapter.Fill(ds, "candidates");
    dataGridView1.DataSource = ds;
    dataGridView1.DataMember = "candidates";
}

Body:
There is an additional , in the select statement just before From .

change the sql select line as :-

string sql = "SELECT studentnumber AS 'Student Number', lastname AS 'Last Name', firstname AS 'First Name', middlename AS 'Middle Name', picture AS 'Picture', course AS 'Course', year AS 'Year', section AS 'Section', partylist AS 'Partylist', information AS 'Information' , position 'Position', election 'Election' FROM candidates";


问:
Large space between navbar brand and navbar menu using bootstrap
I added a picture in navbar brand, and I don't know how to remove the space between it and the following navbar menu.
Unnecessary space in red circle.

Here is my html:

a.navbar-brand {
  height: 48;
  width: 64;
  display: inline-block;
  padding: 1px 0;
}

.collapse.navbar-collapse {
  padding: 1px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <img src="img/name.png" alt="name" height="48" width="64" border="0">
  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
      Code<span class="sr-only">(current)</span>
      </li>
      <li class="nav-item">
        Life
      </li>
      <li class="nav-item">
        About
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="text" placeholder="Hello World">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav></code>```

Do you have any ideas why the white space is there and how should I remove it? Thank you.

答:
Your problem stems from the fact that you are setting a flat 50% width to all objects with type img.

I found this code in your CSS which is directly affecting the image

div img {
    width: 50%;
    margin: auto;
}

I would move this to either id based or class based styling to avoid applying it to absolutely everything on your site.

Hope you manage to fix it and get it displaying the way you like.

Body:
I added a picture in navbar brand, and I don't know how to remove the space between it and the following navbar menu.
Unnecessary space in red circle.

Here is my html:

a.navbar-brand {
  height: 48;
  width: 64;
  display: inline-block;
  padding: 1px 0;
}

.collapse.navbar-collapse {
  padding: 1px 0;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

      Code(current)

        Life

        About

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="text" placeholder="Hello World">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>

Do you have any ideas why the white space is there and how should I remove it? Thank you.


问:
Nativescript and angular 2 app breaks when making http calls
On updating to tns core module 2.2.0 and angular rc4 (officially released version by telerik), My app can no longer make http calls to a server, I keep getting this error

```<code>com.tns.NativeScriptException:
Calling js method onClick failed

EXCEPTION: Error in /data/data/org.nativescript.EatSafe/files/app/pages/login/login.html:5:75
ORIGINAL EXCEPTION: Error: not implemented
ORIGINAL STACKTRACE:
Error: not implemented
    at NativeScriptDomAdapter.Parse5DomAdapter.getCookie (/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/platform-server/src/parse5_adapter.js:619:68)
    at CookieXSRFStrategy.configureRequest (/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/http/src/backends/xhr_backend.js:150:82)
    at XHRBackend.createConnection (/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/http/src/backends/xhr_backend.js:165:28)
    at httpRequest (/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/http/src/http.js:22:20)
    at Http.post (/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/http/src/http.js:78:16)
    at UserService.signin (/data/data/org.nativescript.EatSafe/files/app/shared/services/user.service.js:13:27)
    at LoginComponent.login (/data/data/org.nativescript.EatSafe/files/app/pages/login/login.component.js:31:27)
    at DebugAppView._View_LoginComponent0._handle_tap_8_0 (LoginComponent.template.js:355:28)
    at /data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/linker/view.js:375:24
    at /data/data/org.nativescript.EatSafe/files/app/tns_modules/nativescript-angular/renderer.js:204:26
ERROR CONTEXT:
[object Object]
File: "/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/linker/view.js, line: 365, column: 16

StackTrace:
    Frame: function:'DebugAppView._rethrowWithContext', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/linker/view.js', line: 365, column: 17
    Frame: function:'', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/linker/view.js', line: 378, column: 23
    Frame: function:'', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/nativescript-angular/renderer.js', line: 204, column: 26
    Frame: function:'ZoneDelegate.invoke', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/zone.js/dist/zone-node.js', line: 290, column: 29
    Frame: function:'NgZoneImpl.inner.inner.fork.onInvoke', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/zone/ng_zone_impl.js', line: 53, column: 41
    Frame: function:'ZoneDelegate.invoke', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/zone.js/dist/zone-node.js', line: 289, column: 35
    Frame: function:'Zone.run', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/zone.js/dist/zone-node.js', line: 183, column: 44
    Frame: function:'NgZoneImpl.runInner', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/zone/ng_zone_impl.js', line: 84, column: 71
    Frame: function:'NgZone.run', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/zone/ng_zone.js', line: 235, column: 66
    Frame: function:'zonedCallback', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/nativescript-angular/renderer.js', line: 203, column: 24
    Frame: function:'Observable.notify', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/data/observable/observable.js', line: 174, column: 23
    Frame: function:'Observable._emit', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/data/observable/observable.js', line: 193, column: 18
    Frame: function:'_android.setOnClickListener.android.view.View.OnClickListener.onClick', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/ui/button/button.js', line: 33, column: 32

    at com.tns.Runtime.callJSMethodNative(Native Method)
    at com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:862)
    at com.tns.Runtime.callJSMethodImpl(Runtime.java:727)
    at com.tns.Runtime.callJSMethod(Runtime.java:713)
    at com.tns.Runtime.callJSMethod(Runtime.java:694)
    at com.tns.Runtime.callJSMethod(Runtime.java:684)
    at com.tns.gen.android.view.View_OnClickListener.onClick(View_OnClickListener.java:11)
    at android.view.View.performClick(View.java:5233)
    at android.view.View$PerformClick.run(View.java:21209)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:152)
    at android.app.ActivityThread.main(ActivityThread.java:5507)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

I have been trying to look online for a release log of the update to see if there are any breaking changes, but to no avail. does anyone have any pointers on how to make http calls with the new nativescript angular updates?

Thank you

答:
I got this fixed by importing in app.moudle.ts the following

```<code>import {NativeScriptHttpModule} from 'nativescript-angular/http';
</code>```

And then

```<code> imports: [NativeScriptHttpModule]
</code>```

Body:
On updating to tns core module 2.2.0 and angular rc4 (officially released version by telerik), My app can no longer make http calls to a server, I keep getting this error

com.tns.NativeScriptException:
Calling js method onClick failed

EXCEPTION: Error in /data/data/org.nativescript.EatSafe/files/app/pages/login/login.html:5:75
ORIGINAL EXCEPTION: Error: not implemented
ORIGINAL STACKTRACE:
Error: not implemented
    at NativeScriptDomAdapter.Parse5DomAdapter.getCookie (/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/platform-server/src/parse5_adapter.js:619:68)
    at CookieXSRFStrategy.configureRequest (/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/http/src/backends/xhr_backend.js:150:82)
    at XHRBackend.createConnection (/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/http/src/backends/xhr_backend.js:165:28)
    at httpRequest (/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/http/src/http.js:22:20)
    at Http.post (/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/http/src/http.js:78:16)
    at UserService.signin (/data/data/org.nativescript.EatSafe/files/app/shared/services/user.service.js:13:27)
    at LoginComponent.login (/data/data/org.nativescript.EatSafe/files/app/pages/login/login.component.js:31:27)
    at DebugAppView._View_LoginComponent0._handle_tap_8_0 (LoginComponent.template.js:355:28)
    at /data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/linker/view.js:375:24
    at /data/data/org.nativescript.EatSafe/files/app/tns_modules/nativescript-angular/renderer.js:204:26
ERROR CONTEXT:
[object Object]
File: "/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/linker/view.js, line: 365, column: 16

StackTrace:
    Frame: function:'DebugAppView._rethrowWithContext', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/linker/view.js', line: 365, column: 17
    Frame: function:'', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/linker/view.js', line: 378, column: 23
    Frame: function:'', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/nativescript-angular/renderer.js', line: 204, column: 26
    Frame: function:'ZoneDelegate.invoke', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/zone.js/dist/zone-node.js', line: 290, column: 29
    Frame: function:'NgZoneImpl.inner.inner.fork.onInvoke', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/zone/ng_zone_impl.js', line: 53, column: 41
    Frame: function:'ZoneDelegate.invoke', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/zone.js/dist/zone-node.js', line: 289, column: 35
    Frame: function:'Zone.run', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/zone.js/dist/zone-node.js', line: 183, column: 44
    Frame: function:'NgZoneImpl.runInner', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/zone/ng_zone_impl.js', line: 84, column: 71
    Frame: function:'NgZone.run', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/@angular/core/src/zone/ng_zone.js', line: 235, column: 66
    Frame: function:'zonedCallback', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/nativescript-angular/renderer.js', line: 203, column: 24
    Frame: function:'Observable.notify', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/data/observable/observable.js', line: 174, column: 23
    Frame: function:'Observable._emit', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/data/observable/observable.js', line: 193, column: 18
    Frame: function:'_android.setOnClickListener.android.view.View.OnClickListener.onClick', file:'/data/data/org.nativescript.EatSafe/files/app/tns_modules/ui/button/button.js', line: 33, column: 32

    at com.tns.Runtime.callJSMethodNative(Native Method)
    at com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:862)
    at com.tns.Runtime.callJSMethodImpl(Runtime.java:727)
    at com.tns.Runtime.callJSMethod(Runtime.java:713)
    at com.tns.Runtime.callJSMethod(Runtime.java:694)
    at com.tns.Runtime.callJSMethod(Runtime.java:684)
    at com.tns.gen.android.view.View_OnClickListener.onClick(View_OnClickListener.java:11)
    at android.view.View.performClick(View.java:5233)
    at android.view.View$PerformClick.run(View.java:21209)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:152)
    at android.app.ActivityThread.main(ActivityThread.java:5507)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

I have been trying to look online for a release log of the update to see if there are any breaking changes, but to no avail. does anyone have any pointers on how to make http calls with the new nativescript angular updates?

Thank you

Body:
I got this fixed by importing in app.moudle.ts the following

import {NativeScriptHttpModule} from 'nativescript-angular/http';

And then

 imports: [NativeScriptHttpModule]


问:
UI logic unit test
I have tens of conditions to check that set boolean values for seven or eight ui buttons enabled property.

So I setup boolean variables for each of the buttons (for example, isAction1Allowed, isAction2Allowed, etc.

How would I write a unit test for this case?

Currently, I have one method that contains all the logic which is nice but not sure how to turn into unit test (keep in mind very new to MVC and unit testing)

```<code>public void StateChecker() {  //This method resides in HtmlHelper
  bool isAllowed1 = false;
  bool isAllowed2 = false;
  bool isAllowed3 = false;

  if (condition1) {
    isAllowed1 = true;
  }
  else
  {
    isAllowed2 = true;
  }

  if (condition2) {
    isAllowed4 = true;
    isAllowed2 = true;
  }

// At the end of the method
Button1.Enabled = isAllowed1;
Button2.Enabled = isAllowed2;
Button3.Enabled = isAllowed3;

}
</code>```

Will I have to break the method up? Is there a better way to do what I'm trying to do? Remember there are a lot more conditions and buttons than the example shows but this is the gist of it. Basically, it's a small workflow or state machine.

答:
Here's one way (use optional model): </p>

```<code>  public YourModel{
    public bool IsAction1Allowed {get;set;}
    }

    public ActionResult Index(YourModel model = null){

    model = model ?? new Yourmodel();

    return View(model)
    }

 or (use public properties)

  public MyController:Controller{

    public bool IsAction1Allowed {get;set;}

   public ActionResult Index(){

    vare model = Yourmodel();
    model.IsAction1Allow = IsAction1Allowed

    return View(model)
    }

    }

or (use constructor)

   public MyController(Settings setting){

    public ActionResult Index(){

    vare model = Yourmodel();
    model.IsAction1Allow = settings.IsAction1Allowed

    return View(model)
    }

}
</code>```

Title: UI logic unit test

Body:
I have tens of conditions to check that set boolean values for seven or eight ui buttons enabled property.

So I setup boolean variables for each of the buttons (for example, isAction1Allowed, isAction2Allowed, etc.

How would I write a unit test for this case?

Currently, I have one method that contains all the logic which is nice but not sure how to turn into unit test (keep in mind very new to MVC and unit testing)

public void StateChecker() {  //This method resides in HtmlHelper
  bool isAllowed1 = false;
  bool isAllowed2 = false;
  bool isAllowed3 = false;

  if (condition1) {
    isAllowed1 = true;
  }
  else
  {
    isAllowed2 = true;
  }

  if (condition2) {
    isAllowed4 = true;
    isAllowed2 = true;
  }

// At the end of the method
Button1.Enabled = isAllowed1;
Button2.Enabled = isAllowed2;
Button3.Enabled = isAllowed3;

}

Will I have to break the method up? Is there a better way to do what I'm trying to do? Remember there are a lot more conditions and buttons than the example shows but this is the gist of it. Basically, it's a small workflow or state machine.

Body:
Here's one way (use optional model):

  public YourModel{
    public bool IsAction1Allowed {get;set;}
    }

    public ActionResult Index(YourModel model = null){

    model = model ?? new Yourmodel();

    return View(model)
    }

 or (use public properties)

  public MyController:Controller{

    public bool IsAction1Allowed {get;set;}

   public ActionResult Index(){

    vare model = Yourmodel();
    model.IsAction1Allow = IsAction1Allowed

    return View(model)
    }

    }

or (use constructor)

   public MyController(Settings setting){

    public ActionResult Index(){

    vare model = Yourmodel();
    model.IsAction1Allow = settings.IsAction1Allowed

    return View(model)
    }

}


问:
Query parent data (multi-level) based on a child value, on a json file, using jq
I have a ksh script that retrives (using curl) a json file similar to the one bellow:

```<code>{
  "Type1": {
    "dev": {
      "server": [
        {   "group": "APP1",    "name": "DAPP1002", "ip": "10.1.1.1" },
        {   "group": "APP2",    "name": "DAPP2001", "ip": "10.1.1.2" }
      ]
    },
    "qa": {
      "server": [
        {   "group": "APP1",    "name": "QAPP1002", "ip": "10.1.2.1" },
        {   "group": "APP2",    "name": "QAPP2001", "ip": "10.1.2.2" }
      ]
    },
    "prod": {
      "proxy": "type1.prod.proxy.mydomain.com",
      "server": [
        {   "group": "APP1",    "name": "PAPP1001", "ip": "10.1.3.1" },
        {   "group": "APP1",    "name": "PAPP1002", "ip": "10.1.3.2" },
        {   "group": "APP2",    "name": "PAPP2001", "ip": "10.1.3.3" }
      ]
    }
  },

  "Type2": {
    "dev": {
      "server": [
        {   "group": "APP8",    "name": "DAPP8002", "ip": "10.2.1.1" },
        {   "group": "APP9",    "name": "DAPP9001", "ip": "10.2.1.2" }
      ]
    },
    "qa": {
      "server": [
        {   "group": "APP8",    "name": "QAPP8002", "ip": "10.2.2.1" },
        {   "group": "APP9",    "name": "QAPP9001", "ip": "10.2.2.2" }
      ]
    },
    "prod": {
      "proxy": "type2.prod.proxy.mydomain.com",
      "server": [
        {   "group": "APP8",    "name": "PAPP8001", "ip": "10.2.3.1" },
        {   "group": "APP9",    "name": "PAPP9001", "ip": "10.2.3.2" },
        {   "group": "APP9",    "name": "PAPP9002", "ip": "10.2.3.3" }
      ]
    }
  }
}
</code>```

... based on a server name (field "name") I would have to collect the following info, to pass to a function:

```<code>"Type", "name", "ip", "proxy"
</code>```

(Note that the "proxy" info is optional)

I am new to json, and I am trying to get this filtered with jq but so far, I am out of lucky.
What I acomplished so far is the following jq query, when searching for "PAPP9001" :

```<code>jq '.[] | .[] | select(.server[].name=="PAPP9001") | .proxy as $proxy | .server[] | {proxy: $proxy, name: .name, ip: .ip} | select(.name=="PAPP9001")' curlreturn.json
</code>```

which returns me:

```<code>{
  "proxy": "type2.prod.proxy.mydomain.com",
  "name": "PAPP9001",
  "ip": "10.2.3.2"
}
</code>```

but:

I could not get the "Type" info, at the top level

Considering the number of pipes and the 2 selects, I doubt that this is the most efficient way.

答:
One way to retrieve the key names programmatically is using to_entries.  For example, given your input, this jq filter:

```<code>to_entries[]
| .key as $type
| .value[]
| .proxy as $proxy
| .server[]
| select(.name == "PAPP9001")
| { Type: $type, name, ip, proxy: $proxy }
</code>```

yields:

```<code>{
  "Type": "Type2",
  "name": "PAPP9001",
  "ip": "10.2.3.2",
  "proxy": "type2.prod.proxy.mydomain.com"
}
</code>```

Variations

If, for example, you wanted these four fields as a CSV row, then you could replace the last line of the filter above with:

```<code>| [$type, .name, .ip, $proxy] | @csv
</code>```

See the jq manual for how to use string interpolation.

Body:
I have a ksh script that retrives (using curl) a json file similar to the one bellow:

{
  "Type1": {
    "dev": {
      "server": [
        {   "group": "APP1",    "name": "DAPP1002", "ip": "10.1.1.1" },
        {   "group": "APP2",    "name": "DAPP2001", "ip": "10.1.1.2" }
      ]
    },
    "qa": {
      "server": [
        {   "group": "APP1",    "name": "QAPP1002", "ip": "10.1.2.1" },
        {   "group": "APP2",    "name": "QAPP2001", "ip": "10.1.2.2" }
      ]
    },
    "prod": {
      "proxy": "type1.prod.proxy.mydomain.com",
      "server": [
        {   "group": "APP1",    "name": "PAPP1001", "ip": "10.1.3.1" },
        {   "group": "APP1",    "name": "PAPP1002", "ip": "10.1.3.2" },
        {   "group": "APP2",    "name": "PAPP2001", "ip": "10.1.3.3" }
      ]
    }
  },

  "Type2": {
    "dev": {
      "server": [
        {   "group": "APP8",    "name": "DAPP8002", "ip": "10.2.1.1" },
        {   "group": "APP9",    "name": "DAPP9001", "ip": "10.2.1.2" }
      ]
    },
    "qa": {
      "server": [
        {   "group": "APP8",    "name": "QAPP8002", "ip": "10.2.2.1" },
        {   "group": "APP9",    "name": "QAPP9001", "ip": "10.2.2.2" }
      ]
    },
    "prod": {
      "proxy": "type2.prod.proxy.mydomain.com",
      "server": [
        {   "group": "APP8",    "name": "PAPP8001", "ip": "10.2.3.1" },
        {   "group": "APP9",    "name": "PAPP9001", "ip": "10.2.3.2" },
        {   "group": "APP9",    "name": "PAPP9002", "ip": "10.2.3.3" }
      ]
    }
  }
}

... based on a server name (field "name") I would have to collect the following info, to pass to a function:

"Type", "name", "ip", "proxy"

(Note that the "proxy" info is optional)

I am new to json, and I am trying to get this filtered with jq but so far, I am out of lucky.
What I acomplished so far is the following jq query, when searching for "PAPP9001" :

jq '.[] | .[] | select(.server[].name=="PAPP9001") | .proxy as $proxy | .server[] | {proxy: $proxy, name: .name, ip: .ip} | select(.name=="PAPP9001")' curlreturn.json

which returns me:

{
  "proxy": "type2.prod.proxy.mydomain.com",
  "name": "PAPP9001",
  "ip": "10.2.3.2"
}

but:

I could not get the "Type" info, at the top level

Considering the number of pipes and the 2 selects, I doubt that this is the most efficient way.

Body:
One way to retrieve the key names programmatically is using to_entries.  For example, given your input, this jq filter:

to_entries[]
| .key as $type
| .value[]
| .proxy as $proxy
| .server[]
| select(.name == "PAPP9001")
| { Type: $type, name, ip, proxy: $proxy }

yields:

{
  "Type": "Type2",
  "name": "PAPP9001",
  "ip": "10.2.3.2",
  "proxy": "type2.prod.proxy.mydomain.com"
}

Variations

If, for example, you wanted these four fields as a CSV row, then you could replace the last line of the filter above with:

| [$type, .name, .ip, $proxy] | @csv

See the jq manual for how to use string interpolation.


问:
How to solve: Use of unresolved identifier 'indexPath' in Swift
```<code>func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return interests.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt cellForItemAtindexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath:indexPath) as! InterestCollectionViewCell

    cell.interest = self.interest[indexPath.item]

    return cell
}
</code>```

答:
Correct your method signature as

Swift

```<code>func collectionView(_ collectionView: UICollectionView,
      cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
</code>```

Objective c

```<code>- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
</code>```

documentation

Body:
Correct your method signature as

Swift

func collectionView(_ collectionView: UICollectionView,
      cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

Objective c

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

documentation


问:
getting value of array from certain index in php
I want to get the value of an array type given a certain index. The array's values are

$status = [1,2];

And I used these code to get the value:

$task_state = $status[1];

But it actually thought $status is a string and returns

'['

I know that this is actually quite simple, but I just can't seem to find the answer to my problem. Thank you

答:
i try to copy your script and here what i get

```<code>$status = [1,2];
$task_state = $status[1];
var_dump($status);
exit;
</code>```

the result is :

array(2) { [0]=> int(1) 1=> int(2) }

can you give me line of your code for displaying '['.
may be your php version is the problem. See refrence.

Body:
i try to copy your script and here what i get

$status = [1,2];
$task_state = $status[1];
var_dump($status);
exit;

the result is :

array(2) { [0]=> int(1) 1=> int(2) }

can you give me line of your code for displaying '['.
may be your php version is the problem. See refrence.


问:
Panel List Php not showing all data
I am trying to create a panel list that shows certain rows from my database, however when I'm trying to call it, it only shows 1 data in the row even though i limit it by 5.

Here is my script:

```<code><?php
$link = mysqli_connect("localhost", "root", "", "test");
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM updates order by id desc limit 5";
if($result = mysqli_query($link, $sql)){
    if($list=mysqli_fetch_array($result)){
                echo "<div class=\"container\">";
        echo "<table>";
            echo "<tr>";
            echo "</tr>";

        echo "<div class=\"col-md-4\">";
        echo "<div class=\"panel panel-primary\">";
        echo "<div class=\"panel-heading\">Updates";
        echo "</div>";
        echo "<ul class=\"list-group\">";
        echo "<li class=\"list-group-item\">";
        echo "<b><h4>{$list["updates"]}</b></h4>";
        echo "</li>";
        echo "</div>";
        echo "</div>";
        echo "</div>";
        echo "</div>";
}
        echo "</table>";
        mysqli_free_result($result);
    } else{
        echo "No records matching your query were found.";
    }
{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
</code>```

答:
That's because you are fetching only once, here:

```<code>if ($list=mysqli_fetch_array($result) )
</code>```

Instead wrap this up inside a loop like this:

```<code>$row_count = mysqli_num_rows($result);
if ($row_count <= 0)  {
    echo "No records matching your query were found.";
}
else {
    // you have results

    // panel starts here
    while ($list = mysqli_fetch_array($result)) {
        // do some magic with your results
    }
    // panel ends here
    mysqli_free_result($result);
}
</code>```

I think you got the idea, now you can do the rest. If not let us know again. Happy coding!

Title: Panel List Php not showing all data

Body:
I am trying to create a panel list that shows certain rows from my database, however when I'm trying to call it, it only shows 1 data in the row even though i limit it by 5.

Here is my script:

<?php
$link = mysqli_connect("localhost", "root", "", "test");
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM updates order by id desc limit 5";
if($result = mysqli_query($link, $sql)){
    if($list=mysqli_fetch_array($result)){
                echo "
";
        echo "
";
            echo "
";
            echo "
";

        echo "
";
        echo "
";
        echo "
Updates";
        echo "
";
        echo "
";
        echo "
";
        echo "
{$list["updates"]}
";
        echo "
";
        echo "
";
        echo "
";
        echo "
";
        echo "
";
}
        echo "
";
        mysqli_free_result($result);
    } else{
        echo "No records matching your query were found.";
    }
{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>

Body:
That's because you are fetching only once, here:

if ($list=mysqli_fetch_array($result) )

Instead wrap this up inside a loop like this:

$row_count = mysqli_num_rows($result);
if ($row_count <= 0)  {
    echo "No records matching your query were found.";
}
else {
    // you have results

    // panel starts here
    while ($list = mysqli_fetch_array($result)) {
        // do some magic with your results
    }
    // panel ends here
    mysqli_free_result($result);
}

I think you got the idea, now you can do the rest. If not let us know again. Happy coding!


问:
Scrapy FormRequest return 400 error code
I am trying to scrapy following website in which the pagination is though AJAX request.
http://studiegids.uva.nl/xmlpages/page/2014-2015/zoek-vak

I am sending FormRequest to access the different pages, however I am getting following error.
Retrying http://studiegids.uva.nl/xmlpages/plspub/uva_search.courses_pls> (failed 1 times): 400 Bad Request

Not able to understand what is wrong? Following is the code.

```<code>class Spider(BaseSpider):
name = "zoek"
allowed_domains = ["studiegids.uva.nl"]
start_urls = ["http://studiegids.uva.nl/xmlpages/page/2014-2015/zoek-vak"]

def parse(self, response):
    base_url = "http://studiegids.uva.nl/xmlpages/page/2014-2015/zoek-vak"
    for i in range(1, 10):
        data = {'p_fetch_size': unicode(20),
                'p_page:': unicode(i),
                'p_searchpagetype': u'courses',
                'p_site_lang': u'nl',
                'p_strip': u'/2014-2015',
                'p_ctxparam': u'/xmlpages/page/2014-2015/',
                'p_rsrcpath':u'/xmlpages/resources/TXP/studiegidswebsite/'}

        yield FormRequest.from_response(response,
                                        formdata=data,
                                        callback=self.fetch_details,
                                        dont_click=True)

        # yield FormRequest(base_url,
        #                   formdata=data,
        #                   callback=self.fetch_details)

def fetch_details(self, response):
    # print response.body
    hxs = HtmlXPathSelector(response)
    item = ZoekItem()
    Studiegidsnummer = hxs.select("//div[@class=item-info']//tr[1]/td[2]/p/text()")
    Studielast = hxs.select("//div[@class=item-info']//tr[2]/td[2]/p/text()")
    Voertaal = hxs.select("//div[@class=item-info']//tr[3]/td[2]/p/text()")
    Ingangseis = hxs.select("//div[@class=item-info']//tr[4]/td[2]/p/text()")
    Studiejaar = hxs.select("//div[@class=item-info']//tr[5]/td[2]/p/text()")
    Onderwijsinstituut = hxs.select("//div[@class=item-info']//tr[6]/td[2]/p/text()")

    for i in range(20):
        item['Studiegidsnummer'] = Studiegidsnummer
        item['Studielast'] = Studielast
        item['Voertaal'] = Voertaal
        yield item
</code>```

答: Try also check headers using firebug.</p>

Body:
I am trying to scrapy following website in which the pagination is though AJAX request.
http://studiegids.uva.nl/xmlpages/page/2014-2015/zoek-vak

I am sending FormRequest to access the different pages, however I am getting following error.
Retrying http://studiegids.uva.nl/xmlpages/plspub/uva_search.courses_pls> (failed 1 times): 400 Bad Request

Not able to understand what is wrong? Following is the code.

class Spider(BaseSpider):
name = "zoek"
allowed_domains = ["studiegids.uva.nl"]
start_urls = ["http://studiegids.uva.nl/xmlpages/page/2014-2015/zoek-vak"]

def parse(self, response):
    base_url = "http://studiegids.uva.nl/xmlpages/page/2014-2015/zoek-vak"
    for i in range(1, 10):
        data = {'p_fetch_size': unicode(20),
                'p_page:': unicode(i),
                'p_searchpagetype': u'courses',
                'p_site_lang': u'nl',
                'p_strip': u'/2014-2015',
                'p_ctxparam': u'/xmlpages/page/2014-2015/',
                'p_rsrcpath':u'/xmlpages/resources/TXP/studiegidswebsite/'}

        yield FormRequest.from_response(response,
                                        formdata=data,
                                        callback=self.fetch_details,
                                        dont_click=True)

        # yield FormRequest(base_url,
        #                   formdata=data,
        #                   callback=self.fetch_details)

def fetch_details(self, response):
    # print response.body
    hxs = HtmlXPathSelector(response)
    item = ZoekItem()
    Studiegidsnummer = hxs.select("//div[@class=item-info']//tr[1]/td[2]/p/text()")
    Studielast = hxs.select("//div[@class=item-info']//tr[2]/td[2]/p/text()")
    Voertaal = hxs.select("//div[@class=item-info']//tr[3]/td[2]/p/text()")
    Ingangseis = hxs.select("//div[@class=item-info']//tr[4]/td[2]/p/text()")
    Studiejaar = hxs.select("//div[@class=item-info']//tr[5]/td[2]/p/text()")
    Onderwijsinstituut = hxs.select("//div[@class=item-info']//tr[6]/td[2]/p/text()")

    for i in range(20):
        item['Studiegidsnummer'] = Studiegidsnummer
        item['Studielast'] = Studielast
        item['Voertaal'] = Voertaal
        yield item

Body: Try also check headers using firebug.


问:
Converting/migrating from GCM to FCM for push notification
If I migrate my current GCM configuration to FCM what will happen to all the users of my Android app? Will I have to force all users to update or will the APK continue working as it is?

Please guide me. Thanks in advance.

答:
If you're simply referring to import your GCM project to Firebase, you should still be able to send messages to your users with GCM implemented apps (see my answer here).

For migrating the app implementation from GCM to FCM, you don't necessarily have to force an update with the users. As I mentioned above, GCM is still compatible with FCM, so there's no need to worry about it. It's just advisable to migrate the implementation. As per the FAQ:

How different is GCM from FCM? What is new in FCM SDKs?

FCM is the new version of GCM under the Firebase brand. It inherits GCM’s core infrastructure to make sure we continue to deliver messages reliably on Android, iOS and Chrome.

The new FCM SDK:

Simplifies client development. You no longer have to write your own registration or subscription retry logic.

Enables a new serverless notifications solution with a web console, Firebase Notifications. With Firebase Notifications, anyone can send notifications to target specific audiences based on Firebase Analytics insights. They can then evaluate notification effectiveness by assessing the built-in Notifications Funnel Analysis in the console.

FCM Android and iOS SDKs make messaging and notifications development easier. They offer an out-of-the-box solution so that anyone can send notifications from Firebase Notifications immediately.


问:
Different ways about Passing 2D array of pointer to function C
I met some problems when passing 2d-array to functions today, later I found some solutions like A and B.
I knew that 2d-array is stored in a continuous memory as 1d. So in my opinion, there is no 2 dimensional points in fact, compiler split this continuous numbers and made '2 dimensional' concept.

My question is: in C after I explicitly told compiler the parameter is a 'int**', why it did not pass a '2 dimensional' point?

Someone may point out "in C you did not told compiler the group-length", I think it knew this information because if you try to reexplain the 12 elements' plain memory into arr[2][6] it will be error like "void printArr(int _arr[][6], int _columns, int _rows)".

A little confused please help...

```<code>int arr[][3]={{1,2,3},{5,6,7},{9,10,11},{13,14,15}};

void printArr(int _arr[][3], int _columns, int _rows){ //----->A
void printArr(int (* _arr)[3], int _columns, int _rows){//---->B
void printArr(int** _arr, int _columns, int _rows){//--------->C
    for(int r=0; r< _rows; r++){
        for (int c=0; c<_columns; c++)
            //printf("%4d,", _arr[r][c]);
            printf("%4d,", *(*(_arr+r)+c));
    }
}
int main(){
    printArr(arr, columns, rows);
}
</code>```

答: int ** is a pointer to a pointer to int, not a pointer to a 2-dim array.</p>

Body:
I met some problems when passing 2d-array to functions today, later I found some solutions like A and B.
I knew that 2d-array is stored in a continuous memory as 1d. So in my opinion, there is no 2 dimensional points in fact, compiler split this continuous numbers and made '2 dimensional' concept.

My question is: in C after I explicitly told compiler the parameter is a 'int**', why it did not pass a '2 dimensional' point?

Someone may point out "in C you did not told compiler the group-length", I think it knew this information because if you try to reexplain the 12 elements' plain memory into arr[2][6] it will be error like "void printArr(int _arr[][6], int _columns, int _rows)".

A little confused please help...

int arr[][3]={{1,2,3},{5,6,7},{9,10,11},{13,14,15}};

void printArr(int _arr[][3], int _columns, int _rows){ //----->A
void printArr(int (* _arr)[3], int _columns, int _rows){//---->B
void printArr(int** _arr, int _columns, int _rows){//--------->C
    for(int r=0; r< _rows; r++){
        for (int c=0; c<_columns; c++)
            //printf("%4d,", _arr[r][c]);
            printf("%4d,", *(*(_arr+r)+c));
    }
}
int main(){
    printArr(arr, columns, rows);
}


答:
You are getting this error message because of a unnecessary comma ',' before from keyword:

```<code> ...election 'Election', FROM candidates...
</code>```

Following is the correct version of your SQL statement:

```<code> "SELECT studentnumber AS 'Student Number', lastname AS 'Last Name', firstname AS 'First Name', middlename AS 'Middle Name', picture AS 'Picture', course AS 'Course', year AS 'Year', section AS 'Section', partylist AS 'Partylist', information AS 'Information' , position 'Position', election 'Election' FROM candidates"
</code>```

Title: Why do I keep getting this message but the SQL syntax is working

Body:
You are getting this error message because of a unnecessary comma ',' before from keyword:

 ...election 'Election', FROM candidates...

Following is the correct version of your SQL statement:

 "SELECT studentnumber AS 'Student Number', lastname AS 'Last Name', firstname AS 'First Name', middlename AS 'Middle Name', picture AS 'Picture', course AS 'Course', year AS 'Year', section AS 'Section', partylist AS 'Partylist', information AS 'Information' , position 'Position', election 'Election' FROM candidates"


问:
How do I check if a column is empty or null in MySQL?
I have a column in a table which might contain null or empty values. How do I check if a column is empty or null in the rows present in a table?</p>

```<code>(e.g. null or '' or '  ' or '      ' and ...)
</code>```

答:
Either

```<code>SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 from tablename
</code>```

or

```<code>SELECT case when field1 IS NULL or field1 = ''
        then 'empty'
        else field1
   end as field1 from tablename
</code>```

Body:
I have a column in a table which might contain null or empty values. How do I check if a column is empty or null in the rows present in a table?

(e.g. null or '' or '  ' or '      ' and ...)

Body:
Either

SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 from tablename

or

SELECT case when field1 IS NULL or field1 = ''
        then 'empty'
        else field1
   end as field1 from tablename


问:
In c# , how to iterate IEnumerable in multithreading environment
I am in this situation that there is a large dictionary that is randomly updated by one thread at a fairly high frequency, and there is another thread that tries to take a snapshot of the dictionary to save as history.
I currently using something like this:

```<code>Dictionary<string, object> dict = new Dictionary<string, object>();
var items = dict.Values.ToList();
</code>```

This works fine for most of the time, except it occasionally throws:

System.InvalidOperationException: Collection was modified; enumeration
  operation may not execute.

I understand why this happen, but I don't know what can I do to avoid the collection modified error.

What is the best approach to iterate such collection?

I also tried ConcurrentDictionary, but no luck.
Why? Is ConcurrentDictionary thread safe only at item level?

答:
You can use a monitor with lock keyword to ensure that only reading or only writing is executing at this moment.

```<code>public class SnapshotDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
    private readonly Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();
    private readonly object _lock = new object();

    public void Add(TKey key, TValue value)
    {
        lock (_lock)
        {
            _dictionary.Add(key, value);
        }
    }

    // TODO: Other necessary IDictionary methods

    public Dictionary<TKey, TValue> GetSnaphot()
    {
        lock (_lock)
        {
            return new Dictionary<TKey, TValue>(_dictionary);
        }
    }

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        return GetSnaphot().GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
</code>```

GetSnapshot method returns a snapshot of your dictionary.

I have also overriden GetEnumerator so that it creates a snapshot and then returns snapshot's enumerator.

So, this will work because will be executed on a snapshot:

```<code>var items = snapshotDictionary.GetSnapshot().Values.ToList();

// or

foreach (var item in snapshotDictionary)
{
    // ...
}
</code>```

However, this approach does not allow multithreading writing.

Body:
I am in this situation that there is a large dictionary that is randomly updated by one thread at a fairly high frequency, and there is another thread that tries to take a snapshot of the dictionary to save as history.
I currently using something like this:

Dictionary<string, object> dict = new Dictionary<string, object>();
var items = dict.Values.ToList();

This works fine for most of the time, except it occasionally throws:

System.InvalidOperationException: Collection was modified; enumeration
  operation may not execute.

I understand why this happen, but I don't know what can I do to avoid the collection modified error.

What is the best approach to iterate such collection?

I also tried ConcurrentDictionary, but no luck.
Why? Is ConcurrentDictionary thread safe only at item level?

Body:
You can use a monitor with lock keyword to ensure that only reading or only writing is executing at this moment.

public class SnapshotDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
    private readonly Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();
    private readonly object _lock = new object();

    public void Add(TKey key, TValue value)
    {
        lock (_lock)
        {
            _dictionary.Add(key, value);
        }
    }

    // TODO: Other necessary IDictionary methods

    public Dictionary<TKey, TValue> GetSnaphot()
    {
        lock (_lock)
        {
            return new Dictionary<TKey, TValue>(_dictionary);
        }
    }

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        return GetSnaphot().GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

GetSnapshot method returns a snapshot of your dictionary.

I have also overriden GetEnumerator so that it creates a snapshot and then returns snapshot's enumerator.

So, this will work because will be executed on a snapshot:

var items = snapshotDictionary.GetSnapshot().Values.ToList();

// or

foreach (var item in snapshotDictionary)
{
    // ...
}

However, this approach does not allow multithreading writing.


问:
Django filter queryset __in for *every* item in list (2.0)
I've already read this and this, but they don't solve my problem because they make a final "count" with a comparison to a number that is hard-coded. I want to make a comparison of a number that is the sum of all ingredients of the recipe itself.

Let's imagine that I have some ingredients in my fridge, with their id's (= array of id's). I want to see what I can cook with that. I have my models like this:

```<code>class Ingredient(models.Model):
    label = models.CharField(max_length=200, null=True, blank=True,
                             default=None)
    description = models.TextField(null=True, blank=True, default=None)

class Unit(models.Model):
    label = models.CharField(max_length=200, null=True, blank=True,
                             default=None)
    abbr = models.CharField(max_length=20, null=True, blank=True,
                            default=None)

class IngredientUnit(models.Model):
    ingredient = models.ForeignKey(Ingredient, null=False, blank=True)
    unit = models.ForeignKey(Unit, null=False, blank=True)
    measurable = models.BooleanField(default=True, null=False, blank=True)
    is_int = models.BooleanField(default=True, null=False, blank=True)
    value = models.FloatField(null=True, blank=True, default=0.0)

class Recipe(models.Model):
    label = models.CharField(max_length=200, null=True, blank=True,
                             default=None)
    description = models.TextField(null=True, blank=True, default=None)
    ingredients = models.ManyToManyField(IngredientUnit)
</code>```

I'd like to do this: 'select all recipe that have all' the ingredients of an array of ingredient's pk. For example: "Classic Vanilla Cake" has those ingredients: eggs, all-purpose flour, baking powder, baking soda, butter, sugar, vanilla, buttermilk. If one is missing, "Classic Vanilla Cake" shouldn't be in the resulting query. On the contrary, if there are more ingredients than those required, "Classic Vanilla Cake" should always be in the resulting query.

So far, I've done this, but it's not working.

```<code>    ingredient_ids = self.request.POST.getlist('ingredient[]', [])
    if len(ingredient_ids):
        recipes = Recipe.objects\
            .filter(ingredients__in=ingredient_ids)\
            .annotate(nb_ingredients=Count('ingredients'))\
            .filter(nb_ingredients=len(ingredient_ids))
        print([a for a in recipes])
</code>```

The problem is that nb_ingredients=len(ingredient_ids) should be nb_ingredients=the number of the ingredients of the current recipe

How can I do this?

答:
I think you can try to exclude the recipes which have missing ingredients.
<s>

```<code>Recipe.objects.exclude(~Q(ingredients__in=ingredient_ids)).distinct()
</code>```

</s>

Tested it, its not working.

In theory, what you want:

The problem is that nb_ingredients=len(ingredient_ids) should be
  nb_ingredients=the number of the ingredients of the current recipe

should be achieved with one annotation before the filter and one annotation after the filter (because the order of annotation and filter matters).

I.e. something like this:

```<code>recipes = (Recipe.objects
    .annotate(num_ingredients=Count('ingredients'))
    .filter(ingredients__in=ingredient_ids)
    .annotate(found_ingredients=Count('ingredients'))
    .filter(num_ingredients=F('found_ingredients'))
)
</code>```

however when I tested this, it  wasn't working because the ORM didn't reuse the correct JOIN from the filter. This could be some kind of a bug, I just open a question in the mailing list.

In case you are using Django 1.11, another approach would be use the new Subquery-expressions, can you try this.

```<code>recipes = (Recipe.objects
                .filter(ingredients__in=ingredient_ids)
                .annotate(found_ingredients=Count('ingredients', distinct=True))
                .annotate(num_ingredients=Count(Subquery(
                    Ingredient.objects.filter(recipe=OuterRef('pk')).only('pk')),
                    distinct=True)
                )
                .filter(num_ingredients=F('found_ingredients'))
)
</code>```

Body:
I've already read this and this, but they don't solve my problem because they make a final "count" with a comparison to a number that is hard-coded. I want to make a comparison of a number that is the sum of all ingredients of the recipe itself.

Let's imagine that I have some ingredients in my fridge, with their id's (= array of id's). I want to see what I can cook with that. I have my models like this:

class Ingredient(models.Model):
    label = models.CharField(max_length=200, null=True, blank=True,
                             default=None)
    description = models.TextField(null=True, blank=True, default=None)

class Unit(models.Model):
    label = models.CharField(max_length=200, null=True, blank=True,
                             default=None)
    abbr = models.CharField(max_length=20, null=True, blank=True,
                            default=None)

class IngredientUnit(models.Model):
    ingredient = models.ForeignKey(Ingredient, null=False, blank=True)
    unit = models.ForeignKey(Unit, null=False, blank=True)
    measurable = models.BooleanField(default=True, null=False, blank=True)
    is_int = models.BooleanField(default=True, null=False, blank=True)
    value = models.FloatField(null=True, blank=True, default=0.0)

class Recipe(models.Model):
    label = models.CharField(max_length=200, null=True, blank=True,
                             default=None)
    description = models.TextField(null=True, blank=True, default=None)
    ingredients = models.ManyToManyField(IngredientUnit)

I'd like to do this: 'select all recipe that have all' the ingredients of an array of ingredient's pk. For example: "Classic Vanilla Cake" has those ingredients: eggs, all-purpose flour, baking powder, baking soda, butter, sugar, vanilla, buttermilk. If one is missing, "Classic Vanilla Cake" shouldn't be in the resulting query. On the contrary, if there are more ingredients than those required, "Classic Vanilla Cake" should always be in the resulting query.

So far, I've done this, but it's not working.

    ingredient_ids = self.request.POST.getlist('ingredient[]', [])
    if len(ingredient_ids):
        recipes = Recipe.objects\
            .filter(ingredients__in=ingredient_ids)\
            .annotate(nb_ingredients=Count('ingredients'))\
            .filter(nb_ingredients=len(ingredient_ids))
        print([a for a in recipes])

The problem is that nb_ingredients=len(ingredient_ids) should be nb_ingredients=the number of the ingredients of the current recipe

How can I do this?

Body:
I think you can try to exclude the recipes which have missing ingredients.
<s>

Recipe.objects.exclude(~Q(ingredients__in=ingredient_ids)).distinct()

</s>

Tested it, its not working.

In theory, what you want:

The problem is that nb_ingredients=len(ingredient_ids) should be
  nb_ingredients=the number of the ingredients of the current recipe

should be achieved with one annotation before the filter and one annotation after the filter (because the order of annotation and filter matters).

I.e. something like this:

recipes = (Recipe.objects
    .annotate(num_ingredients=Count('ingredients'))
    .filter(ingredients__in=ingredient_ids)
    .annotate(found_ingredients=Count('ingredients'))
    .filter(num_ingredients=F('found_ingredients'))
)

however when I tested this, it  wasn't working because the ORM didn't reuse the correct JOIN from the filter. This could be some kind of a bug, I just open a question in the mailing list.

In case you are using Django 1.11, another approach would be use the new Subquery-expressions, can you try this.

recipes = (Recipe.objects
                .filter(ingredients__in=ingredient_ids)
                .annotate(found_ingredients=Count('ingredients', distinct=True))
                .annotate(num_ingredients=Count(Subquery(
                    Ingredient.objects.filter(recipe=OuterRef('pk')).only('pk')),
                    distinct=True)
                )
                .filter(num_ingredients=F('found_ingredients'))
)