问:
SyntaxError: Unexpected token C in JSON at position 0
I have this part of code in my application

addComment (body: Object): Observable<Comment[]> {
    //let bodyString = JSON.stringify(body); // Stringify payload
    let bodyString = JSON.parse(JSON.stringify(body || null ))
    let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
    let options = new RequestOptions({ headers: headers }); // Create a request option

    return this.http.post(this.commentsUrl, bodyString, options) // ...using post request
                        .map((res:Response) => res.json()) // ...and calling .json() on the response to return data
                        .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}
```
<p>When I try to add a comment in my application it throws an error as below:</p>
<pre class="lang-none prettyprint-override"><code>POST http://localhost:4200/assets/comments.json 404 (Not Found)
SyntaxError: Unexpected token C in JSON at position 0
</code>```

Someone can help me?

Fully SyntaxError stack:

SyntaxError: Unexpected token C in JSON at position 0
    at Object.parse (<anonymous>)
    at Response.Body.json (body.js:24)
    at CatchSubscriber.selector (comment.service.ts:41)
    at CatchSubscriber.error (catch.js:104)
    at MapSubscriber.Subscriber._error (Subscriber.js:128)
    at MapSubscriber.Subscriber.error (Subscriber.js:102)
    at XMLHttpRequest.onLoad (xhr_backend.js:82)
    at ZoneDelegate.webpackJsonp.1301.ZoneDelegate.invokeTask (zone.js:363)
    at Object.onInvokeTask (ng_zone.js:264)
    at ZoneDelegate.webpackJsonp.1301.ZoneDelegate.invokeTask (zone.js:362)
    at Zone.webpackJsonp.1301.Zone.runTask (zone.js:166)
    at XMLHttpRequest.ZoneTask.invoke (zone.js:416)
```

答:
I was facing the exactly issue.

Just change:

```<code>error.json()
</code>```

to

```<code>JSON.parse(JSON.stringify(error))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this part of code in my application

addComment (body: Object): Observable<Comment[]> {
    //let bodyString = JSON.stringify(body); // Stringify payload
    let bodyString = JSON.parse(JSON.stringify(body || null ))
    let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
    let options = new RequestOptions({ headers: headers }); // Create a request option

    return this.http.post(this.commentsUrl, bodyString, options) // ...using post request
                        .map((res:Response) => res.json()) // ...and calling .json() on the response to return data
                        .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}

When I try to add a comment in my application it throws an error as below:

POST http://localhost:4200/assets/comments.json 404 (Not Found)
SyntaxError: Unexpected token C in JSON at position 0

Someone can help me?

Fully SyntaxError stack:

SyntaxError: Unexpected token C in JSON at position 0
    at Object.parse (<anonymous>)
    at Response.Body.json (body.js:24)
    at CatchSubscriber.selector (comment.service.ts:41)
    at CatchSubscriber.error (catch.js:104)
    at MapSubscriber.Subscriber._error (Subscriber.js:128)
    at MapSubscriber.Subscriber.error (Subscriber.js:102)
    at XMLHttpRequest.onLoad (xhr_backend.js:82)
    at ZoneDelegate.webpackJsonp.1301.ZoneDelegate.invokeTask (zone.js:363)
    at Object.onInvokeTask (ng_zone.js:264)
    at ZoneDelegate.webpackJsonp.1301.ZoneDelegate.invokeTask (zone.js:362)
    at Zone.webpackJsonp.1301.Zone.runTask (zone.js:166)
    at XMLHttpRequest.ZoneTask.invoke (zone.js:416)

Body:
I was facing the exactly issue.

Just change:

error.json()

to

JSON.parse(JSON.stringify(error))


来源: stackexchange

问:
Update fragment replaced by FragmentTransaction with Asynctask
Hi guys i'am here because I've already tried almost everything since running the fragment transaction in Asynctask or in a new thread nothing seems to work and i can't figure out by myself.

What I've tried:

link

link

link

and others

My problem:

The fragment do some heavy work so i implemented the asynctask inside
the

fragment but i can't update the fragment

My UI freezes when replacing with the fragment

I create all my views programmatic

My fragment returns a views

I pretend to display a progressbar while the frag is not ready

My main:

```<code> Bundle bundle = getIntent().getExtras();
        FragmentTransaction fragmentTransaction = getFragmentManager()
                .beginTransaction();
        FragTopics insideTopicsFrag = new FragTopics();
        insideTopicsFrag.setArguments(bundle);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.mainFragment, insideTopicsFrag);
        fragmentTransaction.commit();
</code>```

My fragment:
the createTopics returns a View with all the content, in another words it's the view that in the past was return in the onCreateView.

```<code>public class FragTopics extends Fragment {
View v;
public FragTopics() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    v = new View(getActivity());
    new TopicsAsyncTask().execute();
    return v;
}
private class TopicsAsyncTask extends AsyncTask<Void, Void, Boolean> {
    ManSession session;
    String courseId;
    Long topicId;
    String courseName;
    MoodleCourseContent[] courseTopics;
    MoodleCourseContent singleTopic;
        private final ProgressDialog dialog = new ProgressDialog(getActivity());
    @Override
    protected void onPreExecute() {
        this.dialog.setMessage("loading...");
        this.dialog.show();
    }
    @Override
    protected Boolean doInBackground(Void... params) {
        ObtainData();
        return true;
    }
    @Override
    protected void onPostExecute(Boolean result) {
        this.dialog.dismiss();
        // The createTopics returns the View with all contents
        v = createTopics(singleTopic, courseName, courseId, topicId);

    }
}
</code>```

答:
Change your onCreateView to this:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = new View(getActivity());
new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
           new TopicsAsyncTask().execute();
        }
    }, 200);
return v;
}
</code>```

Hope it still helps

ContentLicense: CC BY-SA 3.0

Body:
Hi guys i'am here because I've already tried almost everything since running the fragment transaction in Asynctask or in a new thread nothing seems to work and i can't figure out by myself.

What I've tried:

link

link

link

and others

My problem:

The fragment do some heavy work so i implemented the asynctask inside
the

fragment but i can't update the fragment

My UI freezes when replacing with the fragment

I create all my views programmatic

My fragment returns a views

I pretend to display a progressbar while the frag is not ready

My main:

 Bundle bundle = getIntent().getExtras();
        FragmentTransaction fragmentTransaction = getFragmentManager()
                .beginTransaction();
        FragTopics insideTopicsFrag = new FragTopics();
        insideTopicsFrag.setArguments(bundle);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.mainFragment, insideTopicsFrag);
        fragmentTransaction.commit();

My fragment:
the createTopics returns a View with all the content, in another words it's the view that in the past was return in the onCreateView.

public class FragTopics extends Fragment {
View v;
public FragTopics() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    v = new View(getActivity());
    new TopicsAsyncTask().execute();
    return v;
}
private class TopicsAsyncTask extends AsyncTask<Void, Void, Boolean> {
    ManSession session;
    String courseId;
    Long topicId;
    String courseName;
    MoodleCourseContent[] courseTopics;
    MoodleCourseContent singleTopic;
        private final ProgressDialog dialog = new ProgressDialog(getActivity());
    @Override
    protected void onPreExecute() {
        this.dialog.setMessage("loading...");
        this.dialog.show();
    }
    @Override
    protected Boolean doInBackground(Void... params) {
        ObtainData();
        return true;
    }
    @Override
    protected void onPostExecute(Boolean result) {
        this.dialog.dismiss();
        // The createTopics returns the View with all contents
        v = createTopics(singleTopic, courseName, courseId, topicId);

    }
}

Body:
Change your onCreateView to this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = new View(getActivity());
new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
           new TopicsAsyncTask().execute();
        }
    }, 200);
return v;
}

Hope it still helps


问:
Google Earth API for Android
I want to ask if Google Earth API is avaialble for developing android application.
If google earth api is not available for android, are there any map api which can be used off network on android?</p>

答:
No, there's no offline API on Android or Google Earth API. You can use the regular Android Google Maps package api, eventually in combination with the Google Maps web api, in case you need routing and directions as well.

Until SDK 0.9, Google had a navigation package/api included, but that has been dropped; I guess due to licensing issues. Note that real-time turn-by-turn navigation on Android is not allowed and against the ToS, while route navigation in general can be done, but only in combination with the maps web api.

ContentLicense: CC BY-SA 2.5

Title: Google Earth API for Android


问:
Ruby Waitir Gem, getting unexpected results
2 weeks ago I put up post about my watir script timing out on me, I was able to get a solution but I realized to late the results I was getting was different than the person that helped me out. Here is the original post: Ruby Watir Gem, Timing Out on Form Input

```<code>require 'watir'

browser = Watir::Browser.new

browser.goto('https://tripadvisor.com/CheapFlightsHome')
browser.text_field(name: 'orig').set('Boston, MA - Logan International Airport (BOS)')
browser.text_field(name: 'dest').set('Milan, Italy - All Airports (MIL)')
browser.execute_script('document.querySelector(".in_date").click()')
browser.execute_script('document.querySelector(".day_28").click()')
browser.execute_script('document.querySelector(".out_date").click()')
browser.execute_script('document.querySelector(".day_2").click()')
browser.span(id: "CHECK_FARES_BUTTON").fire_event :click
puts browser.url
browser.quit
</code>```

The person who wrote that code got this as a result:
https://www.tripadvisor.com/CheapFlightsSearchResults-g187849-a_airport0.BOS-a_airport1.MIL-a_cos.0-a_date0.20170328-a_date1.20170402-a_nearby0.no-a_nearby1.no-a_nonstop.no-a_pax0.a-a_travelers.1-Milan_Lombardy.html

I have the same code in my script and for some reason I'm only getting:
https://www.tripadvisor.com/CheapFlightsHome

It seems as though the button click isn't happening for me, not sure. I tried both chrome and firefox.

答:
First of all your click actually opens another two window and also the time you are clicking it's not exactly receiving the click, Please use this code, it will work for you and you will be left with your expected window</p>

```<code>require 'watir'
caps = Selenium::WebDriver::Remote::Capabilities.firefox(marionette: false)

driver=Selenium::WebDriver.for :firefox, desired_capabilities: caps, profile: "default"

b=Watir::Browser.new driver

b.goto('https://tripadvisor.com/CheapFlightsHome')
b.text_field(name: 'orig').set('Boston, MA - Logan International Airport (BOS)')
b.text_field(name: 'dest').set('Milan, Italy - All Airports (MIL)')
b.execute_script('document.querySelector(".in_date").click()')
b.execute_script('document.querySelector(".day_28").click()')
b.execute_script('document.querySelector(".out_date").click()')
b.execute_script('document.querySelector(".day_2").click()')
begin
b.element(xpath: ".//*[@id='CHECK_FARES_BUTTON']").click
end until b.windows.count>1

b.windows[0].close
b.windows[1].close

puts b.url
b.quit
</code>```

Body:
2 weeks ago I put up post about my watir script timing out on me, I was able to get a solution but I realized to late the results I was getting was different than the person that helped me out. Here is the original post: Ruby Watir Gem, Timing Out on Form Input

require 'watir'

browser = Watir::Browser.new

browser.goto('https://tripadvisor.com/CheapFlightsHome')
browser.text_field(name: 'orig').set('Boston, MA - Logan International Airport (BOS)')
browser.text_field(name: 'dest').set('Milan, Italy - All Airports (MIL)')
browser.execute_script('document.querySelector(".in_date").click()')
browser.execute_script('document.querySelector(".day_28").click()')
browser.execute_script('document.querySelector(".out_date").click()')
browser.execute_script('document.querySelector(".day_2").click()')
browser.span(id: "CHECK_FARES_BUTTON").fire_event :click
puts browser.url
browser.quit

The person who wrote that code got this as a result:
https://www.tripadvisor.com/CheapFlightsSearchResults-g187849-a_airport0.BOS-a_airport1.MIL-a_cos.0-a_date0.20170328-a_date1.20170402-a_nearby0.no-a_nearby1.no-a_nonstop.no-a_pax0.a-a_travelers.1-Milan_Lombardy.html

I have the same code in my script and for some reason I'm only getting:
https://www.tripadvisor.com/CheapFlightsHome

It seems as though the button click isn't happening for me, not sure. I tried both chrome and firefox.

Body:
First of all your click actually opens another two window and also the time you are clicking it's not exactly receiving the click, Please use this code, it will work for you and you will be left with your expected window

require 'watir'
caps = Selenium::WebDriver::Remote::Capabilities.firefox(marionette: false)

driver=Selenium::WebDriver.for :firefox, desired_capabilities: caps, profile: "default"

b=Watir::Browser.new driver

b.goto('https://tripadvisor.com/CheapFlightsHome')
b.text_field(name: 'orig').set('Boston, MA - Logan International Airport (BOS)')
b.text_field(name: 'dest').set('Milan, Italy - All Airports (MIL)')
b.execute_script('document.querySelector(".in_date").click()')
b.execute_script('document.querySelector(".day_28").click()')
b.execute_script('document.querySelector(".out_date").click()')
b.execute_script('document.querySelector(".day_2").click()')
begin
b.element(xpath: ".//*[@id='CHECK_FARES_BUTTON']").click
end until b.windows.count>1

b.windows[0].close
b.windows[1].close

puts b.url
b.quit


问:
Composer cannot find path repo - Laravel spark
So, Laravel spark isn't letting me connect to the github any more and it's causing me to be unable to push to heroku and completely halting my work. I tried placing the spark code in a folder and then making the code path repository. However, when I run composer update it still tries to fetch the code from the same github location. Seems like it isn't finding the repo.

I have tried tons of path variations and placing the code in various locations. Here is the section from the composer:

```<code>    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.2.*",
        "laravel/spark":"*",
....

    "repositories": [
        {
            "type": "path",
            "url": "vendor/laravel/spark"
        },
        {
            "type": "composer",
            "url": "https://spark-satis.laravel.com"
        }
    ],
</code>```

And, in the package composer ...

```<code>"name": "laravel/spark",
"description": "Laravel Spark provides scaffolding for Laravel SaaS applications.",
"keywords": ["laravel", "stripe", "billing", "scaffolding", "saas"],
"license": "MIT",
"authors": [
    {
        "name": "Taylor Otwell",
        "email": "taylorotwell@gmail.com"
    }
],
"require": {
    "php": ">=5.5.9",
    "erusev/parsedown": "~1.0",
    "firebase/php-jwt": "~3.0",
    "guzzlehttp/guzzle": "~6.0",
    "ramsey/uuid": "^3.1",
    "intervention/image": "^2.3"
},
"require-dev": {
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~5.0",
    "mpociot/vat-calculator": "^1.6"
},
"autoload": {
    "psr-4": {
        "Laravel\\Spark\\": "src/"
    }
},
"extra": {
    "branch-alias": {
        "dev-master": "2.0-dev"
    }
},
"minimum-stability": "dev"
</code>```

Is there something that I am missing to ensure that composer uses the path repo instead of looking at github?

答:
Since laravel/spark is not free anymore and cannot be installed or updated with composer

You have to purchase license version to use it.

https://spark.laravel.com/licenses

Body:
So, Laravel spark isn't letting me connect to the github any more and it's causing me to be unable to push to heroku and completely halting my work. I tried placing the spark code in a folder and then making the code path repository. However, when I run composer update it still tries to fetch the code from the same github location. Seems like it isn't finding the repo.

I have tried tons of path variations and placing the code in various locations. Here is the section from the composer:

    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.2.*",
        "laravel/spark":"*",
....

    "repositories": [
        {
            "type": "path",
            "url": "vendor/laravel/spark"
        },
        {
            "type": "composer",
            "url": "https://spark-satis.laravel.com"
        }
    ],

And, in the package composer ...

"name": "laravel/spark",
"description": "Laravel Spark provides scaffolding for Laravel SaaS applications.",
"keywords": ["laravel", "stripe", "billing", "scaffolding", "saas"],
"license": "MIT",
"authors": [
    {
        "name": "Taylor Otwell",
        "email": "taylorotwell@gmail.com"
    }
],
"require": {
    "php": ">=5.5.9",
    "erusev/parsedown": "~1.0",
    "firebase/php-jwt": "~3.0",
    "guzzlehttp/guzzle": "~6.0",
    "ramsey/uuid": "^3.1",
    "intervention/image": "^2.3"
},
"require-dev": {
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~5.0",
    "mpociot/vat-calculator": "^1.6"
},
"autoload": {
    "psr-4": {
        "Laravel\\Spark\\": "src/"
    }
},
"extra": {
    "branch-alias": {
        "dev-master": "2.0-dev"
    }
},
"minimum-stability": "dev"

Is there something that I am missing to ensure that composer uses the path repo instead of looking at github?


问:
httpd(2.4.25), openssl(1.0.2k) - Cannot compile in macOS Sierra Error on make: Undefined symbols for architecture x86_64: "_CRYPTO_malloc_init"
Operating system is macOS Sierra, osx 10.12.3

Configure command line:

```<code>./configure --prefix=/usr/local/mac-dev-env/apache-2.4.25 --enable-so --enable-ssl  --with-ssl=/usr/local/mac-dev-env/openssl-1.0.2k --with-apr=/usr/local/apr --with-apr-util=/usr/local/apr-util
</code>```

Error created by make:

```<code>/usr/local/apr-1.5.2/build-1/libtool --silent --mode=link gcc  -g -O2
-L/usr/local/mac-dev-env/openssl-1.0.2k/lib -lssl -lcrypto -lpthread  \
             -o ab  ab.lo       /usr/local/apr-util-1.5.4/lib/libaprutil-1.la -lexpat -liconv /usr/local/apr-1.5.2/lib/libapr-1.la -lpthread  Undefined symbols for architecture x86_64:   "_CRYPTO_malloc_init", referenced from:
      _main in ab.o   "_OPENSSL_init_ssl", referenced from:
      _main in ab.o   "_OPENSSL_sk_num", referenced from:
      _ssl_proceed_handshake in ab.o   "_OPENSSL_sk_value", referenced from:
      _ssl_proceed_handshake in ab.o   "_SSL_CTX_set_options", referenced from:
      _main in ab.o   "_SSL_in_init", referenced from:
      _main in ab.o
      _ssl_state_cb in ab.o   "_TLS_client_method", referenced from:
      _main in ab.o   "_X509_get_version", referenced from:
      _ssl_print_cert_info in ab.o   "_X509_getm_notAfter", referenced from:
      _ssl_print_cert_info in ab.o   "_X509_getm_notBefore", referenced from:
      _ssl_print_cert_info in ab.o ld: symbol(s) not found for architecture x86_64
</code>```

答:
I went to http://www.linuxfromscratch.org/blfs/view/svn/server/apache.html

From there I found two dependencies Apr-Util-1.5.4 and PCRE-8.40.

I configure the build of apr-util with:

```<code> ./configure --prefix=/usr/local/mac-dev-env/apr-util-1.5.4 --with-apr=/usr/local/mac-dev-env/apr-1.5.2 --with-openssl=/usr/local/mac-dev-env/openssl-1.0.2k --with-crypto
</code>```

Most important was to build apr-util with --with-openssl=/usr/local/mac-dev-env/openssl-1.0.2k --with-crypto.

I then built pcre-8.40 as I had been attempting to build with pcre-8.39.

I believe the root cause was not building with apr-util-1.5.4 with the --with-openssl=/usr/local/mac-dev-env/openssl-1.0.2k --with-crypto options.

My configuration before make for apache-2.4.25 was:

```<code>./configure --prefix=/usr/local/mac-dev-env/apache-2.4.25 --enable-so --enable-ssl  --with-ssl=/usr/local/mac-dev-env/openssl-1.0.2k --with-apr=/usr/local/apr --with-apr-util=/usr/local/mac-dev-env/apr-util-1.5.4 --with-ldap
</code>```

Body:
Operating system is macOS Sierra, osx 10.12.3

Configure command line:

./configure --prefix=/usr/local/mac-dev-env/apache-2.4.25 --enable-so --enable-ssl  --with-ssl=/usr/local/mac-dev-env/openssl-1.0.2k --with-apr=/usr/local/apr --with-apr-util=/usr/local/apr-util

Error created by make:

/usr/local/apr-1.5.2/build-1/libtool --silent --mode=link gcc  -g -O2
-L/usr/local/mac-dev-env/openssl-1.0.2k/lib -lssl -lcrypto -lpthread  \
             -o ab  ab.lo       /usr/local/apr-util-1.5.4/lib/libaprutil-1.la -lexpat -liconv /usr/local/apr-1.5.2/lib/libapr-1.la -lpthread  Undefined symbols for architecture x86_64:   "_CRYPTO_malloc_init", referenced from:
      _main in ab.o   "_OPENSSL_init_ssl", referenced from:
      _main in ab.o   "_OPENSSL_sk_num", referenced from:
      _ssl_proceed_handshake in ab.o   "_OPENSSL_sk_value", referenced from:
      _ssl_proceed_handshake in ab.o   "_SSL_CTX_set_options", referenced from:
      _main in ab.o   "_SSL_in_init", referenced from:
      _main in ab.o
      _ssl_state_cb in ab.o   "_TLS_client_method", referenced from:
      _main in ab.o   "_X509_get_version", referenced from:
      _ssl_print_cert_info in ab.o   "_X509_getm_notAfter", referenced from:
      _ssl_print_cert_info in ab.o   "_X509_getm_notBefore", referenced from:
      _ssl_print_cert_info in ab.o ld: symbol(s) not found for architecture x86_64

Body:
I went to http://www.linuxfromscratch.org/blfs/view/svn/server/apache.html

From there I found two dependencies Apr-Util-1.5.4 and PCRE-8.40.

I configure the build of apr-util with:

 ./configure --prefix=/usr/local/mac-dev-env/apr-util-1.5.4 --with-apr=/usr/local/mac-dev-env/apr-1.5.2 --with-openssl=/usr/local/mac-dev-env/openssl-1.0.2k --with-crypto

Most important was to build apr-util with --with-openssl=/usr/local/mac-dev-env/openssl-1.0.2k --with-crypto.

I then built pcre-8.40 as I had been attempting to build with pcre-8.39.

I believe the root cause was not building with apr-util-1.5.4 with the --with-openssl=/usr/local/mac-dev-env/openssl-1.0.2k --with-crypto options.

My configuration before make for apache-2.4.25 was:

./configure --prefix=/usr/local/mac-dev-env/apache-2.4.25 --enable-so --enable-ssl  --with-ssl=/usr/local/mac-dev-env/openssl-1.0.2k --with-apr=/usr/local/apr --with-apr-util=/usr/local/mac-dev-env/apr-util-1.5.4 --with-ldap


问:
SceneKit avoid lighting on specific node
In SceneKit I'm building a node made of lines to draw the XYZ axes at the center of the scene, like in Cinema4D.

I would like these 3 nodes not to participate to the global lighting and be viewable even if the light is dark / inexistent / too strong. In the picture below you can see that the Z axis appears too heavily lighten and can't be seen.

Is there a way to stop a node participating to the scene's lighting, like with category masks for physics?

In this case, how would the node be lighten in order for it to appear anyway?

答:
SCNLight has a categoryBitMask property. This lets you choose which nodes are affected by the light (Although this is ignored for ambient lights). You could have 2 light source categories, one for your main scene, and another that only affects your lines.

Here is a simple example with 2 nodes, each lit with a different colour light:

```<code>struct LightType {
    static let light1:Int = 0x1 << 1
    static let light2:Int = 0x1 << 2
}

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let scene = SCNScene(named: "art.scnassets/scene.scn")!

        let lightNode1 = SCNNode()
        lightNode1.light = SCNLight()
        lightNode1.light!.type = .omni
        lightNode1.light!.color = UIColor.yellow
        lightNode1.position = SCNVector3(x: 0, y: 10, z: 10)
        lightNode1.light!.categoryBitMask = LightType.light1
        scene.rootNode.addChildNode(lightNode1)

        let lightNode2 = SCNNode()
        lightNode2.light = SCNLight()
        lightNode2.light!.type = .omni
        lightNode2.light!.color = UIColor.red
        lightNode2.position = SCNVector3(x: 0, y: 10, z: 10)
        lightNode2.light!.categoryBitMask = LightType.light2
        scene.rootNode.addChildNode(lightNode2)

        let sphere1 = scene.rootNode.childNode(withName: "sphere1", recursively: true)!
        sphere1.categoryBitMask = LightType.light1
        let sphere2 = scene.rootNode.childNode(withName: "sphere2", recursively: true)!
        sphere2.categoryBitMask = LightType.light2

        let scnView = self.view as! SCNView
        scnView.scene = scene
    }
}
</code>```

Body:
SCNLight has a categoryBitMask property. This lets you choose which nodes are affected by the light (Although this is ignored for ambient lights). You could have 2 light source categories, one for your main scene, and another that only affects your lines.

Here is a simple example with 2 nodes, each lit with a different colour light:

struct LightType {
    static let light1:Int = 0x1 << 1
    static let light2:Int = 0x1 << 2
}

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let scene = SCNScene(named: "art.scnassets/scene.scn")!

        let lightNode1 = SCNNode()
        lightNode1.light = SCNLight()
        lightNode1.light!.type = .omni
        lightNode1.light!.color = UIColor.yellow
        lightNode1.position = SCNVector3(x: 0, y: 10, z: 10)
        lightNode1.light!.categoryBitMask = LightType.light1
        scene.rootNode.addChildNode(lightNode1)

        let lightNode2 = SCNNode()
        lightNode2.light = SCNLight()
        lightNode2.light!.type = .omni
        lightNode2.light!.color = UIColor.red
        lightNode2.position = SCNVector3(x: 0, y: 10, z: 10)
        lightNode2.light!.categoryBitMask = LightType.light2
        scene.rootNode.addChildNode(lightNode2)

        let sphere1 = scene.rootNode.childNode(withName: "sphere1", recursively: true)!
        sphere1.categoryBitMask = LightType.light1
        let sphere2 = scene.rootNode.childNode(withName: "sphere2", recursively: true)!
        sphere2.categoryBitMask = LightType.light2

        let scnView = self.view as! SCNView
        scnView.scene = scene
    }
}


问:
Does multipart/x-mixed-replace wait for client requests?
I'm trying to figure out if it's possible to slow down the server when it's sending multipart/xmixed-replace responses.  I want my client to try to rate limit a motion jpeg stream.  I've found a lot of documentation about what the server sends in an HTTP response but nothing about what the client sends.

What does the client send, if anything, after each part in a multipart/x-mixed-replace response?  If it doesn't send anything, does the server just keep piling on the parts?

答: Try using LiveHTTPHeaders plugin for Mozilla.  I went to Gmail (which uses AJAX) and followed the conversation between the client and server for a few minutes.  It seems this could help you.</p>

OwnerDisplayName: Patrick


问:
Accessing custom data on DayRender in Flextras Calendar
I created a Custom Day Render and I would like to access some custom data that I am providing with in the Flextras Calendar dataProvider.

here is the code that I have

```<code>    <flextras:Calendar
  id="calendar"
  dayRenderer="com.healthways.healthhonors.itemrenderers.MyAwesomeDayRenderer"
  monthHeaderRenderer="com.healthways.healthhonors.itemrenderers.MyAwesomeMonthRenderer"
  displayedYear="2010"
  displayedDate="1"
  displayedMonth="10"
  dateField="data"
  width="100%"
  height="100%"
  />
</code>```

Here is the type of Object that I am creating and storying in an ArrayCollection witch gets passed to the Calenders dataProvider

```<code>myArrayCollection = new ArrayCollection([{date:new Date(), data:myObject}])
</code>```

Here is what what my Day Render looks like

```<code>    package com.healthways.healthhonors.itemrenderers
{
 import com.healthways.vo.DateVO;
 import nl.demonsters.debugger.MonsterDebugger;
 import com.healthways.vo.MedicationVO;
 import mx.collections.ArrayCollection;
 import mx.utils.ObjectUtil;
 import com.flextras.calendar.IDayDataVO;
 import com.flextras.calendar.ICalendarDataVO;
 import mx.events.ResizeEvent;
 import mx.events.FlexEvent;
 import com.healthways.components.DailyPieChart;
 import com.flextras.calendar.defaultRenderers.DayRenderer;

 /**
  * @author Matthew Wallace
  */
 public class CalendarMedicationRenderer extends DayRenderer
 {
  private var chart : DailyPieChart;
  public function CalendarMedicationRenderer()
  {
   init();

  }

  private function init() : void
  {
   percentWidth = 100;
   percentHeight = 100;

   chart = new DailyPieChart();
   this.addElement(chart);

   addEventListener(ResizeEvent.RESIZE, onResize);
   addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
  }

  private function onCreationComplete(event : FlexEvent) : void
  {
         /* here I would like to set chart display object visible
                          based on if I have custom data in the renderer or not */
  }

  private function onResize(event : ResizeEvent) : void
  {
   chart.x = (width * 0.5) - 25;
   chart.y = (height * 0.5) - 25;
  }

  override protected function createExpandDayButton() : void
  {
   //super.createExpandDayButton();
  }

  override protected function createDayTextField() : void
  {
   //super.createDayTextField();
  }

 }
}
</code>```

what I need to understand is how to see if a renderer has custom data so that I can do some logic on the renderers creation complete.

thanks,
Matthew

答:
The dayRenderer in the Flextras Calendar is, conceptually, modeled after itemRenderers in the Flex list based classes.  That means the renderer may be reused when you change a month, day, or year, replacing the current data.

In your current dayRenderer, it is likely you are executing the init() method before any data is set.

You should tie into the Flex Component Lifecycle to make changes when data is created (or changed) instead of using creationComplete.  Since you want to examine the dataProvider, you should look at the dayData object.  I would override the set method, something like this:

```<code>protected var dayDataChanged : Boolean = false;

override public function set dayData(value:IDayDataVO):void{
    super._dayData = value;
    this.dayDataChanged = true;
    this.invalidateProperties();
}
</code>```

You could also make this a bit more advanced to compare the current dataProvider with the new one to see if anything has changed, and invalidateProperties() conditionally if it has / has not.

In commitProperties(), try something like this:

```<code>if(this.dayDataChanged == true){
 // access this.dayData.dataProvider and perform whatever processing is needed
 this.dayDataChanged = false;
}
</code>```

I will add that with your current dataProvider item, the date will default to 'today', which is unusual.  The date is not usually set dynamically to the current date.

I'll also add The dateField in your dataProvider is named 'date' but the dateField property you specify is 'data'.  In that situation, the Calendar may never send a dataPRovider's data to the dayRenderer because it cannot determine what day it should end up on.

Body:
I created a Custom Day Render and I would like to access some custom data that I am providing with in the Flextras Calendar dataProvider.

here is the code that I have

    <flextras:Calendar
  id="calendar"
  dayRenderer="com.healthways.healthhonors.itemrenderers.MyAwesomeDayRenderer"
  monthHeaderRenderer="com.healthways.healthhonors.itemrenderers.MyAwesomeMonthRenderer"
  displayedYear="2010"
  displayedDate="1"
  displayedMonth="10"
  dateField="data"
  width="100%"
  height="100%"
  />

Here is the type of Object that I am creating and storying in an ArrayCollection witch gets passed to the Calenders dataProvider

myArrayCollection = new ArrayCollection([{date:new Date(), data:myObject}])

Here is what what my Day Render looks like

    package com.healthways.healthhonors.itemrenderers
{
 import com.healthways.vo.DateVO;
 import nl.demonsters.debugger.MonsterDebugger;
 import com.healthways.vo.MedicationVO;
 import mx.collections.ArrayCollection;
 import mx.utils.ObjectUtil;
 import com.flextras.calendar.IDayDataVO;
 import com.flextras.calendar.ICalendarDataVO;
 import mx.events.ResizeEvent;
 import mx.events.FlexEvent;
 import com.healthways.components.DailyPieChart;
 import com.flextras.calendar.defaultRenderers.DayRenderer;

 /**
  * @author Matthew Wallace
  */
 public class CalendarMedicationRenderer extends DayRenderer
 {
  private var chart : DailyPieChart;
  public function CalendarMedicationRenderer()
  {
   init();

  }

  private function init() : void
  {
   percentWidth = 100;
   percentHeight = 100;

   chart = new DailyPieChart();
   this.addElement(chart);

   addEventListener(ResizeEvent.RESIZE, onResize);
   addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
  }

  private function onCreationComplete(event : FlexEvent) : void
  {
         /* here I would like to set chart display object visible
                          based on if I have custom data in the renderer or not */
  }

  private function onResize(event : ResizeEvent) : void
  {
   chart.x = (width * 0.5) - 25;
   chart.y = (height * 0.5) - 25;
  }

  override protected function createExpandDayButton() : void
  {
   //super.createExpandDayButton();
  }

  override protected function createDayTextField() : void
  {
   //super.createDayTextField();
  }

 }
}

what I need to understand is how to see if a renderer has custom data so that I can do some logic on the renderers creation complete.

thanks,
Matthew

Body:
The dayRenderer in the Flextras Calendar is, conceptually, modeled after itemRenderers in the Flex list based classes.  That means the renderer may be reused when you change a month, day, or year, replacing the current data.

In your current dayRenderer, it is likely you are executing the init() method before any data is set.

You should tie into the Flex Component Lifecycle to make changes when data is created (or changed) instead of using creationComplete.  Since you want to examine the dataProvider, you should look at the dayData object.  I would override the set method, something like this:

protected var dayDataChanged : Boolean = false;

override public function set dayData(value:IDayDataVO):void{
    super._dayData = value;
    this.dayDataChanged = true;
    this.invalidateProperties();
}

You could also make this a bit more advanced to compare the current dataProvider with the new one to see if anything has changed, and invalidateProperties() conditionally if it has / has not.

In commitProperties(), try something like this:

if(this.dayDataChanged == true){
 // access this.dayData.dataProvider and perform whatever processing is needed
 this.dayDataChanged = false;
}

I will add that with your current dataProvider item, the date will default to 'today', which is unusual.  The date is not usually set dynamically to the current date.

I'll also add The dateField in your dataProvider is named 'date' but the dateField property you specify is 'data'.  In that situation, the Calendar may never send a dataPRovider's data to the dayRenderer because it cannot determine what day it should end up on.


问:
What does onDelete('cascade') mean?

Schema::table('posts', function (Blueprint $table) {
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
```

Does this mean that if I delete a post, the user will also be deleted or does it mean if I delete a user, all their posts will be deleted?

答:
If you're using mysql, take a look at the documentation.

In your case it means: If the user is deleted, the post will also be deleted.

Title: What does onDelete('cascade') mean?

Body:
Schema::table('posts', function (Blueprint $table) {
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Does this mean that if I delete a post, the user will also be deleted or does it mean if I delete a user, all their posts will be deleted?


问:
Remove label for in div
I am using icon picker in my cshtml.
I use it with these codes in my page.

```<code>        <div class="form-group" id="kisayolikon" style="display: none">
            @Html.TextBoxFor(model => model.Kisayol.KisayolIkon, new { @class = "IconPicker ", placeholder = _T("Kisayol Simgesi") })
            @Html.ValidationMessageFor(model => model.Kisayol.KisayolIkon)
        </div>
</code>```

But when I click to button. Categories space comes with a label for (I added screenshot). I want to remove this label for with script or other method. I tried to do it with
in browser

```<code>    $(document).ready(function () {
        $("#kisayolikon .floatlabel-wrapper").removeClass("floatlabel-wrapper");
        $("#kisayolikon .label-for").removeClass("label-for");
        $("#kisayolikon .label-floatlabel").removeClass("label-floatlabel");
        $("#kisayolikon .label").removeClass("label");
        $("kisayolikon label").remove();
        $("kisayolikon > label").remove();
        $(".kisayolikon").empty();
        $("kisayolikon > label").remove();
        $(".selector - category").empty();

        $("kisayolikon label").remove();

        });
</code>```

but none of them worked. it is looks like this when I use inspect element.I want to remove these all label for and  from my div. (I added screenshoot too.)with inspect element

答:
Try this.

```<code>var local = $("name-of-element").parents("label");
$(local).remove();
</code>```

Will remove the top label element.

Title: Remove label for in div

Body:
I am using icon picker in my cshtml.
I use it with these codes in my page.

            @Html.TextBoxFor(model => model.Kisayol.KisayolIkon, new { @class = "IconPicker ", placeholder = _T("Kisayol Simgesi") })
            @Html.ValidationMessageFor(model => model.Kisayol.KisayolIkon)

But when I click to button. Categories space comes with a label for (I added screenshot). I want to remove this label for with script or other method. I tried to do it with
in browser

    $(document).ready(function () {
        $("#kisayolikon .floatlabel-wrapper").removeClass("floatlabel-wrapper");
        $("#kisayolikon .label-for").removeClass("label-for");
        $("#kisayolikon .label-floatlabel").removeClass("label-floatlabel");
        $("#kisayolikon .label").removeClass("label");
        $("kisayolikon label").remove();
        $("kisayolikon > label").remove();
        $(".kisayolikon").empty();
        $("kisayolikon > label").remove();
        $(".selector - category").empty();

        $("kisayolikon label").remove();

        });

but none of them worked. it is looks like this when I use inspect element.I want to remove these all label for and  from my div. (I added screenshoot too.)with inspect element

Body:
Try this.

var local = $("name-of-element").parents("label");
$(local).remove();

Will remove the top label element.


问:
Handling significant (but meaningless) constant changes in .IML files for shared IntelliJ project
I have a relatively simple 3-module IntelliJ project built using Gradle. I'm new to both Gradle and IntelliJ, and am working on getting the tooling/process understood between two of my personal machines.

The projects are stored in Git, but every time I open IntelliJ on one of my respective machines (after pushing changes from the other) my module files are always changed:

```<code>modified:   .idea/modules/core/core.iml
modified:   .idea/modules/service/service.iml
modified:   .idea/modules/web/web.iml
</code>```

The changes are always just the reordering of my library entries:

```<code>-    <orderEntry type="library" scope="TEST" name="Gradle: io.netty:netty-resolver:4.1.6.Final" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: io.projectreactor:reactor-core:2.0.8.RELEASE" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: org.yaml:snakeyaml:1.15" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: org.jodd:jodd-core:3.7.1" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: org.hamcrest:hamcrest-all:1.1" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: org.objenesis:objenesis:1.2" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: cglib:cglib-nodep:2.2" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: org.reactivestreams:reactive-streams:1.0.0" level="project" />
     <orderEntry type="library" scope="TEST" name="Gradle: com.fasterxml.jackson.core:jackson-annotations:2.7.0" level="project" />
+    <orderEntry type="library" scope="TEST" name="Gradle: org.reactivestreams:reactive-streams:1.0.0" level="project" />
+    <orderEntry type="library" scope="TEST" name="Gradle: cglib:cglib-nodep:2.2" level="project" />
+    <orderEntry type="library" scope="TEST" name="Gradle: org.objenesis:objenesis:1.2" level="project" />
+    <orderEntry type="library" scope="TEST" name="Gradle: org.hamcrest:hamcrest-all:1.1" level="project" />
+    <orderEntry type="library" scope="TEST" name="Gradle: org.jodd:jodd-core:3.7.1" level="project" />
+    <orderEntry type="library" scope="TEST" name="Gradle: org.yaml:snakeyaml:1.15" level="project" />
</code>```

And the changes are significant:

```<code>$ git diff --stat
 java/.idea/modules/core/core.iml       | 204 ++++++++++----------
 java/.idea/modules/service/service.iml | 276 +++++++++++++--------------
 java/.idea/modules/web/web.iml         | 338 ++++++++++++++++-----------------
</code>```

This happens every time I swap from one machine to the other.

Is there any way to convince IntelliJ to keep these entries in the same order? It's getting extremely annoying for each one of my commits to have these 3 files included along with whatever other changes I'm making.

I obviously can't .gitignore these three files, as they contain all the other information about my module's configuration - something that it completely makes sense to share.

Note that I'm not using apply plugin 'idea' in my build files, I'm just letting IDEA manage the modules entirely. Is this my mistake?

答:
I obviously can't .gitignore these three files, as they contain all
  the other information about my module's configuration - something
  that it completely makes sense to share.

Actually, you can. These files will be generated from Gradle when you open the project and Synchronize it with Gradle.

See the FAQ about sharing project files and the comments below.

Related bugs:

IDEA-165941 Gradle: orderEntry's in .iml are sorted differently on Refresh with and without change in build.gradle

IDEA-157363 Android: arbitrarily reordering of orderEntry tags in iml files w/o related changes in gradle configuration

Body:
I have a relatively simple 3-module IntelliJ project built using Gradle. I'm new to both Gradle and IntelliJ, and am working on getting the tooling/process understood between two of my personal machines.

The projects are stored in Git, but every time I open IntelliJ on one of my respective machines (after pushing changes from the other) my module files are always changed:

modified:   .idea/modules/core/core.iml
modified:   .idea/modules/service/service.iml
modified:   .idea/modules/web/web.iml

The changes are always just the reordering of my library entries:

-    <orderEntry type="library" scope="TEST" name="Gradle: io.netty:netty-resolver:4.1.6.Final" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: io.projectreactor:reactor-core:2.0.8.RELEASE" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: org.yaml:snakeyaml:1.15" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: org.jodd:jodd-core:3.7.1" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: org.hamcrest:hamcrest-all:1.1" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: org.objenesis:objenesis:1.2" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: cglib:cglib-nodep:2.2" level="project" />
-    <orderEntry type="library" scope="TEST" name="Gradle: org.reactivestreams:reactive-streams:1.0.0" level="project" />
     <orderEntry type="library" scope="TEST" name="Gradle: com.fasterxml.jackson.core:jackson-annotations:2.7.0" level="project" />
+    <orderEntry type="library" scope="TEST" name="Gradle: org.reactivestreams:reactive-streams:1.0.0" level="project" />
+    <orderEntry type="library" scope="TEST" name="Gradle: cglib:cglib-nodep:2.2" level="project" />
+    <orderEntry type="library" scope="TEST" name="Gradle: org.objenesis:objenesis:1.2" level="project" />
+    <orderEntry type="library" scope="TEST" name="Gradle: org.hamcrest:hamcrest-all:1.1" level="project" />
+    <orderEntry type="library" scope="TEST" name="Gradle: org.jodd:jodd-core:3.7.1" level="project" />
+    <orderEntry type="library" scope="TEST" name="Gradle: org.yaml:snakeyaml:1.15" level="project" />

And the changes are significant:

$ git diff --stat
 java/.idea/modules/core/core.iml       | 204 ++++++++++----------
 java/.idea/modules/service/service.iml | 276 +++++++++++++--------------
 java/.idea/modules/web/web.iml         | 338 ++++++++++++++++-----------------

This happens every time I swap from one machine to the other.

Is there any way to convince IntelliJ to keep these entries in the same order? It's getting extremely annoying for each one of my commits to have these 3 files included along with whatever other changes I'm making.

I obviously can't .gitignore these three files, as they contain all the other information about my module's configuration - something that it completely makes sense to share.

Note that I'm not using apply plugin 'idea' in my build files, I'm just letting IDEA manage the modules entirely. Is this my mistake?


问:
Input/Output on a file
I wrote a short program for one of my class and there is something that I just cannot figure out. So I am supposed to write 100 random integers on a file, read back the data and print the integers in increasing order. Everything works fine, but I don't see my final sorted list on the output file, anyone can see why?

Here is my code:

```<code>private final static int NUMBEROFRANDOM = 100;

public static void main(String[] args) throws IOException {

    // Creating my file
    java.io.File file = new java.io.File("Question1.txt");

    // If it already exists, print a message and terminate program
    if (file.exists()) {
        System.out.println("File already exists.");
        System.exit(0);
    }

    // Creating my PrintWriter object
    PrintWriter output = new PrintWriter(file);

    // Creating 100 random numbers between 0 and 100 and printing them on the file
    for (int i = 0; i < NUMBEROFRANDOM; i++) {
        int number = (int) (Math.random() * 101);
        output.print(number + " ");
    }

    // Creating my Scanner object
    Scanner input = new Scanner(file);

    // Creating my array list to store the sorted list of 100 elements
    ArrayList<Integer> sortedList = new ArrayList<Integer>();

    // Reading the elements from the file and adding them into my array list
    while (input.hasNext()) {
        sortedList.add(input.nextInt());
    }

    //Sorting elements from array list
    Collections.sort(sortedList);

    // Printing the elements in increasing order
    for (int i = 0; i < sortedList.size(); i++) {
        //System.out.println(sortedList.get(i));
        output.print(sortedList.get(i));
    }

    // Closing my objects
    input.close();
    output.close();

}
</code>```

Thank you very much, any help is very appreciated!

答:
You need to close the outputstream to get it to write to the file. You are doing this correctly the second time but not the first time.

Add:

```<code>output.close();
</code>```

After:

```<code>// Creating 100 random numbers between 0 and 100 and printing them on the file
 for (int i = 0; i < NUMBEROFRANDOM; i++) {
     int number = (int) (Math.random() * 101);
    output.print(number + " ");
 }
//Here close the first output stream to get the data to the file.
output.close();
</code>```

Title: Input/Output on a file

Body:
I wrote a short program for one of my class and there is something that I just cannot figure out. So I am supposed to write 100 random integers on a file, read back the data and print the integers in increasing order. Everything works fine, but I don't see my final sorted list on the output file, anyone can see why?

Here is my code:

private final static int NUMBEROFRANDOM = 100;

public static void main(String[] args) throws IOException {

    // Creating my file
    java.io.File file = new java.io.File("Question1.txt");

    // If it already exists, print a message and terminate program
    if (file.exists()) {
        System.out.println("File already exists.");
        System.exit(0);
    }

    // Creating my PrintWriter object
    PrintWriter output = new PrintWriter(file);

    // Creating 100 random numbers between 0 and 100 and printing them on the file
    for (int i = 0; i < NUMBEROFRANDOM; i++) {
        int number = (int) (Math.random() * 101);
        output.print(number + " ");
    }

    // Creating my Scanner object
    Scanner input = new Scanner(file);

    // Creating my array list to store the sorted list of 100 elements
    ArrayList<Integer> sortedList = new ArrayList<Integer>();

    // Reading the elements from the file and adding them into my array list
    while (input.hasNext()) {
        sortedList.add(input.nextInt());
    }

    //Sorting elements from array list
    Collections.sort(sortedList);

    // Printing the elements in increasing order
    for (int i = 0; i < sortedList.size(); i++) {
        //System.out.println(sortedList.get(i));
        output.print(sortedList.get(i));
    }

    // Closing my objects
    input.close();
    output.close();

}

Thank you very much, any help is very appreciated!

Body:
You need to close the outputstream to get it to write to the file. You are doing this correctly the second time but not the first time.

Add:

output.close();

After:

// Creating 100 random numbers between 0 and 100 and printing them on the file
 for (int i = 0; i < NUMBEROFRANDOM; i++) {
     int number = (int) (Math.random() * 101);
    output.print(number + " ");
 }
//Here close the first output stream to get the data to the file.
output.close();


问:
React vs Angular: Slow rendering with React
I was doing a comparison of Angular and React and decided to try out a performance test to see how fast a large(ish) list would render in both frameworks.

When I got done with my React prototype with some basic currency formating, it was taking ~2 seconds to render on my fast laptop. With Angular it was barely noticeable -- only when I switched to my phone did it have a noticeable lag.

This was very surprising because I was told that React was supposed to beat the pants off of Angular for performance, but it appears that the opposite is true in this case.

I distilled my prototype down to a very simple app to try to isolate the issue: https://github.com/pselden/react-render-test

In this sample, it's taking almost 200ms to render this simple list after changing the language, and I'm barely doing anything.

Am I doing something wrong here?

```<code>/** @jsx React.DOM */
'use strict';

var React = require('react'),
    Numbers = require('./Numbers');

var numbers = []
for(var i = 0; i < 2000; ++i){
    numbers.push(i);
}

var App = React.createClass({
    getInitialState: function() {
        return { locale: 'en-US' };
    },

    _onChangeLocale: function(event) {
        this.setState({locale: event.target.value});
    },

    render: function() {
        var currentLocale = this.state.locale;

        return (
            <div>
                <select
                    onChange={this._onChangeLocale}>
                    <option value="en-US">English</option>
                    <option value="fr-FR">French</option>
                </select>
                <Numbers numbers={numbers} locales={[currentLocale]} />
            </div>
        );
    }
});

module.exports = App;
</code>```

```<code>/** @jsx React.DOM */
'use strict';

var React = require('react'),
    ReactIntlMixin = require('react-intl');

var Numbers = React.createClass({
    mixins: [ReactIntlMixin],

    getInitialState: function() {
        return {
            numbers: this.props.numbers
        };
    },

    render: function() {
        var self = this;
        var list = this.state.numbers.map(function(number){
            return <li key={number}>{number} - {self.formatNumber(number, {style: 'currency', currency: 'USD'})}</li>
        });

        return <ul>{list}</ul>;
    }
});

module.exports = Numbers;
</code>```

PS: Added an angular version: https://github.com/pselden/angular-render-test

Edit: I opened an issue with react-intl and we investigated and found that there was not that much overhead with using https://github.com/yahoo/react-intl/issues/27 -- it's simply React itself that is slower here.

答:
We have tried to analyze some of the attributes of our frameworks, of course, this is not the whole list. Below there is a table of consolidated and important, in our opinion, of comparing attributes.

Let’s get some more details:

Although Angular vs React differences are many, they can do the same thing, namely to build client interface. Both have their place. For those peoples who like web development above all interesting is innovative AngularJS approach to HTML.

AngularJS really is a full framework and not just a library, as the ReactJS, but ReactJS has better performance than the AngularJS by implementing virtual DOM. In our opinion, you should use AngularJS if:

you plan to carry a lot of unit tests during development,

you want a comprehensive solution for your application.

However, two-way data binding is often touted advantage of using AngularJS, but because it is implemented through a series digest, adding too much complexity for certain functions and expressions can lead to deterioration in performance of your applications.

Body:
I was doing a comparison of Angular and React and decided to try out a performance test to see how fast a large(ish) list would render in both frameworks.

When I got done with my React prototype with some basic currency formating, it was taking ~2 seconds to render on my fast laptop. With Angular it was barely noticeable -- only when I switched to my phone did it have a noticeable lag.

This was very surprising because I was told that React was supposed to beat the pants off of Angular for performance, but it appears that the opposite is true in this case.

I distilled my prototype down to a very simple app to try to isolate the issue: https://github.com/pselden/react-render-test

In this sample, it's taking almost 200ms to render this simple list after changing the language, and I'm barely doing anything.

Am I doing something wrong here?

/** @jsx React.DOM */
'use strict';

var React = require('react'),
    Numbers = require('./Numbers');

var numbers = []
for(var i = 0; i < 2000; ++i){
    numbers.push(i);
}

var App = React.createClass({
    getInitialState: function() {
        return { locale: 'en-US' };
    },

    _onChangeLocale: function(event) {
        this.setState({locale: event.target.value});
    },

    render: function() {
        var currentLocale = this.state.locale;

        return (

                <select
                    onChange={this._onChangeLocale}>
                    <option value="en-US">English</option>
                    <option value="fr-FR">French</option>
                </select>
                <Numbers numbers={numbers} locales={[currentLocale]} />

        );
    }
});

module.exports = App;

/** @jsx React.DOM */
'use strict';

var React = require('react'),
    ReactIntlMixin = require('react-intl');

var Numbers = React.createClass({
    mixins: [ReactIntlMixin],

    getInitialState: function() {
        return {
            numbers: this.props.numbers
        };
    },

    render: function() {
        var self = this;
        var list = this.state.numbers.map(function(number){
            return
{number} - {self.formatNumber(number, {style: 'currency', currency: 'USD'})}

        });

        return
{list}
;
    }
});

module.exports = Numbers;

PS: Added an angular version: https://github.com/pselden/angular-render-test

Edit: I opened an issue with react-intl and we investigated and found that there was not that much overhead with using https://github.com/yahoo/react-intl/issues/27 -- it's simply React itself that is slower here.


问:
I want to disable the Next button if no features were selected to install
this is mi installer and i need disable the next button if no features were selected to install.

```<code><Feature Id="App1" Title="App 1" Level="1" AllowAdvertise='no' InstallDefault='local'>
    <Condition Level="0">INSTALL_FEATURES = 0</Condition>
    <ComponentRef Id="App1" />
</Feature>

<Feature Id="App2" Title="App 2" Level="1" AllowAdvertise='no' InstallDefault='local'>
    <Condition Level="0">INSTALL_FEATURES = 0</Condition>
    <ComponentRef Id="App2" />
</Feature>

<UIRef Id="WixUI_FeatureTree"/>
<UIRef Id="WixUI_ErrorProgressText" />
</code>```

thanks!

答: MSI native UI doesn't allow you to enable and disable a control in the way you want.  The best you can do is write event conditions that check that if none of your features are selected to display a modal dialog with an error message otherwise display the next dialog.  Be sure to consider the ramifications of a maintenance / change and/or upgrade scenario.  </p>

Body:
this is mi installer and i need disable the next button if no features were selected to install.

<Feature Id="App1" Title="App 1" Level="1" AllowAdvertise='no' InstallDefault='local'>
    <Condition Level="0">INSTALL_FEATURES = 0</Condition>
    <ComponentRef Id="App1" />
</Feature>

<Feature Id="App2" Title="App 2" Level="1" AllowAdvertise='no' InstallDefault='local'>
    <Condition Level="0">INSTALL_FEATURES = 0</Condition>
    <ComponentRef Id="App2" />
</Feature>

<UIRef Id="WixUI_FeatureTree"/>
<UIRef Id="WixUI_ErrorProgressText" />

thanks!


问:
how to get the content of web services with angular 2?
i'm using spring framework in the backend and angular2.4 in the frontEnd . this is the rest service of my backEnd

```<code>@RequestMapping(value="/etreprises" ,  method = RequestMethod.GET)
public List<Entreprise> getAllEntreprise() {

    return entrepriseDAO.getAllEntreprise();
}
</code>```

and i add CorsFilter  to allow the communication betwen visualcode and STS

```<code>@Bean
public CorsFilter corsFilter() {

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true); // you USUALLY want this
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("POST");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}
</code>```

and this this the response from the brower

```<code>[{"id":"58db96c945184728e40fa6f9","name":"entr1","lagitude":15.3,"latitude":12.2},{"id":"58db96c945184728e40fa6fa","name":"entr2","lagitude":15.3,"latitude":12.2},{"id":"58db96c945184728e40fa6fb","name":"entr3","lagitude":15.3,"latitude":12.2},{"id":"58db96c945184728e40fa6fc","name":"entr4","lagitude":15.3,"latitude":12.2}]
</code>```

and i'm working the frontEnd with visualcode

```<code>@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  entreprises: Entreprise[];
 ngOnInit(): void {
this.http.get('http://localhost:1616/entreprises')
  .subscribe(data =>{
    console.log(data.json());
    this.entreprises=data.json().data;
   });
  }
  constructor(private http: Http) { }

}
</code>```

and the app.component.html

```<code><h1>
</h1>
<div *ngIf="entreprises">
<div *ngFor ="let x of entreprises">
{{x.name}}
</div>

</div>
</code>```

and this is the response from inspect element

```<code>[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
</code>```

but i can not get the name of the entreprises on the browsers it . a white page without error

答:
I'm not sure, but try something like this:</p>

```<code>export class AppComponent implements OnInit {
  entreprises: Entreprise[];
 ngOnInit(): void {
this.http.get('http://localhost:1616/entreprises')
  .map((response: Response) => response.json())
  .subscribe(data =>{
    console.log(data);
    //this.entreprises=data.json().data;
   });
  }
  constructor(private http: Http) { }

}
</code>```

Body:
i'm using spring framework in the backend and angular2.4 in the frontEnd . this is the rest service of my backEnd

@RequestMapping(value="/etreprises" ,  method = RequestMethod.GET)
public List<Entreprise> getAllEntreprise() {

    return entrepriseDAO.getAllEntreprise();
}

and i add CorsFilter  to allow the communication betwen visualcode and STS

@Bean
public CorsFilter corsFilter() {

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true); // you USUALLY want this
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("POST");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

and this this the response from the brower

[{"id":"58db96c945184728e40fa6f9","name":"entr1","lagitude":15.3,"latitude":12.2},{"id":"58db96c945184728e40fa6fa","name":"entr2","lagitude":15.3,"latitude":12.2},{"id":"58db96c945184728e40fa6fb","name":"entr3","lagitude":15.3,"latitude":12.2},{"id":"58db96c945184728e40fa6fc","name":"entr4","lagitude":15.3,"latitude":12.2}]

and i'm working the frontEnd with visualcode

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  entreprises: Entreprise[];
 ngOnInit(): void {
this.http.get('http://localhost:1616/entreprises')
  .subscribe(data =>{
    console.log(data.json());
    this.entreprises=data.json().data;
   });
  }
  constructor(private http: Http) { }

}

and the app.component.html

{{x.name}}

and this is the response from inspect element

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

but i can not get the name of the entreprises on the browsers it . a white page without error

Body:
I'm not sure, but try something like this:

export class AppComponent implements OnInit {
  entreprises: Entreprise[];
 ngOnInit(): void {
this.http.get('http://localhost:1616/entreprises')
  .map((response: Response) => response.json())
  .subscribe(data =>{
    console.log(data);
    //this.entreprises=data.json().data;
   });
  }
  constructor(private http: Http) { }

}


答: It means that if you delete the 'user' linked, the 'posts' linked to that user will also automatically be deleted.</p>

Title: What does onDelete('cascade') mean?


问:
.htaccess in subdirectory - how to use RewriteBase
I'm trying the following.

I have this directory structure, which is available in our network at IP address xxx.xxx.xxx.xxx

```<code>root
    -dir1
    -dir2
    -dir3
</code>```

Now in my dir1-folder, I have a site that uses the following .htaccess file

```<code>RewriteEngine On
RewriteBase /dir1/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
</code>```

On my site, I am linking the sources and pages with a preceding "/", like "/details" or "/css/app.css"

The problem is, that the links always go to the root folder because of the preceding "/".

What can I do to make the links "stay" in the subdirectory without having to edit all links and sources?

I have tried to use

```<code>RewriteBase /
RewriteBase /dir1
RewriteBase /dir1/
RewriteBase dir1
</code>```

Any help is greatly appreciated. Thanks!

答:
RewriteBase doesn't change anything, because it applies only to relative path targets.

The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path.

Because your target is already the absolute /index.php, you can omit RewriteBase altogether.

From the given .htaccess, it seems index.php returns the requested files. So in this case, I would just prefix the path with the appropriate directory, e.g.

```<code>RewriteRule ^(.*)$ /index.php?path=/dir1/$1 [NC,L,QSA]
</code>```

or maybe give an additional argument, if this works better with the script, like

```<code>RewriteRule ^(.*)$ /index.php?path=$1&subdir=dir1 [NC,L,QSA]
</code>```

Body:
I'm trying the following.

I have this directory structure, which is available in our network at IP address xxx.xxx.xxx.xxx

root
    -dir1
    -dir2
    -dir3

Now in my dir1-folder, I have a site that uses the following .htaccess file

RewriteEngine On
RewriteBase /dir1/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]

On my site, I am linking the sources and pages with a preceding "/", like "/details" or "/css/app.css"

The problem is, that the links always go to the root folder because of the preceding "/".

What can I do to make the links "stay" in the subdirectory without having to edit all links and sources?

I have tried to use

RewriteBase /
RewriteBase /dir1
RewriteBase /dir1/
RewriteBase dir1

Any help is greatly appreciated. Thanks!

Body:
RewriteBase doesn't change anything, because it applies only to relative path targets.

The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path.

Because your target is already the absolute /index.php, you can omit RewriteBase altogether.

From the given .htaccess, it seems index.php returns the requested files. So in this case, I would just prefix the path with the appropriate directory, e.g.

RewriteRule ^(.*)$ /index.php?path=/dir1/$1 [NC,L,QSA]

or maybe give an additional argument, if this works better with the script, like

RewriteRule ^(.*)$ /index.php?path=$1&subdir=dir1 [NC,L,QSA]


问:
ArrayMap put method pushes elements in strange order
I am using ArrayMap for first time in my project and I thought it works just like an array. I expected when I use .put method it inserts it at next index.
But in my case this is not true - after I added all elements one by one the first element I added ended up at index 4 which is kind of strange.

Here are the first three steps which I add elements:

1 - Salads:

2 - Soups:

3 - Appetizers:

So somehow on second step "Soup" element was inserted in index 0 instead of 1 as I was expecting, but strangely on third step "Appetizers" was inserted as expected after "Soup".

This is the code I am using to push key and value pair:

```<code>function ArrayMap<String, DMType> addElement(String typeKey, DMType type) {
    ArrayMap<String, DMType> types = new ArrayMap<>();
    types.put(typeKey, type);

    return types;
}
</code>```

Am I missing something about the behavior of ArrayMap?

答:
It doesn't work as an array, I don't see Array in the name but Map and the documentation clearly states that behaves as a generic key->value mapping, more efficient (memory wise) than traditional HashMap implementation.

Actually I don't see why you care about the order compared to the insertion one. Data is private inside the class and you have no way to obtain the element by the index, so you are basically wondering about a private implementation which is irrelevant for its usage.

If you really want to understand how it stores its data you should take a look at the source code.

Body:
I am using ArrayMap for first time in my project and I thought it works just like an array. I expected when I use .put method it inserts it at next index.
But in my case this is not true - after I added all elements one by one the first element I added ended up at index 4 which is kind of strange.

Here are the first three steps which I add elements:

1 - Salads:

2 - Soups:

3 - Appetizers:

So somehow on second step "Soup" element was inserted in index 0 instead of 1 as I was expecting, but strangely on third step "Appetizers" was inserted as expected after "Soup".

This is the code I am using to push key and value pair:

function ArrayMap<String, DMType> addElement(String typeKey, DMType type) {
    ArrayMap<String, DMType> types = new ArrayMap<>();
    types.put(typeKey, type);

    return types;
}

Am I missing something about the behavior of ArrayMap?


问:
Creating a pivot table based on categorical variables
I am currently doing some analysis in R and can't seem to find a working solution to the following problem:

My raw data is a table containing 3 columns: "user id", "year" and "block".
The block column can either have a value 'north', 'east', 'south', 'west' or 'other'.

What i want to creat now is some sort of pivot table (not sure if this is the right term to use here). This table should consist of a single row for each combination of user_id and year followed by 5 new columns containing a dummy variable referencing whether or not the customer was sitting in the respective block that year or not. Similar to the example below:

I have been trying to get things working through the use of the reshape package in R but it seems to struggle handling the categorical variable "block".
Any tips/help is greatly appreciated!

Thanks in advance

答:
Here's a simple method using Base R and aggregate:

```<code>d <- data.frame("User id"=c(1,1,2,3,1), year=c(2015,2016,2015,2015,2015),
  block=c("north","south","east","west","south"), check.names = F)

f <- function(l, vec) {
  vec[l] <- 1
  vec
}

vec <- setNames(rep(0, 4), levels(d$block))
> aggregate(block~`User id` + year, d, f, vec)

  User id year block.east block.north block.south block.west
1       1 2015          0           1           1          0
2       2 2015          1           0           0          0
3       3 2015          0           0           0          1
4       1 2016          0           0           1          0
</code>```

I added an additional data point to show that it can ouptut multiple dummy flags for the same combination of id and year.

Body:
Here's a simple method using Base R and aggregate:

d <- data.frame("User id"=c(1,1,2,3,1), year=c(2015,2016,2015,2015,2015),
  block=c("north","south","east","west","south"), check.names = F)

f <- function(l, vec) {
  vec[l] <- 1
  vec
}

vec <- setNames(rep(0, 4), levels(d$block))
> aggregate(block~`User id` + year, d, f, vec)

  User id year block.east block.north block.south block.west
1       1 2015          0           1           1          0
2       2 2015          1           0           0          0
3       3 2015          0           0           0          1
4       1 2016          0           0           1          0

I added an additional data point to show that it can ouptut multiple dummy flags for the same combination of id and year.


问:
Why does, in python, Stack's pop method and Queue's dequeue method behave differently when both have same code?
When the pop() method of a list is used in class Stack, it returns the last element of the list (head of the stack) while in class Queue it returns the 1st element. Can anybody explain me the reason behind this?

```<code># coding: utf-8

class Queue (object):
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def enqueue(self, item):
        self.items.insert(0,item)

    def dequeue(self):
        return self.items.pop()

    def size(self):
        return len(self.items)

class Stack(object):
    def__init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
q.enqueue(6)

s = Stack()
s.push(1)
s.push(2)
s.push(3)
s.push(4)
s.push(5)
s.push(6)

q.dequeue() #Output: 1

s.pop() #Output: 6
</code>```

答:
When the pop() method of a list is used [...] in class Queue it returns the 1st element.

No, it does not. It still returns the last element of the list. You should not look at dequeue and pop, you should instead concentrate on the Queue.enqueue and Stack.push methods.

The Stack class appends to the items list, so puts the new element at the end:

```<code>def push(self, item):
    self.items.append(item)
</code>```

while the Queue inserts at the start of the items list:

```<code>def enqueue(self, item):
    self.items.insert(0,item)
</code>```

So when you pop from the stack, you remove the element that was last added. When you pop from the queue, you remove the element that was first added, as everything else was inserted in front  of it.

Put differently, the Queue hold items in chronological order (newest item is at the start of the list), while the Stack holds them in reverse chronological order (newest item is at the end of the list). Popping still removes the last element from the list.

Body:
When the pop() method of a list is used in class Stack, it returns the last element of the list (head of the stack) while in class Queue it returns the 1st element. Can anybody explain me the reason behind this?

# coding: utf-8

class Queue (object):
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def enqueue(self, item):
        self.items.insert(0,item)

    def dequeue(self):
        return self.items.pop()

    def size(self):
        return len(self.items)

class Stack(object):
    def__init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
q.enqueue(6)

s = Stack()
s.push(1)
s.push(2)
s.push(3)
s.push(4)
s.push(5)
s.push(6)

q.dequeue() #Output: 1

s.pop() #Output: 6

Body:
When the pop() method of a list is used [...] in class Queue it returns the 1st element.

No, it does not. It still returns the last element of the list. You should not look at dequeue and pop, you should instead concentrate on the Queue.enqueue and Stack.push methods.

The Stack class appends to the items list, so puts the new element at the end:

def push(self, item):
    self.items.append(item)

while the Queue inserts at the start of the items list:

def enqueue(self, item):
    self.items.insert(0,item)

So when you pop from the stack, you remove the element that was last added. When you pop from the queue, you remove the element that was first added, as everything else was inserted in front  of it.

Put differently, the Queue hold items in chronological order (newest item is at the start of the list), while the Stack holds them in reverse chronological order (newest item is at the end of the list). Popping still removes the last element from the list.


问:
Fix restore invalid column reference editor by clicking Ok?
This SSIS job essentially exports data from an oracle PLSQL database to a SQL Server database.

Whenever I change something in the WHERE clause of the query that will be used for the bulk insert, I get the following screen. I just click 'Ok' and everything's fixed.

Two questions: why do I get this error every time I change the query? I'm not changing the columns or the size. The output is not affected since I'm not touching the columns.

Is it a valid fix just to click 'Ok'? Whenever I see the red X after changing the output query, I literally just double-click on the SQL Server Destination and click 'Ok'.

This is the query. I simply change the WHERE clause; for example, trunc(sysdate)-2 to trunc(sysdate)-1

```<code>SELECT
datetime
,EmplCode
,TotalSales
,TotalRev
TotalTax
FROM Employee
WHERE
Employee.EmplCode like 'STX%'
and trunc(Employee.DATETIME) = trunc(sysdate)-2 --This is what I change
</code>```

Thanks.

答:
Did you rename the columns in the where clause? Are there functions in the where clause? Please show the code in the where clause.

If you right click on the task, and choose advanced, you can view/edit the input and  output columns. You can see then see the effect of clicking on the 'OK' button. SSIS is either renaming or changing the data type of one or more columns. Its probably ok but you should be aware of what SSIS is doing. Trust but verify to quote a former president....

Body:
This SSIS job essentially exports data from an oracle PLSQL database to a SQL Server database.

Whenever I change something in the WHERE clause of the query that will be used for the bulk insert, I get the following screen. I just click 'Ok' and everything's fixed.

Two questions: why do I get this error every time I change the query? I'm not changing the columns or the size. The output is not affected since I'm not touching the columns.

Is it a valid fix just to click 'Ok'? Whenever I see the red X after changing the output query, I literally just double-click on the SQL Server Destination and click 'Ok'.

This is the query. I simply change the WHERE clause; for example, trunc(sysdate)-2 to trunc(sysdate)-1

SELECT
datetime
,EmplCode
,TotalSales
,TotalRev
TotalTax
FROM Employee
WHERE
Employee.EmplCode like 'STX%'
and trunc(Employee.DATETIME) = trunc(sysdate)-2 --This is what I change

Thanks.


问:
urlopen error [Errno 11001] getaddrinfo failed?
Hello everyone I am a beginner programmer in language Python and I need help.

this is my code in Python, it gives an error, please help to fix

urllib.error.URLError: urlopen error [Errno 11001] getaddrinfo failed

Python:

```<code># -*- coding: utf-8 -*-

import urllib.request
from lxml.html import parse

WEBSITE = 'http://allrecipes.com'

URL_PAGE = 'http://allrecipes.com/recipes/110/appetizers-and-snacks/deviled-eggs/?page='

START_PAGE = 1
END_PAGE = 5

def correct_str(s):
    return s.encode('utf-8').decode('ascii', 'ignore').strip()

for i in range(START_PAGE, END_PAGE+1):
    URL = URL_PAGE + str(i)
    HTML = urllib.request.urlopen(URL)

    page = parse(HTML).getroot()

    for elem in page.xpath('//*[@id="grid"]/article[not(contains(@class, "video-card"))]/a[1]'):
        href = WEBSITE + elem.get('href')
        title = correct_str(elem.find('h3').text)

        recipe_page = parse(urllib.request.urlopen(href)).getroot()
        print(correct_str(href))
        photo_url = recipe_page.xpath('//img[@class="rec-photo"]')[0].get('src')

        print('\nName:  |', title)
        print('Photo: |', photo_url)
</code>```

This into command prompt: python I get this error:

```<code>Traceback (most recent call last):
http://allrecipes.com/recipe/236225/crab-stuffed-deviled-eggs/
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 1240, in do_open

    h.request(req.get_method(), req.selector, req.data, headers)
Name:  | Crab-Stuffed Deviled Eggs
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 1083, in request
Photo: | http://images.media-allrecipes.com/userphotos/720x405/1091564.jpg
    self._send_request(method, url, body, headers)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 1128, in _send_request
    self.endheaders(body)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 1079, in endheaders
    self._send_output(message_body)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 911, in _send_output
    self.send(msg)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 854, in send
    self.connect()
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 826, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\socket.py", line 693, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\socket.py", line 732, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Ivan/Dropbox/parser/test.py", line 27, in <module>
    recipe_page = parse(urllib.request.urlopen(href)).getroot()
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 162, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 465, in open
    response = self._open(req, data)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 483, in _open
    '_open', req)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 443, in _call_chain
    result = func(*args)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 1268, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 1242, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed>

Process finished with exit code 1
</code>```

答:
A better way to do this is to use parse as such:

```<code>    from urllib import parse
    href = parse.urljoin(base_url, href)
</code>```

This will will return a complete url for the href in case it is not complete.

Body:
Hello everyone I am a beginner programmer in language Python and I need help.

this is my code in Python, it gives an error, please help to fix

urllib.error.URLError: urlopen error [Errno 11001] getaddrinfo failed

Python:

# -*- coding: utf-8 -*-

import urllib.request
from lxml.html import parse

WEBSITE = 'http://allrecipes.com'

URL_PAGE = 'http://allrecipes.com/recipes/110/appetizers-and-snacks/deviled-eggs/?page='

START_PAGE = 1
END_PAGE = 5

def correct_str(s):
    return s.encode('utf-8').decode('ascii', 'ignore').strip()

for i in range(START_PAGE, END_PAGE+1):
    URL = URL_PAGE + str(i)
    HTML = urllib.request.urlopen(URL)

    page = parse(HTML).getroot()

    for elem in page.xpath('//*[@id="grid"]/article[not(contains(@class, "video-card"))]/a[1]'):
        href = WEBSITE + elem.get('href')
        title = correct_str(elem.find('h3').text)

        recipe_page = parse(urllib.request.urlopen(href)).getroot()
        print(correct_str(href))
        photo_url = recipe_page.xpath('//img[@class="rec-photo"]')[0].get('src')

        print('\nName:  |', title)
        print('Photo: |', photo_url)

This into command prompt: python I get this error:

Traceback (most recent call last):
http://allrecipes.com/recipe/236225/crab-stuffed-deviled-eggs/
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 1240, in do_open

    h.request(req.get_method(), req.selector, req.data, headers)
Name:  | Crab-Stuffed Deviled Eggs
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 1083, in request
Photo: | http://images.media-allrecipes.com/userphotos/720x405/1091564.jpg
    self._send_request(method, url, body, headers)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 1128, in _send_request
    self.endheaders(body)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 1079, in endheaders
    self._send_output(message_body)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 911, in _send_output
    self.send(msg)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 854, in send
    self.connect()
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 826, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\socket.py", line 693, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\socket.py", line 732, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Ivan/Dropbox/parser/test.py", line 27, in <module>
    recipe_page = parse(urllib.request.urlopen(href)).getroot()
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 162, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 465, in open
    response = self._open(req, data)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 483, in _open
    '_open', req)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 443, in _call_chain
    result = func(*args)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 1268, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "C:\Users\Ivan\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 1242, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed>

Process finished with exit code 1

Body:
A better way to do this is to use parse as such:

    from urllib import parse
    href = parse.urljoin(base_url, href)

This will will return a complete url for the href in case it is not complete.


答:
The code you are talking about creates a foreign key / reference to a column on another table. The onDelete('cascade') means that when the row is deleted, it will delete all it's references and attached data too.

For example if you have a User which has a Post and you set onDelete('cascade') on the user, then when the user deletes his account, all posts will be deleted as well.

You can find more information on Laravel excellent documentation.

Title: What does onDelete('cascade') mean?

Body:
Schema::table('posts', function (Blueprint $table) {
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Does this mean that if I delete a post, the user will also be deleted or does it mean if I delete a user, all their posts will be deleted?


问:
How to access/get the value of a Variable inside a nested if statement to outside the main if statement
I have this code sample which I was developing. Here I have declared two variables (initialPath, lastPath) outside the main if-else statement. Inside the main If statement there is a nested if-else statement. I have initialized the variable (initialPath) inside the nested if statement. I need that value to be used outside the nested if-else statement. I have attached my code snippet. If anyone can help to solve my problem, I'd be glad :)</p>

```<code>    FileWriter writer;
    File initialPath=null;
    File lastPath=null;

    if (clicked == 1) {

        int sf = savefile.showSaveDialog(null);

        if (sf == JFileChooser.APPROVE_OPTION) {

            initialPath=savefile.getSelectedFile(); // in here the Variable values is initialized/assigned

            try {

                if (savefile.getFileFilter().equals(filter2)) {

                    String path = savefile.getSelectedFile() + ".java";
                    File file = new File(path);
                    writer = new FileWriter(file, false);
                    System.out.println(savefile.getFileFilter());
                    writer.write(jTextPane1.getText());

                    writer.close();
                } else if (savefile.getFileFilter().equals(filter)) {

                    System.out.println("2");
                    String path = savefile.getSelectedFile() + ".txt";
                    File file = new File(path);
                    writer = new FileWriter(file, false);

                    writer.write(jTextPane1.getText());

                    writer.close();

                } else {
                    System.out.println("No format");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (sf == JFileChooser.CANCEL_OPTION) {

            clicked = 0;

        }

    } else {

        try {

            lastPath=initialPath.getParentFile(); //but in here lastPath become NULL because initialPath is NULL...

    //I need to get the value of initialPath to this ELSE statement

            if (savefile.getFileFilter().equals(filter2)) {

                String path = savefile.getSelectedFile() + ".java";
                File file = new File(path);
                writer = new FileWriter(file, false);
                System.out.println(savefile.getFileFilter());
                writer.write(jTextPane1.getText());

                writer.close();
            } else if (savefile.getFileFilter().equals(filter)) {

                String path = savefile.getSelectedFile() + ".txt";
                File file = new File(path);
                writer = new FileWriter(file, false);

                writer.write(jTextPane1.getText());

                writer.close();

            } else {
                System.out.println("No format");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

答:
You can use initialPath outside as you declared it outside. " I need that value to be used outside the nested if-else statement."

In a short example what you are doing:

```<code>File file;
if(true){
    file = /*you initialize here*/;
} else {
    /*if false file is never initialized but you want to use it here,
      its in scope but null of course.*/
}
</code>```

Initialize file outside if you need it in both if and else blocks, if you can not initialize it outside you should not need that in the else block. A logical error is there.

Body:
I have this code sample which I was developing. Here I have declared two variables (initialPath, lastPath) outside the main if-else statement. Inside the main If statement there is a nested if-else statement. I have initialized the variable (initialPath) inside the nested if statement. I need that value to be used outside the nested if-else statement. I have attached my code snippet. If anyone can help to solve my problem, I'd be glad :)

    FileWriter writer;
    File initialPath=null;
    File lastPath=null;

    if (clicked == 1) {

        int sf = savefile.showSaveDialog(null);

        if (sf == JFileChooser.APPROVE_OPTION) {

            initialPath=savefile.getSelectedFile(); // in here the Variable values is initialized/assigned

            try {

                if (savefile.getFileFilter().equals(filter2)) {

                    String path = savefile.getSelectedFile() + ".java";
                    File file = new File(path);
                    writer = new FileWriter(file, false);
                    System.out.println(savefile.getFileFilter());
                    writer.write(jTextPane1.getText());

                    writer.close();
                } else if (savefile.getFileFilter().equals(filter)) {

                    System.out.println("2");
                    String path = savefile.getSelectedFile() + ".txt";
                    File file = new File(path);
                    writer = new FileWriter(file, false);

                    writer.write(jTextPane1.getText());

                    writer.close();

                } else {
                    System.out.println("No format");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (sf == JFileChooser.CANCEL_OPTION) {

            clicked = 0;

        }

    } else {

        try {

            lastPath=initialPath.getParentFile(); //but in here lastPath become NULL because initialPath is NULL...

    //I need to get the value of initialPath to this ELSE statement

            if (savefile.getFileFilter().equals(filter2)) {

                String path = savefile.getSelectedFile() + ".java";
                File file = new File(path);
                writer = new FileWriter(file, false);
                System.out.println(savefile.getFileFilter());
                writer.write(jTextPane1.getText());

                writer.close();
            } else if (savefile.getFileFilter().equals(filter)) {

                String path = savefile.getSelectedFile() + ".txt";
                File file = new File(path);
                writer = new FileWriter(file, false);

                writer.write(jTextPane1.getText());

                writer.close();

            } else {
                System.out.println("No format");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

Body:
You can use initialPath outside as you declared it outside. " I need that value to be used outside the nested if-else statement."

In a short example what you are doing:

File file;
if(true){
    file = /*you initialize here*/;
} else {
    /*if false file is never initialized but you want to use it here,
      its in scope but null of course.*/
}

Initialize file outside if you need it in both if and else blocks, if you can not initialize it outside you should not need that in the else block. A logical error is there.


问:
Distribution Provisioning Problems
I had an app that I finally got finalized and am ready to post it to the App Store so I started the amazingly awful process...

I have been developing on my laptop, testing on my device, and having no issues with my development certificate and provisioning.

I ended up having to rename my project (Project->rename for anyone who needs to know).  I then rebuilt my project, tested it out on my devices and all is ok.

I went online and created my AppID for the project and then created my App Dist Profile.  I Downloaded it and dragged it into XCode's organizer.  I immediately see "A valid signing identity matching this profile could not be found in your keychain."  I've checked my certificates and double checked that I created the right AppID, profile, etc.. What could possibly cause this?

Am I the only one that is constantly blown away at the amount of work that it takes to actually get ON the app store once the app is done?  Anyone else kind of miss the J2ME days (minus the fee's, J-verified, and VeriSign crap.. haha)

Thanks,

-d

答:
I finally figured it out.  I think because I was around before XCode managed the provisioning stuff that my old certificate was causing issues with the new distribution certificates.  I just erased all my keys, certificates, profiles and started over.

In order I did this:

1) Removed all keys
2) Revoked the certificates on both development and distribution
3) Removed all profiles
4) Created a new Cert Request
5) Downloaded and installed both distribution and development certs
6) Created profiles
7) Installed everything.
8) Opened XCode and went to organizer, profiles, and hit refresh to update my team provisioning profile

It all finally works.

Wow..

Title: Distribution Provisioning Problems