问:
Use json_array_elements(json) and get item ranks
I have a json made of two levels of arrays like :

```<code>[
  {
    name: "Group one",
    races:
    [
     {name: "Race 1"},
     {name: "Race 2"},
    ]
  },
  {
    name: "Group two",
    races:
    [
     {name: "Race 10"},
     {name: "Race 11"},
    ]
  }
]
</code>```

Is it possible to get by magic SQL :

```<code>group_num | race_num | race
int       | int      | json
1         | 1        | {name: "Race 1"}
1         | 2        | {name: "Race 2"}
2         | 1        | {name: "Race 10"}
2         | 2        | {name: "Race 11"}
</code>```

in which :

group_num is the rank of each group in its array

race_num is the rank of each race in its array

I presume this could have something to do with json_array_elements(json) and row_number() OVER () but I can't figure how to make it right !

答:
```<code>with my_table(data) as (
values(
'[
  {
    "name": "Group one",
    "races":
    [
     {"name": "Race 1"},
     {"name": "Race 2"}
    ]
  },
  {
    "name": "Group two",
    "races":
    [
     {"name": "Race 10"},
     {"name": "Race 11"}
    ]
  }
]'::json)
)
select
    group_num,
    rank() over (partition by group_num order by value->>'name') as race_num,
    value as race
from (
    select
        rank() over (order by value->>'name') as group_num,
        value as grp
    from my_table,
    json_array_elements(data)
    ) s,
json_array_elements(grp->'races');
</code>```

Results:

```<code> group_num | race_num |        race
-----------+----------+---------------------
         1 |        1 | {"name": "Race 1"}
         1 |        2 | {"name": "Race 2"}
         2 |        1 | {"name": "Race 10"}
         2 |        2 | {"name": "Race 11"}
(4 rows)
</code>```

Note, your json is invalid, use jsonlint to validate json expressions.

Body:
I have a json made of two levels of arrays like :

[
  {
    name: "Group one",
    races:
    [
     {name: "Race 1"},
     {name: "Race 2"},
    ]
  },
  {
    name: "Group two",
    races:
    [
     {name: "Race 10"},
     {name: "Race 11"},
    ]
  }
]

Is it possible to get by magic SQL :

group_num | race_num | race
int       | int      | json
1         | 1        | {name: "Race 1"}
1         | 2        | {name: "Race 2"}
2         | 1        | {name: "Race 10"}
2         | 2        | {name: "Race 11"}

in which :

group_num is the rank of each group in its array

race_num is the rank of each race in its array

I presume this could have something to do with json_array_elements(json) and row_number() OVER () but I can't figure how to make it right !

Body:
with my_table(data) as (
values(
'[
  {
    "name": "Group one",
    "races":
    [
     {"name": "Race 1"},
     {"name": "Race 2"}
    ]
  },
  {
    "name": "Group two",
    "races":
    [
     {"name": "Race 10"},
     {"name": "Race 11"}
    ]
  }
]'::json)
)
select
    group_num,
    rank() over (partition by group_num order by value->>'name') as race_num,
    value as race
from (
    select
        rank() over (order by value->>'name') as group_num,
        value as grp
    from my_table,
    json_array_elements(data)
    ) s,
json_array_elements(grp->'races');

Results:

 group_num | race_num |        race
-----------+----------+---------------------
         1 |        1 | {"name": "Race 1"}
         1 |        2 | {"name": "Race 2"}
         2 |        1 | {"name": "Race 10"}
         2 |        2 | {"name": "Race 11"}
(4 rows)

Note, your json is invalid, use jsonlint to validate json expressions.


来源: stackexchange

问:
Extending a Collection where the Element type is generic (Swift)
It's simple to extend a Collection type in swift to have a custom function for particular Element types:

```<code>struct MyStruct {
    let string: String
}

extension Set where Element == MyStruct {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}
</code>```

But suppose your Element type is generic?

```<code>protocol MyProtocol {}

struct MyGenericStruct<T: MyProtocol> {
    let string: String
}

// error on next line:
// error: expected '>' to complete generic argument list
// extension Set where Element == MyGenericStruct<T: MyProtocol> {
//                                                 ^
extension Set where Element == MyGenericStruct<T: MyProtocol> {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}

// error on next line:
// error: use of undeclared type 'T'
// extension Set where Element == MyGenericStruct<T> {
//                                                ^
extension Set where Element == MyGenericStruct<T> {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}
</code>```

It's unclear to me how to declare that my element is a generic.

答:
If I do understand the purpose, you probably need to have more implementation in your protocol and structure.

First, element's protocol has to be hashable and equitable.

```<code>protocol MyProtocol: Hashable, Equatable {
    var string: String { get }
}
</code>```

Therefore, MyGenericStruct will look like the following.

```<code>struct MyGenericStruct: MyProtocol {
    let string: String
    var hashValue: Int {
        get {
            return string.hashValue
        }
    }

    static func ==(lhs: MyGenericStruct, rhs: MyGenericStruct) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
}
</code>```

Then, declare extension with constraints specified by a where clause for MyProtocol

```<code>extension Set where Element: MyProtocol {
    func getFirstWith(string: String) -> Element? {
        return filter({$0.string == string}).first
    }
}
</code>```

Finally, let's do a test and see its result.

```<code>// Example
let set: Set = [
    MyGenericStruct(string: "Watermelon"),
    MyGenericStruct(string: "Orange"),
    MyGenericStruct(string: "Banana")
]
let output = set.getFirstWith(string: "Orange")
print(output)
</code>```

In my playground with Xcode 8, I can get Optional(MyGenericStruct(string: "Orange")) in log.

[UPDATED1] To make an Extension on Set<MyGenericStruct> only:

```<code>extension Set where Element == MyGenericStruct {
    func getFirstWith(string: String) -> Element? {
        return filter({$0.string == string}).first
    }
}</code>```

[UPDATED2] In case to keep MyGenericStruct<T: MyProtocol> declaration as stated is necessary, another approach to implement Set extension:

```<code>
protocol MyProtocol {

}

struct BaseStruct1: MyProtocol {

}

struct BaseStruct2: MyProtocol {

}

protocol ContainStringProtocol: Hashable {
    var string: String { get }
}

struct MyGenericStruct<T: MyProtocol>: ContainStringProtocol {
    var string: String
    var hashValue: Int {
        get {
            return string.hashValue
        }
    }

    init(string: String) {
        self.string = string
    }

    static func ==(lhs: MyGenericStruct, rhs: MyGenericStruct) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
}

extension Set where Element: ContainStringProtocol {
    func getFirstWith(string: String) -> Element? {
        return filter({$0.string == string}).first
    }
}

// Example
let set1: Set = [
    MyGenericStruct<BaseStruct1>(string: "Watermelon"),
    MyGenericStruct<BaseStruct1>(string: "Orange"),
    MyGenericStruct<BaseStruct1>(string: "Banana")
]
let output1 = set1.getFirstWith(string: "Orange")
print(output1!)

let set2: Set = [
    MyGenericStruct<BaseStruct2>(string: "Watermelon"),
    MyGenericStruct<BaseStruct2>(string: "Orange"),
    MyGenericStruct<BaseStruct2>(string: "Banana")
]
let output2 = set2.getFirstWith(string: "Orange")
print(output2!)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It's simple to extend a Collection type in swift to have a custom function for particular Element types:

struct MyStruct {
    let string: String
}

extension Set where Element == MyStruct {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}

But suppose your Element type is generic?

protocol MyProtocol {}

struct MyGenericStruct<T: MyProtocol> {
    let string: String
}

// error on next line:
// error: expected '>' to complete generic argument list
// extension Set where Element == MyGenericStruct<T: MyProtocol> {
//                                                 ^
extension Set where Element == MyGenericStruct<T: MyProtocol> {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}

// error on next line:
// error: use of undeclared type 'T'
// extension Set where Element == MyGenericStruct<T> {
//                                                ^
extension Set where Element == MyGenericStruct<T> {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}

It's unclear to me how to declare that my element is a generic.

Body:
If I do understand the purpose, you probably need to have more implementation in your protocol and structure.

First, element's protocol has to be hashable and equitable.

protocol MyProtocol: Hashable, Equatable {
    var string: String { get }
}

Therefore, MyGenericStruct will look like the following.

struct MyGenericStruct: MyProtocol {
    let string: String
    var hashValue: Int {
        get {
            return string.hashValue
        }
    }

    static func ==(lhs: MyGenericStruct, rhs: MyGenericStruct) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
}

Then, declare extension with constraints specified by a where clause for MyProtocol

extension Set where Element: MyProtocol {
    func getFirstWith(string: String) -> Element? {
        return filter({$0.string == string}).first
    }
}

Finally, let's do a test and see its result.

// Example
let set: Set = [
    MyGenericStruct(string: "Watermelon"),
    MyGenericStruct(string: "Orange"),
    MyGenericStruct(string: "Banana")
]
let output = set.getFirstWith(string: "Orange")
print(output)

In my playground with Xcode 8, I can get Optional(MyGenericStruct(string: "Orange")) in log.

[UPDATED1] To make an Extension on Set<MyGenericStruct> only:

extension Set where Element == MyGenericStruct {
    func getFirstWith(string: String) -> Element? {
        return filter({$0.string == string}).first
    }
}

[UPDATED2] In case to keep MyGenericStruct<T: MyProtocol> declaration as stated is necessary, another approach to implement Set extension:

protocol MyProtocol {

}

struct BaseStruct1: MyProtocol {

}

struct BaseStruct2: MyProtocol {

}

protocol ContainStringProtocol: Hashable {
    var string: String { get }
}

struct MyGenericStruct<T: MyProtocol>: ContainStringProtocol {
    var string: String
    var hashValue: Int {
        get {
            return string.hashValue
        }
    }

    init(string: String) {
        self.string = string
    }

    static func ==(lhs: MyGenericStruct, rhs: MyGenericStruct) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
}

extension Set where Element: ContainStringProtocol {
    func getFirstWith(string: String) -> Element? {
        return filter({$0.string == string}).first
    }
}

// Example
let set1: Set = [
    MyGenericStruct<BaseStruct1>(string: "Watermelon"),
    MyGenericStruct<BaseStruct1>(string: "Orange"),
    MyGenericStruct<BaseStruct1>(string: "Banana")
]
let output1 = set1.getFirstWith(string: "Orange")
print(output1!)

let set2: Set = [
    MyGenericStruct<BaseStruct2>(string: "Watermelon"),
    MyGenericStruct<BaseStruct2>(string: "Orange"),
    MyGenericStruct<BaseStruct2>(string: "Banana")
]
let output2 = set2.getFirstWith(string: "Orange")
print(output2!)


问:
Notifications not showing up on database trigger
I am using firebase cloud functions for sending notifications to users when database trigger is called.The registration token is saved in firebase database. The problem is that inspite of registration tokens getting saved, the notifications are not showing up in these devices.
This is index.js

```<code>    const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/Blog').onWrite(event => {
const title = event.data.child('title').val();

const token_no = event.data.child('token_no').val();

  const getDeviceTokensPromise = admin.database().ref(`/Token/${token_no}`).once('value');
  const getBody=admin.database().ref(`/Blog`).once('value');

  return Promise.all([getDeviceTokensPromise,getBody]).then(results => {
    const tokensSnapshot = results[0];
    const notify=results[1];

    if (!tokensSnapshot.hasChildren()) {
      return console.log('There are no notification tokens to send to.');
    }
    console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');

    // Notification details.
    const payload = {
      notification: {
        title: 'You have a new Alert!',
        body: `${notify.child('title').val()}`,

      }
    };

    // Listing all tokens.
    const tokens = Object.keys(tokensSnapshot.val());

    // Send notifications to all tokens.
    return admin.messaging().sendToDevice(tokens, payload).then(response => {
      // For each message check if there was an error.
      const tokensToRemove = [];
      response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
          console.error('Failure sending notification to', tokens[index], error);
          // Cleanup the tokens who are not registered anymore.
          if (error.code === 'messaging/invalid-registration-token' ||
              error.code === 'messaging/registration-token-not-registered') {
            tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
          }
        }
      });
      return Promise.all(tokensToRemove);
    });
  });
});
</code>```

Database snapshot:

```<code>"Token" : {
"token_no" : {
  "ctxjePemYZE:APA91bFJXXyTkyvXOlSY...4VbWu7Vbf7itwbwZu9umSvg_tdB1lKD1d8g" : "true",
  "dgVszInjIW0:APA91bFZE3Av5unZTgp...RUeYb-CUhWjO1otqguhE9NTQZ8XgK6nRIW5" : "true"
}
</code>```

}

答:
Update 2:

Your code uses Object.keys(tokensSnapshot.val()) to get the tokens.  That means the tokens must be the keys under token_no, not the values.  Like this:

```<code>"Token" : {
  "-KoWsMn9rCIitQeNvixr" : {
    "dK1FjGbNr6k:APA91b...S8JK2d69JpO" : "123" // token is the key, value is not significant; could be "123", true, or 0.
  },
  ...
}
</code>```

Update:

You should review the documentation for the Event parameter of a database trigger to get a better understanding of the params and data properties.  params provide acces to the wildcards in the trigger reference, data is the snapshot.  In your code, you want to get values from the snapshot.

Add these changes:

```<code>const title = event.data.child('title').val();
const desp = event.data.child('desp').val();
const token_no = event.data.child('token_no').val()

const payload = {
  notification: {
    title: 'You have a new Alert!',
    body: `${Post.child('title').val()}`,  // <= CHANGED
    //icon: follower.photoURL
  }
};
</code>```

Running the code you posted, with these changes, I am able to send and receive a notification.

There are two problems.  The first is this statement:

```<code>const getDeviceTokensPromise = admin.database().ref(`/Token/{token_no}`).once('value');
</code>```

token_no is not defined.  And when you do define it and want to substitute its value, you will need to add a $:

```<code>`/Token/${token_no}`
</code>```

The second problem is that Post is not defined, which causes function execution to fail.  Check your function logs:

```<code>const payload = {
  notification: {
    title: 'You have a new Alert!',
    body: `${Post.title}`,
    //icon: follower.photoURL
  }
};
</code>```

Body:
I am using firebase cloud functions for sending notifications to users when database trigger is called.The registration token is saved in firebase database. The problem is that inspite of registration tokens getting saved, the notifications are not showing up in these devices.
This is index.js

    const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/Blog').onWrite(event => {
const title = event.data.child('title').val();

const token_no = event.data.child('token_no').val();

  const getDeviceTokensPromise = admin.database().ref(`/Token/${token_no}`).once('value');
  const getBody=admin.database().ref(`/Blog`).once('value');

  return Promise.all([getDeviceTokensPromise,getBody]).then(results => {
    const tokensSnapshot = results[0];
    const notify=results[1];

    if (!tokensSnapshot.hasChildren()) {
      return console.log('There are no notification tokens to send to.');
    }
    console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');

    // Notification details.
    const payload = {
      notification: {
        title: 'You have a new Alert!',
        body: `${notify.child('title').val()}`,

      }
    };

    // Listing all tokens.
    const tokens = Object.keys(tokensSnapshot.val());

    // Send notifications to all tokens.
    return admin.messaging().sendToDevice(tokens, payload).then(response => {
      // For each message check if there was an error.
      const tokensToRemove = [];
      response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
          console.error('Failure sending notification to', tokens[index], error);
          // Cleanup the tokens who are not registered anymore.
          if (error.code === 'messaging/invalid-registration-token' ||
              error.code === 'messaging/registration-token-not-registered') {
            tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
          }
        }
      });
      return Promise.all(tokensToRemove);
    });
  });
});

Database snapshot:

"Token" : {
"token_no" : {
  "ctxjePemYZE:APA91bFJXXyTkyvXOlSY...4VbWu7Vbf7itwbwZu9umSvg_tdB1lKD1d8g" : "true",
  "dgVszInjIW0:APA91bFZE3Av5unZTgp...RUeYb-CUhWjO1otqguhE9NTQZ8XgK6nRIW5" : "true"
}

}

Body:
Update 2:

Your code uses Object.keys(tokensSnapshot.val()) to get the tokens.  That means the tokens must be the keys under token_no, not the values.  Like this:

"Token" : {
  "-KoWsMn9rCIitQeNvixr" : {
    "dK1FjGbNr6k:APA91b...S8JK2d69JpO" : "123" // token is the key, value is not significant; could be "123", true, or 0.
  },
  ...
}

Update:

You should review the documentation for the Event parameter of a database trigger to get a better understanding of the params and data properties.  params provide acces to the wildcards in the trigger reference, data is the snapshot.  In your code, you want to get values from the snapshot.

Add these changes:

const title = event.data.child('title').val();
const desp = event.data.child('desp').val();
const token_no = event.data.child('token_no').val()

const payload = {
  notification: {
    title: 'You have a new Alert!',
    body: `${Post.child('title').val()}`,  // <= CHANGED
    //icon: follower.photoURL
  }
};

Running the code you posted, with these changes, I am able to send and receive a notification.

There are two problems.  The first is this statement:

const getDeviceTokensPromise = admin.database().ref(`/Token/{token_no}`).once('value');

token_no is not defined.  And when you do define it and want to substitute its value, you will need to add a $:

`/Token/${token_no}`

The second problem is that Post is not defined, which causes function execution to fail.  Check your function logs:

const payload = {
  notification: {
    title: 'You have a new Alert!',
    body: `${Post.title}`,
    //icon: follower.photoURL
  }
};


问:
Different result from rails and irb for YoutubeDL.get
I'm using gem 'youtube-dl.rb'.

From irb, I can get full result, about video, but at the rails 4.2 - I can't.

irb

```<code>require 'youtube-dl.rb'
a = YoutubeDL.get "https://www.youtube.com/watch?v=5dsGWM5XGdg", {skip_download: true}
</code>```

Result https://pastebin.com/9SLbs5GF (With a lot of data).

rails c

```<code>require 'youtube-dl.rb'
a = YoutubeDL.get "https://www.youtube.com/watch?v=5dsGWM5XGdg", {skip_download: true}
</code>```

Result from rails console have only this:

```<code> => #<YoutubeDL::Video:0x007fbc29de1498 @url="https://www.youtube.com/watch?v=5dsGWM5XGdg", @options=#<YoutubeDL::Options:0x007fbc29de1448 @store={:skip_download=>true}>, @download_options=#<YoutubeDL::Options:0x007fbc29de1150 @store={:color=>false, :progress=>false, :skip_download=>true}>, @last_download_output="[youtube] 5dsGWM5XGdg: Downloading webpage\n[youtube] 5dsGWM5XGdg: Downloading video info webpage\n[youtube] 5dsGWM5XGdg: Extracting video information\n[youtube] 5dsGWM5XGdg: Downloading MPD manifest\n">
</code>```

How I Can get the same result for RoR?

答: Try to check youtube-dl.rb version inside your rails app and inside your machine enviro</p>

Body:
I'm using gem 'youtube-dl.rb'.

From irb, I can get full result, about video, but at the rails 4.2 - I can't.

irb

require 'youtube-dl.rb'
a = YoutubeDL.get "https://www.youtube.com/watch?v=5dsGWM5XGdg", {skip_download: true}

Result https://pastebin.com/9SLbs5GF (With a lot of data).

rails c

require 'youtube-dl.rb'
a = YoutubeDL.get "https://www.youtube.com/watch?v=5dsGWM5XGdg", {skip_download: true}

Result from rails console have only this:

 => #<YoutubeDL::Video:0x007fbc29de1498 @url="https://www.youtube.com/watch?v=5dsGWM5XGdg", @options=#<YoutubeDL::Options:0x007fbc29de1448 @store={:skip_download=>true}>, @download_options=#<YoutubeDL::Options:0x007fbc29de1150 @store={:color=>false, :progress=>false, :skip_download=>true}>, @last_download_output="[youtube] 5dsGWM5XGdg: Downloading webpage\n[youtube] 5dsGWM5XGdg: Downloading video info webpage\n[youtube] 5dsGWM5XGdg: Extracting video information\n[youtube] 5dsGWM5XGdg: Downloading MPD manifest\n">

How I Can get the same result for RoR?


问:
GTX 970 bandwidth calculation
I am trying to calculate the theoretical bandwidth of gtx970. As per the specs given in:-

http://www.geforce.com/hardware/desktop-gpus/geforce-gtx-970/specifications

Memory clock is 7Gb/s
Memory bus width = 256

Bandwidth = 7*256*2/8  (*2 because it is a DDR)

```<code>      = 448 GB/s
</code>```

However, in the specs it is given as 224GB/s

Why is there a factor 2 difference? Am i making a mistake, if so please correct me.

Thanks

答:
The clock rate reported is an "effective" clock rate and already takes into account the transfer on both rising and falling edges. The trouble is the factor of 2 for DDR.

Some discussion on devtalk here: https://devtalk.nvidia.com/default/topic/995384/theoretical-bandwidth-vs-effective-bandwidth/

Title: GTX 970 bandwidth calculation

Body:
I am trying to calculate the theoretical bandwidth of gtx970. As per the specs given in:-

http://www.geforce.com/hardware/desktop-gpus/geforce-gtx-970/specifications

Memory clock is 7Gb/s
Memory bus width = 256

Bandwidth = 7*256*2/8  (*2 because it is a DDR)

      = 448 GB/s

However, in the specs it is given as 224GB/s

Why is there a factor 2 difference? Am i making a mistake, if so please correct me.

Thanks


问:
Not able to approve tasks in Documentum D2
In one of the workflows, task notification has been sent to an user's inbox. When the user tries to acquire the task, he is getting the error like missing package for the current task of the workflow.

Kindly provide me the suggestion on resolving this issue.

答:
You can either:

Verify if the associated activity definition for the task (from process builder for example) has defined correctly the package/s.

or

Verify if the attached object (document/s or folder/s) to the task exists in repository or the user has at least BROWSE permission on it.

Also, a good idea is to check the D2 app server and JMS logs.


问:
Start an Intent from a On ClickListener
I want to click Start button with sound and go to next activity with intent. The code below doesn't work. The button has sound but cannot go to next activity

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnStart = (Button) findViewById(R.id.btnStart);
    sp = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
    music = sp.load(this, R.raw.munchausen, 1);

    btnStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sp.play(music, 1, 1, 0, 0, 1);
        }
    });
}
public void onClick(View view) {
    Intent intent = new Intent(this, MainActivity2.class);
    startActivity(intent);
}
</code>```

}

答:
```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnStart = (Button) findViewById(R.id.btnStart);
    sp = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
    music = sp.load(this, R.raw.munchausen, 1);

    btnStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sp.play(music, 1, 1, 0, 0, 1);
            Intent intent = new Intent(MainActivity.this, MainActivity2.class);
            startActivity(intent);
        }
    });
}
</code>```

Please change your code to this.

Title: Start an Intent from a On ClickListener

Body:
I want to click Start button with sound and go to next activity with intent. The code below doesn't work. The button has sound but cannot go to next activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnStart = (Button) findViewById(R.id.btnStart);
    sp = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
    music = sp.load(this, R.raw.munchausen, 1);

    btnStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sp.play(music, 1, 1, 0, 0, 1);
        }
    });
}
public void onClick(View view) {
    Intent intent = new Intent(this, MainActivity2.class);
    startActivity(intent);
}

}

Body:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnStart = (Button) findViewById(R.id.btnStart);
    sp = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
    music = sp.load(this, R.raw.munchausen, 1);

    btnStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sp.play(music, 1, 1, 0, 0, 1);
            Intent intent = new Intent(MainActivity.this, MainActivity2.class);
            startActivity(intent);
        }
    });
}

Please change your code to this.


问:
Install NodeJS packages from file with NPM install
Is it possible to install nodejs packages (/modules) from files like in ruby's Gemfile as done with bundle install or python's requirements file (eg: requirements.pip) as done using pip install -r commands ?

Say I have a file where three or four package names are listed.

How would I instruct npm to install packages whose names are found in that file (and resolve dependencies which it also does)?

答: you can use NPM init to create a package.json file which will store the node packages your application is dependent on, then use npm install which will install the node packages indicated in the package.json file</p>


问:
a "preprocessor" for HTML? without JS
In a CSS sheet, I created a new tag

```<code>gb {
    color: green;
}
</code>```

and in the HTML code, I would replace without javascript, all occurences of

```<code><gb> ■ </gb>  <!-- green bullet -->
</code>```

with something like <gb /> . (Like using the C preprocessor, but doing thing in native HTML/CSS, without need to another program (cpp) and action (preprocessing) before sending the page on the web)

In other terms, how could I create custom HTML tag, with content (saving typing the ■ code), but only using HTML/CSS ?

And, yes, a lot of content already address custom HTML tags, but

They generally use Javascript

It is not clear

I can't believe such a little thing could involve these cumbersome solutions.

The idea is just to have a short way to draw an Unicode symbol (and in color) in middle of text.

答:
To use a custom tag that is valid regarding the HTML Living Standard, you'll just need to use a hyphen in your tag name.

```<code><g-b>Hello</g-b>
</code>```

Then you can follow the Valentin's answer "Option 1".

g-b::before {
  content: "\25A0";
  color: green;
}

r-b::before {
  content: "\25A0";
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><g-b>Text 1</g-b>
<br>
<r-b></r-b>Text 2</code>```

Title: a "preprocessor" for HTML? without JS

Body:
In a CSS sheet, I created a new tag

gb {
    color: green;
}

and in the HTML code, I would replace without javascript, all occurences of

<gb> ■ </gb>

with something like <gb /> . (Like using the C preprocessor, but doing thing in native HTML/CSS, without need to another program (cpp) and action (preprocessing) before sending the page on the web)

In other terms, how could I create custom HTML tag, with content (saving typing the ■ code), but only using HTML/CSS ?

And, yes, a lot of content already address custom HTML tags, but

They generally use Javascript

It is not clear

I can't believe such a little thing could involve these cumbersome solutions.

The idea is just to have a short way to draw an Unicode symbol (and in color) in middle of text.

Body:
To use a custom tag that is valid regarding the HTML Living Standard, you'll just need to use a hyphen in your tag name.

<g-b>Hello</g-b>

Then you can follow the Valentin's answer "Option 1".

g-b::before {
  content: "\25A0";
  color: green;
}

r-b::before {
  content: "\25A0";
  color: red;
}

<g-b>Text 1</g-b>
<br>
<r-b></r-b>Text 2


问:
How to get each folds' results in 10-fold cross-validation
Actually, I know there is a GUI method to get each fold's results in 10-fold cross-validation in weka, see here, but I am programming using weka api.

Unfortunately, My results My results from java program are quite different from the results in weka's explore GUI results. My code is partenter image description hereially given below,

```<code>Instances data1 = DataSource.read("D:/Users/.../XX.arff"); // upload the dataset
data1.setClassIndex(data1.numAttributes()-1); // set class index
data1.randomize(new Random(1))
data1.stratify(10); // stratify the dataset into 10 folds
for(int i=0; i<10; i++){
    Instances train = data1.trainCV(10, i);
    Instances test = data1.testCV(10, i);
    RandomForest rf = new RandomForest();
    rf.buildClassifier(train);
    Evaluation eval = new Evaluation(train);
    eval.evaluateModel(rf, test);
    ... // then I compute each folds' results using eval.XXX()
}
</code>```

The results calculated by the above codes of 10-fold cross-validation is different from that obtained the standard weka GUI, I don't know which part of my code is wrong? Can anyone meet the same problem as me?

答:
Yeah, after wasting so much time in exploring the reason why the average of 10 folds' results are mismatched with the results of final 10-fold cross-validation in WEKA, I finally find the 3 points，

1) My Java code is right, which means that randomize(), stratify(), trainCV(), and testCV() are used correctly.

2) The results of 10-fold cross-validation in WEKA are Not equal the mean of the results of each fold.

3) The results of 10-fold cross-validation in WEKA are calculated by confusion matrix.

For the third point, for example, in each fold, WEKA will get precision, recall, f-measure, AUC, ROC, errorRate such measures as well as a confusion matrix, which defined as cm(i). Then, the final results of 10-fold cross validation also can get a confusion matrix CM, which defined as,

```<code>CM = cm(1) + cm(2) + ... cm(10)
</code>```

Finally, the precision, recall, f-measure, AUC, ROC such measures are calculated by this confusion matrix CM, which really supraise me a lot @^@.

Body:
Actually, I know there is a GUI method to get each fold's results in 10-fold cross-validation in weka, see here, but I am programming using weka api.

Unfortunately, My results My results from java program are quite different from the results in weka's explore GUI results. My code is partenter image description hereially given below,

Instances data1 = DataSource.read("D:/Users/.../XX.arff"); // upload the dataset
data1.setClassIndex(data1.numAttributes()-1); // set class index
data1.randomize(new Random(1))
data1.stratify(10); // stratify the dataset into 10 folds
for(int i=0; i<10; i++){
    Instances train = data1.trainCV(10, i);
    Instances test = data1.testCV(10, i);
    RandomForest rf = new RandomForest();
    rf.buildClassifier(train);
    Evaluation eval = new Evaluation(train);
    eval.evaluateModel(rf, test);
    ... // then I compute each folds' results using eval.XXX()
}

The results calculated by the above codes of 10-fold cross-validation is different from that obtained the standard weka GUI, I don't know which part of my code is wrong? Can anyone meet the same problem as me?

Body:
Yeah, after wasting so much time in exploring the reason why the average of 10 folds' results are mismatched with the results of final 10-fold cross-validation in WEKA, I finally find the 3 points，

1) My Java code is right, which means that randomize(), stratify(), trainCV(), and testCV() are used correctly.

2) The results of 10-fold cross-validation in WEKA are Not equal the mean of the results of each fold.

3) The results of 10-fold cross-validation in WEKA are calculated by confusion matrix.

For the third point, for example, in each fold, WEKA will get precision, recall, f-measure, AUC, ROC, errorRate such measures as well as a confusion matrix, which defined as cm(i). Then, the final results of 10-fold cross validation also can get a confusion matrix CM, which defined as,

CM = cm(1) + cm(2) + ... cm(10)

Finally, the precision, recall, f-measure, AUC, ROC such measures are calculated by this confusion matrix CM, which really supraise me a lot @^@.


问:
WordPress: wp_cron which should delete all posts in trash at every 10 a.m. EST
I used Automatically Empty Trash after the number of days the user requires. The user can set the number of days from which the trash should be automatically deleted. But I need to delete all posts in the trash at every 10 a.m. EST.

Anyone, please help me.

答:
you need a cron scheduler
try modifying this code at your needs :

```<code>    <?php
add_action('my_hourly_event', 'do_this_hourly');

function my_activation() {
    if ( !wp_next_scheduled( 'my_hourly_event' ) ) {
        wp_schedule_event(time(), 'hourly', 'my_hourly_event');
    }
}
add_action('wp', 'my_activation');

function do_this_hourly() {
    // do something every hour
}
?>
</code>```

reference from here

Body:
you need a cron scheduler
try modifying this code at your needs :

    <?php
add_action('my_hourly_event', 'do_this_hourly');

function my_activation() {
    if ( !wp_next_scheduled( 'my_hourly_event' ) ) {
        wp_schedule_event(time(), 'hourly', 'my_hourly_event');
    }
}
add_action('wp', 'my_activation');

function do_this_hourly() {
    // do something every hour
}
?>

reference from here


问:
Match Phone Number from Sheet Cell Value to Google Contacts and get Full name and Address
It's my first question, I am feeling nervous.

Here, I am trying to get Customer Full name and address from google contacts. But it's not working. Looking for experts help

```<code>function importContact() {
   var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() == "Stock" ) {
    var r = s.getActiveCell();
    var phone = r.getValue()
  if( r.getColumn() == 10 ) {
      var nextCell1 = r.offset(0, 1);
      var nextCell2 = r.offset(0, 2);
      var contacts = ContactsApp.getContactsByPhone(phone,'Other');
   for(var i = 0, iLen = contacts.length; i < iLen; i++) {
    var fullname = contacts[i].getFullName();
    var address = contacts[i].getAddresses(ContactsApp.Field.HOME_ADDRESS);
    if(fullname) {
       nextCell1.setValue(fullname);
       nextCell2.setValue(address);
    } else {
       nextCell1.setValue('New Customer');
    }
  }
}
}
}
</code>```

Thank you very much

答:
This seems to work for me.  But I don't have addresses for any contacts so I can't verify that.</p>

```<code>function importContact()
{
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();
  if( s.getName() == "Stock" )
  {
    var r = s.getActiveCell();
    var phone = r.getValue();
    if( r.getColumn() == 1 )
    {
      var nextCell1 = r.offset(0, 1);
      var nextCell2 = r.offset(0, 2);
      var contacts = ContactsApp.getContactsByPhone(phone);
      for(var i = 0; i < contacts.length; i++)
      {
        var fullname = contacts[i].getFullName();
        var address = contacts[i].getAddresses();
        if(fullname)
        {
           nextCell1.setValue(fullname);
           nextCell2.setValue(address);
        }
        else
        {
           nextCell1.setValue('New Customer');
        }
      }
    }
  }
}
</code>```

Body:
It's my first question, I am feeling nervous.

Here, I am trying to get Customer Full name and address from google contacts. But it's not working. Looking for experts help

function importContact() {
   var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() == "Stock" ) {
    var r = s.getActiveCell();
    var phone = r.getValue()
  if( r.getColumn() == 10 ) {
      var nextCell1 = r.offset(0, 1);
      var nextCell2 = r.offset(0, 2);
      var contacts = ContactsApp.getContactsByPhone(phone,'Other');
   for(var i = 0, iLen = contacts.length; i < iLen; i++) {
    var fullname = contacts[i].getFullName();
    var address = contacts[i].getAddresses(ContactsApp.Field.HOME_ADDRESS);
    if(fullname) {
       nextCell1.setValue(fullname);
       nextCell2.setValue(address);
    } else {
       nextCell1.setValue('New Customer');
    }
  }
}
}
}

Thank you very much

Body:
This seems to work for me.  But I don't have addresses for any contacts so I can't verify that.

function importContact()
{
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();
  if( s.getName() == "Stock" )
  {
    var r = s.getActiveCell();
    var phone = r.getValue();
    if( r.getColumn() == 1 )
    {
      var nextCell1 = r.offset(0, 1);
      var nextCell2 = r.offset(0, 2);
      var contacts = ContactsApp.getContactsByPhone(phone);
      for(var i = 0; i < contacts.length; i++)
      {
        var fullname = contacts[i].getFullName();
        var address = contacts[i].getAddresses();
        if(fullname)
        {
           nextCell1.setValue(fullname);
           nextCell2.setValue(address);
        }
        else
        {
           nextCell1.setValue('New Customer');
        }
      }
    }
  }
}


问:
How to add whitespace between CheckBoxes in ASP.NET
I have problem adding spaces between CheckBoxes and text next to them. I want to have them intended a little bit, not next to each other without some space.

▓car▓wash▓next and have it like ▓ car ▓ wash ▓ next

CheckBoxes aren't fixed at size, they are gathered from database.

I have CheckBoxList like:

```<code><asp:CheckBoxList ID="chBoxListManufacturer" runat="server" BackColor="LightBlue" BorderColor="Red" CellPadding="5" CssClas="mycheckbox"
       TextAlign="Right" RepeatDirection="Horizontal" RepeatLayout="Flow" OnSelectedIndexChanged="BoxListManufacturer_OnSelectedIndexChanged" AutoPostBack="True" />
</code>```

Css:.mycheckbox {margin-right: 15px;}

I was reading docs, but nothing works.

答: Maybe a trivial answer: put a <code> </code> after each checkbox, this will allow you some space between the control and the following label</p>

Body:
I have problem adding spaces between CheckBoxes and text next to them. I want to have them intended a little bit, not next to each other without some space.

▓car▓wash▓next and have it like ▓ car ▓ wash ▓ next

CheckBoxes aren't fixed at size, they are gathered from database.

I have CheckBoxList like:

<asp:CheckBoxList ID="chBoxListManufacturer" runat="server" BackColor="LightBlue" BorderColor="Red" CellPadding="5" CssClas="mycheckbox"
       TextAlign="Right" RepeatDirection="Horizontal" RepeatLayout="Flow" OnSelectedIndexChanged="BoxListManufacturer_OnSelectedIndexChanged" AutoPostBack="True" />

Css:.mycheckbox {margin-right: 15px;}

I was reading docs, but nothing works.

Body: Maybe a trivial answer: put a &nbsp; after each checkbox, this will allow you some space between the control and the following label


问:
why is my page loading so slowly?
My website: http://jgyboatparty.com/

is loading horrifically slow  and I cant figure out why. I have compressed the images as much as possible and made the video file available as a webm, and yet with a fresh reload the page is taken minutes to load!

Am i missing something here, as for some reason when I look at when elements are loaded, some of the images dont even start loading until 30 seconds in. This all means that my loader goes on for a while. (I have a wait until images loaded function)

Any advice would be much appreciated :)

答:
Do you have enough juice to your server? When pinging you server it takes 71ms, and when i am pinging your govrment's server it's approximately 31ms.

When i am checking the network tab for your website an image which is about 155kb big, takes about 1.2 seconds to load.

Steps to improve your speed might be minify all your scripts.
Do not load all of your content at once.

Title: why is my page loading so slowly?


问:
python Tkinter: how to disallow a window growing bigger than screen size
My routine adds buttons to a window in tkinter. At some point the window becomes bigger (in height) than my actual screen and I cannot access the buttons at the bottom anymore.

Demo code:

```<code>from Tkinter import *

n_buttons = 20 # <- change this as you wish for testing the code

def generate_buttons(n):

    for i in range(n):
        button = Button(myframe, text="Button Clone", height=4)
        button.grid(row=i)

root = Tk()
myframe = Frame(root)
myframe.pack()

generate_buttons(n=n_buttons)

root.mainloop()
</code>```

As a first attempt, I placed the following code into my loop:

```<code>if root.winfo_height() > root.winfo_screenheight():
    print("I'm full!")
    break
</code>```

But 1) it does not work and 2) I'd strongly prefer a solution that checks if the window can take another button before it is created, so that I do not have to destroy it afterwards.

In my real code the buttons a placed as a 2D-grid and my first reaction to an overload of my window would be to increase the number of columns in my frame and then to reduce the height of all buttons. Again, it would be bad if I had to re-generate all buttons until all requirements are met. It would be great if you could help me with a solution that checks if the geometry is possible, before the first button is created. Thanks!

答:
It's difficult to know if a widget will fit since there are so many variables. For example, padding, margins, other widgets on the screen, etc.

That being said, since you know your own application you can account for that. The only thing that's missing is knowing how tall a button is. You can get that from tkinter with the winfo_reqheight and winfo_reqwidth methods which return the height and width requested by the button. Then, it's just a matter of math.

Body:
My routine adds buttons to a window in tkinter. At some point the window becomes bigger (in height) than my actual screen and I cannot access the buttons at the bottom anymore.

Demo code:

from Tkinter import *

n_buttons = 20 # <- change this as you wish for testing the code

def generate_buttons(n):

    for i in range(n):
        button = Button(myframe, text="Button Clone", height=4)
        button.grid(row=i)

root = Tk()
myframe = Frame(root)
myframe.pack()

generate_buttons(n=n_buttons)

root.mainloop()

As a first attempt, I placed the following code into my loop:

if root.winfo_height() > root.winfo_screenheight():
    print("I'm full!")
    break

But 1) it does not work and 2) I'd strongly prefer a solution that checks if the window can take another button before it is created, so that I do not have to destroy it afterwards.

In my real code the buttons a placed as a 2D-grid and my first reaction to an overload of my window would be to increase the number of columns in my frame and then to reduce the height of all buttons. Again, it would be bad if I had to re-generate all buttons until all requirements are met. It would be great if you could help me with a solution that checks if the geometry is possible, before the first button is created. Thanks!


问:
Why doesn't drawing an ellipse with Pen::DashPattern set produce the expected result?
I'm trying to (simply) draw some lines rotating along an ellipse path and thought I had a nice easy way of doing it. Unfortunately, my solution seems to have some problems:

```<code>void EllipseDisplayControl::OnPaint(PaintEventArgs^ e)
{
    Graphics^ gfx = e->Graphics;
    gfx->SmoothingMode = Drawing2D::SmoothingMode::AntiAlias;

    int width = 100;
    int height = 10;

    for( int i = 0; i < 15; i ++ )
    {
        Drawing::Pen^ myPen = (Drawing::Pen^) Drawing::Pens::RoyalBlue->Clone(); //use the standard blue as a start point
        myPen->Color = Drawing::Color::FromArgb(64, 32, 111, 144);
        myPen->Width = 3;
        myPen->DashStyle = Drawing::Drawing2D::DashStyle::Solid;
        gfx->DrawEllipse(myPen, 0, 50+i*20, width, height); // Draw the blue ring

        float ellipseCircumference = Math::PI * Math::Sqrt(2* (Math::Pow(0.5*width,2) + Math::Pow(0.5*height,2)));
        array<Single>^ pattern = {4, ellipseCircumference};

        Drawing::Pen^ myPen2 = (Drawing::Pen^) Drawing::Pens::White->Clone(); //use the standard blue as a start point
        myPen2->DashPattern = pattern;
        myPen2->DashOffset = i*10;
        gfx->DrawEllipse(myPen2, 0, 50+i*20, width, height); // Draw the rotating white dot
    }
}
</code>```

...produces:

http://www.joncage.co.uk/media/img/BadPattern.png

...so why are the second two ellipses fully white? ...and how can I avoid the problem?

答:
This is probably one of the numerous GDI+ bug. This is due to the Antialiasing combined with the DashPattern. Funny though (well, sort of...), if you remove SmoothingMode = AntiAlias, you will get get a wonderful OutOfMemoryException (and if you google on "gdi+ pattern outofmemoryexception" you'll find hundreds of these. What a mess.

Since GDI+ is not really maintained (although it's also used in .NET Framework Winforms, BTW I reproduced your problem with .NET C#), as this link can tell us: Pen.DashPattern throw OutOfMemoryException using a default pen, the only way you can probably work around this is to try various values.

For example, if you change the DashOffset setting with this instead:

```<code> myPen2->DashOffset = i*ellipseCircumference;
</code>```

You will produce a nice set of ellipses, so maybe you can find one combination that really suits you. Good luck :-)

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to (simply) draw some lines rotating along an ellipse path and thought I had a nice easy way of doing it. Unfortunately, my solution seems to have some problems:

void EllipseDisplayControl::OnPaint(PaintEventArgs^ e)
{
    Graphics^ gfx = e->Graphics;
    gfx->SmoothingMode = Drawing2D::SmoothingMode::AntiAlias;

    int width = 100;
    int height = 10;

    for( int i = 0; i < 15; i ++ )
    {
        Drawing::Pen^ myPen = (Drawing::Pen^) Drawing::Pens::RoyalBlue->Clone(); //use the standard blue as a start point
        myPen->Color = Drawing::Color::FromArgb(64, 32, 111, 144);
        myPen->Width = 3;
        myPen->DashStyle = Drawing::Drawing2D::DashStyle::Solid;
        gfx->DrawEllipse(myPen, 0, 50+i*20, width, height); // Draw the blue ring

        float ellipseCircumference = Math::PI * Math::Sqrt(2* (Math::Pow(0.5*width,2) + Math::Pow(0.5*height,2)));
        array<Single>^ pattern = {4, ellipseCircumference};

        Drawing::Pen^ myPen2 = (Drawing::Pen^) Drawing::Pens::White->Clone(); //use the standard blue as a start point
        myPen2->DashPattern = pattern;
        myPen2->DashOffset = i*10;
        gfx->DrawEllipse(myPen2, 0, 50+i*20, width, height); // Draw the rotating white dot
    }
}

...produces:

http://www.joncage.co.uk/media/img/BadPattern.png

...so why are the second two ellipses fully white? ...and how can I avoid the problem?

Body:
This is probably one of the numerous GDI+ bug. This is due to the Antialiasing combined with the DashPattern. Funny though (well, sort of...), if you remove SmoothingMode = AntiAlias, you will get get a wonderful OutOfMemoryException (and if you google on "gdi+ pattern outofmemoryexception" you'll find hundreds of these. What a mess.

Since GDI+ is not really maintained (although it's also used in .NET Framework Winforms, BTW I reproduced your problem with .NET C#), as this link can tell us: Pen.DashPattern throw OutOfMemoryException using a default pen, the only way you can probably work around this is to try various values.

For example, if you change the DashOffset setting with this instead:

 myPen2->DashOffset = i*ellipseCircumference;

You will produce a nice set of ellipses, so maybe you can find one combination that really suits you. Good luck :-)


问:
Where to change highlight color for selected occurrences in Eclipse?
When a method or variable is selected it is highlighted in Eclipse with some color. Can anyone advice where to change that color? I'm working under Windows OS.</p>

答:
This has made me mad for about half an hour.

If the issue appears in JavaScript files, the option is under Preferences -> General -> Editors -> Text Editors -> Annotations and in the Annotation types choose JavaScript Occurences. Mine was set to black, nasty little thing took me too long to fix.


问:
How can I return null or bool from a function
I have this function:

```<code>public bool GetBoolSetting(Settings setting)
{
    return int.Parse(GetStringSetting(setting)) == 0 ? false : true;
}
</code>```

There is a problem in that GetStringSetting(setting) can return null, "0" or "1".  When it returns a null I get an exception.

Is it possible for me to make the GetBoolSetting function return a null if this happens?

答:
You can change the type of your method to Nullable<bool> and continue to your one linear statement like below:

```<code>public bool? GetBoolSetting(Settings setting)
{
    return GetStringSetting(setting) != null ?
           int.Parse(GetStringSetting(setting)) != 0 : new bool?();//Or default(bool?)
}
</code>```

You can also use default(bool?) instead of new bool?() which returns the default value of Nullable bool that is null.

Body:
I have this function:

public bool GetBoolSetting(Settings setting)
{
    return int.Parse(GetStringSetting(setting)) == 0 ? false : true;
}

There is a problem in that GetStringSetting(setting) can return null, "0" or "1".  When it returns a null I get an exception.

Is it possible for me to make the GetBoolSetting function return a null if this happens?

Body:
You can change the type of your method to Nullable<bool> and continue to your one linear statement like below:

public bool? GetBoolSetting(Settings setting)
{
    return GetStringSetting(setting) != null ?
           int.Parse(GetStringSetting(setting)) != 0 : new bool?();//Or default(bool?)
}

You can also use default(bool?) instead of new bool?() which returns the default value of Nullable bool that is null.


问:
Why does iter borrow mutably when used in a pattern guard?
This code:

```<code>fn t(r: &[u8]) {
    match r {
        _ if r.iter().any(|&x| x == b';') => {}
        _ => {}
    }
}
</code>```

gives me the error:

error[E0301]: cannot mutably borrow in a pattern guard
   |
10 |         _ if r.iter().any(|&x| x == b';') => {}
   |              ^^^^^^^^ borrowed mutably in pattern guard
```

I understand that I can not borrow mutably in match patterns, but why does the compiler think that r.iter() borrows mutably? There is a separate method iter_mut for borrowing mutably.

And how can I check that &[u8] contains b';' without introducing separate functions?

答:
The error message is a bit more nuanced — iter doesn't borrow mutably, but the result of iter is being borrowed mutably. This is because Iterator::any takes self by mutable reference:

```<code>fn any<F>(&mut self, f: F) -> bool
where
    F: FnMut(Self::Item) -> bool,
</code>```

Here's a reproduction:

```<code>struct X;

impl X {
    fn new() -> X { X }
    fn predicate(&mut self) -> bool { true }
}

fn main() {
    match () {
        _ if X::new().predicate() => {}
        _ => {}
    }
}
</code>```

I'd just check if the slice contains the value:

```<code>fn t(r: &[u8]) {
    match r {
        _ if r.contains(&b';') => {}
        _ => {}
    }
}
</code>```

Realistically, this is an example of the borrow checker being overly aggressive. Mutably borrowing something from "outside" the match guard is a bad idea, but mutably borrowing something created in the match guard should be safe.

It's likely that this particular case would work when the borrow checker is rewritten to use Rust's MIR layer.

See also:

Rust issue #24535

Body:
This code:

fn t(r: &[u8]) {
    match r {
        _ if r.iter().any(|&x| x == b';') => {}
        _ => {}
    }
}

gives me the error:

error[E0301]: cannot mutably borrow in a pattern guard
   |
10 |         _ if r.iter().any(|&x| x == b';') => {}
   |              ^^^^^^^^ borrowed mutably in pattern guard

I understand that I can not borrow mutably in match patterns, but why does the compiler think that r.iter() borrows mutably? There is a separate method iter_mut for borrowing mutably.

And how can I check that &[u8] contains b';' without introducing separate functions?

Body:
The error message is a bit more nuanced — iter doesn't borrow mutably, but the result of iter is being borrowed mutably. This is because Iterator::any takes self by mutable reference:

fn any<F>(&mut self, f: F) -> bool
where
    F: FnMut(Self::Item) -> bool,

Here's a reproduction:

struct X;

impl X {
    fn new() -> X { X }
    fn predicate(&mut self) -> bool { true }
}

fn main() {
    match () {
        _ if X::new().predicate() => {}
        _ => {}
    }
}

I'd just check if the slice contains the value:

fn t(r: &[u8]) {
    match r {
        _ if r.contains(&b';') => {}
        _ => {}
    }
}

Realistically, this is an example of the borrow checker being overly aggressive. Mutably borrowing something from "outside" the match guard is a bad idea, but mutably borrowing something created in the match guard should be safe.

It's likely that this particular case would work when the borrow checker is rewritten to use Rust's MIR layer.

See also:

Rust issue #24535


问:
Cannot upload development package to Lambda
I am constantly getting this error when trying to upload my development package to lambda. On my windows 7 pro box.

--zip-file must be a zip file with fileb:// prefix.

I have googled and found very little help. I have tried with a full path, with quotes, without, file instead of fileb all without any hope.

My publish Batch file:

```<code>del emailer.zip
cd emailer
"C:\Program Files\WinRAR\rar.exe" a -r emailer.zip
move /y emailer.zip ../emailer.zip
cd ..
aws lambda update-function-code --function-name emailer --zip-file fileb://emailer.zip
</code>```

I have uploaded the development package here in case there is an issue with how I have constructed the package.

Why am I constantly getting this error? what do I need to do/research to resolve this issue?

答:
Your file is not a valid zip file, you have created it through winrar which have created another type of archive

when downloading your file

```<code>fhenri@machine:~/Downloads$ file emailer.zip
emailer.zip: RAR archive data, v1d, os: Win32
</code>```

When create a zip file (unzip zip cli) I am getting

```<code>fhenri@machine:~/Downloads$ file emailer_zip.zip
email_zip.zip: Zip archive data, at least v1.0 to extract
</code>```

If you need to use winrar, you can check use winrar command line to create zip archives to create a correct zip archive, otherwise just winzip or another zip program

Body:
I am constantly getting this error when trying to upload my development package to lambda. On my windows 7 pro box.

--zip-file must be a zip file with fileb:// prefix.

I have googled and found very little help. I have tried with a full path, with quotes, without, file instead of fileb all without any hope.

My publish Batch file:

del emailer.zip
cd emailer
"C:\Program Files\WinRAR\rar.exe" a -r emailer.zip
move /y emailer.zip ../emailer.zip
cd ..
aws lambda update-function-code --function-name emailer --zip-file fileb://emailer.zip

I have uploaded the development package here in case there is an issue with how I have constructed the package.

Why am I constantly getting this error? what do I need to do/research to resolve this issue?

Body:
Your file is not a valid zip file, you have created it through winrar which have created another type of archive

when downloading your file

fhenri@machine:~/Downloads$ file emailer.zip
emailer.zip: RAR archive data, v1d, os: Win32

When create a zip file (unzip zip cli) I am getting

fhenri@machine:~/Downloads$ file emailer_zip.zip
email_zip.zip: Zip archive data, at least v1.0 to extract

If you need to use winrar, you can check use winrar command line to create zip archives to create a correct zip archive, otherwise just winzip or another zip program


答:
The web is full of useful tools that shall aid you in this:

Google pageSpeed for one and GTmetrix another. Make use of these tools to analyse what could be causing your site to be slow.

Also, ensure all of your'e images are properly optimised. Another tool again that may help is Tinypng.

Google's Inspector can also be very useful to help diagnose bottlenecks and so forth. Here's another link that may help you:

https://developers.google.com/web/tools/chrome-devtools/network-performance/

Also, I see you are using various libraries such as owl carousel, Parallax, and fitvids to name three. I would look to try and at least use cdn versions: a CDN is a way to deliver content from your website or mobile application to people more quickly and efficiently, based on their geographic location.

Also, look into lazy loading of your images.

Title: why is my page loading so slowly?

Body:
My website: http://jgyboatparty.com/

is loading horrifically slow  and I cant figure out why. I have compressed the images as much as possible and made the video file available as a webm, and yet with a fresh reload the page is taken minutes to load!

Am i missing something here, as for some reason when I look at when elements are loaded, some of the images dont even start loading until 30 seconds in. This all means that my loader goes on for a while. (I have a wait until images loaded function)

Any advice would be much appreciated :)


问:
php search help
following are my posted variables from search form:

```<code>$city = $_REQUEST['city'];
$location = $_REQUEST['location'];
$bedrooms = $_REQUEST['noofbedrooms'];
$addeddate = $_REQUEST['addeddate'];
$minprice = $_REQUEST['pricefrom'];
$maxprice = $_REQUEST['priceto'];
$minarea = $_REQUEST['areafrom'];
$maxarea = $_REQUEST['areato'];
$propertytype = $_REQUEST['proptype'];
</code>```

so far so good. Now i need some good suggestions for the following scenario.
Almost every element in my field are optional. That means i can get empty values in above variables.

What should be my scenario to create the mysql query for the above variables. On case can be that i use conditions for each and every scenario. eg

```<code>if($city=="")
  $query="";
elseif($location=="")
  $query="";
and so on....
</code>```

i need some professional approach for this.

答: well I answered above, I think as your fields are optional you dont need to go with SQL AND, some somtimes = is not that good as well, you can use LIKE for most cases like location, and price from can be a ">=" etc. please note. </p>

Title: php search help

Body:
following are my posted variables from search form:

$city = $_REQUEST['city'];
$location = $_REQUEST['location'];
$bedrooms = $_REQUEST['noofbedrooms'];
$addeddate = $_REQUEST['addeddate'];
$minprice = $_REQUEST['pricefrom'];
$maxprice = $_REQUEST['priceto'];
$minarea = $_REQUEST['areafrom'];
$maxarea = $_REQUEST['areato'];
$propertytype = $_REQUEST['proptype'];

so far so good. Now i need some good suggestions for the following scenario.
Almost every element in my field are optional. That means i can get empty values in above variables.

What should be my scenario to create the mysql query for the above variables. On case can be that i use conditions for each and every scenario. eg

if($city=="")
  $query="";
elseif($location=="")
  $query="";
and so on....

i need some professional approach for this.


问:
Multiple git repositories with 1 main repository
I'm using my own admin panel for multiple websites.

I have a git repository for just the admin panel, and a seperate git repository for every website.

So my question is: How can I update my admin panel easily. When I commit something to the admin panel repository, how can I automatically merge the new feature into the websites that are using that admin panel.

Do I need a plugin on my server for it or can I run some commands on the server every time something gets commited in the admin panel it merges with the other repositories.

答:
You can use git submodules.

In every repository that depends on the admin panel repository, you should add a submodule. Say repo1 and repo2 depend on the admin panel.

```<code> cd repo1/
 git submodule add <admin_panel_repository_url>
</code>```

And that's it. If the admin panel repository has changed, you can update repo1 and repo2:

```<code>cd repo1/
git submodule update
</code>```

Hope that helps.

Body:
You can use git submodules.

In every repository that depends on the admin panel repository, you should add a submodule. Say repo1 and repo2 depend on the admin panel.

 cd repo1/
 git submodule add <admin_panel_repository_url>

And that's it. If the admin panel repository has changed, you can update repo1 and repo2:

cd repo1/
git submodule update

Hope that helps.


问:
Changing states with  instead of  using ui-router
I'm using AngularJs V1.6. Ui- Router V 1.0.3

I've been trying to learn how to work with ui-router for the past few eeks and I came upon this code today which has me totally confused :-

Html side -

```<code><ul ng-if="!isAuthenticated()" class="nav navbar-nav pull-right">
    <li><a href="/#/login">Login</a></li>
    <li><a href="/#/signup">Sign up</a></li>
</ul>
</code>```

JS -

```<code>$stateProvider
  .state('home', {
    url: '/',
    controller: 'HomeCtrl',
    templateUrl: 'partials/home.html'
  })
  .state('login', {
    url: '/login',
    templateUrl: 'partials/login.html',
    controller: 'LoginCtrl',
    resolve: {
      skipIfLoggedIn: skipIfLoggedIn
    }
  })
</code>```

This is code from Satellizer.

I tried replicating it but all it did was end up showing me the folder structure of my working directory in the browser.
However, I was using ui-router visualizer and upon clicking the route in that, it worked properly. I can't find any samples where ui-router is used this way, how exactly is this above snippet working?

I also read here that typing

```<code><a ui-sref="party">Go To Party</a>
</code>```

will turn it into

```<code><a href="/party" ui-sref="party">Go To Party</a>
</code>```

in our browser. However, in the example I posted intially, there is no ui-sref with the href. Once again, how exactly or what exactly is happening? Is it only working because it's retrieving a separate html file?

答:
I tried replicating it but all it did was end up showing me the folder
  structure of my working directory in the browser.

This happened because the first example in your question uses hash-prefix for generated links and the second example uses html5Mode for links.

When you click on a link with hash prefix mode eg. #/home, the request of that resource is handled at client-side by ui-router and is not sent to the server. But when you click on a link that is without prefix eg. /home, the request goes to the server. Your server needs to understand about this type of request (look at the referenced link below).

The default mode generates # as prefix. If you don't want to have hash prefix # in generated links then you need to enable HTML5Mode like this:

```<code>app.config(["$locationProvider", function($locationProvider) {
  $locationProvider.html5Mode(true);
}]);
</code>```

If you enable this mode, then don't forget to inform Angular about the root URL of your app by adding following to the head section of your HTML file:

<base href="/">

Reference:

Read more about how to configure your server to work with html5Mode here.

About ui-sref directive:

The preferred way of route/state resolution using ui-router in HTML templates is to use ui-sref which is a directive that binds a link i.e. anchor tag ( tag) to a state. If a state has an associated URL, the directive will automatically generate, update the href attribute for you.

This way your HTML template just needs to refer a state name and the link resolution will be done for you which is good as if in future you change the underlying link for states, your templates will still work. This directive uses $state.href() method for link value.

You can directly use the associated link in anchor tag without using this directive. But doing this, you will always need to revise your link if you change url in route config. Let ui-router module help you to manage this without writing any extra line of code and to ease state management.

The usage of this directive is:

ui-sref='stateName' - Navigate to state, no params. 'stateName' can be any valid absolute or relative state, following the same syntax rules as $state.go()

ui-sref='stateName({param: value, param: value})' - Navigate to state, with params.

Example: If you html has following link:

```<code><a ui-sref="home">Home</a>
</code>```

The generated HTML (Html5Mode Off results in prepended '#') will be following provided your route config has a valid state named as home:

```<code><a href="#/home" ui-sref="home">Home</a>
</code>```

Reference:
 - UI Router ui-sref directive

Body:
I'm using AngularJs V1.6. Ui- Router V 1.0.3

I've been trying to learn how to work with ui-router for the past few eeks and I came upon this code today which has me totally confused :-

Html side -

Login

Sign up

JS -

$stateProvider
  .state('home', {
    url: '/',
    controller: 'HomeCtrl',
    templateUrl: 'partials/home.html'
  })
  .state('login', {
    url: '/login',
    templateUrl: 'partials/login.html',
    controller: 'LoginCtrl',
    resolve: {
      skipIfLoggedIn: skipIfLoggedIn
    }
  })

This is code from Satellizer.

I tried replicating it but all it did was end up showing me the folder structure of my working directory in the browser.
However, I was using ui-router visualizer and upon clicking the route in that, it worked properly. I can't find any samples where ui-router is used this way, how exactly is this above snippet working?

I also read here that typing

Go To Party

will turn it into

Go To Party

in our browser. However, in the example I posted intially, there is no ui-sref with the href. Once again, how exactly or what exactly is happening? Is it only working because it's retrieving a separate html file?

Body:
I tried replicating it but all it did was end up showing me the folder
  structure of my working directory in the browser.

This happened because the first example in your question uses hash-prefix for generated links and the second example uses html5Mode for links.

When you click on a link with hash prefix mode eg. #/home, the request of that resource is handled at client-side by ui-router and is not sent to the server. But when you click on a link that is without prefix eg. /home, the request goes to the server. Your server needs to understand about this type of request (look at the referenced link below).

The default mode generates # as prefix. If you don't want to have hash prefix # in generated links then you need to enable HTML5Mode like this:

app.config(["$locationProvider", function($locationProvider) {
  $locationProvider.html5Mode(true);
}]);

If you enable this mode, then don't forget to inform Angular about the root URL of your app by adding following to the head section of your HTML file:

<base href="/">

Reference:

Read more about how to configure your server to work with html5Mode here.

About ui-sref directive:

The preferred way of route/state resolution using ui-router in HTML templates is to use ui-sref which is a directive that binds a link i.e. anchor tag ( tag) to a state. If a state has an associated URL, the directive will automatically generate, update the href attribute for you.

This way your HTML template just needs to refer a state name and the link resolution will be done for you which is good as if in future you change the underlying link for states, your templates will still work. This directive uses $state.href() method for link value.

You can directly use the associated link in anchor tag without using this directive. But doing this, you will always need to revise your link if you change url in route config. Let ui-router module help you to manage this without writing any extra line of code and to ease state management.

The usage of this directive is:

ui-sref='stateName' - Navigate to state, no params. 'stateName' can be any valid absolute or relative state, following the same syntax rules as $state.go()

ui-sref='stateName({param: value, param: value})' - Navigate to state, with params.

Example: If you html has following link:

<a ui-sref="home">Home</a>

The generated HTML (Html5Mode Off results in prepended '#') will be following provided your route config has a valid state named as home:

<a href="#/home" ui-sref="home">Home</a>

Reference:
 - UI Router ui-sref directive


问:
is it posible invoke another client method remotely?
i would like to make an .net or even cross-platform(php, .net) app A and B that communicate each other.
if A insert or update some data in database, then B is refresh its view to display new data. is there any solution about this?

i read this article about WCF before, as far as i know now client only call method that operate for them self. also that article mention that it can notify another client to do something but not specify how-to make 1 client inform another to call some method.

is there any tutorial or help regarding this problem?
Thank you..

答:
There are two (easy) options:

You can use the Azure IoT Hub to invoke methods. I have successfully done it.
More about Azure IoT Hub

If your goal is to generate a near real-time dashboard (report) you can use PowerPI with REST-API and a Push-/Streamingdataset. If you don't want to codding: Look at this post


问:
How to add new fields to document in Cloudant without losing existing ones
I am attempting to add new fields to a document I have in Cloudant based on user input, however when I do an insert I am overwriting the document and losing existing fields, unless I send them with the insert.

For example, I have one command that performs a query to Cloudant to receive a document, and returns me the _id, _rev, name and special_id fields. This document gets passed to a new command that appends a field, such as favorite_food, through an insert (and yes I am using _rev).

Now, the user inputs another command, like "add school". The process starts over, I query Cloudant, and the query I have returns me the _id, _rev, name, and special_id. I append a school field to the doc, do an insert, but then I check the document and favorite_food is gone.

Is there a param that I can pass to the Cloudant insert function to tell it to actually perform an update and not an overwrite?

FYI this is running on Node and using the node-cloudant package. In the docs I can't find any more details about params, and a typical insert looks like:

```<code>cloudantDb.insert(doc, params, function(error, response) {
  if (!error) {
    console.log("success", response);
    resolve(response);
  } else {
    console.log("error", error);
    reject(error);
  }
});
</code>```

答:
Without seeing your code, it's hard to say for sure. There is no magic parameter. In Cloudant, there is no difference between create, update and delete -- they're all essentially creating a revision. You can't "patch" the JSON doc, you need to provide the whole thing, every time. Here's an example:</p>

```<code># Create a new document
curl -XPOST -H 'content-type:application/json' \
    'https://skruger.cloudant.com/testdb' -d '{"name":"stefan"}'
{"ok":true,"id":"5309a1784a9cc45d498e8170af7dcc3c","rev":"1-a0f0b27e1069f45cc121dfe5dc08f280"}

# Add a field
curl -XPUT -H 'content-type:application/json' \
 'https://skruger.cloudant.com/testdb/5309a1784a9cc45d498e8170af7dcc3c' \
  -d '{"_id":"5309a1784a9cc45d498e8170af7dcc3c", "_rev":"1-a0f0b27e1069f45cc121dfe5dc08f280", "name":"stefan", "fish":"pike pearch"}'
{"ok":true,"id":"5309a1784a9cc45d498e8170af7dcc3c","rev":"2-7c3ea3603c3e16962c7b33f50becc771"}

# Fetch it again
curl 'https://skruger.cloudant.com/testdb/5309a1784a9cc45d498e8170af7dcc3c'
{"_id":"5309a1784a9cc45d498e8170af7dcc3c","_rev":"2-7c3ea3603c3e16962c7b33f50becc771","name":"stefan","fish":"pike pearch"}

# And another new field
curl -XPUT -H 'content-type:application/json' \
 'https://skruger.cloudant.com/testdb/5309a1784a9cc45d498e8170af7dcc3c' \
 -d '{"_id":"5309a1784a9cc45d498e8170af7dcc3c", "_rev":"2-7c3ea3603c3e16962c7b33f50becc771", "name":"stefan", "fish":"pike pearch", "sport":"tennis"}'
 {"ok":true,"id":"5309a1784a9cc45d498e8170af7dcc3c","rev":"3-e0f4d1ab1a47b046ea90a0fbbf34ff36"}

# Fetch again
curl 'https://skruger.cloudant.com/testdb/5309a1784a9cc45d498e8170af7dcc3c'
{"_id":"5309a1784a9cc45d498e8170af7dcc3c","_rev":"3-e0f4d1ab1a47b046ea90a0fbbf34ff36","name":"stefan","fish":"pike pearch","sport":"tennis"}
</code>```

Body:
I am attempting to add new fields to a document I have in Cloudant based on user input, however when I do an insert I am overwriting the document and losing existing fields, unless I send them with the insert.

For example, I have one command that performs a query to Cloudant to receive a document, and returns me the _id, _rev, name and special_id fields. This document gets passed to a new command that appends a field, such as favorite_food, through an insert (and yes I am using _rev).

Now, the user inputs another command, like "add school". The process starts over, I query Cloudant, and the query I have returns me the _id, _rev, name, and special_id. I append a school field to the doc, do an insert, but then I check the document and favorite_food is gone.

Is there a param that I can pass to the Cloudant insert function to tell it to actually perform an update and not an overwrite?

FYI this is running on Node and using the node-cloudant package. In the docs I can't find any more details about params, and a typical insert looks like:

cloudantDb.insert(doc, params, function(error, response) {
  if (!error) {
    console.log("success", response);
    resolve(response);
  } else {
    console.log("error", error);
    reject(error);
  }
});

Body:
Without seeing your code, it's hard to say for sure. There is no magic parameter. In Cloudant, there is no difference between create, update and delete -- they're all essentially creating a revision. You can't "patch" the JSON doc, you need to provide the whole thing, every time. Here's an example:

# Create a new document
curl -XPOST -H 'content-type:application/json' \
    'https://skruger.cloudant.com/testdb' -d '{"name":"stefan"}'
{"ok":true,"id":"5309a1784a9cc45d498e8170af7dcc3c","rev":"1-a0f0b27e1069f45cc121dfe5dc08f280"}

# Add a field
curl -XPUT -H 'content-type:application/json' \
 'https://skruger.cloudant.com/testdb/5309a1784a9cc45d498e8170af7dcc3c' \
  -d '{"_id":"5309a1784a9cc45d498e8170af7dcc3c", "_rev":"1-a0f0b27e1069f45cc121dfe5dc08f280", "name":"stefan", "fish":"pike pearch"}'
{"ok":true,"id":"5309a1784a9cc45d498e8170af7dcc3c","rev":"2-7c3ea3603c3e16962c7b33f50becc771"}

# Fetch it again
curl 'https://skruger.cloudant.com/testdb/5309a1784a9cc45d498e8170af7dcc3c'
{"_id":"5309a1784a9cc45d498e8170af7dcc3c","_rev":"2-7c3ea3603c3e16962c7b33f50becc771","name":"stefan","fish":"pike pearch"}

# And another new field
curl -XPUT -H 'content-type:application/json' \
 'https://skruger.cloudant.com/testdb/5309a1784a9cc45d498e8170af7dcc3c' \
 -d '{"_id":"5309a1784a9cc45d498e8170af7dcc3c", "_rev":"2-7c3ea3603c3e16962c7b33f50becc771", "name":"stefan", "fish":"pike pearch", "sport":"tennis"}'
 {"ok":true,"id":"5309a1784a9cc45d498e8170af7dcc3c","rev":"3-e0f4d1ab1a47b046ea90a0fbbf34ff36"}

# Fetch again
curl 'https://skruger.cloudant.com/testdb/5309a1784a9cc45d498e8170af7dcc3c'
{"_id":"5309a1784a9cc45d498e8170af7dcc3c","_rev":"3-e0f4d1ab1a47b046ea90a0fbbf34ff36","name":"stefan","fish":"pike pearch","sport":"tennis"}


问:
Is it possible to create databases programmatically using DBX?
Looks like the TSQLConnection only connects to existing databases, and I could not find another component that allows me to send commands to the database server.

I'm using Delphi 2009 with Firebird and MSSQL.

One idea that came was to connect to a system database (master or tempdb in MSSQL for example) and then send create commands to the server. This could be an option for MSSQL, but I'm not sure for Firebird.

I'm also aware of the new DBX metadata in Delphi 2009, but I couldn't find a way to create databases using it. All examples I've found is to modify existing databases.

答: Erick if you use Devart drivers you can connect without the databasename parameter and send the t-sql create database command.</p>

OwnerDisplayName: Erick Sasse

LastEditorDisplayName: Erick Sasse


问:
How to test a module in odoo 8
I'm starting to learn odoo modules developing
so I created a module named "vetclinic" in odoo/addons

it contains 4 files inside which are:

init.py

openerp.py

vetclinic.py

vetclinic_view.xml

and I created models inside them which I want to test their output.

How could I test it?

I tried this command

```<code>./openerp-server --addons-path=addons -d opt-test -i vetclinic
</code>```

and I got this error

```<code>WARNING opt-test openerp.modules.loading: invalid module names, ignored: vetclinic
</code>```

答:
The files you have created do note form a proper Odoo module. In order for them to do so you must rename a couple of them:

init.py becomes __init__.py

openerp.pybecomes __openerp__.py

Please refer to the Odoo documentation site for more information.

Title: How to test a module in odoo 8

Body:
I'm starting to learn odoo modules developing
so I created a module named "vetclinic" in odoo/addons

it contains 4 files inside which are:

init.py

openerp.py

vetclinic.py

vetclinic_view.xml

and I created models inside them which I want to test their output.

How could I test it?

I tried this command

./openerp-server --addons-path=addons -d opt-test -i vetclinic

and I got this error

WARNING opt-test openerp.modules.loading: invalid module names, ignored: vetclinic


问:
Install NodeJS packages from file with NPM install
Is it possible to install nodejs packages (/modules) from files like in ruby's Gemfile as done with bundle install or python's requirements file (eg: requirements.pip) as done using pip install -r commands ?

Say I have a file where three or four package names are listed.

How would I instruct npm to install packages whose names are found in that file (and resolve dependencies which it also does)?

答:
Just create your package JSON, you can use yarn to manage your packages instead of npm, it's faster.

Inside your package you can create a section of scripts accessed by npm run

scripts: {
  customBuild: 'your sh code/ruby/script whateve'
}

And after you can run on terminal, npm run customBuild for example


问:
All buttons have same width - jQuery
Im programming a calculator and Im trying that all the buttons in the same column has the same width. For that Im using jQuery (Im doing it this way cause I have an exam in some days and I wanna practice).

My HTML code:

```<code><html>
  <head>
    <meta charset="UTF-8">
    <title>CORE2017 P3</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script type="text/javascript" src="calculadora.js"></script>
    <link href="calculadora.css" rel="stylesheet" type="text/css" media="all">
  </head>
  <body onload="igualarBotones()">
    <header>
      <p>Calculator</p>
    </header>
    <section id="main">
      <p>
        Número: <input type="text" id="pantalla"> <button id="Limpiar">Limpiar</button>
      </p>

      <p>
        <button id="suma" class="columna1">+</button>
        <button id="resta" class="columna2">-</button>
        <button id="cuadrado" class="columna3">x<sup>2</sup></button>
      </p>
      <p>
        <button id="inverso" class="columna1">1/x</button>
        <button id="raiz" class="columna2">sqrt(x)</button>
        <button id="pentera" class="columna3">parte_entera(x)</button>
      </p>
      <p>
        <button id="potencia2" class="columna1">2<sup>x</sup></button>
        <button id="factorial" class="columna2">x!</button>
        <button id="igual" class="columna3">=</button>
      </p>

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

My JavaScript code:

```<code>$(function() {
  function igualarBotones(){
    var columna1 = $(".columna1");
    setMax(columna1);
    var columna2 = $(".columna2");
    setMax(columna2);
    var columna3 = $(".columna3");
    setMax(columna3);
  }

  function setMax(columna){
    var maxColumna = -1;
    for(i=0; i<columna.length; i++){
      if(columna[i].css("width") > maxColumna){
        maxColumna = columna[i].css("width");
      }
    }
    for(i=0; i<columna.length; i++){
      columna[i].css("width",maxColumna);
    }
  }

});
</code>```

Anyone knows why it isnt working?

EDIT: I used $(columna[i]).css instead of columna[i].css and it worked. However I dont achieve that my function igualarBotones() gets defined when loading the body, I think it must be something related to how I named or wrote the function. If I write the Javascript this way:

```<code>$(function() {
  var columna1 = $(".columna1");
  setMax(columna1);
  var columna2 = $(".columna2");
  setMax(columna2);
  var columna3 = $(".columna3");
  setMax(columna3);

  function setMax(columna){
    var maxColumna = -1;
    for(i=0; i<columna.length; i++){
      if(parseFloat($(columna[i]).css("width")) > parseFloat(maxColumna)){
        maxColumna = $(columna[i]).css("width");
      }
    }
    columna.css("width",maxColumna);
  }
});
</code>```

it works, but I want to do it with a function igualarBotones() that gets loaded with the body. Any idea what am I doing wrong?

Thank you all, Luis.

答:
I'm not familiar with a .css function in vanilla javascript.  I changed that so it would call the jQuery .css function.  Also, at least in the pen, the function wasn't defined when the body was loading.  Something is still off in how you're finding the max size, but this should get you started.

  function igualarBotones(){
    var columna1 = $(".columna1");
    setMax(columna1);
    var columna2 = $(".columna2");
    setMax(columna2);
    var columna3 = $(".columna3");
    setMax(columna3);
  }

  function setMax(columna){
    var maxColumna = -1;
    for(var i=0; i<columna.length; i++){
      if($(columna[i]).css("width") > maxColumna){
        maxColumna = $(columna[i]).css("width");
      }
    }
    for(i=0; i<columna.length; i++){
      $(columna[i]).css("width",maxColumna);
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <head>
    <meta charset="UTF-8">
    <title>CORE2017 P3</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script type="text/javascript" src="calculadora.js"></script>
    <link href="calculadora.css" rel="stylesheet" type="text/css" media="all">
  </head>
  <body onload="igualarBotones();">
    <header>
      <p>Calculator</p>
    </header>
    <section id="main">
      <p>
        Número: <input type="text" id="pantalla"> <button id="Limpiar">Limpiar</button>
      </p>

      <p>
        <button id="suma" class="columna1">+</button>
        <button id="resta" class="columna2">-</button>
        <button id="cuadrado" class="columna3">x<sup>2</sup></button>
      </p>
      <p>
        <button id="inverso" class="columna1">1/x</button>
        <button id="raiz" class="columna2">sqrt(x)</button>
        <button id="pentera" class="columna3">parte_entera(x)</button>
      </p>
      <p>
        <button id="potencia2" class="columna1">2<sup>x</sup></button>
        <button id="factorial" class="columna2">x!</button>
        <button id="igual" class="columna3">=</button>
      </p>

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

Title: All buttons have same width - jQuery

Body:
Im programming a calculator and Im trying that all the buttons in the same column has the same width. For that Im using jQuery (Im doing it this way cause I have an exam in some days and I wanna practice).

My HTML code:

    <meta charset="UTF-8">
    <title>CORE2017 P3</title>

    <link href="calculadora.css" rel="stylesheet" type="text/css" media="all">

Calculator

        Número: <input type="text" id="pantalla"> <button id="Limpiar">Limpiar</button>

        <button id="suma" class="columna1">+</button>
        <button id="resta" class="columna2">-</button>
        <button id="cuadrado" class="columna3">x2</button>

        <button id="inverso" class="columna1">1/x</button>
        <button id="raiz" class="columna2">sqrt(x)</button>
        <button id="pentera" class="columna3">parte_entera(x)</button>

        <button id="potencia2" class="columna1">2x</button>
        <button id="factorial" class="columna2">x!</button>
        <button id="igual" class="columna3">=</button>

My JavaScript code:

$(function() {
  function igualarBotones(){
    var columna1 = $(".columna1");
    setMax(columna1);
    var columna2 = $(".columna2");
    setMax(columna2);
    var columna3 = $(".columna3");
    setMax(columna3);
  }

  function setMax(columna){
    var maxColumna = -1;
    for(i=0; i<columna.length; i++){
      if(columna[i].css("width") > maxColumna){
        maxColumna = columna[i].css("width");
      }
    }
    for(i=0; i<columna.length; i++){
      columna[i].css("width",maxColumna);
    }
  }

});

Anyone knows why it isnt working?

EDIT: I used $(columna[i]).css instead of columna[i].css and it worked. However I dont achieve that my function igualarBotones() gets defined when loading the body, I think it must be something related to how I named or wrote the function. If I write the Javascript this way:

$(function() {
  var columna1 = $(".columna1");
  setMax(columna1);
  var columna2 = $(".columna2");
  setMax(columna2);
  var columna3 = $(".columna3");
  setMax(columna3);

  function setMax(columna){
    var maxColumna = -1;
    for(i=0; i<columna.length; i++){
      if(parseFloat($(columna[i]).css("width")) > parseFloat(maxColumna)){
        maxColumna = $(columna[i]).css("width");
      }
    }
    columna.css("width",maxColumna);
  }
});

it works, but I want to do it with a function igualarBotones() that gets loaded with the body. Any idea what am I doing wrong?

Thank you all, Luis.

Body:
I'm not familiar with a .css function in vanilla javascript.  I changed that so it would call the jQuery .css function.  Also, at least in the pen, the function wasn't defined when the body was loading.  Something is still off in how you're finding the max size, but this should get you started.

  function igualarBotones(){
    var columna1 = $(".columna1");
    setMax(columna1);
    var columna2 = $(".columna2");
    setMax(columna2);
    var columna3 = $(".columna3");
    setMax(columna3);
  }

  function setMax(columna){
    var maxColumna = -1;
    for(var i=0; i<columna.length; i++){
      if($(columna[i]).css("width") > maxColumna){
        maxColumna = $(columna[i]).css("width");
      }
    }
    for(i=0; i<columna.length; i++){
      $(columna[i]).css("width",maxColumna);
    }
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <head>
    <meta charset="UTF-8">
    <title>CORE2017 P3</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script type="text/javascript" src="calculadora.js"></script>
    <link href="calculadora.css" rel="stylesheet" type="text/css" media="all">
  </head>
  <body onload="igualarBotones();">
    <header>
      <p>Calculator</p>
    </header>
    <section id="main">
      <p>
        Número: <input type="text" id="pantalla"> <button id="Limpiar">Limpiar</button>
      </p>

      <p>
        <button id="suma" class="columna1">+</button>
        <button id="resta" class="columna2">-</button>
        <button id="cuadrado" class="columna3">x<sup>2</sup></button>
      </p>
      <p>
        <button id="inverso" class="columna1">1/x</button>
        <button id="raiz" class="columna2">sqrt(x)</button>
        <button id="pentera" class="columna3">parte_entera(x)</button>
      </p>
      <p>
        <button id="potencia2" class="columna1">2<sup>x</sup></button>
        <button id="factorial" class="columna2">x!</button>
        <button id="igual" class="columna3">=</button>
      </p>

    </section>
  </body>
</html>


问:
Extending a Collection where the Element type is generic (Swift)
It's simple to extend a Collection type in swift to have a custom function for particular Element types:

```<code>struct MyStruct {
    let string: String
}

extension Set where Element == MyStruct {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}
</code>```

But suppose your Element type is generic?

```<code>protocol MyProtocol {}

struct MyGenericStruct<T: MyProtocol> {
    let string: String
}

// error on next line:
// error: expected '>' to complete generic argument list
// extension Set where Element == MyGenericStruct<T: MyProtocol> {
//                                                 ^
extension Set where Element == MyGenericStruct<T: MyProtocol> {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}

// error on next line:
// error: use of undeclared type 'T'
// extension Set where Element == MyGenericStruct<T> {
//                                                ^
extension Set where Element == MyGenericStruct<T> {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}
</code>```

It's unclear to me how to declare that my element is a generic.

答:
Details

Swift 3.1, xCode 8.3.3

Solution

```<code>import Foundation

struct MyStruct:Hashable {

    let string: String

    static func == (lhs: MyStruct, rhs: MyStruct) -> Bool {
        return lhs.string == rhs.string
    }

    var hashValue: Int {
        return string.hash
    }
}

extension Set where Element == MyStruct {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}

var set = Set<MyStruct>()
set.insert(MyStruct(string: "123"))
set.insert(MyStruct(string: "231"))
print(String(describing:set.getFirstWith(string: "123")))
print(String(describing:set.getFirstWith(string: "231")))

///////////////////////////////////

protocol MyProtocol {}

struct MyType1: MyProtocol {}
struct MyType2: MyProtocol {}

struct MyGenericStruct<T: MyProtocol>: Hashable {
    let string: String

    static func == (lhs: MyGenericStruct, rhs: MyGenericStruct) -> Bool {
        return lhs.string == rhs.string
    }

    var hashValue: Int {
        return string.hash
    }
}

extension Set where Element == AnyHashable {
    func getFirstWith(string: String) -> Element? {

        return filter{ element -> Bool in
            if let _element = element as? MyGenericStruct<MyType1> {
                if  _element.string == string {
                    return true
                }
            }
            if let _element = element as? MyGenericStruct<MyType2> {
                if  _element.string == string {
                    return true
                }
            }
            return false
        }.first

    }
}

var set2 = Set<AnyHashable>()
set2.insert(MyGenericStruct<MyType1>(string: "abc"))
set2.insert(MyGenericStruct<MyType2>(string: "cba"))
print(String(describing: set2.getFirstWith(string: "abc")))
print(String(describing:set2.getFirstWith(string: "cba")))
</code>```

Result

Body:
It's simple to extend a Collection type in swift to have a custom function for particular Element types:

struct MyStruct {
    let string: String
}

extension Set where Element == MyStruct {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}

But suppose your Element type is generic?

protocol MyProtocol {}

struct MyGenericStruct<T: MyProtocol> {
    let string: String
}

// error on next line:
// error: expected '>' to complete generic argument list
// extension Set where Element == MyGenericStruct<T: MyProtocol> {
//                                                 ^
extension Set where Element == MyGenericStruct<T: MyProtocol> {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}

// error on next line:
// error: use of undeclared type 'T'
// extension Set where Element == MyGenericStruct<T> {
//                                                ^
extension Set where Element == MyGenericStruct<T> {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}

It's unclear to me how to declare that my element is a generic.

Body:
Details

Swift 3.1, xCode 8.3.3

Solution

import Foundation

struct MyStruct:Hashable {

    let string: String

    static func == (lhs: MyStruct, rhs: MyStruct) -> Bool {
        return lhs.string == rhs.string
    }

    var hashValue: Int {
        return string.hash
    }
}

extension Set where Element == MyStruct {
    func getFirstWith(string: String) -> Element? {
        return filter({ $0.string == string }).first
    }
}

var set = Set<MyStruct>()
set.insert(MyStruct(string: "123"))
set.insert(MyStruct(string: "231"))
print(String(describing:set.getFirstWith(string: "123")))
print(String(describing:set.getFirstWith(string: "231")))

///////////////////////////////////

protocol MyProtocol {}

struct MyType1: MyProtocol {}
struct MyType2: MyProtocol {}

struct MyGenericStruct<T: MyProtocol>: Hashable {
    let string: String

    static func == (lhs: MyGenericStruct, rhs: MyGenericStruct) -> Bool {
        return lhs.string == rhs.string
    }

    var hashValue: Int {
        return string.hash
    }
}

extension Set where Element == AnyHashable {
    func getFirstWith(string: String) -> Element? {

        return filter{ element -> Bool in
            if let _element = element as? MyGenericStruct<MyType1> {
                if  _element.string == string {
                    return true
                }
            }
            if let _element = element as? MyGenericStruct<MyType2> {
                if  _element.string == string {
                    return true
                }
            }
            return false
        }.first

    }
}

var set2 = Set<AnyHashable>()
set2.insert(MyGenericStruct<MyType1>(string: "abc"))
set2.insert(MyGenericStruct<MyType2>(string: "cba"))
print(String(describing: set2.getFirstWith(string: "abc")))
print(String(describing:set2.getFirstWith(string: "cba")))

Result


问:
Can I set an attached device as default launch target?
In Eclipse I am developing an application using Google APIs (maps) on a Nexus One.

 When I launch the application for debugging on the device i get:

"Automatic Target Mode: Unable to detect device compatibility. Please
  select a target device."

and the "Android Device Chooser" pops up.

I can select the Nexus One and everything is ok. It annoys me, however, that i need to select the device every time i want to test something.

Setting a build target name to any standard android version (not using Google apis) automatically launches my app without showing the Android Device Chooser. But since i need the maps, that is not an option for me.

Is there a way to force an application using Google apis, to be launched on the attached device without showing the Android Device Chooser?

答: Go to your project properties. Select Run/Debug Settings, click the Edit button of your run configuration, select the Target tab in the upcoming dialog, switch the selectboxes to "Automatic" and check the checkbox by your device.