问:
Load yaml list as dictionary
I'm doing a simple yaml load and running into a small issue:

code:

```<code>with open(target, 'r') as stream:
    try:
        data = (yaml.load(stream))
    except Exception as exc:
        print (exc)

print(data)
</code>```

First yaml file:

```<code>test:
  - foo: 1
  - bar: 2
test2:
  - foo: 1
  - bar: 2
</code>```

Second yaml file:

```<code>foo: 1
bar: 2
</code>```

I only need the values in the test group, so when I'm trying to access the data from the first yaml I use print(data['test']) which returns these values:

```<code>[{'foo': '1'}, {'bar': '2'}]
</code>```

On the second one, I use the print(data) line and I get:

```<code>{'foo': '1'}, {'bar': '2'}
</code>```

I know of a couple ways I could solve the problem, replacing the brackets with nothing or using an iterative loop to create a new object but that seems really convoluted. Is there a better way I can get the results I'm looking for without jumping through hoops and creating code that's harder to read?

答:
You will get a dictionary for the yaml data which you are reading.

```<code>{'test': [{'foo': 1}, {'bar': 2}], 'test2': [{'foo': 1}, {'bar': 2}]}
</code>```

If you want to get the values of the test group as a dictionary you'll need to create the list of dicts into a dict manually.

```<code>dicta = {k:v for d in data['test'] for k, v in d.items()}
print(dicta) # {'foo': 1, 'bar': 2}
</code>```

Title: Load yaml list as dictionary

Body:
I'm doing a simple yaml load and running into a small issue:

code:

with open(target, 'r') as stream:
    try:
        data = (yaml.load(stream))
    except Exception as exc:
        print (exc)

print(data)

First yaml file:

test:
  - foo: 1
  - bar: 2
test2:
  - foo: 1
  - bar: 2

Second yaml file:

foo: 1
bar: 2

I only need the values in the test group, so when I'm trying to access the data from the first yaml I use print(data['test']) which returns these values:

[{'foo': '1'}, {'bar': '2'}]

On the second one, I use the print(data) line and I get:

{'foo': '1'}, {'bar': '2'}

I know of a couple ways I could solve the problem, replacing the brackets with nothing or using an iterative loop to create a new object but that seems really convoluted. Is there a better way I can get the results I'm looking for without jumping through hoops and creating code that's harder to read?

Body:
You will get a dictionary for the yaml data which you are reading.

{'test': [{'foo': 1}, {'bar': 2}], 'test2': [{'foo': 1}, {'bar': 2}]}

If you want to get the values of the test group as a dictionary you'll need to create the list of dicts into a dict manually.

dicta = {k:v for d in data['test'] for k, v in d.items()}
print(dicta) # {'foo': 1, 'bar': 2}


来源: stackexchange

问:
Query with 3 parameters to dynamodb with dynamoose
I am trying to consult a DynamoDB table with 3 parameters, but it does not work. However, with 1 parameter it works perfectly.

I'm work with NodeJs, DynamoDB, Dynamoose... and here is my code:

```<code>    var params = {

        TableName: "DifferentTermsPages",

        KeyConditionExpression:"#providerName = :providerName and #productType = :productType and #language = :language",

        ExpressionAttributeNames: {
            "#providerName":"providerName",
            "#productType":"productType",
            "#language":"language"
            },

        ExpressionAttributeValues: {
            ":providerName":providerName,
            ":productType":productType,
            ":language":language
            }

        };

       OcrController.getDifferencesFromDB(params)
        .then(function(dataDB) {
            console.log("DATA = ", dataDB);
        }).catch(function(err) {
            console.error(err);
       });
</code>```

Call to another function with a promise:

```<code>  getDifferencesFromDB(params) {

    return new Promise(function(resolve, reject) {

        DifferentTermsPagesModel.scan(params).exec().then(function (err, data) {
          if(err) {
            reject(err);
          }
          else {
            console.log("OK!!");
            resolve(data);
          }
        });

    });
  }
</code>```

The error that shows me...

```<code>TypeError: Cannot read property 'toDynamo' of undefined
at Scan.exec (/API/src/node_modules/dynamoose/lib/Scan.js:57:23)
at ...
</code>```

Where is my error?? How can I resolve it? Or another form to make this...

答:
As you are using the scan api, please use FilterExpression rather than KeyConditionExpression.

```<code>FilterExpression:"#providerName = :providerName AND #productType = :productType AND #language = :language",
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to consult a DynamoDB table with 3 parameters, but it does not work. However, with 1 parameter it works perfectly.

I'm work with NodeJs, DynamoDB, Dynamoose... and here is my code:

    var params = {

        TableName: "DifferentTermsPages",

        KeyConditionExpression:"#providerName = :providerName and #productType = :productType and #language = :language",

        ExpressionAttributeNames: {
            "#providerName":"providerName",
            "#productType":"productType",
            "#language":"language"
            },

        ExpressionAttributeValues: {
            ":providerName":providerName,
            ":productType":productType,
            ":language":language
            }

        };

       OcrController.getDifferencesFromDB(params)
        .then(function(dataDB) {
            console.log("DATA = ", dataDB);
        }).catch(function(err) {
            console.error(err);
       });

Call to another function with a promise:

  getDifferencesFromDB(params) {

    return new Promise(function(resolve, reject) {

        DifferentTermsPagesModel.scan(params).exec().then(function (err, data) {
          if(err) {
            reject(err);
          }
          else {
            console.log("OK!!");
            resolve(data);
          }
        });

    });
  }

The error that shows me...

TypeError: Cannot read property 'toDynamo' of undefined
at Scan.exec (/API/src/node_modules/dynamoose/lib/Scan.js:57:23)
at ...

Where is my error?? How can I resolve it? Or another form to make this...

Body:
As you are using the scan api, please use FilterExpression rather than KeyConditionExpression.

FilterExpression:"#providerName = :providerName AND #productType = :productType AND #language = :language",


问:
unable to point swarm master on EC2 to consul registry on another EC2
I am receiving the following error when trying to point a swarm master on one EC2 instance to a registry using Consul on another EC2 instance:

```<code>Running pre-create checks...
Creating machine...
(swarm-master) Launching instance...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with ubuntu(systemd)...
Installing Docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Error creating machine: Error running provisioning: ssh command error:
command : sudo systemctl -f start docker
err     : exit status 1
output  : Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details.
</code>```

I've noted tips to point directly to a docker engine location, upgraded to the latest docker-machine version, and opened port 8500 on the registry EC2's security group, but this did not resolve my issue.

Here is how I'm running:

create registry:

```<code>docker-machine create \
        --driver amazonec2 \
        --amazonec2-vpc-id vpc-12345678 \
        --amazonec2-region us-east-1 \
        --amazonec2-zone b \
        --amazonec2-instance-type t2.micro \
        --amazonec2-subnet-id subnet-12345678 \
        --amazonec2-security-group swarm_sg \
        --amazonec2-keypair-name swarm \
        --amazonec2-ssh-keypath ~/.docker/machine/certs/swarm \
        swarm-registry
</code>```

assume registry machine

```<code>eval $(docker-machine env swarm-registry)
</code>```

run consul

```<code>docker run -d \
        -p "8500:8500" \
        -h "consul" \
        progrium/consul -server -bootstrap
</code>```

create swarm master:

```<code>docker-machine create \
        --driver amazonec2 \
        --amazonec2-vpc-id vpc-12345678 \
        --amazonec2-region us-east-1 \
        --amazonec2-zone b \
        --amazonec2-instance-type t2.micro \
        --amazonec2-subnet-id subnet-12345678 \
        --amazonec2-security-group swarm_sg \
        --amazonec2-keypair-name swarm \
        --amazonec2-ssh-keypath ~/.docker/machine/certs/swarm \
        --engine-install-url="https://web.archive.org/web/20170623081500/https://get.docker.com" \
        --swarm \
        --swarm-master \
        --swarm-discovery="consul://172.31.56.214:8500" \
        --engine-opt="cluster-store=consul://172.31.56.214:8500" \
        --engine-opt="cluster-advertise=eth1:2376" \
        swarm-master
</code>```

where 172.31.56.214 is the private IP address of the swarm-registry machine's host EC2.  furthermore, when running w/o trying to point to Consul i don't have a problem.  that is, creating the master without the following lines is possible:

```<code>        --swarm-discovery="consul://172.31.56.214:8500" \
        --engine-opt="cluster-store=consul://172.31.56.214:8500" \
        --engine-opt="cluster-advertise=eth1:2376" \
</code>```

Any help is sincerely appreciated.

答: My problem was my network interface name was not eth1.  It is eth0.  As an aside, I'd be interested in understanding how AWS interfaces are named.  They appear to vary across our EC2 instance types (e.g. eth0, eth1, ens3).</p>

Body:
I am receiving the following error when trying to point a swarm master on one EC2 instance to a registry using Consul on another EC2 instance:

Running pre-create checks...
Creating machine...
(swarm-master) Launching instance...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with ubuntu(systemd)...
Installing Docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Error creating machine: Error running provisioning: ssh command error:
command : sudo systemctl -f start docker
err     : exit status 1
output  : Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details.

I've noted tips to point directly to a docker engine location, upgraded to the latest docker-machine version, and opened port 8500 on the registry EC2's security group, but this did not resolve my issue.

Here is how I'm running:

create registry:

docker-machine create \
        --driver amazonec2 \
        --amazonec2-vpc-id vpc-12345678 \
        --amazonec2-region us-east-1 \
        --amazonec2-zone b \
        --amazonec2-instance-type t2.micro \
        --amazonec2-subnet-id subnet-12345678 \
        --amazonec2-security-group swarm_sg \
        --amazonec2-keypair-name swarm \
        --amazonec2-ssh-keypath ~/.docker/machine/certs/swarm \
        swarm-registry

assume registry machine

eval $(docker-machine env swarm-registry)

run consul

docker run -d \
        -p "8500:8500" \
        -h "consul" \
        progrium/consul -server -bootstrap

create swarm master:

docker-machine create \
        --driver amazonec2 \
        --amazonec2-vpc-id vpc-12345678 \
        --amazonec2-region us-east-1 \
        --amazonec2-zone b \
        --amazonec2-instance-type t2.micro \
        --amazonec2-subnet-id subnet-12345678 \
        --amazonec2-security-group swarm_sg \
        --amazonec2-keypair-name swarm \
        --amazonec2-ssh-keypath ~/.docker/machine/certs/swarm \
        --engine-install-url="https://web.archive.org/web/20170623081500/https://get.docker.com" \
        --swarm \
        --swarm-master \
        --swarm-discovery="consul://172.31.56.214:8500" \
        --engine-opt="cluster-store=consul://172.31.56.214:8500" \
        --engine-opt="cluster-advertise=eth1:2376" \
        swarm-master

where 172.31.56.214 is the private IP address of the swarm-registry machine's host EC2.  furthermore, when running w/o trying to point to Consul i don't have a problem.  that is, creating the master without the following lines is possible:

        --swarm-discovery="consul://172.31.56.214:8500" \
        --engine-opt="cluster-store=consul://172.31.56.214:8500" \
        --engine-opt="cluster-advertise=eth1:2376" \

Any help is sincerely appreciated.


问:
Haxe: Native Interface properties implementable?
I've got this compiletime errors when I make some class implement an interface with properties that have been fromerly defined in some native sub class, like openfl.display.Sprite. It occurs when I'm targeting flash, not js.

```<code>Field get_someValue needed by SomeInterface is missing
Field set_someValue needed by SomeInterface is missing
Field someValue has different property access than in SomeInterface (var should be (get,set))
</code>```

In contrast, there's no problem with interface definitions of 'native' methods or 'non-native' properties. Those work.

Do I have to avoid that (not so typical) use of interfaces with haxe and rewrite my code? Or is there any way to bypass this problem?

Thanks in advance.

Example:

```<code>class NativePropertyInterfaceImplTest
{
    public function new()
    {
        var spr:FooSprite = new FooSprite();
        spr.visible = !spr.visible;
    }
}

class FooSprite extends Sprite implements IFoo
{
    public function new()
    {
        super();
    }
}

interface IFoo
{
    public var visible (get, set):Bool; // Cannot use this ):
}
</code>```

答:
Need to provide the method signatures in an Interface. Currently its just a property declaration.

The error message is saying it all.

Field get_someValue needed by SomeInterface is missing
Field set_someValue needed by SomeInterface is missing

Hopefully that helps.

Body:
I've got this compiletime errors when I make some class implement an interface with properties that have been fromerly defined in some native sub class, like openfl.display.Sprite. It occurs when I'm targeting flash, not js.

Field get_someValue needed by SomeInterface is missing
Field set_someValue needed by SomeInterface is missing
Field someValue has different property access than in SomeInterface (var should be (get,set))

In contrast, there's no problem with interface definitions of 'native' methods or 'non-native' properties. Those work.

Do I have to avoid that (not so typical) use of interfaces with haxe and rewrite my code? Or is there any way to bypass this problem?

Thanks in advance.

Example:

class NativePropertyInterfaceImplTest
{
    public function new()
    {
        var spr:FooSprite = new FooSprite();
        spr.visible = !spr.visible;
    }
}

class FooSprite extends Sprite implements IFoo
{
    public function new()
    {
        super();
    }
}

interface IFoo
{
    public var visible (get, set):Bool; // Cannot use this ):
}


问:
Process json data at server (nodejs) side or using show function of couchdb?
I am using couchdb and nodejs for server side.
I have a document with all transactions history array saved on couchdb. The array can have multiple transactions with same trnxId with different status. I need to filter the history based on some parameters and to fetch latest records but not deleted ones.

Doc in couchDB

```<code>{
  "_id": "hist",
  "_rev": "3-62da7472a24652fd5cf42e01bcef294f",
  "type": "history",
  "status": "ACTIVE",
  "accounts": {
    "payment": [
      {
        "trnxId": "5784365893938",
        "trnxDate": "2017-11-07T06:12:15.000Z",
        "trnxMode": "cash",
        "amount": 50,
        "trnxStatus": "new",
        "accName": "Cash",
        "category": "others",
        "comments": "no comments"
      }
    ],
    "expense": [],
    "transfer": []
  }
}
</code>```

For filtering, i'm using below code in node js:

```<code>var __ = require('lodash');
function fetchAllHist(docObj, trnxType) {
    var trnxArray = docObj.accounts[trnxType];
    var histArray = [];
    for (var i = trnxArray.length - 1; i >= 0; i--) { //inverse loop as trnxArray is having data in ascending order over creation date
        var trnxId = trnxArray[i].trnxId;
        if (__.findIndex(histArray, { 'trnxId':  trnxId }) == -1) {
            histArray.push(trnxArray[i]);
        }
    }
    histArray = __.reject(histArray, { 'trnxStatus': "deleted" });
    return histArray;
};
</code>```

Can i do the same processing in couchDB itself using Show function? I this case, i won't be able to use lodash functions.
Please guide me which way is better, either node js or Show function of couchDB?

答:
To use lodash you may put lodash code as a string into, say, .lodash branch of your design document. Then you can use lodash inside your show function putting require("lodash") into show fn code.

Using show functions, however, implies some limitations:

you only have 64Mb of RAM for any query server instance, so your processed doc can not be very long;

query server uses old SpiderMonkey engine, which means you have only ES5 onboard, so no arrow functions and other ES6 niceties;

built-in query server code (like shows/lists) tend to be painful for debugging.

It might be reasonable in some cases, like if you plan to distribute your code using sync mechanics, or do not want to decouple some of your biz logic bits from map/reduce code.

However, in most cases if you have application layer, better use application layer.

Body:
I am using couchdb and nodejs for server side.
I have a document with all transactions history array saved on couchdb. The array can have multiple transactions with same trnxId with different status. I need to filter the history based on some parameters and to fetch latest records but not deleted ones.

Doc in couchDB

{
  "_id": "hist",
  "_rev": "3-62da7472a24652fd5cf42e01bcef294f",
  "type": "history",
  "status": "ACTIVE",
  "accounts": {
    "payment": [
      {
        "trnxId": "5784365893938",
        "trnxDate": "2017-11-07T06:12:15.000Z",
        "trnxMode": "cash",
        "amount": 50,
        "trnxStatus": "new",
        "accName": "Cash",
        "category": "others",
        "comments": "no comments"
      }
    ],
    "expense": [],
    "transfer": []
  }
}

For filtering, i'm using below code in node js:

var __ = require('lodash');
function fetchAllHist(docObj, trnxType) {
    var trnxArray = docObj.accounts[trnxType];
    var histArray = [];
    for (var i = trnxArray.length - 1; i >= 0; i--) { //inverse loop as trnxArray is having data in ascending order over creation date
        var trnxId = trnxArray[i].trnxId;
        if (__.findIndex(histArray, { 'trnxId':  trnxId }) == -1) {
            histArray.push(trnxArray[i]);
        }
    }
    histArray = __.reject(histArray, { 'trnxStatus': "deleted" });
    return histArray;
};

Can i do the same processing in couchDB itself using Show function? I this case, i won't be able to use lodash functions.
Please guide me which way is better, either node js or Show function of couchDB?


问:
Firebase - How do I make a new table/structure?
So I am currently developing an API which gets data from Firebase and depending on that data the button changes its color. However, when I tried to make a new structure for my buttons. It won't let me make one.

I tried the answers here: How to insert data of two tables in Firebase? and here: How can I create an empty table from android app in Firebase? but neither did work for me.

Here's my sample code:

```<code>public class Normal extends AppCompatActivity {

    Button suite, normal, room1;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;
    private DatabaseReference mFirebaseDatabase1;
    private FirebaseDatabase mFirebaseInstance;

    //FIREBASE AUTH FIELDS

    DatabaseReference mSearchedLocationReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_normal);

        mFirebaseInstance = FirebaseDatabase.getInstance();

        //FIREBASE
        mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");
        mSearchedLocationReference = mFirebaseDatabase1.child("Room1").child("RoomStatus");

        //ASSIGN ID's

        room1 = (Button) findViewById(R.id.room2);

        room1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mFirebaseDatabase1.child("Rooms").child("Room1").child("RoomStatus").setValue("Green");
                startActivity(new Intent(Normal.this, room2.class));
            }
        });

        mSearchedLocationReference.addValueEventListener(new ValueEventListener() { //attach listener

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) { //something changed!
                for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
                    String location = locationSnapshot.getValue().toString();
                    Log.d("Locations updated", "location: " + location); //log
                    if ( location.equals("Green")){
                        room1.setBackgroundColor(Color.GREEN);
                    }else if ( location.equals("Red")){
                        room1.setBackgroundColor(Color.RED);

                    }
                    else{
                        room1.setBackgroundColor(Color.YELLOW);

                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) { //update UI here if error occurred.

            }
        });

    }
}
</code>```

PS: I created the User structure (which is for my login) on another class.

答:
I think the problem is when you are changing the value when (room 1) is clicked. You already declared this reference like this:

```<code>mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");
</code>```

when you clicked the button (room 1) you triggered this reference to change value :

```<code>mFirebaseDatabase1.child("Rooms").child("Room1").child("RoomStatus").setValue("Green");
</code>```

In other words

you are saying that you want to access

Rooms/Rooms/Room1/RoomStatus/Green

but you should be looking for this

Rooms/Room1/RoomStatus/Green

you have an extra child called Rooms that is repeated and causing the problem

Possible Solution

do this in the click listener of room 1

```<code>   room1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mFirebaseDatabase1.child("Room1").child("RoomStatus").setValue("Green");
            startActivity(new Intent(Normal.this, room2.class));
        }
    });
</code>```

I just removed the extra(.child("Rooms")).

Body:
So I am currently developing an API which gets data from Firebase and depending on that data the button changes its color. However, when I tried to make a new structure for my buttons. It won't let me make one.

I tried the answers here: How to insert data of two tables in Firebase? and here: How can I create an empty table from android app in Firebase? but neither did work for me.

Here's my sample code:

public class Normal extends AppCompatActivity {

    Button suite, normal, room1;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;
    private DatabaseReference mFirebaseDatabase1;
    private FirebaseDatabase mFirebaseInstance;

    //FIREBASE AUTH FIELDS

    DatabaseReference mSearchedLocationReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_normal);

        mFirebaseInstance = FirebaseDatabase.getInstance();

        //FIREBASE
        mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");
        mSearchedLocationReference = mFirebaseDatabase1.child("Room1").child("RoomStatus");

        //ASSIGN ID's

        room1 = (Button) findViewById(R.id.room2);

        room1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mFirebaseDatabase1.child("Rooms").child("Room1").child("RoomStatus").setValue("Green");
                startActivity(new Intent(Normal.this, room2.class));
            }
        });

        mSearchedLocationReference.addValueEventListener(new ValueEventListener() { //attach listener

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) { //something changed!
                for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
                    String location = locationSnapshot.getValue().toString();
                    Log.d("Locations updated", "location: " + location); //log
                    if ( location.equals("Green")){
                        room1.setBackgroundColor(Color.GREEN);
                    }else if ( location.equals("Red")){
                        room1.setBackgroundColor(Color.RED);

                    }
                    else{
                        room1.setBackgroundColor(Color.YELLOW);

                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) { //update UI here if error occurred.

            }
        });

    }
}

PS: I created the User structure (which is for my login) on another class.

Body:
I think the problem is when you are changing the value when (room 1) is clicked. You already declared this reference like this:

mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");

when you clicked the button (room 1) you triggered this reference to change value :

mFirebaseDatabase1.child("Rooms").child("Room1").child("RoomStatus").setValue("Green");

In other words

you are saying that you want to access

Rooms/Rooms/Room1/RoomStatus/Green

but you should be looking for this

Rooms/Room1/RoomStatus/Green

you have an extra child called Rooms that is repeated and causing the problem

Possible Solution

do this in the click listener of room 1

   room1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mFirebaseDatabase1.child("Room1").child("RoomStatus").setValue("Green");
            startActivity(new Intent(Normal.this, room2.class));
        }
    });

I just removed the extra(.child("Rooms")).


问:
Wkhtmltopdf inconsistent output
I'm outputting some html via wkhtmltopdf, and using a custom header and footer.

The header html is as follows:

```<code><!doctype html>
<html>
<head>
    <style>
        body {
            font-size: 12px;
            margin: 0;
            padding: 0;
        }

        .page-header {
            background: #2A5266 -webkit-linear-gradient(
                left,
                #cbd5da 0,
                #cbd5da 50pt,
                white 50pt,
                white 75pt,
                #cbd5da 75pt,
                #cbd5da 100pt,
                white 100pt,
                white 125pt,
                #2A5266 125pt,
                #2A5266
            );
            height: 72pt;
            border: none;
            margin: 0;
            padding: 0;
            width: 100%;
            position: relative;
            display: block;
        }
    </style>
</head>
<body>

    <div class="page-header">
    </div>

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

The footer html is:

```<code><!doctype html>
<html>
<head>
    <style>
        body {
            font-size: 12px;
            margin: 0;
            padding: 0;
        }

        .page-footer {
            background: #2A5266 -webkit-linear-gradient(
                left,
                #cbd5da 0,
                #cbd5da 50pt,
                white 50pt,
                white 75pt,
                #cbd5da 75pt,
                #cbd5da 100pt,
                white 100pt,
                white 125pt,
                #2A5266 125pt,
                #2A5266
            );
            height: 26pt;
            border: none;
            margin: 0;
            padding: 0;
            width: 100%;
            position: relative;
            display: block;
        }
    </style>
</head>
<body>

<div class="page-footer"></div>

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

And the command that I'm using is as follows:

```<code>wkhtmltopdf -L 0cm -R 0cm -T 2.75cm -B 0.7cm -O landscape --footer-html http://foo.com/footer --header-html http://foo.com/header --header-spacing 5 http://foo.com/html output.pdf
</code>```

Everything is working 100% correctly, but the header doesn't make use of the linear-gradient. Its almost like the linear-gradient is completely ignored, because the header is just a solid dark blue color. As you can see, the html for the header and footer are just about identical, so it doesn't make sense that it works for the footer, and not the header.

If I change the position:absolute on the header, then the header gradient appears, but that causes too many other issues.

答: In the end I used a table with an explicit width setting for each td element, and that works perfectly.</p>

Title: Wkhtmltopdf inconsistent output

Body:
I'm outputting some html via wkhtmltopdf, and using a custom header and footer.

The header html is as follows:

<!doctype html>

The footer html is:

<!doctype html>

And the command that I'm using is as follows:

wkhtmltopdf -L 0cm -R 0cm -T 2.75cm -B 0.7cm -O landscape --footer-html http://foo.com/footer --header-html http://foo.com/header --header-spacing 5 http://foo.com/html output.pdf

Everything is working 100% correctly, but the header doesn't make use of the linear-gradient. Its almost like the linear-gradient is completely ignored, because the header is just a solid dark blue color. As you can see, the html for the header and footer are just about identical, so it doesn't make sense that it works for the footer, and not the header.

If I change the position:absolute on the header, then the header gradient appears, but that causes too many other issues.


问:
Firebase google auth (swift)
Following the firebase docs i added the authentication with google account and this is part of the code that i have in my app delegate

```<code> func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {

        if let error = error {
            print("Failed to log into Google: ", error)
            return
        }
            print("Successfully logged into Google", user)
        guard let idToken = user.authentication.idToken else { return }
        guard let accessToken = user.authentication.accessToken else { return }
        let credentials = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)

        Auth.auth().signIn(with: credentials, completion: { (user, error) in
            if let err = error {
                print("Failed to create a Firebase User with Google account: ", err)
                return
            }

            guard let uid = user?.uid else { return }

            print("Successfully logged into Firebase with Google", uid)

        })
    }

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
        // Perform any operations when the user disconnects from app here.
        // ...
    }
</code>```

but the google button

```<code> fileprivate func setupGoogleButtons() {

        googleButton.frame = CGRect(x: 189, y: 532, width: 118, height: 41)
        view.addSubview(googleButton)

        GIDSignIn.sharedInstance().uiDelegate = self
}
</code>```

is obviously in a viewController, what i would like to do is an automatically self.performSegue(withIdentifier: "goToHome1", sender: self) as soon as the user logs in with his google account, because at the moment after login the user always finds on the same VC. How can i do this?

UPDATE

I solve my problem following this question Google and Facebook Firebase Auth using swift 3

答:
The Auth class has a function addAuthStateDidChangeListener:, check it here.

It will trigger any time the user changes, particularly when the user logs in, the callback will return a non-nil user. That's the time you want to perform the segue.

Title: Firebase google auth (swift)

Body:
Following the firebase docs i added the authentication with google account and this is part of the code that i have in my app delegate

 func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {

        if let error = error {
            print("Failed to log into Google: ", error)
            return
        }
            print("Successfully logged into Google", user)
        guard let idToken = user.authentication.idToken else { return }
        guard let accessToken = user.authentication.accessToken else { return }
        let credentials = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)

        Auth.auth().signIn(with: credentials, completion: { (user, error) in
            if let err = error {
                print("Failed to create a Firebase User with Google account: ", err)
                return
            }

            guard let uid = user?.uid else { return }

            print("Successfully logged into Firebase with Google", uid)

        })
    }

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
        // Perform any operations when the user disconnects from app here.
        // ...
    }

but the google button

 fileprivate func setupGoogleButtons() {

        googleButton.frame = CGRect(x: 189, y: 532, width: 118, height: 41)
        view.addSubview(googleButton)

        GIDSignIn.sharedInstance().uiDelegate = self
}

is obviously in a viewController, what i would like to do is an automatically self.performSegue(withIdentifier: "goToHome1", sender: self) as soon as the user logs in with his google account, because at the moment after login the user always finds on the same VC. How can i do this?

UPDATE

I solve my problem following this question Google and Facebook Firebase Auth using swift 3


问:
frequency count on considering four columns in r
currently i am trying to count frequency of set of sequence of data frame.

```<code>A  B
1  a
1  b
1  c
2  a
2  b
2  c
</code>```

i have this data frame and i would like to count frequency of "B" of another data frame looking like this

```<code>C  D
1  a
1  a
1  b
1  b
2  b
2  c
2  c
</code>```

As you can see the number of rows is different so datatable(counts) does not work. i would like to it to look like this after frequency count is done

```<code>a  b  freq
1  a   2
1  b   2
1  c   0
2  a   0
2  b   1
2  c   2
</code>```

As you can see it makes counts of all the frequency even the 0 as the on some groups there is no data on it.

thanks for anyone that helps!

答:
This looks to be a question of how to tabulate frequencies across two factors without dropping missing levels.

Here's the dplyr solution. This assumes that dfAB, as in your example data, contains no duplicates (dfAB is interchangeable with the output of expand.grid if you don't already have the level combinations in a data frame)

```<code>library(dplyr)
dfAB %>%
  # need at least one non-joining variable to tell matches from non-matches
  left_join(mutate(dfCD, dummy = 1), by = c("A" = "C", "B" = "D")) %>%
  group_by(A, B) %>%
  summarize(freq = sum(dummy, na.rm = TRUE))
</code>```

Output:

```<code># A tibble: 6 x 3
# Groups:   A [?]
      A     B  freq
  <dbl> <chr> <dbl>
1     1     a     2
2     1     b     2
3     1     c     0
4     2     a     0
5     2     b     1
6     2     c     2
</code>```

(if there are duplicates in dfAB, add a distinct call to the chain before the join)

Body:
currently i am trying to count frequency of set of sequence of data frame.

A  B
1  a
1  b
1  c
2  a
2  b
2  c

i have this data frame and i would like to count frequency of "B" of another data frame looking like this

C  D
1  a
1  a
1  b
1  b
2  b
2  c
2  c

As you can see the number of rows is different so datatable(counts) does not work. i would like to it to look like this after frequency count is done

a  b  freq
1  a   2
1  b   2
1  c   0
2  a   0
2  b   1
2  c   2

As you can see it makes counts of all the frequency even the 0 as the on some groups there is no data on it.

thanks for anyone that helps!

Body:
This looks to be a question of how to tabulate frequencies across two factors without dropping missing levels.

Here's the dplyr solution. This assumes that dfAB, as in your example data, contains no duplicates (dfAB is interchangeable with the output of expand.grid if you don't already have the level combinations in a data frame)

library(dplyr)
dfAB %>%
  # need at least one non-joining variable to tell matches from non-matches
  left_join(mutate(dfCD, dummy = 1), by = c("A" = "C", "B" = "D")) %>%
  group_by(A, B) %>%
  summarize(freq = sum(dummy, na.rm = TRUE))

Output:

# A tibble: 6 x 3
# Groups:   A [?]
      A     B  freq
  <dbl> <chr> <dbl>
1     1     a     2
2     1     b     2
3     1     c     0
4     2     a     0
5     2     b     1
6     2     c     2

(if there are duplicates in dfAB, add a distinct call to the chain before the join)


问:
randomizing a sequence in a 1d array in c
**This is not generating a number, it is rearranging the number in 1d array
Need help in randomizing the sequence of 0,1,2,3 number in rbox array. however when random, it shows 1,1,1,1 or 2,2,2,2 etc. anyone have idea how to randomize the sequence into 0,3,2,1 or 2,0,1,3 etc?</p>

```<code>srand(time(NULL));
int randomm = rand()%4;
int rbox[4];
int x;

for(x=0;x<4;x++)
{
    rbox[x] = 0;
}
for(x=0;x<4;x++)
{
    rbox[x] = randomm;
}
for(x=0;x<4;x++)
{
    printf("%i", rbox[x]);
}
</code>```

答:
Fill the array, then shuffle it and print the shuffled array.</p>

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

#define SIZE 4

int main() {
    int rbox[SIZE] = { 0};
    int loop = 0;
    int index = 0;
    int swap = 0;

    srand ( time( NULL));
    for ( loop = 0; loop < SIZE; loop++) {
        rbox[loop] = loop;
    }
    loop = SIZE;
    while ( loop) {
        index = rand ( ) % loop;
        loop--;
        swap = rbox[index];
        rbox[index] = rbox[loop];
        rbox[loop] = swap;;
    }
    for ( loop = 0; loop < SIZE; loop++) {
        printf ( "%d ", rbox[loop]);
    }
    printf ( "\n");

    return 0;
}
</code>```

Body:
**This is not generating a number, it is rearranging the number in 1d array
Need help in randomizing the sequence of 0,1,2,3 number in rbox array. however when random, it shows 1,1,1,1 or 2,2,2,2 etc. anyone have idea how to randomize the sequence into 0,3,2,1 or 2,0,1,3 etc?

srand(time(NULL));
int randomm = rand()%4;
int rbox[4];
int x;

for(x=0;x<4;x++)
{
    rbox[x] = 0;
}
for(x=0;x<4;x++)
{
    rbox[x] = randomm;
}
for(x=0;x<4;x++)
{
    printf("%i", rbox[x]);
}

Body:
Fill the array, then shuffle it and print the shuffled array.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SIZE 4

int main() {
    int rbox[SIZE] = { 0};
    int loop = 0;
    int index = 0;
    int swap = 0;

    srand ( time( NULL));
    for ( loop = 0; loop < SIZE; loop++) {
        rbox[loop] = loop;
    }
    loop = SIZE;
    while ( loop) {
        index = rand ( ) % loop;
        loop--;
        swap = rbox[index];
        rbox[index] = rbox[loop];
        rbox[loop] = swap;;
    }
    for ( loop = 0; loop < SIZE; loop++) {
        printf ( "%d ", rbox[loop]);
    }
    printf ( "\n");

    return 0;
}


问:
Xcode 7 UI Testing: Dismiss Push and Location alerts
I encountered a problem with Xcode 7 UI Testing.

The app displays two alerts after my user logs in, the Request Location Alert and the Push Notifications Alert. Those notifications are shown one right after the other. The Location one appears first.

I try to dismiss them automatically to start my tests.

In order to do that, I add two UIInterruptionMonitor, the first one for the Location Alert and the second one for the Notification Push Alert.

```<code>    addUIInterruptionMonitorWithDescription("Location Dialog") { (alert) -> Bool in
        /* Dismiss Location Dialog */
        if alert.collectionViews.buttons["Allow"].exists {
            alert.collectionViews.buttons["Allow"].tap()
            return true
        }
        return false
    }
    addUIInterruptionMonitorWithDescription("Push Dialog") { (alert) -> Bool in
        /* Dismiss Push Dialog */
        if alert.collectionViews.buttons["OK"].exists {
            alert.collectionViews.buttons["OK"].tap()
            return true
        }
        return false
    }
</code>```

But only the Location one is triggered, the handler of Push Notifications UIInterruptionMonitor is never called.

If I return true in the Request Location UIInterruptionMonitor as this other post accepted answer specifies. Both handler are called but the alert parameter in both UIInterruptionMonitor links to the Request Location Alert View so the "OK" button is never found.

How can I dismiss those two successive alerts views?

答:
```<code>class BaseTest: XCTestCase {
    let pushSent = NSNotification.Name.init("alert.pushSent")
    var notificationMonitor: NSObjectProtocol?

    override func setUp() {
        listenNotifications()
        let app = XCUIApplication()

        notificationMonitor = addUIInterruptionMonitor(withDescription: "Push Notifications") { [unowned self] (alert) -> Bool in
            let btnAllow = app.buttons["Allow"]
            //1:
            if btnAllow.exists {
                btnAllow.tap()
                NotificationCenter.default.post(name: self.pushSent, object: nil)
                return true
            }
            //2:
            //takeScreenshot
            XCTFail("Unexpected System Alert")
            return false
        }
        //3:
        //add code for "Request Location" monitor

        app.launchEnvironment = ["UITEST_DISABLE_ANIMATIONS" : "YES"]
        //4:
        app.launch()

    }

    func listenNotifications() {
        NotificationCenter.default.addObserver(forName: pushSent, object: nil, queue: nil) { (notification) in
            if let locationDialogHandeler = self.notificationMonitor {
                //5:
                self.removeUIInterruptionMonitor(locationDialogHandeler)
            }
        }
    }
}
</code>```

1: Check if you're in the correct alert, tap the button and find a way to remove the monitor (I'm using NotificationCenter)

2: If you enter a monitor and can not find the right button, it means it's an unexpected flow. Fail the test (but take a screenshot first).

3: Add other monitors

4: I am adding monitor even before launching the app. If you add a monitor after the alert appears, it will not be triggered.

5: Remove the monitor, that way when a new alert appears, the next monitor in the stack will be called.

P.S: You should add monitors in reverse order, therefore, add "Request Location" after "Push Notifications"

Body:
I encountered a problem with Xcode 7 UI Testing.

The app displays two alerts after my user logs in, the Request Location Alert and the Push Notifications Alert. Those notifications are shown one right after the other. The Location one appears first.

I try to dismiss them automatically to start my tests.

In order to do that, I add two UIInterruptionMonitor, the first one for the Location Alert and the second one for the Notification Push Alert.

    addUIInterruptionMonitorWithDescription("Location Dialog") { (alert) -> Bool in
        /* Dismiss Location Dialog */
        if alert.collectionViews.buttons["Allow"].exists {
            alert.collectionViews.buttons["Allow"].tap()
            return true
        }
        return false
    }
    addUIInterruptionMonitorWithDescription("Push Dialog") { (alert) -> Bool in
        /* Dismiss Push Dialog */
        if alert.collectionViews.buttons["OK"].exists {
            alert.collectionViews.buttons["OK"].tap()
            return true
        }
        return false
    }

But only the Location one is triggered, the handler of Push Notifications UIInterruptionMonitor is never called.

If I return true in the Request Location UIInterruptionMonitor as this other post accepted answer specifies. Both handler are called but the alert parameter in both UIInterruptionMonitor links to the Request Location Alert View so the "OK" button is never found.

How can I dismiss those two successive alerts views?

Body:
class BaseTest: XCTestCase {
    let pushSent = NSNotification.Name.init("alert.pushSent")
    var notificationMonitor: NSObjectProtocol?

    override func setUp() {
        listenNotifications()
        let app = XCUIApplication()

        notificationMonitor = addUIInterruptionMonitor(withDescription: "Push Notifications") { [unowned self] (alert) -> Bool in
            let btnAllow = app.buttons["Allow"]
            //1:
            if btnAllow.exists {
                btnAllow.tap()
                NotificationCenter.default.post(name: self.pushSent, object: nil)
                return true
            }
            //2:
            //takeScreenshot
            XCTFail("Unexpected System Alert")
            return false
        }
        //3:
        //add code for "Request Location" monitor

        app.launchEnvironment = ["UITEST_DISABLE_ANIMATIONS" : "YES"]
        //4:
        app.launch()

    }

    func listenNotifications() {
        NotificationCenter.default.addObserver(forName: pushSent, object: nil, queue: nil) { (notification) in
            if let locationDialogHandeler = self.notificationMonitor {
                //5:
                self.removeUIInterruptionMonitor(locationDialogHandeler)
            }
        }
    }
}

1: Check if you're in the correct alert, tap the button and find a way to remove the monitor (I'm using NotificationCenter)

2: If you enter a monitor and can not find the right button, it means it's an unexpected flow. Fail the test (but take a screenshot first).

3: Add other monitors

4: I am adding monitor even before launching the app. If you add a monitor after the alert appears, it will not be triggered.

5: Remove the monitor, that way when a new alert appears, the next monitor in the stack will be called.

P.S: You should add monitors in reverse order, therefore, add "Request Location" after "Push Notifications"


问:
How to use customize 404.html from decorator.py in django?
I have 4 types of user; client, officer, production_manager, service_manager. Therefore, I was creating 4 groups for each user. These users are my 4 apps in my project. In the corresponding views.py, in the methods, I'm using a decorator to give access only to a certain user, like this @group_required('client_group'). Here is my decorator method:

check_group.py

```<code>def group_required(*group_names):
    """Requires user membership in at least one of the groups passed in."""
    def in_groups(u):
        if u.is_authenticated():
            if bool(u.groups.filter(name__in=group_names)) | u.is_superuser:
                return True
        raise Http404
    return user_passes_test(in_groups)
</code>```

Now if a client is logged in and trying to access a certain view from url , like, officer/password, then he cannot get access of that view. I am using raise HTTP404.

This is the structure of my project:

```<code>project
|-app
|-app
|-app
|-app
|-user_group
|--|--check_group.py
|--|--404.html
</code>```

But the 404 page shown by django is its default. It's not taking my 404.html.

Then in the check_group.py, I changed the code form my raise Http404 to

template = loader.get_template("404.html")
return HttpResponse(template.render())

But then I'm getting an error

officer/password doesn't contain any template 404.html

Then I put 404.html in the officer/template but still getting the same error.

I want to use my customize 404.html rather than django's built-in 404 from the decorator method, I mean, the method I wrote, check_group.py.

How can I do it?

答:
You can do that by specifying handler in urls.py

```<code>handler404 = 'user_group.views.handler404'
</code>```

Then you define view to render custom 404 html

```<code>def handler404(request):
    return render(request, '404.html')
</code>```

Here is the documentation on customizing error views.

Body:
I have 4 types of user; client, officer, production_manager, service_manager. Therefore, I was creating 4 groups for each user. These users are my 4 apps in my project. In the corresponding views.py, in the methods, I'm using a decorator to give access only to a certain user, like this @group_required('client_group'). Here is my decorator method:

check_group.py

def group_required(*group_names):
    """Requires user membership in at least one of the groups passed in."""
    def in_groups(u):
        if u.is_authenticated():
            if bool(u.groups.filter(name__in=group_names)) | u.is_superuser:
                return True
        raise Http404
    return user_passes_test(in_groups)

Now if a client is logged in and trying to access a certain view from url , like, officer/password, then he cannot get access of that view. I am using raise HTTP404.

This is the structure of my project:

project
|-app
|-app
|-app
|-app
|-user_group
|--|--check_group.py
|--|--404.html

But the 404 page shown by django is its default. It's not taking my 404.html.

Then in the check_group.py, I changed the code form my raise Http404 to

template = loader.get_template("404.html")
return HttpResponse(template.render())

But then I'm getting an error

officer/password doesn't contain any template 404.html

Then I put 404.html in the officer/template but still getting the same error.

I want to use my customize 404.html rather than django's built-in 404 from the decorator method, I mean, the method I wrote, check_group.py.

How can I do it?

Body:
You can do that by specifying handler in urls.py

handler404 = 'user_group.views.handler404'

Then you define view to render custom 404 html

def handler404(request):
    return render(request, '404.html')

Here is the documentation on customizing error views.


问:
How to save form data that include image using nodejs posted using angular 2
I am creating a application using mean stack, in which i am using angular 2 for the client side. I had created a form that contain some input fields and a image. Now, for submitting the form i am using formdata to send data to the node server. now I am unable to show, access and save the data at the node server. Please somebody help me as I am new to mean stack.

data array:

```<code>const newProduct = {
    category: this.pcategory,
    name: this.name,
    description: this.description,
    price: this.price,
    quantity: this.quantity,
    image: this.fileName
}
</code>```

here is the code for sending data:
imagedata contain the data of the file

```<code>addProduct(newProduct, imagedata:File) {
    let formData: FormData = new FormData();
    formData.append('body', JSON.stringify(newProduct));
    formData.append('file', image, newProduct.imagedata);
    let headers = new Headers();
    headers.append("enctype", "multipart/form-data");
    headers.append("Accept", "application/json");
    let options = new RequestOptions({ headers: headers });
    return this.http.post('http://localhost:3000/product/add' ,formData, options).map((response: Response) => response.json());
}
</code>```

here is the code for receiving and saving data:

```<code>function (req, res) {

        var storage = multer.diskStorage({//multers disk storage settings

            destination: function (req, file, callback) {

                callback(null, './uploads');

            }

        });
        var upload = multer({//multer settings

            storage: storage

        }).any();

        var model = new Model(req.body);
        model.save(function (err) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.status(201).json(model);
            }
        });
        upload(req, res, function (err) {
            if (err) {
                // An error occurred when uploading
                console.log(err);
                return res.status(422).send("an Error occured")
            }
        });
    }
</code>```

答:
In angular 2 you cannot upload image with this approach consider using this Angular 2 module ng2-file-uploader. You can see the demo app here Angular File Uploads with an Express Backend
.</p>

Body:
I am creating a application using mean stack, in which i am using angular 2 for the client side. I had created a form that contain some input fields and a image. Now, for submitting the form i am using formdata to send data to the node server. now I am unable to show, access and save the data at the node server. Please somebody help me as I am new to mean stack.

data array:

const newProduct = {
    category: this.pcategory,
    name: this.name,
    description: this.description,
    price: this.price,
    quantity: this.quantity,
    image: this.fileName
}

here is the code for sending data:
imagedata contain the data of the file

addProduct(newProduct, imagedata:File) {
    let formData: FormData = new FormData();
    formData.append('body', JSON.stringify(newProduct));
    formData.append('file', image, newProduct.imagedata);
    let headers = new Headers();
    headers.append("enctype", "multipart/form-data");
    headers.append("Accept", "application/json");
    let options = new RequestOptions({ headers: headers });
    return this.http.post('http://localhost:3000/product/add' ,formData, options).map((response: Response) => response.json());
}

here is the code for receiving and saving data:

function (req, res) {

        var storage = multer.diskStorage({//multers disk storage settings

            destination: function (req, file, callback) {

                callback(null, './uploads');

            }

        });
        var upload = multer({//multer settings

            storage: storage

        }).any();

        var model = new Model(req.body);
        model.save(function (err) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.status(201).json(model);
            }
        });
        upload(req, res, function (err) {
            if (err) {
                // An error occurred when uploading
                console.log(err);
                return res.status(422).send("an Error occured")
            }
        });
    }


问:
how to merge a collection of Maps using streams
I have a collection of maps:

```<code>Collection<Map<String,Double>> myCol = table.values();
</code>```

I would like to transform this into a Map

```<code>Map<String, Double>
</code>```

such that, for a matching key, values are summed up. Using a for loop, it is rather simple:

```<code>Map<String, Double> outMap = new HashMap<>();
for (Map<String, Double> map : myCol) {
    outMap =  mergeMaps(outMap, map);
}
</code>```

and mergeMaps() is defined as

```<code>mergeMaps(Map<String, Double> m1, Map<String, Double> m2){
    Map<String, Double> outMap = new TreeMap<>(m1);
    m2.forEach((k,v) -> outMap.merge(k,v,Double::sum)); /*sum values if key exists*/
    return outMap;
}
</code>```

However, I would like to use streams to get a map from collection. I have tried as follows:

```<code>Map<String, Double> outMap = new HashMap<>();
myCol.stream().forEach(e-> outMap.putAll(mergeMaps(outMap,e)));
return outMap;
</code>```

This works without a problem. However, can I still improve it? I mean, how can I use collectors in it?

答:
Well, the other proposed solutions show that a pure stream solution is short, but if you wanted to use your existing mergeFunction (because in other cases it is more complex for example), you could just hand it over to Stream.reduce:

```<code>Optional<Map<String, Double>> outMap = myCol.stream().reduce((m1, m2) -> mergeMaps(m1, m2));
</code>```

Your initial approach with the forEach is pretty much a streamyfied for loop and violates the concept of functions having no side effects. The reduce (or the above collects) handles all the data merging internally, without changing the input collection.

Body:
I have a collection of maps:

Collection<Map<String,Double>> myCol = table.values();

I would like to transform this into a Map

Map<String, Double>

such that, for a matching key, values are summed up. Using a for loop, it is rather simple:

Map<String, Double> outMap = new HashMap<>();
for (Map<String, Double> map : myCol) {
    outMap =  mergeMaps(outMap, map);
}

and mergeMaps() is defined as

mergeMaps(Map<String, Double> m1, Map<String, Double> m2){
    Map<String, Double> outMap = new TreeMap<>(m1);
    m2.forEach((k,v) -> outMap.merge(k,v,Double::sum)); /*sum values if key exists*/
    return outMap;
}

However, I would like to use streams to get a map from collection. I have tried as follows:

Map<String, Double> outMap = new HashMap<>();
myCol.stream().forEach(e-> outMap.putAll(mergeMaps(outMap,e)));
return outMap;

This works without a problem. However, can I still improve it? I mean, how can I use collectors in it?

Body:
Well, the other proposed solutions show that a pure stream solution is short, but if you wanted to use your existing mergeFunction (because in other cases it is more complex for example), you could just hand it over to Stream.reduce:

Optional<Map<String, Double>> outMap = myCol.stream().reduce((m1, m2) -> mergeMaps(m1, m2));

Your initial approach with the forEach is pretty much a streamyfied for loop and violates the concept of functions having no side effects. The reduce (or the above collects) handles all the data merging internally, without changing the input collection.


问:
How to feed with 2 or more inputs a Neural Network in Matlab
I want to feed a Neural Network with more than one input (using the Matlab tool Box).

If I declare the input vector like P = [1 2 3 4; 1 2 3 4; 1 2 3 4;1 2 3 4], the target as T = [1 2 3 4] and then the network as net = newff(P,T,1);, when I look at the network parameters it says numInputs: 1, while in my mind the number of inputs should be 3 (one for each row).

My question is: how to feed the network with 3 separated inputs?

Thanks in advance,
Regards
G.B.

答:
You have to distinguish between the following parameters:

The dimension of the input vector to the neural network. In your example, the first layer has one input vector of dimension 4. This parameter is called R in Matlab's documentation.

The number of different inputs to the network, which is how many sets of vectors are input to the network. From the Neural Network Toolbox doc's:

net.numInputs
  This property defines
  the number of inputs a network
  receives. It can be set to 0 or a
  positive integer. Clarification: The
  number of network inputs and the size
  of a network input are not the same
  thing. The number of inputs defines
  how many sets of vectors the network
  receives as input. The size of each
  input (i.e., the number of elements in
  each input vector) is determined by
  the input size (net.inputs{i}.size).
  Most networks have only one input,
  whose size is determined by the
  problem.

The number of samples of the input which is given to the network. In your example, you have 3 samples of 4-dimensional vectors.

With this in mind, if you meant to feed the network with 3 samples, then your code is ok. If, on the other hand, you really need 3 different sets of inputs, you can manually change the numInputs parameter in your network, or you can create a custom network:

```<code>net = network(numInputs,numLayers,biasConnect,inputConnect, layerConnect,outputConnect);
</code>```

with the number of inputs numInputs as you need, but them you need to customize it yourself. You can read more about it here: http://www.mathworks.com/help/toolbox/nnet/network.html#667825

ContentLicense: CC BY-SA 2.5

Body:
You have to distinguish between the following parameters:

The dimension of the input vector to the neural network. In your example, the first layer has one input vector of dimension 4. This parameter is called R in Matlab's documentation.

The number of different inputs to the network, which is how many sets of vectors are input to the network. From the Neural Network Toolbox doc's:

net.numInputs
  This property defines
  the number of inputs a network
  receives. It can be set to 0 or a
  positive integer. Clarification: The
  number of network inputs and the size
  of a network input are not the same
  thing. The number of inputs defines
  how many sets of vectors the network
  receives as input. The size of each
  input (i.e., the number of elements in
  each input vector) is determined by
  the input size (net.inputs{i}.size).
  Most networks have only one input,
  whose size is determined by the
  problem.

The number of samples of the input which is given to the network. In your example, you have 3 samples of 4-dimensional vectors.

With this in mind, if you meant to feed the network with 3 samples, then your code is ok. If, on the other hand, you really need 3 different sets of inputs, you can manually change the numInputs parameter in your network, or you can create a custom network:

net = network(numInputs,numLayers,biasConnect,inputConnect, layerConnect,outputConnect);

with the number of inputs numInputs as you need, but them you need to customize it yourself. You can read more about it here: http://www.mathworks.com/help/toolbox/nnet/network.html#667825


问:
Shell invoked via SQLPLUS.exe HOST command on MSWindows
How does SQLPLUS know which program to invoke (on MS Windows) when the user supplies a HOST command? </p>

<p>(I am looking to replace cmd.exe with something more restrictive, but would rather not break the existing MSWindows installation)</p>

答:
Identifying the Shell for SQL*Plus

To identify the shell that SQL*Plus will use when invoking the HOST command, it states to set the environment variable, SHELL. This is the 12c documentation.

My answer will focus on changing the shell to powershell.

On Windows 7 with Powershell 5.1, I can invoke this command to set my environment variable, SHELL, systemically for my laptop:

[Environment]::SetEnvironmentVariable("SHELL", "powershell.exe" , "Machine")

Next, I start a SQL*Plus session and I invoke the host command, host %shell% get-host.  Here is my execution of this command.

```<code>SCOTT@db>host %shell% get-host

Name             : ConsoleHost
Version          : 5.1.14409.1012
InstanceId       : b2585ba7-ea5f-452f-ba4f-d3dfc3032890
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace
</code>```

Intuitively, one would expect to invoke host followed by a shell command (e.g. in my case a powershell command), but this fails:

```<code>SCOTT@db>host get-host
'get-host' is not recognized as an internal or external command,
operable program or batch file.
</code>```

Based on these results and removing the need to set the SHELL environment variable, this would be similar to my other host invocation:

```<code>SCOTT@db>host powershell get-host

Name             : ConsoleHost
Version          : 5.1.14409.1012
InstanceId       : 305716aa-30dc-4ef8-9184-0cfce94254e5
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace
</code>```

Summary

Perhaps having the environment variable, SHELL, identified as a non-default shell works on some non-Windows 7 operating system, this set-up based on documentation has not made a difference.

Outside of SQL*Plus settings and changing environment variables, if you are considering changing the default shell in general on Windows, I see these options:

-Change group policy (e.g. see this link)

-Modify appropriate registry keys based on Microsoft Developer Network's directions.  There are a number of important notes on this link and you need to make sure these directions correspond with the Windows version you are working with.

Body:
How does SQLPLUS know which program to invoke (on MS Windows) when the user supplies a HOST command?

(I am looking to replace cmd.exe with something more restrictive, but would rather not break the existing MSWindows installation)

Body:
Identifying the Shell for SQL*Plus

To identify the shell that SQL*Plus will use when invoking the HOST command, it states to set the environment variable, SHELL. This is the 12c documentation.

My answer will focus on changing the shell to powershell.

On Windows 7 with Powershell 5.1, I can invoke this command to set my environment variable, SHELL, systemically for my laptop:

[Environment]::SetEnvironmentVariable("SHELL", "powershell.exe" , "Machine")

Next, I start a SQL*Plus session and I invoke the host command, host %shell% get-host.  Here is my execution of this command.

SCOTT@db>host %shell% get-host

Name             : ConsoleHost
Version          : 5.1.14409.1012
InstanceId       : b2585ba7-ea5f-452f-ba4f-d3dfc3032890
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

Intuitively, one would expect to invoke host followed by a shell command (e.g. in my case a powershell command), but this fails:

SCOTT@db>host get-host
'get-host' is not recognized as an internal or external command,
operable program or batch file.

Based on these results and removing the need to set the SHELL environment variable, this would be similar to my other host invocation:

SCOTT@db>host powershell get-host

Name             : ConsoleHost
Version          : 5.1.14409.1012
InstanceId       : 305716aa-30dc-4ef8-9184-0cfce94254e5
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

Summary

Perhaps having the environment variable, SHELL, identified as a non-default shell works on some non-Windows 7 operating system, this set-up based on documentation has not made a difference.

Outside of SQL*Plus settings and changing environment variables, if you are considering changing the default shell in general on Windows, I see these options:

-Change group policy (e.g. see this link)

-Modify appropriate registry keys based on Microsoft Developer Network's directions.  There are a number of important notes on this link and you need to make sure these directions correspond with the Windows version you are working with.


问:
Cannot import module - why does sys.path not find PYTHONPATH?
I am running Python 3.6.1 on a Windows 7 machine. I have some scripts in H:\Myname\Python\myscripts.

I have created the user variable PYTHONPATH and set it to the folder above. I do not have admin rights so I can create a user variable only.

In that folder, I have a myscripts.py file with some functions.

If I try to access it running import myscripts from a file stored elsewhere, it doesn't work: I get a ModuleNotFoundError

If I print sys.path, the folder I have set in PYTHONPATH is not there.

Why? What am I doing wrong? Isn't sys.path supposed to show PYTHONPATH?
Does the fact that H is a network drive have anything to do with it?

I can't seem to find anything on the web for this problem in relation to Windows (but lots for Unix systems).

答:
A common way to fix this quickly is to use

sys.path.append("path/to/module")

Be careful with '\\' if you are using Windows.

Not exactly answering your question but this could fix the problem.

ContentLicense: CC BY-SA 4.0


问:
How to have a public/private git repository with pull request among the two
I have a public repository on github and each user of my group has a fork of it. The policy is that committing directly to the main repo is forbidden and all the changes must come in as pull requests from the forks so that they can be reviewed before being merged to the main repo.

Given that sometimes we develop code that must stay private for a certain period before going public in the main repo, I would like to have the following situation:

Main repo public

Forks private

Be able to make pull requests from the forks to the main repo

Keep things easy, given that some user are git beginners

Now, on Github this is not possible because private forks are not allowed.

What strategy can I use to achieve a similar behavior?

答:
I just did something similar to this.
The solution what worked for me was to create a new private Repo as a bare clone of your main repo, and push the all the new changes to this private repo, and once the changes are ready to be made public, push the changes to the public repo.

I followed the steps from : Answer to this question by: Martin Konicek

Duplicate the repo (details here):

Create a new repo (private-repo) via the Github UI. Then:

git clone --bare https://github.com/exampleuser/public-repo.git
cd public-repo.git
git push --mirror https://github.com/yourname/private-repo.git
cd ..
rm -rf public-repo.git

Clone the private repo so you can work on it:

git clone https://github.com/yourname/private-repo.git
cd private-repo
make some changes
git commit
git push origin master

To pull new changes from the public repo:

cd private-repo
git remote add public https://github.com/exampleuser/public-repo.git
git pull public master # Creates a merge commit
git push origin master

The private repo now has the latest code from the public repo plus your changes.

Create a pull request private repo -> public repo:

Ceating a pull request requires push access to the public repo because you need to push to a branch there (here's why).

```<code>git clone https://github.com/exampleuser/public-repo.git
cd public-repo
git remote add private_repo https://github.com/yourname/private-repo.git
git checkout -b pull_request_branch
git pull private_repo master
git push origin pull_request_branch
</code>```

Now simply create a pull request via the Github UI for public-repo, as described here.

Once project you review the pull request, you can merge it.

After the first time you just have to pull from the required remote (Public or Private) and push to the (private). Once done with the changes, push the changes to (Private : to keep it up to date) and some branch on Public so a pull request to master can be created.

Body:
I just did something similar to this.
The solution what worked for me was to create a new private Repo as a bare clone of your main repo, and push the all the new changes to this private repo, and once the changes are ready to be made public, push the changes to the public repo.

I followed the steps from : Answer to this question by: Martin Konicek

Duplicate the repo (details here):

Create a new repo (private-repo) via the Github UI. Then:

git clone --bare https://github.com/exampleuser/public-repo.git
cd public-repo.git
git push --mirror https://github.com/yourname/private-repo.git
cd ..
rm -rf public-repo.git

Clone the private repo so you can work on it:

git clone https://github.com/yourname/private-repo.git
cd private-repo
make some changes
git commit
git push origin master

To pull new changes from the public repo:

cd private-repo
git remote add public https://github.com/exampleuser/public-repo.git
git pull public master # Creates a merge commit
git push origin master

The private repo now has the latest code from the public repo plus your changes.

Create a pull request private repo -> public repo:

Ceating a pull request requires push access to the public repo because you need to push to a branch there (here's why).

git clone https://github.com/exampleuser/public-repo.git
cd public-repo
git remote add private_repo https://github.com/yourname/private-repo.git
git checkout -b pull_request_branch
git pull private_repo master
git push origin pull_request_branch

Now simply create a pull request via the Github UI for public-repo, as described here.

Once project you review the pull request, you can merge it.

After the first time you just have to pull from the required remote (Public or Private) and push to the (private). Once done with the changes, push the changes to (Private : to keep it up to date) and some branch on Public so a pull request to master can be created.


问:
Vue.js - Detect Nested Property Value Changes
I'm dynamically binding to an Array of objects in a Vue.js 2.0 app. I want to respond to changes as values in that Array change. At this time, as shown in this Fiddle, I have the following:

html

```<code><div id="app">
  <table>
    <thead>
      <tr>
        <th v-for="(col, index) in cols">
          <input :placeholder="col.title" v-model="inputValues[col.prop]" />
        </th>
      </tr>
    </thead>

    <tbody>
      <tr v-for="(item, index) in items">
        <td>{{ item.name }}</td>
        <td>{{ item.age }}</td>
        <td>{{ item.birthday }}</td>
      </tr>
    </tbody>
  </table>

  <hr />
  <textarea>{{ inputValues }}</textarea>
</div>
</code>```

javascript

```<code>new Vue({
  el: '#app',
  data: {
    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' },
    ],

    inputValues: [],

    items: [
      { id:1, name:'Andreas Winchell', age:47, birthday:'08-04-1970' },
      { id:2, name:'Victoria Hodges', age:80, birthday:'01-24-1937' },
      { id:2, name:'James Morris', age:59, birthday:'06-14-1958' },
      { id:2, name:'Larry Walker', age:68, birthday:'08-07-1949' },
      { id:2, name:'Lee Maynard', age:46, birthday:'04-17-1971' }
    ]
  },

  methods: {
    buttonClick: function() {
      alert(JSON.stringify(this.inputValues));
    }
  }
})
</code>```

I can't seem to find a way to bind to changes in any of the values entered into the header. How do I detect and react to property values changes in an Array?

答:
Update 2022

Vue 3 will detect all changes in a reactive array. Square bracket syntax is no longer a limitation.

You can use arrays in your data, but Vue will not detect direct changes to the array referencing an item by its index. Vue will detect changes made with push(), pop(), slice() etc.

Arrays like 'Cols' are a disaster. 'Name', 'Age' and 'Birthday' are code (property names), not data. You really don't want to be iterating over an array generating forms like this. Keep it simple and code your three inputs.

Body:
I'm dynamically binding to an Array of objects in a Vue.js 2.0 app. I want to respond to changes as values in that Array change. At this time, as shown in this Fiddle, I have the following:

html

          <input :placeholder="col.title" v-model="inputValues[col.prop]" />

        {{ item.name }}
        {{ item.age }}
        {{ item.birthday }}

  <textarea>{{ inputValues }}</textarea>

javascript

new Vue({
  el: '#app',
  data: {
    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' },
    ],

    inputValues: [],

    items: [
      { id:1, name:'Andreas Winchell', age:47, birthday:'08-04-1970' },
      { id:2, name:'Victoria Hodges', age:80, birthday:'01-24-1937' },
      { id:2, name:'James Morris', age:59, birthday:'06-14-1958' },
      { id:2, name:'Larry Walker', age:68, birthday:'08-07-1949' },
      { id:2, name:'Lee Maynard', age:46, birthday:'04-17-1971' }
    ]
  },

  methods: {
    buttonClick: function() {
      alert(JSON.stringify(this.inputValues));
    }
  }
})

I can't seem to find a way to bind to changes in any of the values entered into the header. How do I detect and react to property values changes in an Array?


问:
Opening a file in a Metro app from command line
I need a way to open a file in a Metro app from command line.

So far I've figured out how to start the app from command line without any third-party scripts

```<code>explorer shell:AppsFolder\Microsoft.Reader_8wekyb3d8bbwe!Microsoft.Reader
</code>```

but I haven't been able to figure out how to include a file name yet.

Launching

```<code>explorer shell:AppsFolder\Microsoft.Reader_8wekyb3d8bbwe!Microsoft.Reader example.pdf
</code>```

just opens up a default explorer window.

Any idea from Windows 8 experts on how to accomplish this without any third-party tools/cmdlets/etc.?

Note: In fact I'm using Windows 10 but I guess if there's a Windows 8 / 8.1 way to do it, it'll work for 10, too.

答:
Not sure if it works on Windows 8, but on Windows 10 I use this:

```<code>cmd /C start <app-name>:
</code>```

For example, to start Slack:

```<code>cmd /C start slack:
</code>```

Body:
I need a way to open a file in a Metro app from command line.

So far I've figured out how to start the app from command line without any third-party scripts

explorer shell:AppsFolder\Microsoft.Reader_8wekyb3d8bbwe!Microsoft.Reader

but I haven't been able to figure out how to include a file name yet.

Launching

explorer shell:AppsFolder\Microsoft.Reader_8wekyb3d8bbwe!Microsoft.Reader example.pdf

just opens up a default explorer window.

Any idea from Windows 8 experts on how to accomplish this without any third-party tools/cmdlets/etc.?

Note: In fact I'm using Windows 10 but I guess if there's a Windows 8 / 8.1 way to do it, it'll work for 10, too.

Body:
Not sure if it works on Windows 8, but on Windows 10 I use this:

cmd /C start <app-name>:

For example, to start Slack:

cmd /C start slack:


问:
How can I be sure a constructor function only runs once?
Is there any way for this code in the constructor of my service TranslatorService is calling just one time for all application or on demande, and not all time homecomponent is load ????

```<code>this.translations$ = translationsCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        ...
      })
</code>```

translation class for my translate retrive from firestore ex:

```<code>{
  "WELCOME": {
   "FR": "bienvenue",
   "GB": "Welcome"
 }
}

export interface Translation {
    [code: string]: TranslationInfo;

}

export interface TranslationInfo {
    [language: string]: string;
}
</code>```

my core module

```<code>import { NgModule } from '@angular/core';
import { AuthService } from './auth.service';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { TranslatorService } from '../services/translator.service';
@NgModule({
imports: [
    AngularFireAuthModule,
    AngularFirestoreModule
],
providers: [AuthService, TranslatorService]
})
export class CoreModule { }
</code>```

injected in appmodule

```<code>@NgModule({
declarations: [
...

],
imports: [
...
    CoreModule,
...
],
providers: [AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

my translator service

```<code>    @Injectable()
export class TranslatorService {

  translationsCollection: AngularFirestoreCollection<Translation>;
  translations$: Observable<any>;
  public translations: Translation[];

  constructor(private afs: AngularFirestore) {
    var translationsCollection = this.afs.collection("translations");
    this.translations$ = translationsCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        ...
      })
    });
</code>```

my component

```<code>    export class HomeComponent implements OnInit {
translations$: Observable<any>;
constructor(private translator: TranslatorService) { }

ngOnInit() {
    this.translations$ = this.translator.translations$;
}
</code>```

my component view

```<code><div *ngFor="let translation of translations$|async">
```{{translation | json}}```
</div>
</code>```

答:
I have done something similar in one of my projects. You just need to move your translation code one level above. i.e.

Make a component called translation component which wraps all the components and put your logic in it. That way it will be loaded only once through the application life cycle.

You route config should then look something as follows:

```<code>const routes: Routes = [
    {
        path: '', component: LanguageComponent,
        children: [
            { path: '', component: HomeComponent },
            { path: 'login', component: LoginComponent },
        ]
    }
];
</code>```

Basically all your application is wrapped into Language component.

Body:
Is there any way for this code in the constructor of my service TranslatorService is calling just one time for all application or on demande, and not all time homecomponent is load ????

this.translations$ = translationsCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        ...
      })

translation class for my translate retrive from firestore ex:

{
  "WELCOME": {
   "FR": "bienvenue",
   "GB": "Welcome"
 }
}

export interface Translation {
    [code: string]: TranslationInfo;

}

export interface TranslationInfo {
    [language: string]: string;
}

my core module

import { NgModule } from '@angular/core';
import { AuthService } from './auth.service';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { TranslatorService } from '../services/translator.service';
@NgModule({
imports: [
    AngularFireAuthModule,
    AngularFirestoreModule
],
providers: [AuthService, TranslatorService]
})
export class CoreModule { }

injected in appmodule

@NgModule({
declarations: [
...

],
imports: [
...
    CoreModule,
...
],
providers: [AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }

my translator service

    @Injectable()
export class TranslatorService {

  translationsCollection: AngularFirestoreCollection<Translation>;
  translations$: Observable<any>;
  public translations: Translation[];

  constructor(private afs: AngularFirestore) {
    var translationsCollection = this.afs.collection("translations");
    this.translations$ = translationsCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        ...
      })
    });

my component

    export class HomeComponent implements OnInit {
translations$: Observable<any>;
constructor(private translator: TranslatorService) { }

ngOnInit() {
    this.translations$ = this.translator.translations$;
}

my component view

{{translation | json}}

Body:
I have done something similar in one of my projects. You just need to move your translation code one level above. i.e.

Make a component called translation component which wraps all the components and put your logic in it. That way it will be loaded only once through the application life cycle.

You route config should then look something as follows:

const routes: Routes = [
    {
        path: '', component: LanguageComponent,
        children: [
            { path: '', component: HomeComponent },
            { path: 'login', component: LoginComponent },
        ]
    }
];

Basically all your application is wrapped into Language component.


问:
AngularJS Ng-model-options not able to select object in getter-setter function
I have a problem selecting an object from ng-model with ng-model-options and getter-setter function. I am binding to the ng-model getter-setter function setGetSelectedItem which has to accept an object from ng-options - in my case, item and to assign its properies to the properties of another object specific_data. It does, the object is passed correctly but I am not able to select the option in the select options.

```<code><select name="item" ng-model="setGetSelectedItem"
        ng-options="item as item.title for item in items"
        ng-model-options="{getterSetter: true}">
  <option value="">-- Please select --</option>
</select>
</code>```

And in the controller:

```<code>$scope.items = [{

"description": "Item description",
  "item_type": "OUT",
  "id": 1,
  "title": "Default item"
}];

$scope._objectDataRaw = {
  specific_data: {}
};

$scope.setGetSelectedItem = function(value) {

if (arguments.length) {
  $scope._objectDataRaw.specific_data.property_id = value.id;
  $scope._objectDataRaw.specific_data.property_title = value.title;
  $scope._objectDataRaw.specific_data.property_description =
  value.description;

   return $scope._objectDataRaw.specific_data;
 }
};
</code>```

Here is a jsfiddle with the problem:
Can not select the object

And I need it to pass it as an object, and not as object.property.
Any help would be greatly appreciated.

答:
I think your code should be:

angular.module('myApp', [])
      .controller('Ctrl1', function($scope) {

        $scope.items = [{
          "description": "Item description",
          "item_type": "OUT",
          "id": 1,
          "title": "Default item"
        }];

        $scope._objectDataRaw = {
          specific_data: {}
        };

        $scope.setGetSelectedItem = function(value) {
          if (arguments.length) {

            $scope._objectDataRaw.specific_data.property_id = value.id;
            $scope._objectDataRaw.specific_data.property_title = value.title;
            $scope._objectDataRaw.specific_data.property_description = value.description;

            return $scope._objectDataRaw.specific_data;
          }
        };
      });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Ctrl1">
      <div>
        <select name="item" ng-repeat="item in items">
          <option value="">-- Please select --</option>
          <option value="" ng-click="setGetSelectedItem(item)">{{item.title}}</option>
        </select>
      </div>
    </div></code>```

Body:
I have a problem selecting an object from ng-model with ng-model-options and getter-setter function. I am binding to the ng-model getter-setter function setGetSelectedItem which has to accept an object from ng-options - in my case, item and to assign its properies to the properties of another object specific_data. It does, the object is passed correctly but I am not able to select the option in the select options.

<select name="item" ng-model="setGetSelectedItem"
        ng-options="item as item.title for item in items"
        ng-model-options="{getterSetter: true}">
  <option value="">-- Please select --</option>
</select>

And in the controller:

$scope.items = [{

"description": "Item description",
  "item_type": "OUT",
  "id": 1,
  "title": "Default item"
}];

$scope._objectDataRaw = {
  specific_data: {}
};

$scope.setGetSelectedItem = function(value) {

if (arguments.length) {
  $scope._objectDataRaw.specific_data.property_id = value.id;
  $scope._objectDataRaw.specific_data.property_title = value.title;
  $scope._objectDataRaw.specific_data.property_description =
  value.description;

   return $scope._objectDataRaw.specific_data;
 }
};

Here is a jsfiddle with the problem:
Can not select the object

And I need it to pass it as an object, and not as object.property.
Any help would be greatly appreciated.

Body:
I think your code should be:

angular.module('myApp', [])
      .controller('Ctrl1', function($scope) {

        $scope.items = [{
          "description": "Item description",
          "item_type": "OUT",
          "id": 1,
          "title": "Default item"
        }];

        $scope._objectDataRaw = {
          specific_data: {}
        };

        $scope.setGetSelectedItem = function(value) {
          if (arguments.length) {

            $scope._objectDataRaw.specific_data.property_id = value.id;
            $scope._objectDataRaw.specific_data.property_title = value.title;
            $scope._objectDataRaw.specific_data.property_description = value.description;

            return $scope._objectDataRaw.specific_data;
          }
        };
      });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Ctrl1">
      <div>
        <select name="item" ng-repeat="item in items">
          <option value="">-- Please select --</option>
          <option value="" ng-click="setGetSelectedItem(item)">{{item.title}}</option>
        </select>
      </div>
    </div>


问:
Is it possible to use a user input's value in sass?
I am creating a colour palette and i have seen a lot of ways online to it using sass which i am using in the project, however i am taking a user input (hex code) and wish to print them out with different percentage variants - to show the user a lighter/darker version of #ff0000 for example.

Is this possible? I have seen things such as:

```<code>$color: #3cb878;
$light: lighten($color,15%);
$dark: darken($color,15%);
</code>```

And ideally i would like "$color" to be the user input and then i can print multiple percentage variants out.

Thanks!

答:
Yes you can!

There is a SASS compiler written in JavaScript that you can run inside the browser.

https://github.com/medialize/sass.js/

You'll have to perform a search and replace on the SASS source code via JavaScript, and then compile it. You can then show this to the user by inserting it into the DOM.

To run the library is really simple:

```<code><script src="dist/sass.js"></script>
<script>
  var scss = '$someVar: 123px; .some-selector { width: $someVar; }';
  sass.compile(scss, function(result) {
    console.log(result);
  });
</script>
</code>```

Body:
I am creating a colour palette and i have seen a lot of ways online to it using sass which i am using in the project, however i am taking a user input (hex code) and wish to print them out with different percentage variants - to show the user a lighter/darker version of #ff0000 for example.

Is this possible? I have seen things such as:

$color: #3cb878;
$light: lighten($color,15%);
$dark: darken($color,15%);

And ideally i would like "$color" to be the user input and then i can print multiple percentage variants out.

Thanks!

Body:
Yes you can!

There is a SASS compiler written in JavaScript that you can run inside the browser.

https://github.com/medialize/sass.js/

You'll have to perform a search and replace on the SASS source code via JavaScript, and then compile it. You can then show this to the user by inserting it into the DOM.

To run the library is really simple:

<script src="dist/sass.js"></script>
<script>
  var scss = '$someVar: 123px; .some-selector { width: $someVar; }';
  sass.compile(scss, function(result) {
    console.log(result);
  });
</script>


问:
How to display PHP echo's in different div elements in an Ajax response
```<code>if ($_POST['username']==""){
 echo "enter your username"; //echo 1
}
if ($_POST['password']==""){
 echo "enter your password"; //echo 2
}

 <div class="username-error"> <!-- echo 1 has to be displayed here --></div>
    <div class="password-error"> <!-- echo 2 has to be displayed here --> </div>
</code>```

```<code>    $.ajax({
              url: $url,
              type: $type,
              data :formData,
              cache: false,
              contentType: false,
              processData: false,
              success: function(response){
                $('.username-error').html(response);
                $('.password-error').html(response);
              }
            });
</code>```

If I want to display this two echo's separately in two div elements in another page through ajax, how would i do it? below are the two div's that i want them to be displayed separately.

答:
You need to format your output in a way that your JS script might be able to read it.

MyPHP.php

```<code>$usernameError = "" ;
$passwordError = "";

if ($_POST['username']==""){
   $usernameError = "enter your username";
}
if ($_POST['password']==""){
   $passwordError = "enter your password";
}
echo json_encode(['usernameError' => $usernameError, 'passwordError' => $passwordError]);
</code>```

JS (Assuming that you are using jQuery)

```<code>$.ajax({
    data: {username: 'Username', password: 'password'},
    method: 'post',
    dataType: 'json',
})
.done(function(response){
    $('.username-error').text(response.usernameError);
    $('.password-error').text(response.passwordError);
})
</code>```

Body:
if ($_POST['username']==""){
 echo "enter your username"; //echo 1
}
if ($_POST['password']==""){
 echo "enter your password"; //echo 2
}

    $.ajax({
              url: $url,
              type: $type,
              data :formData,
              cache: false,
              contentType: false,
              processData: false,
              success: function(response){
                $('.username-error').html(response);
                $('.password-error').html(response);
              }
            });

If I want to display this two echo's separately in two div elements in another page through ajax, how would i do it? below are the two div's that i want them to be displayed separately.

Body:
You need to format your output in a way that your JS script might be able to read it.

MyPHP.php

$usernameError = "" ;
$passwordError = "";

if ($_POST['username']==""){
   $usernameError = "enter your username";
}
if ($_POST['password']==""){
   $passwordError = "enter your password";
}
echo json_encode(['usernameError' => $usernameError, 'passwordError' => $passwordError]);

JS (Assuming that you are using jQuery)

$.ajax({
    data: {username: 'Username', password: 'password'},
    method: 'post',
    dataType: 'json',
})
.done(function(response){
    $('.username-error').text(response.usernameError);
    $('.password-error').text(response.passwordError);
})


问:
My favicon code isn't working.... I did the code like it said in a guide
So I'm building a website for my friend using Github hosting, and I want it to have a favicon. I have implemented this code: </p>

```<code><!--Favicon-->
    <!-- Opera Speed Dial Favicon -->
  <link rel="icon" type="image/png" href="favicon.png" />

<!-- Standard Favicon -->
  <link rel="icon" type="image/x-icon" href="favicon.ico" />

<!-- For iPhone 4 Retina display: -->
  <link rel="apple-touch-icon-precomposed" sizes="114x114" href="favicon.png">

<!-- For iPad: -->
  <link rel="apple-touch-icon-precomposed" sizes="72x72" href="favicon.png">

<!-- For iPhone: -->
  <link rel="apple-touch-icon-precomposed" href="favicon.png">
</code>```

<p>but whenever I open the page, there's no favicon. I got the code from this guide here, but alas, it's not working... If someone could help me it'd be greatly appreciated... The github pages version can be found here. </p>

答:
I accessed the website from Firefox and the favicon appeared correctly. When I accessed in Chrome, an error occurred while trying to open the file '/favicon.ico'.
This is because some browsers ignore the url inside the href tag and search only for a file named '/favicon.ico' in root directory.
So, to solve your problem just create a file called "favicon.ico" in the root directory, replace the url in link tag and all browsers will recognize the favicon. Like this:</p>

```<code><link rel="icon" href="favicon.ico" />
</code>```

Body:
So I'm building a website for my friend using Github hosting, and I want it to have a favicon. I have implemented this code:

  <link rel="icon" type="image/png" href="favicon.png" />

  <link rel="icon" type="image/x-icon" href="favicon.ico" />

  <link rel="apple-touch-icon-precomposed" sizes="114x114" href="favicon.png">

  <link rel="apple-touch-icon-precomposed" sizes="72x72" href="favicon.png">

  <link rel="apple-touch-icon-precomposed" href="favicon.png">

but whenever I open the page, there's no favicon. I got the code from this guide here, but alas, it's not working... If someone could help me it'd be greatly appreciated... The github pages version can be found here.

Body:
I accessed the website from Firefox and the favicon appeared correctly. When I accessed in Chrome, an error occurred while trying to open the file '/favicon.ico'.
This is because some browsers ignore the url inside the href tag and search only for a file named '/favicon.ico' in root directory.
So, to solve your problem just create a file called "favicon.ico" in the root directory, replace the url in link tag and all browsers will recognize the favicon. Like this:

<link rel="icon" href="favicon.ico" />


问:
Convert UIView to SVG format
Is it possible to convert contents of UIView to SVG format? (Basically save it to file in SVG format) I know that we can convert it to PDF. But not able to find any clear references on how to convert to SVG format. I have a requirement to convert the current screen to file with SVG format and send it to another system for processing by that.</p>

答:
I'm worried that you don't understand what SVG output is.  SVG is a description of a path or paths.  So if your view is just some random view that you hope to get "magicked" over to a bunch of paths, I think you are in trouble.  If it is an image, or some picture that someone drew, look in another direction.

If, however,  you have paths, there are answers like this that show how to convert CGPaths to an SVG view:
https://stackoverflow.com/a/22213852/793607

Title: Convert UIView to SVG format


问:
Spark : Error Not found value SC
I have just started with Spark. I have CDH5 Installed with Spark . However when I try to use sparkcontext it gives Error as below

```<code><console>:17: error: not found: value sc
       val distdata = sc.parallelize(data)
</code>```

I have researched about this and found error: not found: value sc

and tried to start spark context with ./spark-shell . It gives error No such File or Directory

答: Starting a new terminal fixes the problem in my case.</p>

Title: Spark : Error Not found value SC

Body:
I have just started with Spark. I have CDH5 Installed with Spark . However when I try to use sparkcontext it gives Error as below

<console>:17: error: not found: value sc
       val distdata = sc.parallelize(data)

I have researched about this and found error: not found: value sc

and tried to start spark context with ./spark-shell . It gives error No such File or Directory