问:
Hide Registration form, show another form after success
Trying to hide the registration form, after submit and all checks comes success, then hide this form, then show another one for choose product form.
Been trying to see if the settimeout would do the trick, but only shows a white blank page after success.

Anyone got any idea? Thanks =)

```<code>setTimeout('$(".signin-form").fadeOut(500, function(){ $(".ChooseProductForm").fadein(500); }); ',2000);
</code>```

Sorry, i misunderstood the hole jQuery, so read my way up to understand a bit more and fixed this question while many other problems as well :-)

答:
Good finding for syntax error in function parameters.
But my suggestion is if you are using fadeIn and fadeOut animation methods, setTimeOut will bring unwanted delays to users. So instead using timer function just do animation to hide and display contents.</p>

Body:
Trying to hide the registration form, after submit and all checks comes success, then hide this form, then show another one for choose product form.
Been trying to see if the settimeout would do the trick, but only shows a white blank page after success.

Anyone got any idea? Thanks =)

setTimeout('$(".signin-form").fadeOut(500, function(){ $(".ChooseProductForm").fadein(500); }); ',2000);

Sorry, i misunderstood the hole jQuery, so read my way up to understand a bit more and fixed this question while many other problems as well :-)


来源: stackexchange

问:
Generate schema SQL with SQLAlchemy
How does one generate the SQL/Migrate Code/Whatever with SQLAlchemy when using the Declarative Base?

```<code>from sqlalchemy import *
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('mysql://root:password@localhost/mydb_dev', echo=True)
metadata = MetaData(bind=engine)

class User(Base):
    __table__ = Table("users", metadata, autoload=True)

    id = Column(Integer, primary_key=True)
    display_name = Column(String)
    email = Column(String)
    password = Column(String)

    def __repr__(self):
        return "<User(id='{}', display_name='{}', email='{}')>".format(self.id, self.display_name, self.email)

class Site(Base):
    __table__ = Table("sites", metadata, autoload=True)

    id = Column(Integer, primary_key=True)
    name = Column(String)
    urls = relationship("URL")

    def __repr__(self):
        return "<Site(id='{}', name='{}')>".format(self.id, self.name)
</code>```

I have this so far, I'd like to see what SQLAlchemy would generate as a schema.

Or, does SQLAlchemy do this at all? Is this a case where I create and manage the database and it's schema separately, and I just update my entities to reflect it?

Do understand that I am used to Doctrine2, and im very new to SQLAlchemy

Thanks!

答:
You can create the db models by calling:

metadata.create_all()

http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.MetaData.create_all

Note that this only works for the creation of previously non-existent models, and doesn't handle updates or downgrades. Check out alembic for even finer control:

http://alembic.zzzcomputing.com/en/latest/

ContentLicense: CC BY-SA 3.0

Title: Generate schema SQL with SQLAlchemy

Body:
How does one generate the SQL/Migrate Code/Whatever with SQLAlchemy when using the Declarative Base?

from sqlalchemy import *
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('mysql://root:password@localhost/mydb_dev', echo=True)
metadata = MetaData(bind=engine)

class User(Base):
    __table__ = Table("users", metadata, autoload=True)

    id = Column(Integer, primary_key=True)
    display_name = Column(String)
    email = Column(String)
    password = Column(String)

    def __repr__(self):
        return "<User(id='{}', display_name='{}', email='{}')>".format(self.id, self.display_name, self.email)

class Site(Base):
    __table__ = Table("sites", metadata, autoload=True)

    id = Column(Integer, primary_key=True)
    name = Column(String)
    urls = relationship("URL")

    def __repr__(self):
        return "<Site(id='{}', name='{}')>".format(self.id, self.name)

I have this so far, I'd like to see what SQLAlchemy would generate as a schema.

Or, does SQLAlchemy do this at all? Is this a case where I create and manage the database and it's schema separately, and I just update my entities to reflect it?

Do understand that I am used to Doctrine2, and im very new to SQLAlchemy

Thanks!


问:
What algorithm to use for getting a sub CIDR from a base CIDR?
I have a VPC and let's say its CIDR block is 10.0.0.0/16. And I have a couple of random subnets in that VPC. Their CIDRs could be something like 10.0.128.0/19, 10.0.32.0/19, 10.0.208.0/22. CIDR blocks for subnets must be covered by the CIDR block of the VPC. Also, no overlap of CIDRs among subnets is allowed.

My question is:
Given such a VPC and subnets, how to find a good CIDR block with specific size for a new subnets I want to create(let's say /22). The good, from my point of view, means better using of space. Let's say if I just want a small CIDR block, it shouldn't return me a CIDR right in the middle of the VPC CIDR, which prevent potential big CIDR block being placed in the future. Other definitions of good are welcomed. There is no guarantee for any initial states.

I don't know if there is a standard algorithm for such problem. What I am currently thinking of is making use of a binary tree. The left child means 0 while right child means 1. All leaves represent CIDR blocks that are in used. To get a new CIDR block, the problem is basically creating a leave at some level depends on the desired size of the block. How to create a good leaves I still don't know yet.

BTW, I am writing Java code. I couldn't find a library for this. If there is an existing library, please also let me know!

答:
A binary tree is the right structure for this, but it needn't go down to the leaf level. Only take it down as far as needed. Every leaf in the tree represents either an allocation or an available block. By definition, the size of every CIDR block is a power of two. So, if a node/block has children, it has exactly two. If a node has children (is not a leaf), its block is not available.

So, your top-level block and its initial allocations breaks down like this (tree represented from the left edge for ease of drawing. *** marks allocated blocks. [I've probably fat-fingered something here but the basic idea should be clear: every /16 has two /17 children, every /17 has two /18 children, etc. unless that node is available in which case it has no children.]):

```<code>                    /---- 10.0.0.0/19
                    |
            /---  10.0.0.0/18
            |       |
            |       \---- 10.0.32.0/19***
            |
     /--- 10.0.0.0/17
    |       \
    |        ---- 10.0.64.0/18
    |
  10.0.0.0/16
    |
    |               /---- 10.0.128.0/19***
    |               |
    |       /---- 10.0.128.0/18
    |       |       |
    |       |       \---- 10.0.160.0/19
    |       |
     \--- 10.0.128.0/17
            |
            |               /---- 10.0.192.0/20
            |               |
            |       /---- 10.0.192.0/19
            |       |       |
            |       |       |               /---- 10.0.208.0/22***
            |       |       |               |
            |       |       |       /---- 10.0.208.0/21
            |       |       |       |       |
            |       |       |       |       \---- 10.0.212.0/22
            |       |       |       |
            |       |       \---- 10.0.208.0/20
            |       |               |
            |       |               \---- 10.0.216.0/21
            |       |
            \---- 10.0.192.0/18
                    |
                    \---- 10.0.224.0/19
</code>```

So for example, to find a block of /24, first traverse the tree (in any order) looking for a block that is exactly /24 in size. If you find one, you're done; mark it allocated and return it. During the traversal, keep track of the smallest block you find that is greater in size than /24. (Obviously if you get to any node in the tree that is smaller than /24, you don't need to traverse its subtree any further since the size will only go down from there.)

If you don't find one that is exactly /24, you then go to the one you saved which is the smallest block greater in size than /24. You then cut that block in two, replacing it with two half-size blocks. Grab either one of those (arbitrarily). If it's /24 you're done. If not, you recurse to cut that block in two and so forth. Eventually, you will have found a /24.

Let's say that the smallest block greater in size than /24 was a /21. By recursively carving it up that way, you will have carved the /21 up into: two /24s (one you allocated, one still available), an available /23, and an available /22.

If a block is returned to you, you can combine it with its companion block iff that block is available (i.e. a leaf and not marked allocated). If you can combine it with its companion, you may be able to combine its parent with the parent's twin as well.

(BTW, this is compatible with @mcdowella's answer; just adding details.)

Body:
A binary tree is the right structure for this, but it needn't go down to the leaf level. Only take it down as far as needed. Every leaf in the tree represents either an allocation or an available block. By definition, the size of every CIDR block is a power of two. So, if a node/block has children, it has exactly two. If a node has children (is not a leaf), its block is not available.

So, your top-level block and its initial allocations breaks down like this (tree represented from the left edge for ease of drawing. *** marks allocated blocks. [I've probably fat-fingered something here but the basic idea should be clear: every /16 has two /17 children, every /17 has two /18 children, etc. unless that node is available in which case it has no children.]):

                    /---- 10.0.0.0/19
                    |
            /---  10.0.0.0/18
            |       |
            |       \---- 10.0.32.0/19***
            |
     /--- 10.0.0.0/17
    |       \
    |        ---- 10.0.64.0/18
    |
  10.0.0.0/16
    |
    |               /---- 10.0.128.0/19***
    |               |
    |       /---- 10.0.128.0/18
    |       |       |
    |       |       \---- 10.0.160.0/19
    |       |
     \--- 10.0.128.0/17
            |
            |               /---- 10.0.192.0/20
            |               |
            |       /---- 10.0.192.0/19
            |       |       |
            |       |       |               /---- 10.0.208.0/22***
            |       |       |               |
            |       |       |       /---- 10.0.208.0/21
            |       |       |       |       |
            |       |       |       |       \---- 10.0.212.0/22
            |       |       |       |
            |       |       \---- 10.0.208.0/20
            |       |               |
            |       |               \---- 10.0.216.0/21
            |       |
            \---- 10.0.192.0/18
                    |
                    \---- 10.0.224.0/19

So for example, to find a block of /24, first traverse the tree (in any order) looking for a block that is exactly /24 in size. If you find one, you're done; mark it allocated and return it. During the traversal, keep track of the smallest block you find that is greater in size than /24. (Obviously if you get to any node in the tree that is smaller than /24, you don't need to traverse its subtree any further since the size will only go down from there.)

If you don't find one that is exactly /24, you then go to the one you saved which is the smallest block greater in size than /24. You then cut that block in two, replacing it with two half-size blocks. Grab either one of those (arbitrarily). If it's /24 you're done. If not, you recurse to cut that block in two and so forth. Eventually, you will have found a /24.

Let's say that the smallest block greater in size than /24 was a /21. By recursively carving it up that way, you will have carved the /21 up into: two /24s (one you allocated, one still available), an available /23, and an available /22.

If a block is returned to you, you can combine it with its companion block iff that block is available (i.e. a leaf and not marked allocated). If you can combine it with its companion, you may be able to combine its parent with the parent's twin as well.

(BTW, this is compatible with @mcdowella's answer; just adding details.)


问:
Remove quotes from start and end of string in PHP
I have strings like these:

"my value1" => my value1
"my Value2" => my Value2
myvalue3 => myvalue3
```

<p>I need to get rid of <code>"</code> (double-quotes) in end and start, if these exist, but if there is this kind of character inside String then it should be left there. Example:</p>

<pre class="lang-none prettyprint-override"><code>"my " value1" => my " value1
</code>```

How can I do this in PHP - is there function for this or do I have to code it myself?

答:
If you like performance over clarity this is the way:

```<code>// Remove double quotes at beginning and/or end of output
$len=strlen($output);
if($output[0]==='"') $iniidx=1; else $iniidx=0;
if($output[$len-1]==='"') $endidx=-1; else $endidx=$len-1;
if($iniidx==1 || $endidx==-1) $output=substr($output,$iniidx,$endidx);
</code>```

The comment helps with clarity...
brackets in an array-like usage on strings is possible and demands less processing effort than equivalent methods, too bad there isnt a length variable or a last char index

Body:
I have strings like these:

"my value1" => my value1
"my Value2" => my Value2
myvalue3 => myvalue3

I need to get rid of " (double-quotes) in end and start, if these exist, but if there is this kind of character inside String then it should be left there. Example:

"my " value1" => my " value1

How can I do this in PHP - is there function for this or do I have to code it myself?

Body:
If you like performance over clarity this is the way:

// Remove double quotes at beginning and/or end of output
$len=strlen($output);
if($output[0]==='"') $iniidx=1; else $iniidx=0;
if($output[$len-1]==='"') $endidx=-1; else $endidx=$len-1;
if($iniidx==1 || $endidx==-1) $output=substr($output,$iniidx,$endidx);

The comment helps with clarity...
brackets in an array-like usage on strings is possible and demands less processing effort than equivalent methods, too bad there isnt a length variable or a last char index


问:
Strategy Pattern the right thing?
i hope you can help me with my problem:

I have a Class doing soap calls. But if the soap definition changes i'll have to write a new class or inherit from it etc.
So I came to the solution to write something like that:

```<code>switch(version)
{
  case "1.0":
     saopV1.getData()
  case "2.0":
     soapV2.getData()
}
</code>```

Well pretty bad code, i know. Then I read about the Strategy pattern and i thought, wow that's what i need to get rid of this bad switch-case thing:

```<code>abstract SoapVersion
{
    public SoapVersion GetSoapVersion(string version)
    {
         //Damn switch-case thing
         //with return new SoapV1() and return new SoapV2()
    }
    public string[] virtual getData()
    {
          //Basic Implementation
    }
}

class SoapV1:SoapVersion
{
       public override string[] getData()
       {
           //Detail Implementation
       }
}

class SoapV2:SoapVersion
{//the same like soapv1}
</code>```

But i can't avoid using "ifs" or switch cases in my code. Is this possible using OO-techniques??

Edit:
The GetSoapVersion-Function should be static

答: It is a difference if you have your switch-cases only in factories, or all over your code. You have your decision (what implementation to choose) on a single point.</p>

ContentLicense: CC BY-SA 2.5

Title: Strategy Pattern the right thing?

Body:
i hope you can help me with my problem:

I have a Class doing soap calls. But if the soap definition changes i'll have to write a new class or inherit from it etc.
So I came to the solution to write something like that:

switch(version)
{
  case "1.0":
     saopV1.getData()
  case "2.0":
     soapV2.getData()
}

Well pretty bad code, i know. Then I read about the Strategy pattern and i thought, wow that's what i need to get rid of this bad switch-case thing:

abstract SoapVersion
{
    public SoapVersion GetSoapVersion(string version)
    {
         //Damn switch-case thing
         //with return new SoapV1() and return new SoapV2()
    }
    public string[] virtual getData()
    {
          //Basic Implementation
    }
}

class SoapV1:SoapVersion
{
       public override string[] getData()
       {
           //Detail Implementation
       }
}

class SoapV2:SoapVersion
{//the same like soapv1}

But i can't avoid using "ifs" or switch cases in my code. Is this possible using OO-techniques??

Edit:
The GetSoapVersion-Function should be static


问:
Why is this c code not changing the value of arr[3]?
I am creating an int array and then tricking c into believing that it's an array of short values. I know it's not good practice but I am just trying to understand why this isn't working. Shouldn't this change the value of arr[3] ?

```<code>#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    int arr[5];
    arr[0] = 0; arr[1] = 0; arr[2] = 0; arr[4] = 0;
    arr[3] = 128;
    ((short*)arr)[6] = 128; // Shouldn't this change arr[3] ? as 6,7 indices in the arr of short would compromise of arr[3] in arr of ints?
    int i = 0;
    for (i = 0; i < 5; i++){
        printf("%d\n", arr[i]);
    }
    return 0;
}
</code>```

PS: Here's a deeper clarification:
When I cast int array to a short array, it seemingly becomes an array of 10 short elements (not 5). So when I change arr[6], I am changing only the first 16 bits of the int arr[3]. So arr[3] should still change and it is NOT that I am changing it to 128 again and not seeing the change.

FOR CLARIFICATION: THIS CODE IS ONLY FOR EXPERIMENTAL REASONS! I AM JUST LEARNING HOW POINTERS WORK AND I GET THAT ITS NOT GOOD PRACTICE.

答:
Your code has undefined behavior, because you are writing a datum with a declared type through a pointer to a different type, and the different type is not char.

```<code>int arr[5];
/* ... */
((short*)arr)[6] = /* ANYTHING */;
</code>```

The compiler is entitled to generate machine code that doesn't include the write to ((short*)arr)[6] at all, and this is quite likely with modern compilers.  It's also entitled to delete the entire body of main on the theory that all possible executions of the program provoke undefined behavior, therefore the program will never actually be run.

(Some people say that when you write a program with undefined behavior, the C compiler is entitled to make demons fly out of your nose, but as a retired compiler developer I can assure you that most C compilers can't actually do that.)

Body:
I am creating an int array and then tricking c into believing that it's an array of short values. I know it's not good practice but I am just trying to understand why this isn't working. Shouldn't this change the value of arr[3] ?

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    int arr[5];
    arr[0] = 0; arr[1] = 0; arr[2] = 0; arr[4] = 0;
    arr[3] = 128;
    ((short*)arr)[6] = 128; // Shouldn't this change arr[3] ? as 6,7 indices in the arr of short would compromise of arr[3] in arr of ints?
    int i = 0;
    for (i = 0; i < 5; i++){
        printf("%d\n", arr[i]);
    }
    return 0;
}

PS: Here's a deeper clarification:
When I cast int array to a short array, it seemingly becomes an array of 10 short elements (not 5). So when I change arr[6], I am changing only the first 16 bits of the int arr[3]. So arr[3] should still change and it is NOT that I am changing it to 128 again and not seeing the change.

FOR CLARIFICATION: THIS CODE IS ONLY FOR EXPERIMENTAL REASONS! I AM JUST LEARNING HOW POINTERS WORK AND I GET THAT ITS NOT GOOD PRACTICE.

Body:
Your code has undefined behavior, because you are writing a datum with a declared type through a pointer to a different type, and the different type is not char.

int arr[5];
/* ... */
((short*)arr)[6] = /* ANYTHING */;

The compiler is entitled to generate machine code that doesn't include the write to ((short*)arr)[6] at all, and this is quite likely with modern compilers.  It's also entitled to delete the entire body of main on the theory that all possible executions of the program provoke undefined behavior, therefore the program will never actually be run.

(Some people say that when you write a program with undefined behavior, the C compiler is entitled to make demons fly out of your nose, but as a retired compiler developer I can assure you that most C compilers can't actually do that.)


问:
Storing references to values, in arrays, then reassigning the original variable (JavaScript)
This is what I want to do:

I have an object that stores a state and also an array of the previous states.

var object = { currentState: [Object], previousStates: [[Object], [Object]] };

When the state changes I want to store the reference to currrentState's object in the previous states array so that it can be reused, then create a new state (or reuse an old state) and store it in currentState WITHOUT changing the original object passed to the array. If it makes any difference at all, the states are instantiated class objects.

Is this possible?

I have looked at lots of resources on passing by reference and passing by value but I think I need it explained in the context of an example. Which example will store a new state at currentState without changing the previous value pushed to the array if either?

```<code>function changeState1(states) {
    states.previousStates.push(states.currentState);
    states.currentState = new State();
}

function changeState2(states) {
    var newState = new State();
    states.previousStates.push(states.currentState);
    states.currentState = newState;
}
</code>```

EDIT:

I should probably mention that my intention is to create efficient code. I don't want to recreate states from classes on the fly if I can reuse old instances. It's better for memory usage and reduces garbage collection.

答:
Maybe something like this?

var obj = newObjectState;
object.previousStates.push(object.currentState);
object.currentState = obj;

Of course this is all a kind of pseudocode but could be the answer you are looking for?

Body:
This is what I want to do:

I have an object that stores a state and also an array of the previous states.

var object = { currentState: [Object], previousStates: [[Object], [Object]] };

When the state changes I want to store the reference to currrentState's object in the previous states array so that it can be reused, then create a new state (or reuse an old state) and store it in currentState WITHOUT changing the original object passed to the array. If it makes any difference at all, the states are instantiated class objects.

Is this possible?

I have looked at lots of resources on passing by reference and passing by value but I think I need it explained in the context of an example. Which example will store a new state at currentState without changing the previous value pushed to the array if either?

function changeState1(states) {
    states.previousStates.push(states.currentState);
    states.currentState = new State();
}

function changeState2(states) {
    var newState = new State();
    states.previousStates.push(states.currentState);
    states.currentState = newState;
}

EDIT:

I should probably mention that my intention is to create efficient code. I don't want to recreate states from classes on the fly if I can reuse old instances. It's better for memory usage and reduces garbage collection.


问:
Should I add the async modifier if I return a Task in an expensive method?
The C# compiler already warns us if we have a method that has the async modifier but does not use the await operator.

According to this answer there's no point adding an await to the end of an async method (and in that case, just remove the async modifier).

But what if the method has an expensive synchronous operation it needs to perform before calling a subsequent true async method?

For example, if I'm using HttpClient:

```<code>private readonly HttpClient client = ...

public Task<HttpResponseMessage> CallMyWebServiceMethod() {

    HttpRequestMessage request = this.SomeExpensiveButSynchronousMethod();

    return this.client.SendAsync( request );
}
</code>```

This code would block the caller (due to SomeExpensiveButSynchronousMethod).

However, if I change the code to this:

```<code>public async Task<HttpResponseMessage> CallMyWebServiceMethod() {

    HttpRequestMessage request = this.SomeExpensiveButSynchronousMethod();

    return await this.client.SendAsync( request );
}
</code>```

and I call it like so:

```<code>HttpResponse response = await myWrapper.CallMyWebServiceMethod();
</code>```

...I understand the TPL would spin up a background thread immediately and then run CallMyWebServiceMethod in the background thread, resuming whatever the parent code wants, making the entire call non-blocking in the process, before resuming after the Task completes and returns the HttpResponse.

...if that's the case then it seems contradictory.

If I'm wrong, and the call is blocking until it gets to SendAsync then how can I execute SomeExpensiveButSynchronousMethod on the same background thread as the HttpClient uses for its request?

答:
Your expensive method is going to block the caller either way. async doesn't magically create threads for you, that's what Task does (sometimes).  So, if you add async and await the SendAsync, you're just adding state-machine overhead needlessly.

see also http://blog.stephencleary.com/2016/12/eliding-async-await.html

Body:
The C# compiler already warns us if we have a method that has the async modifier but does not use the await operator.

According to this answer there's no point adding an await to the end of an async method (and in that case, just remove the async modifier).

But what if the method has an expensive synchronous operation it needs to perform before calling a subsequent true async method?

For example, if I'm using HttpClient:

private readonly HttpClient client = ...

public Task<HttpResponseMessage> CallMyWebServiceMethod() {

    HttpRequestMessage request = this.SomeExpensiveButSynchronousMethod();

    return this.client.SendAsync( request );
}

This code would block the caller (due to SomeExpensiveButSynchronousMethod).

However, if I change the code to this:

public async Task<HttpResponseMessage> CallMyWebServiceMethod() {

    HttpRequestMessage request = this.SomeExpensiveButSynchronousMethod();

    return await this.client.SendAsync( request );
}

and I call it like so:

HttpResponse response = await myWrapper.CallMyWebServiceMethod();

...I understand the TPL would spin up a background thread immediately and then run CallMyWebServiceMethod in the background thread, resuming whatever the parent code wants, making the entire call non-blocking in the process, before resuming after the Task completes and returns the HttpResponse.

...if that's the case then it seems contradictory.

If I'm wrong, and the call is blocking until it gets to SendAsync then how can I execute SomeExpensiveButSynchronousMethod on the same background thread as the HttpClient uses for its request?


问:
Nodejs -- req and res arguments of callback function in createServer()

I am confused about 'parser = this' mean, because I can't find there is calling about this function, so what 'this' mean in this native code?

This is the link of github: https://github.com/nodejs/node/blob/v0.12/lib/_http_common.js

答: It's so that parser has scope when the code is called asynchronously.


问:
Unit test controller, angularJS and jasmine
Hi I've been trying to unit test basic functions in my controller however I can't seem to connect when setting up the unit test.

Error: [$injector:modulerr] Failed to instantiate module myApp due to:
[$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Here is my controller:

```<code>    var myApp = angular.module("myApp", []);
myApp.controller('studentController', function($scope,$route,$routeParams,$http,$location){

//Get all students
    $scope.getStudents = function(){
        $http.get('/api/student/').then(function(response){
            $scope.students = response.data;
        });
    };
</code>```

and my test:

```<code>describe("studentController", function () {
    beforeEach(module('myApp'));

    var $controller;
    beforeEach(inject(function (_$controller_){
        $controller = _$controller_;
    }))

    describe("studentController", function(){
        it("should get student data", function (){
            var $scope = {};
            $scope.getStudents();
            expect($scope.students.length).toBe(15)
        })
    })

    });
</code>```

I have included both these files in the jasmine html file along with the angular-mocks.js

any help would be much appreciated

答:
You are injecting $route, but you are not loading the ngRoute module. Load the file angular-route.js and state the dependency:

```<code>var myApp = angular.module("myApp", ['ngRoute']);
</code>```

Body:
Hi I've been trying to unit test basic functions in my controller however I can't seem to connect when setting up the unit test.

Error: [$injector:modulerr] Failed to instantiate module myApp due to:
[$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Here is my controller:

    var myApp = angular.module("myApp", []);
myApp.controller('studentController', function($scope,$route,$routeParams,$http,$location){

//Get all students
    $scope.getStudents = function(){
        $http.get('/api/student/').then(function(response){
            $scope.students = response.data;
        });
    };

and my test:

describe("studentController", function () {
    beforeEach(module('myApp'));

    var $controller;
    beforeEach(inject(function (_$controller_){
        $controller = _$controller_;
    }))

    describe("studentController", function(){
        it("should get student data", function (){
            var $scope = {};
            $scope.getStudents();
            expect($scope.students.length).toBe(15)
        })
    })

    });

I have included both these files in the jasmine html file along with the angular-mocks.js

any help would be much appreciated

Body:
You are injecting $route, but you are not loading the ngRoute module. Load the file angular-route.js and state the dependency:

var myApp = angular.module("myApp", ['ngRoute']);


问:
What's the easiest way to run a .js javascript file on windows?
When you try and run (not edit) a Javascript file, It will give an error that sounds like it is missing a reference in your code.  For Example, I got:

```<code>Line: 3 Char: 1

Error: 'document' is undefined'

Code: 800A1391

Source: Microsoft JScript runtime error
</code>```

Is it trying to execute a program similar to VBScript?  Should I be running it with another program?

答:
Windows Script Host (WSH) is a Microsoft technology used to run script files in various languages: it connects a script file with a script engine to run it. It has been around since Windows 95 and it's documentation can be found on the web.

If you double click on a .js file, and if WSH has not been disabled, it results in Microsoft's "JScript" script engine being run to execute the script with JavaScript bindings for the execution environment which include access to the file system and shell. It does not provide a browser environment or HTML rendering, so document flags as undefined.

To run a browser script, run it in a browser. Systems scripts might be written to run under WSH but there is a newer "PowerShell" replacement under Windows. NW.js and Node.js provide alternative cross platform capabilities and features.

Note that the name "JScript" originated during browser wars of the last century. Let's not go there ;-)

Body:
When you try and run (not edit) a Javascript file, It will give an error that sounds like it is missing a reference in your code.  For Example, I got:

Line: 3 Char: 1

Error: 'document' is undefined'

Code: 800A1391

Source: Microsoft JScript runtime error

Is it trying to execute a program similar to VBScript?  Should I be running it with another program?


答:
I understand the TPL would spin up a background thread immediately and then run CallMyWebServiceMethod

No, that's not what happens. The first synchronous part of an async method executes synchronously. If you want make sure it does not block the current thread, you should use Task.Run().

Title: Should I add the async modifier if I return a Task in an expensive method?


问:
Loading a file as string with React Native packager
Is it possible with React Native Packager to load a text file as a string? As the same as Webpack's Raw Loader.

Example:

```<code>const someString = require('./something.txt');
console.log(someString);
</code>```

What is the closest way to achieve this?

答:
See How to load local text file into string variable in ReactNative Project?

While you can't require a text file with React Native, you can require a JSON file. If it's possible to switch to JSON, you'll be set.

Body:
Is it possible with React Native Packager to load a text file as a string? As the same as Webpack's Raw Loader.

Example:

const someString = require('./something.txt');
console.log(someString);

What is the closest way to achieve this?


问:
How to access object inside parse method?
I can't figure out how to access an object inside parse function.
I want to create an object Check which needs Product object to be created. products attribute is a list of objects which are sources of urls.

```<code>class GenericScraper(scrapy.Spider):
    name = 'will_be_overriden'
    custom_settings = {'CONCURRENT_REQUESTS': 32,
                       'DOWNLOAD_DELAY':0.5}
    def __init__(self, occs):
        super(GenericScraper,self).__init__()
        self.name = products[0].site.name
        self.products = products
        self.xpath = self.product[0].site.xpaths.first().xpath

    def start_requests(self):
        for product in self.products:
            yield scrapy.Request(url=product.url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        text = hxs.select(self.xpath+'/text()').extract()
        Check.objects.create(text=text,product=product) # CAN'T ACCESS CURRENT PRODUCT

        responselog.debug(response)
</code>```

Is it possible?

答:
use the Request meta attribute to communicate between callbacks. I assume you want to associate a product object to each request you make, so something like:

```<code>def start_requests(self):
    for product in self.products:
        yield scrapy.Request(
            url=product.url,
            callback=self.parse,
            meta={'product': product},
        )

def parse(self, response):
    current_product = response.meta['product']
    ...
</code>```

Body:
I can't figure out how to access an object inside parse function.
I want to create an object Check which needs Product object to be created. products attribute is a list of objects which are sources of urls.

class GenericScraper(scrapy.Spider):
    name = 'will_be_overriden'
    custom_settings = {'CONCURRENT_REQUESTS': 32,
                       'DOWNLOAD_DELAY':0.5}
    def __init__(self, occs):
        super(GenericScraper,self).__init__()
        self.name = products[0].site.name
        self.products = products
        self.xpath = self.product[0].site.xpaths.first().xpath

    def start_requests(self):
        for product in self.products:
            yield scrapy.Request(url=product.url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        text = hxs.select(self.xpath+'/text()').extract()
        Check.objects.create(text=text,product=product) # CAN'T ACCESS CURRENT PRODUCT

        responselog.debug(response)

Is it possible?

Body:
use the Request meta attribute to communicate between callbacks. I assume you want to associate a product object to each request you make, so something like:

def start_requests(self):
    for product in self.products:
        yield scrapy.Request(
            url=product.url,
            callback=self.parse,
            meta={'product': product},
        )

def parse(self, response):
    current_product = response.meta['product']
    ...


问:
How to add default constructor in SQLiteOpenHelper?
My app works fine but when I try to generate signed APK I get this error in my messages.

```<code>Error:Error: This class should provide a default constructor (a public constructor with no arguments) (com.example.emilythacker.myapplication.MyDBHandler) [Instantiatable]
</code>```

When I add the empty constructor

```<code> public MyDBHandler(){}
</code>```

to my code I get this error instead

```<code>    Error:(18, 25) error: no suitable constructor found for SQLiteOpenHelper(no arguments)
constructor SQLiteOpenHelper.SQLiteOpenHelper(Context,String,CursorFactory,int) is not applicable
(actual and formal argument lists differ in length)
constructor SQLiteOpenHelper.SQLiteOpenHelper(Context,String,CursorFactory,int,DatabaseErrorHandler) is not applicable
(actual and formal argument lists differ in length)
</code>```

Here is my MyDBHelper.class

```<code>public class MyDBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 4;
private static final String DATABASE_NAME = "products.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";

public MyDBHandler(){

}

public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_PRODUCTNAME + " TEXT " +
            ");";
    db.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
    onCreate(db);
}

//add a new row to the database
public void addProduct(Products product){

    SQLiteDatabase db = this.getReadableDatabase();
    if(DatabaseUtils.queryNumEntries(db, TABLE_PRODUCTS) <= 4){
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.get_productname());
        db.insert(TABLE_PRODUCTS, null, values);
        db.close();
    }
    else{
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.get_productname());
        db.insert(TABLE_PRODUCTS, null, values);
        deleteProduct();
        db.close();
    }
}

//code coming from MainActivity
public void addButtonClicked(String highscore1){
    Products product = new Products(highscore1);
    addProduct(product);
    updateDatabase();
}

//code coming from MainActivity
public void updateDatabase(){
        String dbString = databaseToString();
        MainActivity.productText.setText(dbString);
}

//delete a product from the database
public void deleteProduct(){
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DELETE FROM products WHERE _id NOT IN"+
                //only reading first digit of double digit numbers
               //" (SELECT _id FROM products ORDER BY  productname DESC LIMIT 5)");
            //this runs but isnt putting double digit scores into the high score textView
            " (SELECT _id FROM products ORDER BY CAST(productname AS NUMBER) DESC LIMIT 5)");

}

//print out the database as a string
public String databaseToString(){
    String dbString = "";
    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";

    //Cursor point to location in your results
    Cursor c = db.query(TABLE_PRODUCTS, null, null, null, null, null, COLUMN_PRODUCTNAME +" DESC");
    //Move to the first row in your results
    c.moveToFirst();

    while(!c.isAfterLast()){
        if(c.getString(c.getColumnIndex("productname")) != null){
            dbString += c.getString(c.getColumnIndex("productname"));
            dbString += "\n";
        }
        c.moveToNext();

    }

    db.close();
    return dbString;

}
</code>```

How can I fix this?

答: This is an Android Lint error that only gets checked on release builds.  If you have MyDBHandler declared in your Android Manifest you need to delete it as it is not an activity and does not need to be declared.</p>

Body:
My app works fine but when I try to generate signed APK I get this error in my messages.

Error:Error: This class should provide a default constructor (a public constructor with no arguments) (com.example.emilythacker.myapplication.MyDBHandler) [Instantiatable]

When I add the empty constructor

 public MyDBHandler(){}

to my code I get this error instead

    Error:(18, 25) error: no suitable constructor found for SQLiteOpenHelper(no arguments)
constructor SQLiteOpenHelper.SQLiteOpenHelper(Context,String,CursorFactory,int) is not applicable
(actual and formal argument lists differ in length)
constructor SQLiteOpenHelper.SQLiteOpenHelper(Context,String,CursorFactory,int,DatabaseErrorHandler) is not applicable
(actual and formal argument lists differ in length)

Here is my MyDBHelper.class

public class MyDBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 4;
private static final String DATABASE_NAME = "products.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";

public MyDBHandler(){

}

public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_PRODUCTNAME + " TEXT " +
            ");";
    db.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
    onCreate(db);
}

//add a new row to the database
public void addProduct(Products product){

    SQLiteDatabase db = this.getReadableDatabase();
    if(DatabaseUtils.queryNumEntries(db, TABLE_PRODUCTS) <= 4){
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.get_productname());
        db.insert(TABLE_PRODUCTS, null, values);
        db.close();
    }
    else{
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.get_productname());
        db.insert(TABLE_PRODUCTS, null, values);
        deleteProduct();
        db.close();
    }
}

//code coming from MainActivity
public void addButtonClicked(String highscore1){
    Products product = new Products(highscore1);
    addProduct(product);
    updateDatabase();
}

//code coming from MainActivity
public void updateDatabase(){
        String dbString = databaseToString();
        MainActivity.productText.setText(dbString);
}

//delete a product from the database
public void deleteProduct(){
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DELETE FROM products WHERE _id NOT IN"+
                //only reading first digit of double digit numbers
               //" (SELECT _id FROM products ORDER BY  productname DESC LIMIT 5)");
            //this runs but isnt putting double digit scores into the high score textView
            " (SELECT _id FROM products ORDER BY CAST(productname AS NUMBER) DESC LIMIT 5)");

}

//print out the database as a string
public String databaseToString(){
    String dbString = "";
    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";

    //Cursor point to location in your results
    Cursor c = db.query(TABLE_PRODUCTS, null, null, null, null, null, COLUMN_PRODUCTNAME +" DESC");
    //Move to the first row in your results
    c.moveToFirst();

    while(!c.isAfterLast()){
        if(c.getString(c.getColumnIndex("productname")) != null){
            dbString += c.getString(c.getColumnIndex("productname"));
            dbString += "\n";
        }
        c.moveToNext();

    }

    db.close();
    return dbString;

}

How can I fix this?


问:
Testing UWP Bluetooth Application
I am trying to develop some tests for a Windows 10 UWP application which uses Windows.Devices.Bluetooth.BluetoothLEDevice. I have a plain class that is part of my application which has a private BluetoothLEDevice type field.

```<code>class MyDevice
{
    private Windows.Devices.Bluetooth.BluetoothLEDevice BluetoothLEDevice;

    public string SomeProperty { get; set; }

    public MyDevice(Windows.Devices.Bluetooth.BluetoothLEDevice bluetoothLEDevice)
    {
        BluetoothLEDevice = bluetoothLEDevice;

        var characteristic = BluetoothLEDevice.GetGattService(...)
            .GetCharacteristics(...)
            .First();

        characteristic.ValueChanged += OnValueChanged;
    }

    // TODO: Write tests for this method
    private OnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
    {
        string message = Encoding.ASCII.GetString(args.CharacteristicValue.ToArray());

        // Parse `message`

        SomeProperty = parsed;
    }

    ...
}
</code>```

The methods of said class use the events and methods of bluetoothLEDevice, some are private and others are public. How can I test the public methods of MyDevice?

I have tried something like this which I think could work, but I can see that it will take hundreds of lines of code and quite a few extra classes because I would need to implement a lot of stuff in FakeBluetoothLEDevice in orde for it to work properly.

I changed MyDevice to accept a wrapper instead and then create two implementations of the wrapper. One for testing, and the other for real use.

```<code>class MyDevice
{
    private MyApp.IBluetoothLEDeviceWrapper bluetoothLEDevice;
}
</code>```

Then in my test I use the fake.

```<code>private void ValueChangedEventDataParsingTest()
{
    var device = new FakeBluetoothLEDevice();

    var myDevice = new MyDevice(device);

    device.InvokeValueChanged("this is the value for a fake ValueChangedEvent");

    Assert.Equals(probe.SomeProperty, "expected");
}
</code>```

Are there any frameworks (available for UWP) that would help me achieve what I want? Or even a better approach that would save me some pain?

答:
In stead of focusing on implementation concerns focus on what functionality you want your abstraction to expose. Using your simplified example I was able to replicate it with some refactors to only interact with the desired functionality.

```<code>[TestClass]
public class DeviceTests {
    [TestMethod]
    public void _ValueChangedEventDataParsingTest() {
        //Arrange
        var message = "message";
        var expected = "expected";
        var device = new FakeBluetoothLEDevice(message, expected);
        var sut = new MyDevice(device);

        //Act
        device.InvokeValueChanged(message);

        //Assert
        Assert.AreEqual(expected, sut.SomeProperty);
    }

    public interface IBlueToothService {
        Action<string> ValueChangedHandler { get; set; }
    }

    public class FakeBluetoothLEDevice : IBlueToothService {
        private string message;
        private string parsed;

        public FakeBluetoothLEDevice(string message, string expected) {
            this.message = message;
            this.parsed = expected;
        }
        public Action<string> ValueChangedHandler { get; set; }

        public void InvokeValueChanged(string p) {
            var handler = ValueChangedHandler ?? delegate { };
            if (p == message) {
                ValueChangedHandler(parsed);
            }
        }
    }

    public class MyDevice {
        private IBlueToothService device;

        public string SomeProperty { get; set; }

        public MyDevice(IBlueToothService device) {
            this.device = device;
            device.ValueChangedHandler = handler;
        }

        private void handler(string parsedValue) {
            SomeProperty = parsedValue;
        }
    }
}
</code>```

Use separation of concerns and move the heavy lifting of implementation concerns behind the actual implementations. It vastly simplifies the consumers of such functionality.

If the concern is to test he parsing functionality then abstract the out into its own concern as well. Don't have classes doing more than they need to (SRP)

```<code>private OnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) {
    string message = Encoding.ASCII.GetString(args.CharacteristicValue.ToArray());

    // Parse `message`
    var parsed = parsingServce.Parse(message);

    SomeProperty = parsed;
}
</code>```

That way the parsing service implementation will only need to be tested for ts core functionality.

But from an abstraction perspective the parser is not needed as a dependency when testing higher level functionality.

I advise reviewing the current design and refactoring it to be more SOLID.

Title: Testing UWP Bluetooth Application

Body:
I am trying to develop some tests for a Windows 10 UWP application which uses Windows.Devices.Bluetooth.BluetoothLEDevice. I have a plain class that is part of my application which has a private BluetoothLEDevice type field.

class MyDevice
{
    private Windows.Devices.Bluetooth.BluetoothLEDevice BluetoothLEDevice;

    public string SomeProperty { get; set; }

    public MyDevice(Windows.Devices.Bluetooth.BluetoothLEDevice bluetoothLEDevice)
    {
        BluetoothLEDevice = bluetoothLEDevice;

        var characteristic = BluetoothLEDevice.GetGattService(...)
            .GetCharacteristics(...)
            .First();

        characteristic.ValueChanged += OnValueChanged;
    }

    // TODO: Write tests for this method
    private OnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
    {
        string message = Encoding.ASCII.GetString(args.CharacteristicValue.ToArray());

        // Parse `message`

        SomeProperty = parsed;
    }

    ...
}

The methods of said class use the events and methods of bluetoothLEDevice, some are private and others are public. How can I test the public methods of MyDevice?

I have tried something like this which I think could work, but I can see that it will take hundreds of lines of code and quite a few extra classes because I would need to implement a lot of stuff in FakeBluetoothLEDevice in orde for it to work properly.

I changed MyDevice to accept a wrapper instead and then create two implementations of the wrapper. One for testing, and the other for real use.

class MyDevice
{
    private MyApp.IBluetoothLEDeviceWrapper bluetoothLEDevice;
}

Then in my test I use the fake.

private void ValueChangedEventDataParsingTest()
{
    var device = new FakeBluetoothLEDevice();

    var myDevice = new MyDevice(device);

    device.InvokeValueChanged("this is the value for a fake ValueChangedEvent");

    Assert.Equals(probe.SomeProperty, "expected");
}

Are there any frameworks (available for UWP) that would help me achieve what I want? Or even a better approach that would save me some pain?

Body:
In stead of focusing on implementation concerns focus on what functionality you want your abstraction to expose. Using your simplified example I was able to replicate it with some refactors to only interact with the desired functionality.

[TestClass]
public class DeviceTests {
    [TestMethod]
    public void _ValueChangedEventDataParsingTest() {
        //Arrange
        var message = "message";
        var expected = "expected";
        var device = new FakeBluetoothLEDevice(message, expected);
        var sut = new MyDevice(device);

        //Act
        device.InvokeValueChanged(message);

        //Assert
        Assert.AreEqual(expected, sut.SomeProperty);
    }

    public interface IBlueToothService {
        Action<string> ValueChangedHandler { get; set; }
    }

    public class FakeBluetoothLEDevice : IBlueToothService {
        private string message;
        private string parsed;

        public FakeBluetoothLEDevice(string message, string expected) {
            this.message = message;
            this.parsed = expected;
        }
        public Action<string> ValueChangedHandler { get; set; }

        public void InvokeValueChanged(string p) {
            var handler = ValueChangedHandler ?? delegate { };
            if (p == message) {
                ValueChangedHandler(parsed);
            }
        }
    }

    public class MyDevice {
        private IBlueToothService device;

        public string SomeProperty { get; set; }

        public MyDevice(IBlueToothService device) {
            this.device = device;
            device.ValueChangedHandler = handler;
        }

        private void handler(string parsedValue) {
            SomeProperty = parsedValue;
        }
    }
}

Use separation of concerns and move the heavy lifting of implementation concerns behind the actual implementations. It vastly simplifies the consumers of such functionality.

If the concern is to test he parsing functionality then abstract the out into its own concern as well. Don't have classes doing more than they need to (SRP)

private OnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) {
    string message = Encoding.ASCII.GetString(args.CharacteristicValue.ToArray());

    // Parse `message`
    var parsed = parsingServce.Parse(message);

    SomeProperty = parsed;
}

That way the parsing service implementation will only need to be tested for ts core functionality.

But from an abstraction perspective the parser is not needed as a dependency when testing higher level functionality.

I advise reviewing the current design and refactoring it to be more SOLID.


问:
Good tool to visualise database schema?
Are there any good tools for visualising a pre-existing database schema? I'm using MySQL if it matters.

I'm currently using MySQL Workbench to process an SQL create script dump, but it's clunky, slow and a manual process to drag all the tables about (which would be okay if it wasn't so slow).

答: I usually use SchemaSpy to do this, but recently I found a really simple article on sqlfairy that just uses the dump file to create the structure graph</p>

OwnerDisplayName: Mat

Title: Good tool to visualise database schema?


问:
Change FAB (Floating Action Button) srcCompat using java
I an using a Floating Action Button with a set icon using XML

```<code>app:srcCompat="@mipmap/my_image"
</code>```

I want to use java so that if a certain condition is true, the FAB's icon can change to something like my_image2

I have declared my FAB in my java class, but how do I change the icon? Thanks.

答:
Per the FloatingActionButton documentation:

As this class descends from ImageView, you can control the icon which is displayed via setImageDrawable(Drawable).

You can, of course, use any of the setImage variants, such as setImageResource if you have a resource id.

Body:
I an using a Floating Action Button with a set icon using XML

app:srcCompat="@mipmap/my_image"

I want to use java so that if a certain condition is true, the FAB's icon can change to something like my_image2

I have declared my FAB in my java class, but how do I change the icon? Thanks.


问:
Static javascript tag with dynamically constructed URL
I have a static script declaration as a requirement, is it possible to have its URL dynamically constructed once browser wants to download it?

```<code><script async src='https://my-known-host.com/script.js?param1=<dynamicValue>'
</script>
</code>```

This parameter is generated on the client and let's say I want it to be just a random number.

I want to generate random on client side because server caches pages and this request should have a unique random number every time paged is loaded (even from cache)

I need to have it statically declared in order to start the download right away (even before browser parsed to the line of declaration)

Is it possible?

答:
Yeah, a common approach is to write a script that injects the script tag. Something like this:

```<code><script type="text/javascript">

setTimeout(function(){
  var a = document.createElement("script");
  var b = document.getElementsByTagName("script")[0];

  // this adds some number, for example
  // you can tweak it to be a random number if you want
  a.src = document.location.protocol +
  "my-known-host.com/script.js?param1=" +
  Math.floor(new Date().getTime()/3600000);

  a.async = true;
  a.type = "text/javascript";
  b.parentNode.insertBefore(a,b)
}, 1);

</script>
</code>```

I actually took this example script from an analytics provider (crazyegg.com), but Google Analytics does a similar approach. In other words, it's a common thing.

Body:
I have a static script declaration as a requirement, is it possible to have its URL dynamically constructed once browser wants to download it?

This parameter is generated on the client and let's say I want it to be just a random number.

I want to generate random on client side because server caches pages and this request should have a unique random number every time paged is loaded (even from cache)

I need to have it statically declared in order to start the download right away (even before browser parsed to the line of declaration)

Is it possible?

Body:
Yeah, a common approach is to write a script that injects the script tag. Something like this:

<script type="text/javascript">

setTimeout(function(){
  var a = document.createElement("script");
  var b = document.getElementsByTagName("script")[0];

  // this adds some number, for example
  // you can tweak it to be a random number if you want
  a.src = document.location.protocol +
  "my-known-host.com/script.js?param1=" +
  Math.floor(new Date().getTime()/3600000);

  a.async = true;
  a.type = "text/javascript";
  b.parentNode.insertBefore(a,b)
}, 1);

</script>

I actually took this example script from an analytics provider (crazyegg.com), but Google Analytics does a similar approach. In other words, it's a common thing.


问:
Cant get required output from loop
I am trying to get a certain output pattern from the array but can't seem to get what I'm looking for and now sure why. Link is the desired output. Sorry if formatting is not good. Array size is inputted by the user.

```<code>public class A3_Q2 {

    int [][] pattern2 = new int[arraySize][arraySize];

    number = 1;
    int i;
    int j;
    int newNumber = arraySize-1;

    for (i = 0; i < arraySize; i++)

    {

        if (i == 0)
        {

            for (j = 0; j < arraySize; j++)
            {
                pattern2[i][j] = number;
                System.out.printf("%3d", pattern2[i][j]);
                number++;
            }

        }

        else
        {
            for(j = 0; j < i; j++)
            {
                pattern2[i][j] = number + newNumber;
                System.out.printf("%3d", pattern2[i][j]);
                newNumber++;
            }
            newNumber = arraySize-1;
            while(j < arraySize)
            {
                pattern2[i][j] = number;
                System.out.printf("%3d", pattern2[i][j]);
                number++;
                j++;
            }

        }
        System.out.println("");
   }
</code>```

Desired Output:

  1  2  3  4  5
 10  6  7  8  9
 14 15 11 12 13
 18 19 20 16 17
 22 23 24 25 21
```

This image shows the out-of-sequence cells highlighted:

答:
There is no need to separately handle specific rows. Value should be calculated with formula that can be applied universally using modulo operator.

This should do the trick:

```<code>for (i = 0; i < arraySize; i++) {
    for (j = 0; j < arraySize; j++) {
        int value = i * arraySize + (j - i + arraySize + 1) % arraySize;
        if (value % arraySize == 0) {
            value += arraySize;
        }
        pattern2[i][j] = value;
        System.out.printf("%3d", pattern2[i][j]);
    }
    System.out.println("");
}
</code>```

Title: Cant get required output from loop

Body:
I am trying to get a certain output pattern from the array but can't seem to get what I'm looking for and now sure why. Link is the desired output. Sorry if formatting is not good. Array size is inputted by the user.

public class A3_Q2 {

    int [][] pattern2 = new int[arraySize][arraySize];

    number = 1;
    int i;
    int j;
    int newNumber = arraySize-1;

    for (i = 0; i < arraySize; i++)

    {

        if (i == 0)
        {

            for (j = 0; j < arraySize; j++)
            {
                pattern2[i][j] = number;
                System.out.printf("%3d", pattern2[i][j]);
                number++;
            }

        }

        else
        {
            for(j = 0; j < i; j++)
            {
                pattern2[i][j] = number + newNumber;
                System.out.printf("%3d", pattern2[i][j]);
                newNumber++;
            }
            newNumber = arraySize-1;
            while(j < arraySize)
            {
                pattern2[i][j] = number;
                System.out.printf("%3d", pattern2[i][j]);
                number++;
                j++;
            }

        }
        System.out.println("");
   }

Desired Output:

  1  2  3  4  5
 10  6  7  8  9
 14 15 11 12 13
 18 19 20 16 17
 22 23 24 25 21

This image shows the out-of-sequence cells highlighted:

Body:
There is no need to separately handle specific rows. Value should be calculated with formula that can be applied universally using modulo operator.

This should do the trick:

for (i = 0; i < arraySize; i++) {
    for (j = 0; j < arraySize; j++) {
        int value = i * arraySize + (j - i + arraySize + 1) % arraySize;
        if (value % arraySize == 0) {
            value += arraySize;
        }
        pattern2[i][j] = value;
        System.out.printf("%3d", pattern2[i][j]);
    }
    System.out.println("");
}


问:
Set kendo DataSource without calling read()
Is it possible to set the DataSource of a Kendo ListView without having the DataSource then call the read() method?

I have a main DataSource that I am using on a ListView and all of the child ListViews but am just filtering it for each ListView depending on a few conditions. The way that I'm doing this is once all of the data has been bound to the main ListView then I create all of the child ListViews and assign the same datasource with filtering.

The issue I'm having here is once I assign the filtered DataSource to the new ListView it seems to be calling the read method again.

```<code>baSurveyGroupTemplateDataSource: new kendo.data.DataSource({
    transport: {
        read: {
            async: false,
            url: "/Url/to/data"
            dataType: "json",
            type: "GET",
            data: {
                id: $("#TemplateId").val()
            },
        }
    }
}),
groupDataBound: function (e) {
    $(".childBaSuveyGroupTemplate").each(function () {
        viewModel.seedGroup(this);
    });
},
seedGroup: function (parentGroup) {
    var childrenGroupList = $(parentGroup);
    var parentGroupId = childrenGroupList.data("id");
    var childrenGroupDataSource = new kendo.data.DataSource(viewModel.baSurveyGroupTemplateDataSource);
    childrenGroupDataSource.query({
        filter: ({ field: "BaSurveyGroupTemplateParentId", operator: "eq", value: parentGroupId })
    });
    childrenGroupList.kendoListView({
        template: kendo.template($("#baSurveyGroupTemplateDisplayTemplate").html()),
        dataSource: childrenGroupDataSource
    });
}
</code>```

Let me know if I need to clarify anything. It's hard to try and put what I'm doing and the problem I'm having into words.

答:
Try adding this to your ListView configuration:

```<code>autoBind: false
</code>```

From the kendo documentation at http://docs.telerik.com/kendo-ui/api/javascript/ui/listview#configuration-autoBind

If set to false the widget will not bind to the data source during
  initialization. In this case data binding will occur when the change
  event of the data source is fired. By default the widget will bind to
  the data source specified in the configuration.

Setting autoBind to false is useful when multiple widgets are bound to
  the same data source. Disabling automatic binding ensures that the
  shared data source does not make more than one request to the remote
  service.

Then manually trigger the datasource read once you have everything set:

```<code>childrenGroupDataSource.read();  // "read()" will fire the "change" event of the dataSource and the widget will be bound
</code>```

Body:
Is it possible to set the DataSource of a Kendo ListView without having the DataSource then call the read() method?

I have a main DataSource that I am using on a ListView and all of the child ListViews but am just filtering it for each ListView depending on a few conditions. The way that I'm doing this is once all of the data has been bound to the main ListView then I create all of the child ListViews and assign the same datasource with filtering.

The issue I'm having here is once I assign the filtered DataSource to the new ListView it seems to be calling the read method again.

baSurveyGroupTemplateDataSource: new kendo.data.DataSource({
    transport: {
        read: {
            async: false,
            url: "/Url/to/data"
            dataType: "json",
            type: "GET",
            data: {
                id: $("#TemplateId").val()
            },
        }
    }
}),
groupDataBound: function (e) {
    $(".childBaSuveyGroupTemplate").each(function () {
        viewModel.seedGroup(this);
    });
},
seedGroup: function (parentGroup) {
    var childrenGroupList = $(parentGroup);
    var parentGroupId = childrenGroupList.data("id");
    var childrenGroupDataSource = new kendo.data.DataSource(viewModel.baSurveyGroupTemplateDataSource);
    childrenGroupDataSource.query({
        filter: ({ field: "BaSurveyGroupTemplateParentId", operator: "eq", value: parentGroupId })
    });
    childrenGroupList.kendoListView({
        template: kendo.template($("#baSurveyGroupTemplateDisplayTemplate").html()),
        dataSource: childrenGroupDataSource
    });
}

Let me know if I need to clarify anything. It's hard to try and put what I'm doing and the problem I'm having into words.

Body:
Try adding this to your ListView configuration:

autoBind: false

From the kendo documentation at http://docs.telerik.com/kendo-ui/api/javascript/ui/listview#configuration-autoBind

If set to false the widget will not bind to the data source during
  initialization. In this case data binding will occur when the change
  event of the data source is fired. By default the widget will bind to
  the data source specified in the configuration.

Setting autoBind to false is useful when multiple widgets are bound to
  the same data source. Disabling automatic binding ensures that the
  shared data source does not make more than one request to the remote
  service.

Then manually trigger the datasource read once you have everything set:

childrenGroupDataSource.read();  // "read()" will fire the "change" event of the dataSource and the widget will be bound


问:
Conflicting versions of Data.Map
I'm working with this module Algorithms.Geometry.LineSegmentIntersection.BentleyOttman using the function "intersections"  that returns something of type Intersections which in turn is an alias for Map (Point 2 r) (Associated p r). So, I try to manipulate that result with the corresponding functions of the Data.Map.Lazy module, but I get the following error:

Any ideas on how to fix it? Thanks!

答:
Tough to know for sure without more details, but I will assume you are using stack and the latest LTS snapshot (8.6 as of the time I'm writing this).

This could be happening because LTS 8.6 has containers-0.5.7.1, and you are attempting to use a function that is in a newer version (containers-0.5.10.1) which hasn't made its way from Hackage to Stackage yet.

To resolve this, modify your stack.yaml file to include:

```<code>extra-deps:
- containers-0.5.10.1
</code>```

Title: Conflicting versions of Data.Map

Body:
Tough to know for sure without more details, but I will assume you are using stack and the latest LTS snapshot (8.6 as of the time I'm writing this).

This could be happening because LTS 8.6 has containers-0.5.7.1, and you are attempting to use a function that is in a newer version (containers-0.5.10.1) which hasn't made its way from Hackage to Stackage yet.

To resolve this, modify your stack.yaml file to include:

extra-deps:
- containers-0.5.10.1


问:
Handling multiple Select options with one submit button
I use mysql for inserting data into dropdown menu. I got multiple dropdown menus - each dropdown menu has name id - this information i get from database($stmt). The content of each dropdown menu I get by another mysql query $stmt2.
I need to determine which id was set in every dropdown menu. These values I need to use later. This is my solution, which doesn't work. It won't print out anything.

```<code>echo "<table class ='centered_div' border='1px solid black'>";
echo "<tr><td>ID</td><td>food</td><td>g</td></tr>";
while($rows = $stmt->fetch()){

    echo "<tr><td>" . $rows['id'] . "</td><td>".$rows['food'];
    echo "<form action='upravit_plan.php' method='post'><select name =".$rows['id']." > ";
    $stmt2 = $db->query($q2);
    echo "<option value ='nothing'> choose one </option>";
    while($rows2 = $stmt2->fetch())
    {
        echo '<option value = '.$rows2['id'].'>'.$rows2['food'].'</option>';
    }
    echo "</select></form>";
    echo "</td> <td>" . $rows['g'] . "g</td></tr><br> ";

};
echo "<tr><td colspan='3'><form action='upravit_plan.php' method='post'><input name = 'go' type='submit' value='OK'/></form></td></tr>";
echo "</table>";

if(isset($_POST['go']))
{
    $stmt = $db->query($q);
    while ($rows = $stmt->fetch())
    {

     echo $_POST[$rows['id']];  // trying to print values

    }
}
</code>```

答:
You need to have all elements in a single form. You should also try to separate your PHP from your HTML, this might be a good start but still needs things like HTML escaping. Note in particular the use of alternative syntax and short echo tags. </p>

```<code><form action='upravit_plan.php' method='post'>
<table class ='centered_div' border='1px solid black'>
  <tr>
    <th>ID</th>
    <th>food</th>
    <th>g</th>
  </tr>

<?php while($rows = $stmt->fetch()):?>
  <tr>
    <td><?=$rows['id']?></td>
    <td>
      <?=$rows['food']?>
      <select name="<?=$rows['id']?>">
        <option value ='nothing'> choose one </option>

<?php while($rows2 = $stmt2->fetch()):?>
        <option value="<?=$rows2['id']?>"><?=$rows2['food']?></option>

<?php endwhile;?>
      </select>
    </td>
    <td><?=$rows['g']?>g</td>
  </tr>

<?php endwhile;?>
  <tr>
    <td colspan='3'><input name='go' type='submit' value='OK'/></td>
  </tr>
</table>
</form>

<?php
if(isset($_POST['go']))
{
    $stmt = $db->query($q);
    while ($rows = $stmt->fetch())
    {

     echo $_POST[$rows['id']];  // trying to print values

    }
}
?>
</code>```

Body:
I use mysql for inserting data into dropdown menu. I got multiple dropdown menus - each dropdown menu has name id - this information i get from database($stmt). The content of each dropdown menu I get by another mysql query $stmt2.
I need to determine which id was set in every dropdown menu. These values I need to use later. This is my solution, which doesn't work. It won't print out anything.

echo "
";
echo "
ID	food	g
";
while($rows = $stmt->fetch()){

    echo "
" . $rows['id'] . "	".$rows['food'];
    echo "<form action='upravit_plan.php' method='post'><select name =".$rows['id']." > ";
    $stmt2 = $db->query($q2);
    echo "<option value ='nothing'> choose one </option>";
    while($rows2 = $stmt2->fetch())
    {
        echo '<option value = '.$rows2['id'].'>'.$rows2['food'].'</option>';
    }
    echo "</select></form>";
    echo "	 " . $rows['g'] . "g

 ";

};
echo "
<form action='upravit_plan.php' method='post'><input name = 'go' type='submit' value='OK'/></form>
";
echo "
";

if(isset($_POST['go']))
{
    $stmt = $db->query($q);
    while ($rows = $stmt->fetch())
    {

     echo $_POST[$rows['id']];  // trying to print values

    }
}

Body:
You need to have all elements in a single form. You should also try to separate your PHP from your HTML, this might be a good start but still needs things like HTML escaping. Note in particular the use of alternative syntax and short echo tags.

<form action='upravit_plan.php' method='post'>
<table class ='centered_div' border='1px solid black'>
  <tr>
    <th>ID</th>
    <th>food</th>
    <th>g</th>
  </tr>

<?php while($rows = $stmt->fetch()):?>
  <tr>
    <td><?=$rows['id']?></td>
    <td>
      <?=$rows['food']?>
      <select name="<?=$rows['id']?>">
        <option value ='nothing'> choose one </option>

<?php while($rows2 = $stmt2->fetch()):?>
        <option value="<?=$rows2['id']?>"><?=$rows2['food']?></option>

<?php endwhile;?>
      </select>
    </td>
    <td><?=$rows['g']?>g</td>
  </tr>

<?php endwhile;?>
  <tr>
    <td colspan='3'><input name='go' type='submit' value='OK'/></td>
  </tr>
</table>
</form>

<?php
if(isset($_POST['go']))
{
    $stmt = $db->query($q);
    while ($rows = $stmt->fetch())
    {

     echo $_POST[$rows['id']];  // trying to print values

    }
}
?>


问:
Google PageSpeed Insights - Too much compressing on images
I am currently optimizing our website and I'm surprised by the Google PageSpeed Insights. For days, I've been trying to reach a good ranking and I'm concentrating on optimizing the images. But Google PageSpeed Insights says that the pictures mostly still require a compression of 90%. You can already see that the pictures have been severely compromised and have lost in quality.

The page I'm optimizing is  knorke. de

For example:
The suggestions in the analysis show that the image "Wicked-Print-Logo.jpg" can be compressed by 95%. The image has a size of 16 KB. I do not believe that it's possible to compress the file anymore, without losing image quality.

What am I doing wrong?

Why is Google so strict here?

I'm thankful for every suggestion.

答:
I did a test speed insight of your page, Google already helped you to much, because it offert to you the possibility to download optimized assets (images, css and js) for your website. You just have to download it and replace your images with images optimized by Google.

Note that the decision lies to you, if you think that images optimized by google are very bad  quality, you are not oblige to use them.

I also suggest you to configure the cache browser, it could help a little boost your score

Find the link just under all test notifications.


问:
Azure App service API app host vs API app
I have a question, I created recently an API app using visual studio 2017, I noticed that the name of the app says it's "API app host" which is different from the earlier one created a year ago "API app".
the problem that I am facing is that while I am trying to publish using visual studio 2017, the application that has "API host app" isn't listed at all as a candidate in the list.
as a workaround I am downloading the publish profile from azure portal and using that to publish using visual studio, as the last one can't find the targeted API app in the list.
is this a known issue ?
this picture shows that we have two types of API apps, API App and API app host</p>

答: Make sure you have the Azure SDK 2.5.1 Release installed on your VS, you should be able to see something similar to the image below, this is how you can publish to App Api.

ContentLicense: CC BY-SA 4.0


问:
Import Error - (Python 2.7)
I've been trying to solve an import error I've been getting the whole day and it's just driving me crazy. I've literally went through every Stack Overflow similar question and tried out every single solution and nothing seems to do the magic for me.

I'm currently running a script on my Terminal by doing

```<code>$ python camelcamelcamel-import.py
</code>```

The error I'm getting is:

```<code> Traceback (most recent call last):
 File "camelcamelcamel-import.py", line 1, in <module>
 import sys, mechanize, lxml.html
 File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lxml/html/init.py", line 54, in <module>
 from .. import etree
 ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lxml/etree.so, 2): Symbol not found: _xsltDocDefaultLoader
 Referenced from:        /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lxml/etree.so
 Expected in: dynamic lookup
</code>```

I've tried installing/uninstall the modules, the same thing for pip and nothing seems to work for me.

Any help would be extremely appreciated, thank you!

答:
Reinstall libxslt and libxml2 using brew.

```<code>brew install libxslt libxml2
</code>```

If you see errors during install, execute this:

```<code>xcode-select --install
</code>```

Title: Import Error - (Python 2.7)

Body:
I've been trying to solve an import error I've been getting the whole day and it's just driving me crazy. I've literally went through every Stack Overflow similar question and tried out every single solution and nothing seems to do the magic for me.

I'm currently running a script on my Terminal by doing

$ python camelcamelcamel-import.py

The error I'm getting is:

 Traceback (most recent call last):
 File "camelcamelcamel-import.py", line 1, in <module>
 import sys, mechanize, lxml.html
 File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lxml/html/init.py", line 54, in <module>
 from .. import etree
 ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lxml/etree.so, 2): Symbol not found: _xsltDocDefaultLoader
 Referenced from:        /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lxml/etree.so
 Expected in: dynamic lookup

I've tried installing/uninstall the modules, the same thing for pip and nothing seems to work for me.

Any help would be extremely appreciated, thank you!

Body:
Reinstall libxslt and libxml2 using brew.

brew install libxslt libxml2

If you see errors during install, execute this:

xcode-select --install


问:
connecting hidden convolution layers
I have studied ordinary fully connected ANNs, I am starting to study convnets. I am struggling to understand how hidden layers connect. I do understand how the input matrix forward feeds a smaller field of values to the feature maps in the first hidden layer, by moving the local receptive field along one each time and forward feeding through the same/shared weights (for each feature map), so there are only one group of weights per feature map that are of the same structure as the local receptive field. Please correct me if I am wrong. Then, the feature maps use pooling to simplify the maps. The next part is when I get confused, here is a link to a 3d CNN visualisation to help explain my confusion

http://scs.ryerson.ca/~aharley/vis/conv/

Draw a digit between 0-9 into the top left pad and you'll see how it works. Its really cool. So, on the layer after the first pooling layer (the 4th row up containing 16 filters) if yoau hover your mouse over the filters you can see how the weights connect to the previous pooling layer. Try different filters on this row and what I do not understand is the rule that connects the second convolution layer to the previous pool layer. E.g on the filters to the very left, they are fully connected to the pooling layer. But on the ones nearer to the right, they only connect to about 3 of the previous pooled layers. Looks random.

I hope my explanation makes sense. I am essentially confused about what the pattern is that connects hidden pooled layers to the following hidden convolution layer. Even if my example is a bit odd, I would still appreciate some sort of explanation or link to a good explanation.

Thanks a lot.

答:
Welcome to the magic of self-trained CNNs.  It's confusing because the network makes up these rules as it trains.  This is an image-processing example; most of these happen to train in a fashion that loosely parallels the learning in a simplified model of the visual cortex in vertebrates.

In general, the first layer's kernels "learn" to "recognize" very simple features of the input: lines and edges in various orientations.  The next layer combines those for more complex features, perhaps a left-facing half-circle, or a particular angle orientation.  The deeper you go in the model, the more complex the "decisions" get, and the kernels get more complex, and/or less recognizable.

The difference in connectivity from left to right may be an intentional sorting by the developer, or mere circumstance in the model.  Some features need to "consult" only a handful of the previous layer's kernels; others need a committee of the whole.  Note how simple features connect to relatively few kernels, while the final decision has each of the ten categories checking in with a large proportion of the "pixel"-level units in the last FC layer.

You might look around for some kernel visualizations for larger CNN implementations, such as those in the ILSVRC: GoogleNet, ResNet, VGG, etc.  Those have some striking kernels through the layers, including fuzzy matches to a wheel & fender, the front part of a standing mammal, various types of faces, etc.

Does that help at all?

All of this is the result of organic growth over the training period.

Title: connecting hidden convolution layers


问:
ORACLE SQL statement to call table without only customers with product views
I have tables as follows:

```<code>Customer(CustomerID, UserName, Email, CustomerType)
CustomerVisit(CustomerVisitID, CustomerID, VisitDateTime, VisitLength)
Product(ProductCode, ProductName, ProductDescription, QuantityInStock, UnitPrice)
ProductView(CustomerVisitID, ProductCode, AddedToBasket)
</code>```

And I have the command as follows

```<code>select customerid, customervisitid,  count(customervisitid)
from customer_aqd, productview_aqd
group by customerid, customervisitid
</code>```

Any idea how I can represent all the items viewed with the customervisitid and customerid without having repeating customersid as I don't want anyone who doesn't have any productview data.

So, just to be clear, I only want to be able to see the customers who have a productview in the table and see how many customervisits they have with their customerid but only if they have a productview data.

答:
Inner join the CustomerVisit_aqd table to the ProductView_aqd table:

```<code>select cv.customerid, cv.customervisitid,  count(cv.customervisitid)
from productview_aqd p
inner join customervisit_aqd cv on cv.CustomerVisitID = p.CustomerVisitID
group by cv.customerid, cv.customervisitid
</code>```

Body:
I have tables as follows:

Customer(CustomerID, UserName, Email, CustomerType)
CustomerVisit(CustomerVisitID, CustomerID, VisitDateTime, VisitLength)
Product(ProductCode, ProductName, ProductDescription, QuantityInStock, UnitPrice)
ProductView(CustomerVisitID, ProductCode, AddedToBasket)

And I have the command as follows

select customerid, customervisitid,  count(customervisitid)
from customer_aqd, productview_aqd
group by customerid, customervisitid

Any idea how I can represent all the items viewed with the customervisitid and customerid without having repeating customersid as I don't want anyone who doesn't have any productview data.

So, just to be clear, I only want to be able to see the customers who have a productview in the table and see how many customervisits they have with their customerid but only if they have a productview data.

Body:
Inner join the CustomerVisit_aqd table to the ProductView_aqd table:

select cv.customerid, cv.customervisitid,  count(cv.customervisitid)
from productview_aqd p
inner join customervisit_aqd cv on cv.CustomerVisitID = p.CustomerVisitID
group by cv.customerid, cv.customervisitid


问:
Location of Maven Home on Cloud Foundry
I have an application that programmatically runs Maven command "clean package" at runtime, using plugin maven-invoker.
To be able to run this application on Cloud Foundry, we need to set Maven Home on the invoker.

This question is similar to Maven Invoker: IllegalStateException, except that we are deploying on Cloud Foundry but don't know how to get the value for Maven Home.

Is it possible to get it from CF environment?

答:
The Java build pack does not install Maven or set any Maven related environment variables.  You can however set whatever environment variables that you like via cf set-env or in the env block of your manifest.yml file.

https://docs.cloudfoundry.org/devguide/deploy-apps/manifest.html#env-block

Your app when running on CF will run as the vcap user and it runs out of /home/vcap/app (or reference $HOME env variable).  If you need to pick a location to use for Maven home, I would suggest putting it under that directory.

Title: Location of Maven Home on Cloud Foundry


问:
Open .txt file in Python after skipping lines - Encoding issue
I am trying to open a .txt file in Python.

Before flagging this of as repeat, please do take a look at the code and the file below.

I have used this snippet to read similar files before, however this particular batch of files does not work.

```<code>location="sample/sample2/"
filename=location+"Detector_-3000um.txt"
skip=25 #Skip the first 25 lines
</code>```

The code to open it is -

```<code>f=open(filename)
num_lines = sum(1 for line in f)
print "Skipping the first "+str(skip)+" lines"
data=np.zeros((num_lines-skip+1,num_lines-skip+1))
f.close()
f=open(filename)
i=0
for _ in range(skip):  #skip unwanted rows
    next(f)
for line in f:
    data[i,:]=line.split()
    i+=1
f.close()
</code>```

Its a 501x501 data set with the first row and column being the row and column numbers resp.

The data set is attached here.

I also tried using panda - pd.read_csv(filename,skiprows) however it gives this error -

```<code>CParserError: Error tokenizing data. C error: Expected 1 fields in line 49, saw 501
</code>```

答:
I think, there is nothing wrong with your code, the problem is the file encoding.

I converted your file encoding to 'utf-8', then both your code and read_csv() from pandas work properly.

```<code>pd.read_csv(myfile, skiprows=24, header=0, index_col=0,sep='\t')
</code>```

There are many ways to convert the encoding, for example use notepad++(windows), the way I did or please see here: How to convert a file to utf-8 in Python?

Body:
I am trying to open a .txt file in Python.

Before flagging this of as repeat, please do take a look at the code and the file below.

I have used this snippet to read similar files before, however this particular batch of files does not work.

location="sample/sample2/"
filename=location+"Detector_-3000um.txt"
skip=25 #Skip the first 25 lines

The code to open it is -

f=open(filename)
num_lines = sum(1 for line in f)
print "Skipping the first "+str(skip)+" lines"
data=np.zeros((num_lines-skip+1,num_lines-skip+1))
f.close()
f=open(filename)
i=0
for _ in range(skip):  #skip unwanted rows
    next(f)
for line in f:
    data[i,:]=line.split()
    i+=1
f.close()

Its a 501x501 data set with the first row and column being the row and column numbers resp.

The data set is attached here.

I also tried using panda - pd.read_csv(filename,skiprows) however it gives this error -

CParserError: Error tokenizing data. C error: Expected 1 fields in line 49, saw 501

Body:
I think, there is nothing wrong with your code, the problem is the file encoding.

I converted your file encoding to 'utf-8', then both your code and read_csv() from pandas work properly.

pd.read_csv(myfile, skiprows=24, header=0, index_col=0,sep='\t')

There are many ways to convert the encoding, for example use notepad++(windows), the way I did or please see here: How to convert a file to utf-8 in Python?


问:
How to uncheck all MaterialUI Toggle components using a button or outside event?
Say you have multiple <Toggle /> components for an app that filters clothes by size. You toggle through the sizes and then you want to clear all the filters by clicking a button rather than uncheck all the toggles.

How can this be accomplished specifically with materials-ui Toggles? There's nothing in the documentation that says how you can uncheck the toggles using an outside element, such as a button.

答:
For this functionality, you have to maintain the state for all the Toggle component. When you click the button, then you have to update the state of all the toggles.

for eg.

```<code>constructor(props) {
  super(props);
    this.state = {
      toggle1: false,
      toggle2: false,
  };
}

uncheckAllToggle = () => {
  this.setState({
    toggle1: false,
    toggle2: false
  });
}

render() {
  return (
    <div>
      <Toggle
        label="toggle1"
        toggled={this.state.toggle1}
        onToggle={() => this.setState({toggle1: !this.state.toggle1})}
      />
      <Toggle
        label="toggle2"
        toggled={this.state.toggle2}
        onToggle={() => this.setState({toggle2: !this.state.toggle2})}
      />
     <FlatButton
       label={'UnCheck All Toggle'}
       onClick={this.uncheckAllToggle}
     />
    </div>
  )
}
</code>```

Body:
For this functionality, you have to maintain the state for all the Toggle component. When you click the button, then you have to update the state of all the toggles.

for eg.

constructor(props) {
  super(props);
    this.state = {
      toggle1: false,
      toggle2: false,
  };
}

uncheckAllToggle = () => {
  this.setState({
    toggle1: false,
    toggle2: false
  });
}

render() {
  return (
    <div>
      <Toggle
        label="toggle1"
        toggled={this.state.toggle1}
        onToggle={() => this.setState({toggle1: !this.state.toggle1})}
      />
      <Toggle
        label="toggle2"
        toggled={this.state.toggle2}
        onToggle={() => this.setState({toggle2: !this.state.toggle2})}
      />
     <FlatButton
       label={'UnCheck All Toggle'}
       onClick={this.uncheckAllToggle}
     />
    </div>
  )
}


问:
Detect HTML5 Geolocation Support Using PHP
I need to detect HTML5 Geolocation support using PHP so that I can load a backup JavaScript that supports Geolocation using IP Address.

How to do this with or without PHP.

答:
Without PHP:

http://fortuito.us/diveintohtml5/detect.html#geolocation

With PHP:

you have to check the browser version

http://chrisschuld.com/projects/browser-php-detecting-a-users-browser-from-php/

(note: http://apptools.com/phptools/browser/)


问:
How to create an array of references
Create an array of references

I've read the link above and known how to create an array of references in Java. But it doesn't seem to work...

Here is my test:

```<code>Character []c1 = {'a', 'x'};
Character []c2 = new Character[1];
c2[0] = c1[0]; // I try to make c2[0] as the reference of c1[0]
c1[0] = 'b';

System.out.println(c1[0]);    // b
System.out.println(c2[0]);    // a
</code>```

Is there any way such that I can make c2[0] as a reference of c1[0] so that any change in c1[0] will update the value in c2[0].

答: Java passes all primitive data types as value, and not by reference. However, objects are passed by reference. So what you could do for this example is create a wrapper object for a Character and create an array of that instead.</p>

Title: How to create an array of references

Body:
Create an array of references

I've read the link above and known how to create an array of references in Java. But it doesn't seem to work...

Here is my test:

Character []c1 = {'a', 'x'};
Character []c2 = new Character[1];
c2[0] = c1[0]; // I try to make c2[0] as the reference of c1[0]
c1[0] = 'b';

System.out.println(c1[0]);    // b
System.out.println(c2[0]);    // a

Is there any way such that I can make c2[0] as a reference of c1[0] so that any change in c1[0] will update the value in c2[0].


问:
Adding methods to existing class without much changes
i need to include new methods into an existing class without changing too much inside that class. I dont know how to do this. Since i cannot use eg include_once('mynew.class.php') and then write all my new code inside, i tried the following and it works.

I can add new methods inside B and they are processes by A as i want them to.

```<code>class A extends B {
"the existing code"
}
class B {
 "my new code"
}
</code>```

I think this is not the right way, because in this case B should have the main logic and A should get the new code, right?

I don't now how to simulate something like include inside a class.

Of course i can write my new functions inside existing A without inheritance, but in this case i want to do as i explained, and barely touch the existing files.

Any suggestions? Hope anyone understands this problem.

Thanks

答:
Try using a Trait. It basically lets you reuse (or include in your case) functions in a class.

Code example

```<code><?php
trait SayHello {
   public function sayHello() {
       echo 'Hello';
   }
}

class Base {
    use SayHello;
}

$o = new Base();
$o->sayHello();
?>
</code>```

Body:
i need to include new methods into an existing class without changing too much inside that class. I dont know how to do this. Since i cannot use eg include_once('mynew.class.php') and then write all my new code inside, i tried the following and it works.

I can add new methods inside B and they are processes by A as i want them to.

class A extends B {
"the existing code"
}
class B {
 "my new code"
}

I think this is not the right way, because in this case B should have the main logic and A should get the new code, right?

I don't now how to simulate something like include inside a class.

Of course i can write my new functions inside existing A without inheritance, but in this case i want to do as i explained, and barely touch the existing files.

Any suggestions? Hope anyone understands this problem.

Thanks

Body:
Try using a Trait. It basically lets you reuse (or include in your case) functions in a class.

Code example

<?php
trait SayHello {
   public function sayHello() {
       echo 'Hello';
   }
}

class Base {
    use SayHello;
}

$o = new Base();
$o->sayHello();
?>


问:
CakePHP: Adding default faculty/department values while adding a new University
New programmer with with CakePHP, I have 3 controllers: Universities, Faculties, Departments.

My tables are:
universities (id, name, country_id),
faculties(id, name, university_id),
departments (id, name, faculty_id).

When I add a new University, I need to create automatically a default value ('n/a') as a Faculty for this University, and for this created Faculty a default value ('n/a') as Department.
in our system, we need the university having at least one faculty and one faculty.department. So if the new university id = 10, then after saving, I need to create a new faculty (let's say faculties.id = 25) with university_i=10. and a new department with faculty_id = 25.

This is my code UniversitiesController add function

```<code>$university = $this->Universities->newEntity();

if ($this->request->is('post')) {
   $university = $this->Universities->patchEntity($university, $this->request->data);
   if ($this->Universities->save($university)) {
       $this->Flash->success(__('The university has been saved.'));
       return $this->redirect(['action' => 'index']);
   } else {
       $this->Flash->error(__('The university could not be saved. Please, try again.'));
   }
}
</code>```

Any help please?

答:
If I understood correctly is that in the list of universities or faculties you want to have a default value (first value of your list) as (n/a)'s. If that is the case, I had the same issue, the answer was very simple. In the table where you have the list of universities as a first value add the n/a as a value, I recommend to leave it like it is so the first value on your table or SQL result will be displayed as the default value.

next in the option list on your file.ctp you just add values like this...

```<code>echo $this->Form->control('universities', [
                'options' => $universities,
                'title' => 'Select the university',
                'alt' => 'Select the university',
                'label' => 'Select the university',
                'class'=> 'classForOption',
                'empty' => false
            ]);
</code>```

Being the 'empty' => false the answer of your question. I hope !

Regards

Body:
New programmer with with CakePHP, I have 3 controllers: Universities, Faculties, Departments.

My tables are:
universities (id, name, country_id),
faculties(id, name, university_id),
departments (id, name, faculty_id).

When I add a new University, I need to create automatically a default value ('n/a') as a Faculty for this University, and for this created Faculty a default value ('n/a') as Department.
in our system, we need the university having at least one faculty and one faculty.department. So if the new university id = 10, then after saving, I need to create a new faculty (let's say faculties.id = 25) with university_i=10. and a new department with faculty_id = 25.

This is my code UniversitiesController add function

$university = $this->Universities->newEntity();

if ($this->request->is('post')) {
   $university = $this->Universities->patchEntity($university, $this->request->data);
   if ($this->Universities->save($university)) {
       $this->Flash->success(__('The university has been saved.'));
       return $this->redirect(['action' => 'index']);
   } else {
       $this->Flash->error(__('The university could not be saved. Please, try again.'));
   }
}

Any help please?

Body:
If I understood correctly is that in the list of universities or faculties you want to have a default value (first value of your list) as (n/a)'s. If that is the case, I had the same issue, the answer was very simple. In the table where you have the list of universities as a first value add the n/a as a value, I recommend to leave it like it is so the first value on your table or SQL result will be displayed as the default value.

next in the option list on your file.ctp you just add values like this...

echo $this->Form->control('universities', [
                'options' => $universities,
                'title' => 'Select the university',
                'alt' => 'Select the university',
                'label' => 'Select the university',
                'class'=> 'classForOption',
                'empty' => false
            ]);

Being the 'empty' => false the answer of your question. I hope !

Regards