问:
PHP Get all users data and check lastonline for each
I want to get each users lastonline time and then check to see if the time now minus their last online time is smaller than 600 seconds after their last login.

I have made a little peice of code which works but not what I want it to do.
I want it to get each users information. For some reason, this code updates every users info depending on 1 user im pretty sure. When I change the smaller than sign in my code to a bigger than sign, they all change with it even-though my users last online time is 1 minute ago.

My code :

```<code><?php
    $user_grab = mysqli_query($con, "SELECT * FROM users");
    while($users_ = mysqli_fetch_array($user_grab)) {

        foreach($users as $user) {
            $last_online = $users_['lastonline'];

            if(time() - $last_online < user_session_timeout()) {
                echo '
                     <div class="chat-list-item -available" style="background: rgba(255,255,255,0.1);">
                        <img class="chat-list-avatar" src="'.$users_['profile_picture'].'"/><i class="fa fa-circle chat-list-status"> </i>
                        <div class="chat-list-user">'.$users_['username'].'</div>
                        <div class="chat-list-excerpt">Online</div>
                     </div>
                ';
            } else {
                echo '
                     <div class="chat-list-item -offline" style="background: rgba(255,255,255,0.1); padding: 5px;">
                        <img class="chat-list-avatar" src="'.$users_['profile_picture'].'"/><i class="fa fa-circle chat-list-status"> </i>
                        <div class="chat-list-user">'.$users_['username'].'</div>
                        <div class="chat-list-excerpt">Offline</div>
                     </div>
                ';
            }
        }
    }
?>
</code>```

My user_session_timeout just reads the time a user hasn't changed page until the users should be redirected

Code for user_session_timeout():

```<code>function user_session_timeout() {
global $con;
    $grab_user_timeout_sql = mysqli_query($con, "SELECT user_session_timeout FROM sitesettings");
    $row = mysqli_fetch_array($grab_user_timeout_sql);
    return $row['user_session_timeout'];
}
</code>```

Picture of my users all offline display

Proof that each users last online time is different

答:
$users_["lastonline"] is a string containing a date and time. You need to parse it to a numeric timestamp so you can subtract it from time().

```<code>$last_online = strtotime($users_['lastonline']);
</code>```

Body:
I want to get each users lastonline time and then check to see if the time now minus their last online time is smaller than 600 seconds after their last login.

I have made a little peice of code which works but not what I want it to do.
I want it to get each users information. For some reason, this code updates every users info depending on 1 user im pretty sure. When I change the smaller than sign in my code to a bigger than sign, they all change with it even-though my users last online time is 1 minute ago.

My code :

<?php
    $user_grab = mysqli_query($con, "SELECT * FROM users");
    while($users_ = mysqli_fetch_array($user_grab)) {

        foreach($users as $user) {
            $last_online = $users_['lastonline'];

            if(time() - $last_online < user_session_timeout()) {
                echo '

'.$users_['username'].'

Online

                ';
            } else {
                echo '

'.$users_['username'].'

Offline

                ';
            }
        }
    }
?>

My user_session_timeout just reads the time a user hasn't changed page until the users should be redirected

Code for user_session_timeout():

function user_session_timeout() {
global $con;
    $grab_user_timeout_sql = mysqli_query($con, "SELECT user_session_timeout FROM sitesettings");
    $row = mysqli_fetch_array($grab_user_timeout_sql);
    return $row['user_session_timeout'];
}

Picture of my users all offline display

Proof that each users last online time is different

Body:
$users_["lastonline"] is a string containing a date and time. You need to parse it to a numeric timestamp so you can subtract it from time().

$last_online = strtotime($users_['lastonline']);


来源: stackexchange

问:
Ionic released app is very slow and so much delay (Only slow on device)
hi when test my app in ionic lab very good but when create apk file and install to device very slow. delay for click on button
delay to push page
delay to open modal
close modal,

delay for anything

答:
If you are running your app in development mode it takes some time to fire the platform.ready() event since it has assertions and various necessary framework checks turned on.

Try running the app in production mode to speed up and optimize the start of your application

If you're in an ionic 2 app, you can enable this by doing the following,

open src/app/main.ts

```<code>Import enableProdMode from Angular 2 core

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

import { AppModule } from './app.module';
</code>```

Then call the enableProdMode() function before bootstraping your module

```<code>enableProdMode();

platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

and now while running the app through cli try adding a flag like "--prod"

ionic run android --prod
In ionic 3.x, you don't have to enable anything in the code. you can simply run it using the cli command,

```<code>ionic cordova run android --prod
</code>```

Hope that helps

ContentLicense: CC BY-SA 3.0

Body:
If you are running your app in development mode it takes some time to fire the platform.ready() event since it has assertions and various necessary framework checks turned on.

Try running the app in production mode to speed up and optimize the start of your application

If you're in an ionic 2 app, you can enable this by doing the following,

open src/app/main.ts

Import enableProdMode from Angular 2 core

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

import { AppModule } from './app.module';

Then call the enableProdMode() function before bootstraping your module

enableProdMode();

platformBrowserDynamic().bootstrapModule(AppModule);

and now while running the app through cli try adding a flag like "--prod"

ionic run android --prod
In ionic 3.x, you don't have to enable anything in the code. you can simply run it using the cli command,

ionic cordova run android --prod

Hope that helps


问:
Spinner's onItemSelected callback called twice after a rotation if non-zero position is selected
When I create my activity, I setup a Spinner, assigning it a listener and an initial value. I know that the onItemSelected callback is called automatically during application initialization. What I find strange is that this happens twice when the device is rotated, causing me some problems that I will have to circumvent someway. This does not happen if the spinner initial selection is zero. I was able to isolate the issue, here's the simplest activity triggering it:

```<code>public class MainActivity extends Activity implements OnItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i("Test","Activity onCreate");
    setContentView(R.layout.activity_main);
    ((Spinner)findViewById(R.id.spinner1)).setSelection(2);
    ((Spinner)findViewById(R.id.spinner1)).setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> spin, View selview, int pos, long selId)
{
    Log.i("Test","spin:"+spin+" sel:"+selview+" pos:"+pos+" selId:"+selId);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {}
}
</code>```

And here's the logcat shown when the application is started and then the device rotated:

```<code>    I/Test( 9881): spin:android.widget.Spinner@4052f508 sel:android.widget.TextView@40530b08 pos:2 selId:2
    I/Test( 9881): Activity onCreate
    I/Test( 9881): spin:android.widget.Spinner@40535d80 sel:android.widget.TextView@40538758 pos:2 selId:2
    I/Test( 9881): spin:android.widget.Spinner@40535d80 sel:android.widget.TextView@40538758 pos:2 selId:2
</code>```

Is this the expected behaviour? Am I missing something?

答:
Just use setSelection(#, false) before setting the listener:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    spinner.setSelection(2, false);
    spinner.setOnItemSelectedListener(this);
}
</code>```

The key is the second parameter. It says to not animate the transition, executing the action immediately and preventing onItemSelected from being fired twice, because a call is already made by the system.

Body:
When I create my activity, I setup a Spinner, assigning it a listener and an initial value. I know that the onItemSelected callback is called automatically during application initialization. What I find strange is that this happens twice when the device is rotated, causing me some problems that I will have to circumvent someway. This does not happen if the spinner initial selection is zero. I was able to isolate the issue, here's the simplest activity triggering it:

public class MainActivity extends Activity implements OnItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i("Test","Activity onCreate");
    setContentView(R.layout.activity_main);
    ((Spinner)findViewById(R.id.spinner1)).setSelection(2);
    ((Spinner)findViewById(R.id.spinner1)).setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> spin, View selview, int pos, long selId)
{
    Log.i("Test","spin:"+spin+" sel:"+selview+" pos:"+pos+" selId:"+selId);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {}
}

And here's the logcat shown when the application is started and then the device rotated:

    I/Test( 9881): spin:android.widget.Spinner@4052f508 sel:android.widget.TextView@40530b08 pos:2 selId:2
    I/Test( 9881): Activity onCreate
    I/Test( 9881): spin:android.widget.Spinner@40535d80 sel:android.widget.TextView@40538758 pos:2 selId:2
    I/Test( 9881): spin:android.widget.Spinner@40535d80 sel:android.widget.TextView@40538758 pos:2 selId:2

Is this the expected behaviour? Am I missing something?

Body:
Just use setSelection(#, false) before setting the listener:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    spinner.setSelection(2, false);
    spinner.setOnItemSelectedListener(this);
}

The key is the second parameter. It says to not animate the transition, executing the action immediately and preventing onItemSelected from being fired twice, because a call is already made by the system.

ContentLicense: CC BY-SA 4.0


问:
opening a modal with the click of a button
The next code uses a Modal react component:

```<code>export class AddWorkLogEditor extends React.Component {
    constructor(props) {
        super(props);

        this.addWorkLog = this.addWorkLog.bind(this);
        this.onOpenModal = this.onOpenModal.bind(this);
        this.onCloseModal = this.onCloseModal.bind(this);
        this.state = {
             open:true

           };
      }

  onOpenModal() {
     this.setState({open: this.props.openModal});
  }

  onCloseModal() {
     this.setState({open:false});
  }

  addWorkLog() {

   }

 render() {
      const bstyle = {
         backgroundColor: 'green',
         textAlign:"left",
         paddingLeft: '0px',
         color: 'white'
    };
 const {open} = this.state;
       return (
           <div>
                <Modal open={open} onClose={this.onCloseModal} little>
                <h3>hi gi</h3>

                 <Button bsStyle="success" bsSize="small" onClick ={(ev) => {console.log(ev)} }> Save </Button>
                 </Modal>
            </div>
       );
    }
}
</code>```

I am trying to call it using:

```<code>addWorkLog()
{
      return <AddWorkLogEditor/>;
}
</code>```

and

```<code> createAddWorkLogButton () {

    return (
        <button style={ { color: '#007a86'} } onClick={this.addWorkLog} >Add Work Log</button>
    );
 }
</code>```

I mean, after I click at this button nothing shows up. Is there another way to call that modal? I am importing the modal from:

import Modal from 'react-responsive-modal'

答:
You are trying to render the modal only once the button is clicked, while that's  quite natural for non-react environments, in react it works in a different way. In the simplest solution the Modal should be always rendered, and when a user clicks the button you change the modal open property to true.

```<code>{ /* all the markup of your page */ }
<button onClick={() => this.setState({showModal: true})}>Add Work Log</button>
{ /* anything else */ }

{ /* modal is here but it is hidden */ }
<Modal open={this.state.showModal}>...</Modal>
</code>```

Alternatively, you can just skip the modal rendering at all until the showModal becomes true.

```<code>this.state.showModal && <Modal open>...</Modal>
</code>```

Body:
The next code uses a Modal react component:

export class AddWorkLogEditor extends React.Component {
    constructor(props) {
        super(props);

        this.addWorkLog = this.addWorkLog.bind(this);
        this.onOpenModal = this.onOpenModal.bind(this);
        this.onCloseModal = this.onCloseModal.bind(this);
        this.state = {
             open:true

           };
      }

  onOpenModal() {
     this.setState({open: this.props.openModal});
  }

  onCloseModal() {
     this.setState({open:false});
  }

  addWorkLog() {

   }

 render() {
      const bstyle = {
         backgroundColor: 'green',
         textAlign:"left",
         paddingLeft: '0px',
         color: 'white'
    };
 const {open} = this.state;
       return (

                <Modal open={open} onClose={this.onCloseModal} little>

hi gi

                 <Button bsStyle="success" bsSize="small" onClick ={(ev) => {console.log(ev)} }> Save </Button>
                 </Modal>

       );
    }
}

I am trying to call it using:

addWorkLog()
{
      return <AddWorkLogEditor/>;
}

and

 createAddWorkLogButton () {

    return (
        <button style={ { color: '#007a86'} } onClick={this.addWorkLog} >Add Work Log</button>
    );
 }

I mean, after I click at this button nothing shows up. Is there another way to call that modal? I am importing the modal from:

import Modal from 'react-responsive-modal'

Body:
You are trying to render the modal only once the button is clicked, while that's  quite natural for non-react environments, in react it works in a different way. In the simplest solution the Modal should be always rendered, and when a user clicks the button you change the modal open property to true.

{ /* all the markup of your page */ }
<button onClick={() => this.setState({showModal: true})}>Add Work Log</button>
{ /* anything else */ }

{ /* modal is here but it is hidden */ }
<Modal open={this.state.showModal}>...</Modal>

Alternatively, you can just skip the modal rendering at all until the showModal becomes true.

this.state.showModal && <Modal open>...</Modal>


问:
How to exit only an 'if' block in Python and not the entire program
Here I want to exit the if block, but I don't want to use sys.exit() as it will terminate the program. I have a few lines to be executed at the end, hence I want to exit the if block only.
I can't use break as it flags an error "break outside loop".

In this I want the program to exit the block at "if (retry == 3)", line 55 and print the lines at the end. However, it’s not happening until it is using sys.exit(), where it’s completely exiting the program.

```<code>import random
import sys

loop = ''
retry = 0
loop = input('Do you want to play lottery? yes/no: ')
if loop != 'yes':
    print('Thank you!! Visit again.')
    sys.exit()
fireball = input('Do you want to play fireball? yes/no: ')

lotto_numbers = sorted(random.sample(range(0, 4), 3))
fireball_number = random.randint(0, 3)

while loop == 'yes':

    user_input1 = int(input('Please enter the first number: '))
    user_input2 = int(input('Please enter the second number: '))
    user_input3 = int(input('Please enter the third number: '))
    print('Your numbers are: ', user_input1, user_input2, user_input3)

    def check():
        if lotto_numbers != [user_input1, user_input2, user_input3]:
            return False

        else:
            return True

    def fbcheck():
        if lotto_numbers == [user_input1, user_input2, fireball_number]:
            return True
        elif lotto_numbers == [fireball_number, user_input2, user_input3]:
            return True
        elif lotto_numbers == [user_input1, fireball_number, user_input3]:
            return True
        else:
            return False

    retry += 1
    result = check()
    if (result == True):
        print("Congratulations!! You won!!")
    else:
        print("Oops!! You lost.")

    if (fireball == 'yes'):
        fb_result = fbcheck()
        if (fb_result == True):

            print("Congratulations, you won a fireball!!")
        else:
            print("Sorry, you lost the fireball.")
    print('No of retries remaining: ', (3 - retry))
    if (retry == 3):

        sys.exit()

    loop = input('Do you want to try again? yes/no: ')
    continue
else:

    pass

print("Winning combination: ", lotto_numbers)
if (fireball == 'yes'):
    print('fireball no: ', fireball_number)
print('Thank you!! Visit again.')
</code>```

答:
I think I gotcha your willing.

You want to execute something after the if condition is executed? So, create a subtask, and call it!

```<code>def finish_program():
  print("something")
  a = "foo"
  print("finish program")

loop = input('Do u want to play lottery ? yes/no : ')
if loop!='yes':
    print('Thank you!! visit again.')
    finish_program()
</code>```

Body:
Here I want to exit the if block, but I don't want to use sys.exit() as it will terminate the program. I have a few lines to be executed at the end, hence I want to exit the if block only.
I can't use break as it flags an error "break outside loop".

In this I want the program to exit the block at "if (retry == 3)", line 55 and print the lines at the end. However, it’s not happening until it is using sys.exit(), where it’s completely exiting the program.

import random
import sys

loop = ''
retry = 0
loop = input('Do you want to play lottery? yes/no: ')
if loop != 'yes':
    print('Thank you!! Visit again.')
    sys.exit()
fireball = input('Do you want to play fireball? yes/no: ')

lotto_numbers = sorted(random.sample(range(0, 4), 3))
fireball_number = random.randint(0, 3)

while loop == 'yes':

    user_input1 = int(input('Please enter the first number: '))
    user_input2 = int(input('Please enter the second number: '))
    user_input3 = int(input('Please enter the third number: '))
    print('Your numbers are: ', user_input1, user_input2, user_input3)

    def check():
        if lotto_numbers != [user_input1, user_input2, user_input3]:
            return False

        else:
            return True

    def fbcheck():
        if lotto_numbers == [user_input1, user_input2, fireball_number]:
            return True
        elif lotto_numbers == [fireball_number, user_input2, user_input3]:
            return True
        elif lotto_numbers == [user_input1, fireball_number, user_input3]:
            return True
        else:
            return False

    retry += 1
    result = check()
    if (result == True):
        print("Congratulations!! You won!!")
    else:
        print("Oops!! You lost.")

    if (fireball == 'yes'):
        fb_result = fbcheck()
        if (fb_result == True):

            print("Congratulations, you won a fireball!!")
        else:
            print("Sorry, you lost the fireball.")
    print('No of retries remaining: ', (3 - retry))
    if (retry == 3):

        sys.exit()

    loop = input('Do you want to try again? yes/no: ')
    continue
else:

    pass

print("Winning combination: ", lotto_numbers)
if (fireball == 'yes'):
    print('fireball no: ', fireball_number)
print('Thank you!! Visit again.')

Body:
I think I gotcha your willing.

You want to execute something after the if condition is executed? So, create a subtask, and call it!

def finish_program():
  print("something")
  a = "foo"
  print("finish program")

loop = input('Do u want to play lottery ? yes/no : ')
if loop!='yes':
    print('Thank you!! visit again.')
    finish_program()


问:
keeping the one view on the front and doing another activity in Android
I want to play the audio file in my application but the condition is that I want to play the selected sound file in background that means when the Timer CountDown(I have created one separate View for the Timer CountDown) gets over the audio file should play with the Same Timer CountDown View as it is.

The Timer CountDown Layout View should be maintained and the audio file should be played.

Can anyone please help me here because I am able to play the selected file finely, but All I want to do is just to play it with the Timer CountDown View maintained.

答:
How are you playing the audio file? With MediaPlayer you should be able to achieve what you want.

This question could also be helpful.

ContentLicense: CC BY-SA 2.5


问:
Task progress from a ZeroMQ worker
Fairly new to ZeroMQ. I have a simple REQ/REP queue like below. I am using PHP but that doesn't matter as any language binding would be fine for me.
This is client to request a task

```<code>$ctx = new ZMQContext();
$req = new ZMQSocket($ctx, ZMQ::SOCKET_REQ);
$req->connect('tcp://localhost:5454');
$req->send("Export Data as Zip");
echo $i . ":" . $req->recv().PHP_EOL;
</code>```

And this is a worker to actually perform the task.

```<code>$ctx = new ZMQContext();
$srvr = new ZMQSocket($ctx, ZMQ::SOCKET_REP);
$srvr->bind("tcp://*:5454");
echo "Server is started at port $port" . PHP_EOL;
while(true)
{
    $msg = $srvr->recv();
    echo "Message = " . $msg . PHP_EOL;
    // Do the work here, takes 10 min, knows the count of lines added and remaining
    $srvr->send($msg . " is exported as zip file" . date('H:i:s'));
}
</code>```

As the task of exporting data takes about 10 min, I want to connect to the server from a different client and get the progress/ percentage of the task done.
I am wondering if that's even a valid approach.

I tried this approach where REQ/REP part works but I get nothing in PUB/SUB part

Server part

```<code>$ctx = new ZMQContext();
$srvr = new ZMQSocket($ctx, ZMQ::SOCKET_REP);
$srvr->bind("tcp://*:5454");

// add PUB socket to publish progress
$c = new ZMQContext();
$p = new ZMQSocket($c, ZMQ::SOCKET_PUB);
$p->bind("tcp://*:5460");

echo "Server is started at port 5454" . PHP_EOL;
$prog = 0;
while(true)
{
    $p->send($prog++ . '%'); // this part doesn't get to the progress client
    $msg = $srvr->recv();
    echo "Message = " . $msg . PHP_EOL;
    sleep(2);// some long task
    $srvr->send($msg . " Done zipping " . date('H:i:s'));
}
</code>```

Progress client

```<code>$ctx = new ZMQContext();
$stat = new ZMQSocket($ctx, ZMQ::SOCKET_SUB);
$stat->connect('tcp://localhost:5460');
while (true){
    echo $stat->recv() . PHP_EOL; //nothing shows here
}
</code>```

Request client

```<code>$ctx = new ZMQContext();
$req = new ZMQSocket($ctx, ZMQ::SOCKET_REQ);
$req->connect('tcp://localhost:5454');
for($i=0;$i<100;$i++){
    $req->send("$i : Zip the file please");
    echo $i . ":" . $req->recv().PHP_EOL; //works and get the output
}
</code>```

答:
You need only use PUB/SUB if there is more than one client wanting to receive the same progress updates. Just use PUSH/PULL for a simple, point to point transfer that works over tcp.

Philosophical Discussion

With problems such as this to solve there's two approaches.

Use additional sockets to convey additional message types,

Use just two sockets, but convey more than one message type through them

You're talking about doing 1). It might be worth contemplating 2), though I must emphasise that I know next to nothing of PHP and so don't know if there are language features that encourage one to have separate request and progress clients.

If you do, your original client needs a loop (after it has sent the request) to receive multiple messages, either progress update messages or the final result. Your server, whilst it is doing its 10 minute lookup, will send regular progress update messages, and the final result message at the end. You would probably use PUSH/PULL client to server, and the same again for the progress / result from the server back to the client.

It is architecturally more flexible to follow 2). Once you have a means of sending two or more message types through a single socket and of decoding them at the receiving end, you can send more. For example, you could decide to add a 'cancel' message from the client to the server, or a partial results message from the server back to the client. This is much easier to extend than to keep adding more sockets to your architecture simply because you want to add another message flow between the client and server. Again, I don't know enough about PHP to say that this would definitely be the right way of doing it in that language. It certainly makes a lot of sense in C, C++.

I find things like Google Protocol Buffers (I prefer ASN.1) very useful for this kind of thing. These allow you to define the types of messages you want to send, and (at least with GPB), combine them together inside a single 'oneof' (in ASN.1 one uses tagging to tell different messages apart). GPB and ASN.1 are handy because then you can use different languages, OSes and platforms in your system without really having to worry about what it is being sent. And being binary (not text) they're more efficient across network connections.

Title: Task progress from a ZeroMQ worker

Body:
Fairly new to ZeroMQ. I have a simple REQ/REP queue like below. I am using PHP but that doesn't matter as any language binding would be fine for me.
This is client to request a task

$ctx = new ZMQContext();
$req = new ZMQSocket($ctx, ZMQ::SOCKET_REQ);
$req->connect('tcp://localhost:5454');
$req->send("Export Data as Zip");
echo $i . ":" . $req->recv().PHP_EOL;

And this is a worker to actually perform the task.

$ctx = new ZMQContext();
$srvr = new ZMQSocket($ctx, ZMQ::SOCKET_REP);
$srvr->bind("tcp://*:5454");
echo "Server is started at port $port" . PHP_EOL;
while(true)
{
    $msg = $srvr->recv();
    echo "Message = " . $msg . PHP_EOL;
    // Do the work here, takes 10 min, knows the count of lines added and remaining
    $srvr->send($msg . " is exported as zip file" . date('H:i:s'));
}

As the task of exporting data takes about 10 min, I want to connect to the server from a different client and get the progress/ percentage of the task done.
I am wondering if that's even a valid approach.

I tried this approach where REQ/REP part works but I get nothing in PUB/SUB part

Server part

$ctx = new ZMQContext();
$srvr = new ZMQSocket($ctx, ZMQ::SOCKET_REP);
$srvr->bind("tcp://*:5454");

// add PUB socket to publish progress
$c = new ZMQContext();
$p = new ZMQSocket($c, ZMQ::SOCKET_PUB);
$p->bind("tcp://*:5460");

echo "Server is started at port 5454" . PHP_EOL;
$prog = 0;
while(true)
{
    $p->send($prog++ . '%'); // this part doesn't get to the progress client
    $msg = $srvr->recv();
    echo "Message = " . $msg . PHP_EOL;
    sleep(2);// some long task
    $srvr->send($msg . " Done zipping " . date('H:i:s'));
}

Progress client

$ctx = new ZMQContext();
$stat = new ZMQSocket($ctx, ZMQ::SOCKET_SUB);
$stat->connect('tcp://localhost:5460');
while (true){
    echo $stat->recv() . PHP_EOL; //nothing shows here
}

Request client

$ctx = new ZMQContext();
$req = new ZMQSocket($ctx, ZMQ::SOCKET_REQ);
$req->connect('tcp://localhost:5454');
for($i=0;$i<100;$i++){
    $req->send("$i : Zip the file please");
    echo $i . ":" . $req->recv().PHP_EOL; //works and get the output
}


问:
How to get OS language and locale?
My app changes the language at runtime and advises the user to restart the app. I do it like this:

```<code>    typealias LanguageLocaleType = (language: String?, locale: String?, title: String)

    let elements: [LanguageLocaleType] = [
        (nil, nil, "System Default"),
        ("en", "en_US", "English"),
        ("ar", "ar_SA", "Arabic"),
    ]

    //...func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)...

    let element = elements[indexPath.row]

    guard let language = element.language else {
        // How to really reset app back to OS language/locale???
        UserDefaults.standard.removeObject(forKey: "AppleLanguages")
        UserDefaults.standard.removeObject(forKey: "AppleLocale")
        return
    }

    UserDefaults.standard.set([language], forKey: "AppleLanguages")

    if let locale = element.locale, !locale.isEmpty,
        Locale.current.identifier != locale,
        !Locale.current.identifier.hasPrefix("\(language)_") {
            UserDefaults.standard.set(locale, forKey: "AppleLocale")
    }
</code>```

I want to offer to set languages in a list with the right one selected, one of which being offered it to set language back to System Default. However, there's no way to find the OS-level language and locale that I could find. Since after I mess around with setting the UserDefaults, Bundle.main.preferredLocalizations is not reliable and do not match the system default (event when I remove the key from the User Default).

Is there a way to get the OS-level language and locale instead of the app-level?

答:
I found an answer which seems to do something similar, by playing with the Bundle language files of your app. As in setting the proper one.

While you state that playing with Bundle properties seems to fiddle with your use case, I'd look into saving the setted language with Core Data, inside an app file, or inside and XML (.plist). You could set up a checking method in didFinishWithOptions which checks the presence of this variable then runs the language prompt if absent or leaves as is if present (adding a check to make sure the right language is set would be wise). Since this does not alter the Settings-set language, you'd always have a quick reference point outside of your app through NSLocale to switch back to it with ease if the user so chooses.

Here's the post

Disclaimer 1 : i haven't tested this, but it seems like a plausible, and Apple-Tolerated thing to do.
Disclaimer 2 : as the OP in the link states, and as some have mentioned here, changing app language is not recommended by Apple. Notably due to NSLocale keys, and how frequently Swift is updated which could lead to your code being unuseable or requiring massive overhaul.. As i mentioned in a comment above, i'd reconsider this use-case sadly :(

Title: How to get OS language and locale?

Body:
My app changes the language at runtime and advises the user to restart the app. I do it like this:

    typealias LanguageLocaleType = (language: String?, locale: String?, title: String)

    let elements: [LanguageLocaleType] = [
        (nil, nil, "System Default"),
        ("en", "en_US", "English"),
        ("ar", "ar_SA", "Arabic"),
    ]

    //...func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)...

    let element = elements[indexPath.row]

    guard let language = element.language else {
        // How to really reset app back to OS language/locale???
        UserDefaults.standard.removeObject(forKey: "AppleLanguages")
        UserDefaults.standard.removeObject(forKey: "AppleLocale")
        return
    }

    UserDefaults.standard.set([language], forKey: "AppleLanguages")

    if let locale = element.locale, !locale.isEmpty,
        Locale.current.identifier != locale,
        !Locale.current.identifier.hasPrefix("\(language)_") {
            UserDefaults.standard.set(locale, forKey: "AppleLocale")
    }

I want to offer to set languages in a list with the right one selected, one of which being offered it to set language back to System Default. However, there's no way to find the OS-level language and locale that I could find. Since after I mess around with setting the UserDefaults, Bundle.main.preferredLocalizations is not reliable and do not match the system default (event when I remove the key from the User Default).

Is there a way to get the OS-level language and locale instead of the app-level?


问:
install mysql keyring plugin
I was trying to install keyring plugin on MySQL 5.7.18.

I edited my.ini file.  It was blank so I added the following text and restarted MySQL.

```<code>[mysqld]
early-plugin-load=keyring_file.dll
</code>```

I ran the following command to install the plugin.

```<code>mysql> install plugin keyring_file soname 'keyring_file.dll';
</code>```

I then ran the following sql to check:

```<code>mysql> SELECT PLUGIN_NAME, PLUGIN_STATUS
    ->        FROM INFORMATION_SCHEMA.PLUGINS
    ->        WHERE PLUGIN_NAME LIKE 'keyring%';
+--------------+---------------+
| PLUGIN_NAME  | PLUGIN_STATUS |
+--------------+---------------+
| keyring_file | ACTIVE        |
+--------------+---------------+
1 row in set (0.00 sec)
</code>```

But when I tried to alter a table to use encryption, I got errors.

```<code>mysql> ALTER TABLE t1 ENCRYPTION='Y';
ERROR 3185 (HY000): Can't find master key from keyring, please check keyring
plugin is loaded.
</code>```

Did I miss a step somewhere?

答:
Harriett, do the following:

Check the user that the MySQL service runs as (e.g., NETWORK SERVICE)

Create a keyring folder in C:/Program Files/MySQL/MySQL Server 5.7

Explicitly grant the MySQL service user permissions on the keyring folder

By default on Windows when using keyring_file, the keyring file is stored in C:/Program Files/MySQL/MySQL Server 5.7/keyring/keyring (I determined this by running SHOW VARIABLES LIKE 'keyring%' after installing the plugin and confirming its loading as you described).

After creating the keyring folder in C:/Program Files/MySQL/MySQL Server 5.7 right-click, then Properties -> Security, then Edit -> Add etc. Once the user is added check "Modify" in addition to Read & execute, List folder contents, Read and Write.

Then restart the MySQL service and you should be able to create an encrypted table without error.

NOTE: For security reasons you should go back and remove all users/groups you don't think will absolutely need to have access to the keyring folder (e.g., local machine users). On Unix the docs recommend that the mysql user and group alone have access to the folder.

Title: install mysql keyring plugin

Body:
I was trying to install keyring plugin on MySQL 5.7.18.

I edited my.ini file.  It was blank so I added the following text and restarted MySQL.

[mysqld]
early-plugin-load=keyring_file.dll

I ran the following command to install the plugin.

mysql> install plugin keyring_file soname 'keyring_file.dll';

I then ran the following sql to check:

mysql> SELECT PLUGIN_NAME, PLUGIN_STATUS
    ->        FROM INFORMATION_SCHEMA.PLUGINS
    ->        WHERE PLUGIN_NAME LIKE 'keyring%';
+--------------+---------------+
| PLUGIN_NAME  | PLUGIN_STATUS |
+--------------+---------------+
| keyring_file | ACTIVE        |
+--------------+---------------+
1 row in set (0.00 sec)

But when I tried to alter a table to use encryption, I got errors.

mysql> ALTER TABLE t1 ENCRYPTION='Y';
ERROR 3185 (HY000): Can't find master key from keyring, please check keyring
plugin is loaded.

Did I miss a step somewhere?


问:
Parsing XML file in python
```<code>    import requests
    import xml.etree.ElementTree as ET

    def abc(area_code, office_code):
        args = area_code + office_code
     url = (described bellow)
     r = requests.get(url=url)
     tree=ET.ElementTree()
     parsed_data=tree.parse(r.content)
      return parsed_data

   abc('503', '402')
</code>```

where url is

```<code>url="http://www.networksolutions.ds.adp.com/NSPhoneToolDB/template/GetBusRouteFilterExpressions.xml?"\
               "Telnum=" +args+ "&FilterNamePrefix=ORPORTCDK&ReturnResult=detail"
</code>```

when i run this thing i am getting

```<code><Element 'GetBusRouteFilterExpressions' at 0x7f2abf526f48>
</code>```

as output instead of entire file.

答:
You're giving it the response object itself.

Try giving it the content of the response like so parsed_data=tree.parse(r.content).

Title: Parsing XML file in python

Body:
    import requests
    import xml.etree.ElementTree as ET

    def abc(area_code, office_code):
        args = area_code + office_code
     url = (described bellow)
     r = requests.get(url=url)
     tree=ET.ElementTree()
     parsed_data=tree.parse(r.content)
      return parsed_data

   abc('503', '402')

where url is

url="http://www.networksolutions.ds.adp.com/NSPhoneToolDB/template/GetBusRouteFilterExpressions.xml?"\
               "Telnum=" +args+ "&FilterNamePrefix=ORPORTCDK&ReturnResult=detail"

when i run this thing i am getting

<Element 'GetBusRouteFilterExpressions' at 0x7f2abf526f48>

as output instead of entire file.


问:
Creating custom Label in C# and passing data in events
I had been playing around with an idea for a game, and implementation was going fairly well, but I have hit a stumbling block.

Basically, I have a form, which will show talent trees.  I am just going to use labels to display the relevant details, and I want to create them programmatically.  The display part is working fine, the part I am having trouble with is adding an event handler to the labels.

I want to be able to pass data during the event handling, so that I can identify which specific label was clicked, but I am hitting a brick wall.  So when a particular label is clicked, the name of its associated skill (just passing a string) will be sent to the event handler.  Any help would be appreciated.  Here is the relevant code that I have:

```<code>        public void DisplayTree()
    {
        int i=0;
        startPoint.X = 40;
        startPoint.Y = 125;

        foreach(SkillNode s in tree.tier1)
        {
            for (i=0; i < s.labels.Count;i++ )
            {
                //Displays a label for each available rank for a skill
                s.labels.ElementAt(i).Text = (i+1).ToString()+"/"+s.maxRank.ToString();
                s.labels.ElementAt(i).Location = startPoint;
                startPoint.Y += s.labels.ElementAt(i).Height + 2;
                s.labels.ElementAt(i).Name = "lbl"+s.name+i.ToString();

                //Only enable it to be clicked if the user is at the correct rank
                if (s.rank == i)
                {
                    s.labels.ElementAt(i).Enabled = true;
                }
                else
                {
                    s.labels.ElementAt(i).Enabled = false;
                }
                //Add Event here
                //I want to pass the name of the skill with the event

                this.Controls.Add(s.labels.ElementAt(i));
            }
            startPoint.X += s.title.Width + 5;
            startPoint.Y = 125;
        }
    }
    public void LabelClick()
    {
        //Code here to pick out the name of the label

    }
</code>```

答:
When you create an event and want to follow the official C# styleguide, you follow the following pattern:

```<code>public delegate void {YourName}EventHandler(object sender, {YourName}EventArgs args);
public event {YourName}EventHandler EventName;
</code>```

Every information about what happened in the event or can be manipulated by the subscriber is stored in a class that inherits EventArgs. The delegate also contains a reference to the sender, which is the object that fires the event.

When you fire an event you do the following, regularly in a protected method that has the same name as the Event with an "On" as prefix:

```<code>EventName?.Invoke(this, new {YourName}EventArgs() { Initialize Stuff });
</code>```

As you can see, you can work with the sender and identify the object. In your case you could also change object sender to UIElement sender (or similar) to make it easier to identify stuff without a cast.

Body:
I had been playing around with an idea for a game, and implementation was going fairly well, but I have hit a stumbling block.

Basically, I have a form, which will show talent trees.  I am just going to use labels to display the relevant details, and I want to create them programmatically.  The display part is working fine, the part I am having trouble with is adding an event handler to the labels.

I want to be able to pass data during the event handling, so that I can identify which specific label was clicked, but I am hitting a brick wall.  So when a particular label is clicked, the name of its associated skill (just passing a string) will be sent to the event handler.  Any help would be appreciated.  Here is the relevant code that I have:

        public void DisplayTree()
    {
        int i=0;
        startPoint.X = 40;
        startPoint.Y = 125;

        foreach(SkillNode s in tree.tier1)
        {
            for (i=0; i < s.labels.Count;i++ )
            {
                //Displays a label for each available rank for a skill
                s.labels.ElementAt(i).Text = (i+1).ToString()+"/"+s.maxRank.ToString();
                s.labels.ElementAt(i).Location = startPoint;
                startPoint.Y += s.labels.ElementAt(i).Height + 2;
                s.labels.ElementAt(i).Name = "lbl"+s.name+i.ToString();

                //Only enable it to be clicked if the user is at the correct rank
                if (s.rank == i)
                {
                    s.labels.ElementAt(i).Enabled = true;
                }
                else
                {
                    s.labels.ElementAt(i).Enabled = false;
                }
                //Add Event here
                //I want to pass the name of the skill with the event

                this.Controls.Add(s.labels.ElementAt(i));
            }
            startPoint.X += s.title.Width + 5;
            startPoint.Y = 125;
        }
    }
    public void LabelClick()
    {
        //Code here to pick out the name of the label

    }

Body:
When you create an event and want to follow the official C# styleguide, you follow the following pattern:

public delegate void {YourName}EventHandler(object sender, {YourName}EventArgs args);
public event {YourName}EventHandler EventName;

Every information about what happened in the event or can be manipulated by the subscriber is stored in a class that inherits EventArgs. The delegate also contains a reference to the sender, which is the object that fires the event.

When you fire an event you do the following, regularly in a protected method that has the same name as the Event with an "On" as prefix:

EventName?.Invoke(this, new {YourName}EventArgs() { Initialize Stuff });

As you can see, you can work with the sender and identify the object. In your case you could also change object sender to UIElement sender (or similar) to make it easier to identify stuff without a cast.


问:
.NET - Timer Elapsed Event Overlap
Is there a way to detect that elapsed events of timer are overlapping? For example, I create a Timer with 200ms interval between elapsed events but the executed code at event is taking more than 200ms. As a result, another elapsed event is executed before the last one is finished. Also is there a way to prevent this from happening such that another event is not invoked before the last one is finished?</p>

答:
If you want your timer events to happen on the 200ms mark and just skip one (rather than postpone them) if the previous is still running then you could use locking code.

If you use the method Monitor.TryEnter then it will return a boolean telling you if it has got the lock (and thus if another thread is already in the locked code). This will enable you to just skip over and wait for the next run time if you want (or write out debug messages complaining that its taking too long or something).

Whether this is a good solution really depends on what your timer is wanting to do. Often the method others have suggested of starting the timer for the next event once the previous one finishes is more than sufficient for the job.

Title: .NET - Timer Elapsed Event Overlap


问:
Find sequence algorithm for a list of expressions?
Is it possible to use sympy to find the algorithm for a sequence of expressions?

For example, if I have the following list:

```<code>s = [ fraction(1/1), fraction(1/2), fraction(1/4), ... ]
</code>```

Can sympy extract the expression representing this list of expressions?

```<code>>> fraction(1/(2**(x-1)))
</code>```

答:
As described, this is not a well-defined task. The formula 1/(1+x*(x-1)/2) also fits the given data. More generally, for any finite set of data points there are infinitely many formulas that match all points exactly; which one should be returned as the answer?

SymPy does have interpolation routines interpolate and rational_interpolate; the former returns a polynomial and the latter a rational function passing through the given points. (Reference.) Polynomial interpolation can be used in your example if you know that an exponential function should fit, and therefore take the logarithm of data, as follows:

```<code>s = [Rational(1, 1), Rational(1, 2), Rational(1, 4)]
x = Symbol('x', real=True)
result = exp(interpolate([log(y) for y in s], x)).simplify()
print(result)
</code>```

This prints 2**(-x + 1). The idea is that taking logarithm turns exponential function into linear, which can be constructed with interpolate.

But generally speaking, the problems of fitting a curve of some form to given data are solved numerically with packages like scikit-learn.

Body:
Is it possible to use sympy to find the algorithm for a sequence of expressions?

For example, if I have the following list:

s = [ fraction(1/1), fraction(1/2), fraction(1/4), ... ]

Can sympy extract the expression representing this list of expressions?

>> fraction(1/(2**(x-1)))

Body:
As described, this is not a well-defined task. The formula 1/(1+x*(x-1)/2) also fits the given data. More generally, for any finite set of data points there are infinitely many formulas that match all points exactly; which one should be returned as the answer?

SymPy does have interpolation routines interpolate and rational_interpolate; the former returns a polynomial and the latter a rational function passing through the given points. (Reference.) Polynomial interpolation can be used in your example if you know that an exponential function should fit, and therefore take the logarithm of data, as follows:

s = [Rational(1, 1), Rational(1, 2), Rational(1, 4)]
x = Symbol('x', real=True)
result = exp(interpolate([log(y) for y in s], x)).simplify()
print(result)

This prints 2**(-x + 1). The idea is that taking logarithm turns exponential function into linear, which can be constructed with interpolate.

But generally speaking, the problems of fitting a curve of some form to given data are solved numerically with packages like scikit-learn.


问:
CMake: Replace compile flags of an INTERFACE target
I need to replace the /std:c++14 flag of an INTERFACE target (header-only library) with /std:c++17. CMake doesn't support setting C++17 flags in VS directly yet (see How to enable /std:c++17 in VS2017 with CMake) so I need to manually replace it.

However get_target_property(my_compile_flags mylib COMPILE_OPTIONS) to retrieve the list of currently set flags to then subsequently replace /std:c++14 with /std:c++17 doesn't work:

INTERFACE_LIBRARY targets may only have whitelisted properties.  The property "COMPILE_OPTIONS" is not allowed.

You can set them however via target_compile_features(...) and manually via e.g. target_compile_options(mylib INTERFACE /std:c++17). But the latter command adds the flag, without removing /std:c++14.

How to go about that?

答:
For an interface library you need to change INTERFACE_COMPILE_DEFINITIONS instead of COMPILE_DEFINITIONS (see add_library(INTERFACE)).

Here is a full example I've tested with VS2017 (using /std:c++latest since not yet supported /std:c++17 may be ignored/removed by CMake):

cmake_minimum_required(VERSION 3.8)

project(InterfaceLibCppStd)

include(CheckCXXCompilerFlag)

file(WRITE "mylib/Definitions.h" [=[
    #define HELLO_TEXT "Hello Interface Lib"
]=])
add_library(mylib INTERFACE)

target_include_directories(mylib INTERFACE "mylib")
target_compile_options(mylib INTERFACE "/std:c++14")

file(WRITE "main.cpp" [=[
    #include "Definitions.h"
    #include <iostream>

    int main()
    {
        std::cout << HELLO_TEXT << std::endl;
    }
]=])
add_executable(myexe "main.cpp")

if (MSVC_VERSION GREATER_EQUAL "1900")
    CHECK_CXX_COMPILER_FLAG("/std:c++latest" _cpp_latest_flag_supported)
    if (_cpp_latest_flag_supported)
        get_target_property(_opt_old mylib INTERFACE_COMPILE_OPTIONS)
        string(REPLACE "14" "latest" _opt_new "${_opt_old}")
        set_target_properties(mylib PROPERTIES INTERFACE_COMPILE_OPTIONS "${_opt_new}")
   endif()
endif()

target_link_libraries(myexe PUBLIC mylib)
```


问:
R: Extract columns from list of data.frames in a tibble
I am wondering how to manipulate a list containing data.frames stored in a tibble.

Specifically, I would like to extract two columns from a data.frame that are stored in a tibble list column.

I would like to go from this tibble c

```<code>random_data<-list(a=letters[1:10],b=LETTERS[1:10])
x<-as.data.frame(random_data, stringsAsFactors=FALSE)
y<-list()
y[[1]]<-x[1,,drop=FALSE]
y[[3]]<-x[2,,drop=FALSE]
c<-tibble(z=c(1,2,3),my_data=y)
</code>```

to this tibble d

```<code>d<-tibble(z=c(1,2,3),a=c('a',NA,'b'),b=c('A',NA,'B'))
</code>```

thanks

Iain

答:
You could create a function f to change out the NULL values, then apply it to the my_data column and finish with unnest.

```<code>library(dplyr); library(tidyr)

unnest(mutate(c, my_data = lapply(my_data, f)))
# # A tibble: 3 x 3
#       z     a     b
#   <dbl> <chr> <chr>
# 1     1     a     A
# 2     2  <NA>  <NA>
# 3     3     b     B
</code>```

Where f is a helper function to change out the NULL values, and is defined as

```<code>f <- function(x) {
    if(is.null(x)) data.frame(a = NA, b = NA) else x
}
</code>```

Body:
I am wondering how to manipulate a list containing data.frames stored in a tibble.

Specifically, I would like to extract two columns from a data.frame that are stored in a tibble list column.

I would like to go from this tibble c

random_data<-list(a=letters[1:10],b=LETTERS[1:10])
x<-as.data.frame(random_data, stringsAsFactors=FALSE)
y<-list()
y[[1]]<-x[1,,drop=FALSE]
y[[3]]<-x[2,,drop=FALSE]
c<-tibble(z=c(1,2,3),my_data=y)

to this tibble d

d<-tibble(z=c(1,2,3),a=c('a',NA,'b'),b=c('A',NA,'B'))

thanks

Iain

Body:
You could create a function f to change out the NULL values, then apply it to the my_data column and finish with unnest.

library(dplyr); library(tidyr)

unnest(mutate(c, my_data = lapply(my_data, f)))
# # A tibble: 3 x 3
#       z     a     b
#   <dbl> <chr> <chr>
# 1     1     a     A
# 2     2  <NA>  <NA>
# 3     3     b     B

Where f is a helper function to change out the NULL values, and is defined as

f <- function(x) {
    if(is.null(x)) data.frame(a = NA, b = NA) else x
}


问:
How to parse an array that is in a json object
I'm having issues drilling down into a json object that has an array in it. The issue I'm running into is that when I get inside that object it returns object Object.

My code looks like this:

```<code>(function(){
   var rivetAPI = "https://url";
   $.ajax({
          url:rivetAPI,
          type:"GET",
          dataType:"json",
          success: function(obj){
          //var myData = JSON.stringify(obj);

          $.each(obj.data, function(index, value){
             $('.data').text(value);
           })
      }
   });
})();
</code>```

I'm keeping the URL private, but wanted to show that it's coming from a HTTPS just in case that might be part of the problem.

The JSON is formatted as such:

```<code>{ "data": [
  {
     "likes": 10,
     "imageURL": "url",
     "mediaThumbURL": "url",
     "mediaDisplayURL": null,
     "mediaOriginalURL": "url",
     "userProfilePictureURL": null,
     "externalLink": null,
     "description": "The sun was setting behind the mounted memorial to Kaiser Wilhelm I.  (30 May 2015)",
     "mediaType": "Photo",
     "caption": "Sunset behind the memorial to Wilhelm I, Koblenz, Germany",
     "latitude": 50.364437,
     "longitude": 7.605915,
     "mediaID": "e9908afe-c9e1-11e5-829e-22000ae606bd",
     "userName": null,
     "googlePlaceId": "ChIJnX0jdld7vkcRYLPaENXUIgQ",
     "locationText": "Koblenz",
     "identifier": {
        "type": "MemberActivity",
        "id": "e9908afe-c9e1-11e5-829e-22000ae606bd"
     },
     "tags": {
        "itinerary": [
           "rhinegetaway"
        ],
        "season": [
           "spring"
        ],
        "cruise-itinerary": [
           "rhine-getaway"
        ],
        "_country": [
           "DE"
        ],
        "_city": [
           "lutzel"
        ]
     },
     "source": {
        "type": "ProjectActivity",
        "id": "54b97332-b9e4-11e3-876f-22000a240faf"
     },
     "valid": true
  },
  {
     "likes": 10,
     etc....

  }
}
</code>```

答:
You are experiencing this issue because you are looping over array of object and for this purpose you have to use nested loops as follow (Replace your call back code with following function):

```<code>function callback(obj){
  $.each(obj.data, function(index, element){
      // this outer loop will iterate over each object in array
      $.each(element, function(key, value){
          // this inner loop will iterate over each value in object
          if(value instanceof Object){
             // element is object parse it accordingly
             // you can apply parse logic based on key; as each object is of different type.
          }else{
             $('.data').text(value);
          }
      });
  });
}
</code>```

This loop will show all properties of an object you don't have to access individual property like value.likes. However, you have to write parser for the keys which have objects as their value. Obviously this is solution for showing all properties from object. In case you want access only few properties then drop inner loop and access those properties as element.likes.

Body:
I'm having issues drilling down into a json object that has an array in it. The issue I'm running into is that when I get inside that object it returns object Object.

My code looks like this:

(function(){
   var rivetAPI = "https://url";
   $.ajax({
          url:rivetAPI,
          type:"GET",
          dataType:"json",
          success: function(obj){
          //var myData = JSON.stringify(obj);

          $.each(obj.data, function(index, value){
             $('.data').text(value);
           })
      }
   });
})();

I'm keeping the URL private, but wanted to show that it's coming from a HTTPS just in case that might be part of the problem.

The JSON is formatted as such:

{ "data": [
  {
     "likes": 10,
     "imageURL": "url",
     "mediaThumbURL": "url",
     "mediaDisplayURL": null,
     "mediaOriginalURL": "url",
     "userProfilePictureURL": null,
     "externalLink": null,
     "description": "The sun was setting behind the mounted memorial to Kaiser Wilhelm I.  (30 May 2015)",
     "mediaType": "Photo",
     "caption": "Sunset behind the memorial to Wilhelm I, Koblenz, Germany",
     "latitude": 50.364437,
     "longitude": 7.605915,
     "mediaID": "e9908afe-c9e1-11e5-829e-22000ae606bd",
     "userName": null,
     "googlePlaceId": "ChIJnX0jdld7vkcRYLPaENXUIgQ",
     "locationText": "Koblenz",
     "identifier": {
        "type": "MemberActivity",
        "id": "e9908afe-c9e1-11e5-829e-22000ae606bd"
     },
     "tags": {
        "itinerary": [
           "rhinegetaway"
        ],
        "season": [
           "spring"
        ],
        "cruise-itinerary": [
           "rhine-getaway"
        ],
        "_country": [
           "DE"
        ],
        "_city": [
           "lutzel"
        ]
     },
     "source": {
        "type": "ProjectActivity",
        "id": "54b97332-b9e4-11e3-876f-22000a240faf"
     },
     "valid": true
  },
  {
     "likes": 10,
     etc....

  }
}

Body:
You are experiencing this issue because you are looping over array of object and for this purpose you have to use nested loops as follow (Replace your call back code with following function):

function callback(obj){
  $.each(obj.data, function(index, element){
      // this outer loop will iterate over each object in array
      $.each(element, function(key, value){
          // this inner loop will iterate over each value in object
          if(value instanceof Object){
             // element is object parse it accordingly
             // you can apply parse logic based on key; as each object is of different type.
          }else{
             $('.data').text(value);
          }
      });
  });
}

This loop will show all properties of an object you don't have to access individual property like value.likes. However, you have to write parser for the keys which have objects as their value. Obviously this is solution for showing all properties from object. In case you want access only few properties then drop inner loop and access those properties as element.likes.


问:
Set custom cookies using Google Apps Script
is it possible to set a custom cookie through a Google Apps script gadget embedded in a Google site.  I've been trying using the HtmlService class (through document.coookie in a script from the html file) but it doesn't seem to generate the cookie.  I'm assuming this must be by design (i.e. Caja sanitisation).  Is there another way?

Thanks

答:
It's acctually possible if you use the iframe option just like this:

```<code>function doGet(e) {
    return HtmlService.createHtmlOutputFromFile("index.html")
                .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
// after that you may use (On "index.html"):
// document.cookie = "cookieName=1234";
</code>```

best regards.

Body:
It's acctually possible if you use the iframe option just like this:

function doGet(e) {
    return HtmlService.createHtmlOutputFromFile("index.html")
                .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
// after that you may use (On "index.html"):
// document.cookie = "cookieName=1234";

best regards.


问:
Google Analytics Real Time Event Not triggering on Page Load
I want to send user data to GA on my page load when user is logged in(once home page loaded). I have below Tags and trigger(having custom event) created, but the event is not triggering. I have click event which is working fine.Not sure why on page load it is not working.

datalayer is like below email property used as condition to trigger event.If not with enhanced commerce what is the other way to get event triggered and data is pushed to GA

```<code>   dataLayer.push({
          'event': 'userdata',
          'ecommerce': {
             'currencyCode': 'DLR',
             'User': {
                     'email': userEmail,
                     'UserName': userName,
                     'OutletNumber': outletNumber
              }
           }
  });
</code>```

答:
There is your problem @Adi. "email" is not key for datalyer variable. It's inside "ecommerce" as part of value. The simplest fix for you would be just to replicate "email": userEmail as separate value e.g.:</p>

```<code> dataLayer.push({
  'event': 'userdata',
  'email': userEmail,
  'ecommerce': { 'currencyCode': 'DLR', 'email': userEmail, 'UserName': userName, 'OutletNumber': outletNumber }
});
</code>```

Body:
I want to send user data to GA on my page load when user is logged in(once home page loaded). I have below Tags and trigger(having custom event) created, but the event is not triggering. I have click event which is working fine.Not sure why on page load it is not working.

datalayer is like below email property used as condition to trigger event.If not with enhanced commerce what is the other way to get event triggered and data is pushed to GA

   dataLayer.push({
          'event': 'userdata',
          'ecommerce': {
             'currencyCode': 'DLR',
             'User': {
                     'email': userEmail,
                     'UserName': userName,
                     'OutletNumber': outletNumber
              }
           }
  });

Body:
There is your problem @Adi. "email" is not key for datalyer variable. It's inside "ecommerce" as part of value. The simplest fix for you would be just to replicate "email": userEmail as separate value e.g.:

 dataLayer.push({
  'event': 'userdata',
  'email': userEmail,
  'ecommerce': { 'currencyCode': 'DLR', 'email': userEmail, 'UserName': userName, 'OutletNumber': outletNumber }
});


问:
About mobile game porting
I would like to ask a few questions regarding mobile game porting...

Let say if I have a simple 2D C++ game engine and have a PC game based on that engine and I want to port it to different mobile platforms BREW, J2ME, iPhone, Android, Symbian, etc..

Do I need to re-code the engine and the game for each platform? or is there an easier and more efficient way? I am sure the process is complicated since different phones have different graphic/processor/memory/etc. I am just curious about the overview of mobile game porting process. :)

Thanks!

答: This of course depends on in which language your "simple engine" is written. Java is supposed to be easier to move between platforms, since it in effect is a platform of its own. If your engine is written in something more low-level, like C++, it will likely depend on platform-specific libraries for graphics and input, since C++ doesn't provide you with that.</p>

Title: About mobile game porting

OwnerDisplayName: unwind


问:
How should I use OpenID to authenticate to WCF Data Services from a Windows Phone 7 app?
I have a Windows Phone application which is reading and writing data from a WCF Data Services service which is hosted in and ASP.NET MVC 3 application.

I can configure both client and server as necessary. I'd like to use OpenID if practical, and once a user is authenticated on the phone they should be able to browse through data which is associated with their OpenID.

How should I configure client and server to make that work?

答:
To use OpenID in your app you should look at using an embedded WebBrowser control which connects to the provider site (or your site which can redirect).  When the OpenID provider returns to your site (embedded in the browser control) you'd pass necessary identifiers back to the app.

There's an example of doing this with a twitter app (using OAuth) at http://blog.markarteaga.com/OAuthWithSilverlightForWindowsPhone7.aspx


问:
lift-json with scala 2.10
I am following the tutorial here and stuck with json-lift dependency.

This is the dependency in my plugings.sbt file:

```<code>addSbtPlugin("net.liftweb" %% "lift-json" % "2.4")
</code>```

The error is below and it seems to be something related to scala 10.2 not being compatible but anyone know of a way I can get lift-json working with scala 10.2 ?

```<code>haknick '~/Projects/NickProjects/sometryouts/myscalatrys/scalatra/live-aq-first' --> scala -version
Scala code runner version 2.10.2 -- Copyright 2002-2013, LAMP/EPFL
haknick '~/Projects/NickProjects/sometryouts/myscalatrys/scalatra/live-aq-first' --> scala -version
Scala code runner version 2.10.2 -- Copyright 2002-2013, LAMP/EPFL
haknick '~/Projects/NickProjects/sometryouts/myscalatrys/scalatra/live-aq-first' --> sbt
[info] Loading project definition from /Users/kreshnikmati/Projects/NickProjects/sometryouts/myscalatrys/scalatra/live-aq-first/project
[info] Updating {file:/Users/kreshnikmati/Projects/NickProjects/sometryouts/myscalatrys/scalatra/live-aq-first/project/}default-7238ba...
[info] Resolving net.liftweb#lift-json;2.5 ...
[warn]  module not found: net.liftweb#lift-json;2.5
[warn] ==== typesafe-ivy-releases: tried
[warn]   http://repo.typesafe.com/typesafe/ivy-releases/net.liftweb/lift-json/scala_2.9.2/sbt_0.12/2.5/ivys/ivy.xml
[warn] ==== sbt-plugin-releases: tried
[warn]   http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases/net.liftweb/lift-json/scala_2.9.2/sbt_0.12/2.5/ivys/ivy.xml
[warn] ==== local: tried
[warn]   /Users/kreshnikmati/.ivy2/local/net.liftweb/lift-json/scala_2.9.2/sbt_0.12/2.5/ivys/ivy.xml
[warn] ==== public: tried
[warn]   http://repo1.maven.org/maven2/net/liftweb/lift-json_2.9.2_0.12/2.5/lift-json-2.5.pom
[info] Resolving org.scala-sbt#precompiled-2_10_1;0.12.3 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: net.liftweb#lift-json;2.5: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn]  Note: Some unresolved dependencies have extra attributes.  Check that these dependencies exist with the requested attributes.
[warn]      net.liftweb:lift-json:2.5 (sbtVersion=0.12, scalaVersion=2.9.2)
[warn]
sbt.ResolveException: unresolved dependency: net.liftweb#lift-json;2.5: not found
    at sbt.IvyActions$.sbt$IvyActions$$resolve(IvyActions.scala:214)
    at sbt.IvyActions$$anonfun$update$1.apply(IvyActions.scala:122)
    at sbt.IvyActions$$anonfun$update$1.apply(IvyActions.scala:121)
    at sbt.IvySbt$Module$$anonfun$withModule$1.apply(Ivy.scala:117)
    at sbt.IvySbt$Module$$anonfun$withModule$1.apply(Ivy.scala:117)
    at sbt.IvySbt$$anonfun$withIvy$1.apply(Ivy.scala:105)
    at sbt.IvySbt.liftedTree1$1(Ivy.scala:52)
    at sbt.IvySbt.action$1(Ivy.scala:52)
    at sbt.IvySbt$$anon$3.call(Ivy.scala:61)
    at xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:98)
    at xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:81)
    at xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:102)
    at xsbt.boot.Using$.withResource(Using.scala:11)
    at xsbt.boot.Using$.apply(Using.scala:10)
    at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:62)
    at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:52)
    at xsbt.boot.Locks$.apply0(Locks.scala:31)
    at xsbt.boot.Locks$.apply(Locks.scala:28)
    at sbt.IvySbt.withDefaultLogger(Ivy.scala:61)
    at sbt.IvySbt.withIvy(Ivy.scala:102)
    at sbt.IvySbt.withIvy(Ivy.scala:98)
    at sbt.IvySbt$Module.withModule(Ivy.scala:117)
    at sbt.IvyActions$.update(IvyActions.scala:121)
    at sbt.Classpaths$$anonfun$work$1$1.apply(Defaults.scala:955)
    at sbt.Classpaths$$anonfun$work$1$1.apply(Defaults.scala:953)
    at sbt.Classpaths$$anonfun$doWork$1$1$$anonfun$58.apply(Defaults.scala:976)
    at sbt.Classpaths$$anonfun$doWork$1$1$$anonfun$58.apply(Defaults.scala:974)
    at sbt.Tracked$$anonfun$lastOutput$1.apply(Tracked.scala:35)
    at sbt.Classpaths$$anonfun$doWork$1$1.apply(Defaults.scala:978)
    at sbt.Classpaths$$anonfun$doWork$1$1.apply(Defaults.scala:973)
    at sbt.Tracked$$anonfun$inputChanged$1.apply(Tracked.scala:45)
    at sbt.Classpaths$.cachedUpdate(Defaults.scala:981)
    at sbt.Classpaths$$anonfun$47.apply(Defaults.scala:858)
    at sbt.Classpaths$$anonfun$47.apply(Defaults.scala:855)
    at sbt.Scoped$$anonfun$hf10$1.apply(Structure.scala:586)
    at sbt.Scoped$$anonfun$hf10$1.apply(Structure.scala:586)
    at scala.Function1$$anonfun$compose$1.apply(Function1.scala:49)
    at sbt.Scoped$Reduced$$anonfun$combine$1$$anonfun$apply$12.apply(Structure.scala:311)
    at sbt.Scoped$Reduced$$anonfun$combine$1$$anonfun$apply$12.apply(Structure.scala:311)
    at sbt.$tilde$greater$$anonfun$$u2219$1.apply(TypeFunctions.scala:41)
    at sbt.std.Transform$$anon$5.work(System.scala:71)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:232)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:232)
    at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:18)
    at sbt.Execute.work(Execute.scala:238)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:232)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:232)
    at sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:160)
    at sbt.CompletionService$$anon$2.call(CompletionService.scala:30)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:680)
[error] (*:update) sbt.ResolveException: unresolved dependency: net.liftweb#lift-json;2.5: not found
Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore?
</code>```

答:
Sbt file using Scala 2.11.8:</p>

```<code>name := "Basic Lift-JSON Demo"

version := "1.0"

scalaVersion := "2.11.8"

libraryDependencies += "net.liftweb" % "lift-webkit_2.11" % "3.1.0"
</code>```

Title: lift-json with scala 2.10

Body:
I am following the tutorial here and stuck with json-lift dependency.

This is the dependency in my plugings.sbt file:

addSbtPlugin("net.liftweb" %% "lift-json" % "2.4")

The error is below and it seems to be something related to scala 10.2 not being compatible but anyone know of a way I can get lift-json working with scala 10.2 ?

haknick '~/Projects/NickProjects/sometryouts/myscalatrys/scalatra/live-aq-first' --> scala -version
Scala code runner version 2.10.2 -- Copyright 2002-2013, LAMP/EPFL
haknick '~/Projects/NickProjects/sometryouts/myscalatrys/scalatra/live-aq-first' --> scala -version
Scala code runner version 2.10.2 -- Copyright 2002-2013, LAMP/EPFL
haknick '~/Projects/NickProjects/sometryouts/myscalatrys/scalatra/live-aq-first' --> sbt
[info] Loading project definition from /Users/kreshnikmati/Projects/NickProjects/sometryouts/myscalatrys/scalatra/live-aq-first/project
[info] Updating {file:/Users/kreshnikmati/Projects/NickProjects/sometryouts/myscalatrys/scalatra/live-aq-first/project/}default-7238ba...
[info] Resolving net.liftweb#lift-json;2.5 ...
[warn]  module not found: net.liftweb#lift-json;2.5
[warn] ==== typesafe-ivy-releases: tried
[warn]   http://repo.typesafe.com/typesafe/ivy-releases/net.liftweb/lift-json/scala_2.9.2/sbt_0.12/2.5/ivys/ivy.xml
[warn] ==== sbt-plugin-releases: tried
[warn]   http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases/net.liftweb/lift-json/scala_2.9.2/sbt_0.12/2.5/ivys/ivy.xml
[warn] ==== local: tried
[warn]   /Users/kreshnikmati/.ivy2/local/net.liftweb/lift-json/scala_2.9.2/sbt_0.12/2.5/ivys/ivy.xml
[warn] ==== public: tried
[warn]   http://repo1.maven.org/maven2/net/liftweb/lift-json_2.9.2_0.12/2.5/lift-json-2.5.pom
[info] Resolving org.scala-sbt#precompiled-2_10_1;0.12.3 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: net.liftweb#lift-json;2.5: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn]  Note: Some unresolved dependencies have extra attributes.  Check that these dependencies exist with the requested attributes.
[warn]      net.liftweb:lift-json:2.5 (sbtVersion=0.12, scalaVersion=2.9.2)
[warn]
sbt.ResolveException: unresolved dependency: net.liftweb#lift-json;2.5: not found
    at sbt.IvyActions$.sbt$IvyActions$$resolve(IvyActions.scala:214)
    at sbt.IvyActions$$anonfun$update$1.apply(IvyActions.scala:122)
    at sbt.IvyActions$$anonfun$update$1.apply(IvyActions.scala:121)
    at sbt.IvySbt$Module$$anonfun$withModule$1.apply(Ivy.scala:117)
    at sbt.IvySbt$Module$$anonfun$withModule$1.apply(Ivy.scala:117)
    at sbt.IvySbt$$anonfun$withIvy$1.apply(Ivy.scala:105)
    at sbt.IvySbt.liftedTree1$1(Ivy.scala:52)
    at sbt.IvySbt.action$1(Ivy.scala:52)
    at sbt.IvySbt$$anon$3.call(Ivy.scala:61)
    at xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:98)
    at xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:81)
    at xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:102)
    at xsbt.boot.Using$.withResource(Using.scala:11)
    at xsbt.boot.Using$.apply(Using.scala:10)
    at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:62)
    at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:52)
    at xsbt.boot.Locks$.apply0(Locks.scala:31)
    at xsbt.boot.Locks$.apply(Locks.scala:28)
    at sbt.IvySbt.withDefaultLogger(Ivy.scala:61)
    at sbt.IvySbt.withIvy(Ivy.scala:102)
    at sbt.IvySbt.withIvy(Ivy.scala:98)
    at sbt.IvySbt$Module.withModule(Ivy.scala:117)
    at sbt.IvyActions$.update(IvyActions.scala:121)
    at sbt.Classpaths$$anonfun$work$1$1.apply(Defaults.scala:955)
    at sbt.Classpaths$$anonfun$work$1$1.apply(Defaults.scala:953)
    at sbt.Classpaths$$anonfun$doWork$1$1$$anonfun$58.apply(Defaults.scala:976)
    at sbt.Classpaths$$anonfun$doWork$1$1$$anonfun$58.apply(Defaults.scala:974)
    at sbt.Tracked$$anonfun$lastOutput$1.apply(Tracked.scala:35)
    at sbt.Classpaths$$anonfun$doWork$1$1.apply(Defaults.scala:978)
    at sbt.Classpaths$$anonfun$doWork$1$1.apply(Defaults.scala:973)
    at sbt.Tracked$$anonfun$inputChanged$1.apply(Tracked.scala:45)
    at sbt.Classpaths$.cachedUpdate(Defaults.scala:981)
    at sbt.Classpaths$$anonfun$47.apply(Defaults.scala:858)
    at sbt.Classpaths$$anonfun$47.apply(Defaults.scala:855)
    at sbt.Scoped$$anonfun$hf10$1.apply(Structure.scala:586)
    at sbt.Scoped$$anonfun$hf10$1.apply(Structure.scala:586)
    at scala.Function1$$anonfun$compose$1.apply(Function1.scala:49)
    at sbt.Scoped$Reduced$$anonfun$combine$1$$anonfun$apply$12.apply(Structure.scala:311)
    at sbt.Scoped$Reduced$$anonfun$combine$1$$anonfun$apply$12.apply(Structure.scala:311)
    at sbt.$tilde$greater$$anonfun$$u2219$1.apply(TypeFunctions.scala:41)
    at sbt.std.Transform$$anon$5.work(System.scala:71)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:232)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:232)
    at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:18)
    at sbt.Execute.work(Execute.scala:238)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:232)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:232)
    at sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:160)
    at sbt.CompletionService$$anon$2.call(CompletionService.scala:30)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:680)
[error] (*:update) sbt.ResolveException: unresolved dependency: net.liftweb#lift-json;2.5: not found
Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore?

Body:
Sbt file using Scala 2.11.8:

name := "Basic Lift-JSON Demo"

version := "1.0"

scalaVersion := "2.11.8"

libraryDependencies += "net.liftweb" % "lift-webkit_2.11" % "3.1.0"


问:
How can I set an entire select option object as a model?
I found that the selected model contains only the id property of an option object property. Is it possible for the selected model to contain the whole object?

HTML

```<code><div ng-dropdown-multiselect="" options="exampleData" selected-model="exampleModel"></div>
</code>```

JavaScript

```<code>$scope.exampleModel = [];
$scope.exampleData = [
   {id: 1, code: 'CA': label: "California"},
   {id: 2, code: 'MN' label: "Minnesota"},
   {id: 3, code: 'NY', label: "New York"} ];
</code>```

So, in this case, if I select the first option, the model becomes the following:

```<code>$scope.exampleModel = [{"id":"CA"}]
</code>```

I need the model to contain the whole option object as follows:

```<code>$scope.exampleModel = [{id: 1, code: 'CA': label: "California"}]
</code>```

答:
You can update it on the onSelectionChanged callback event.

var app = angular.module('app', ['angularjs-dropdown-multiselect']);

app.controller('MainCtrl', function($scope) {
  $scope.exampleModel = [];
  $scope.exampleData = [{
    id: 1,
    code: 'CA',
    label: "California"
  }, {
    id: 2,
    code: 'MN',
    label: "Minnesota"
  }, {
    id: 3,
    code: 'NY',
    label: "New York"
  }];
  $scope.exampleEvents = {
    onSelectionChanged: function() {

      $scope.exampleModel.forEach(function(selectedData) {
        var data = $scope.exampleData.find(function(item) {
          return item.id == selectedData.id;
        });
        if (data != null) {
          angular.copy(data, selectedData);
        }
      });
      console.log("Change:", $scope.exampleModel);
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="app">

<head>
  <link data-require="bootstrap@*" data-semver="3.3.2" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
  <script data-require="jquery@2.1.3" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
  <script data-require="bootstrap@*" data-semver="3.3.2" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-dropdown-multiselect/1.11.8/angularjs-dropdown-multiselect.min.js"></script>
</head>

<body ng-controller="MainCtrl">
  <div ng-dropdown-multiselect="" options="exampleData" selected-model="exampleModel" events="exampleEvents"></div>
</body>

</html></code>```

Body:
I found that the selected model contains only the id property of an option object property. Is it possible for the selected model to contain the whole object?

HTML

JavaScript

$scope.exampleModel = [];
$scope.exampleData = [
   {id: 1, code: 'CA': label: "California"},
   {id: 2, code: 'MN' label: "Minnesota"},
   {id: 3, code: 'NY', label: "New York"} ];

So, in this case, if I select the first option, the model becomes the following:

$scope.exampleModel = [{"id":"CA"}]

I need the model to contain the whole option object as follows:

$scope.exampleModel = [{id: 1, code: 'CA': label: "California"}]

Body:
You can update it on the onSelectionChanged callback event.

var app = angular.module('app', ['angularjs-dropdown-multiselect']);

app.controller('MainCtrl', function($scope) {
  $scope.exampleModel = [];
  $scope.exampleData = [{
    id: 1,
    code: 'CA',
    label: "California"
  }, {
    id: 2,
    code: 'MN',
    label: "Minnesota"
  }, {
    id: 3,
    code: 'NY',
    label: "New York"
  }];
  $scope.exampleEvents = {
    onSelectionChanged: function() {

      $scope.exampleModel.forEach(function(selectedData) {
        var data = $scope.exampleData.find(function(item) {
          return item.id == selectedData.id;
        });
        if (data != null) {
          angular.copy(data, selectedData);
        }
      });
      console.log("Change:", $scope.exampleModel);
    }
  }
});

<!DOCTYPE html>
<html ng-app="app">

<head>
  <link data-require="bootstrap@*" data-semver="3.3.2" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
  <script data-require="jquery@2.1.3" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
  <script data-require="bootstrap@*" data-semver="3.3.2" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-dropdown-multiselect/1.11.8/angularjs-dropdown-multiselect.min.js"></script>
</head>

<body ng-controller="MainCtrl">
  <div ng-dropdown-multiselect="" options="exampleData" selected-model="exampleModel" events="exampleEvents"></div>
</body>

</html>


问:
Is there a way to make webpack not show all the chunks it's compiling?
The default webpack CLI output is way too verbose for my liking. As soon as I import React from one of my files, the output explodes, showing all of the chunks (?) being packed:

```<code>webpack result is served from /
content is served from /Users/me/myproject
Hash: aaaf5afc6582f3222f55
Version: webpack 1.12.14
Time: 1175ms
   Asset    Size  Chunks             Chunk Names
index.js  677 kB       0  [emitted]  main
chunk    {0} index.js (main) 643 kB [rendered]
    [0] ./src/app.js 574 bytes {0} [built] [1 error]
    [1] ./~/react/react.js 56 bytes {0} [built]
    [2] ./~/react/lib/React.js 1.49 kB {0} [built]
    [3] ./~/react/lib/ReactDOM.js 3.71 kB {0} [built]
    [4] ./~/process/browser.js 2.06 kB {0} [built]

...

  [155] ./~/fbjs/lib/mapObject.js 1.47 kB {0} [built]
  [156] ./~/react/lib/onlyChild.js 1.21 kB {0} [built]
  [157] ./~/react/lib/deprecated.js 1.77 kB {0} [built]
  [158] ./~/react-dom/index.js 63 bytes {0} [built]
  [159] ./src/component.js 339 bytes {0} [built] [1 error]
</code>```

I really don't care about all of that extra information. I'd be happy with a way to either:

Disable the chunks altogether, just showing the overall progress

Only show my own code, not stuff I'm importing from my node_modules

At the moment my webpack command is webpack-dev-server --progress. My webpack config is pretty basic, just specifying entry, output, and loaders for babel and eslint.

答:
In the webpack.config.ts, you can try

```<code>devServer : {
  stats: 'minimal',
  watchOptions: {
   poll: undefined,
   aggregateTimeout: 300,
   ignored: /node_modules/
 }
}
</code>```

Hope that works.

Body:
The default webpack CLI output is way too verbose for my liking. As soon as I import React from one of my files, the output explodes, showing all of the chunks (?) being packed:

webpack result is served from /
content is served from /Users/me/myproject
Hash: aaaf5afc6582f3222f55
Version: webpack 1.12.14
Time: 1175ms
   Asset    Size  Chunks             Chunk Names
index.js  677 kB       0  [emitted]  main
chunk    {0} index.js (main) 643 kB [rendered]
    [0] ./src/app.js 574 bytes {0} [built] [1 error]
    [1] ./~/react/react.js 56 bytes {0} [built]
    [2] ./~/react/lib/React.js 1.49 kB {0} [built]
    [3] ./~/react/lib/ReactDOM.js 3.71 kB {0} [built]
    [4] ./~/process/browser.js 2.06 kB {0} [built]

...

  [155] ./~/fbjs/lib/mapObject.js 1.47 kB {0} [built]
  [156] ./~/react/lib/onlyChild.js 1.21 kB {0} [built]
  [157] ./~/react/lib/deprecated.js 1.77 kB {0} [built]
  [158] ./~/react-dom/index.js 63 bytes {0} [built]
  [159] ./src/component.js 339 bytes {0} [built] [1 error]

I really don't care about all of that extra information. I'd be happy with a way to either:

Disable the chunks altogether, just showing the overall progress

Only show my own code, not stuff I'm importing from my node_modules

At the moment my webpack command is webpack-dev-server --progress. My webpack config is pretty basic, just specifying entry, output, and loaders for babel and eslint.

Body:
In the webpack.config.ts, you can try

devServer : {
  stats: 'minimal',
  watchOptions: {
   poll: undefined,
   aggregateTimeout: 300,
   ignored: /node_modules/
 }
}

Hope that works.


问:
Roundcube install, getting MYSQL_ATTR_FOUND_ROWS fatal error
I'm installing Roundcube 0.9.0 on a shared host server.

I have PHP 5.3.8 with PDO activated however when i'm installing roundcube, this is what response I get:

```<code>Check DB config
Fatal error: Undefined class constant 'MYSQL_ATTR_FOUND_ROWS' in /home/neuas/domains/anthonysalvador.info/public_html/webmail/program/lib/Roundcube/rcube_db_mysql.php on line 127
</code>```

I have contacted my host, they turned me away. I contacted Roundcube, they turned me away. Is there something I could be overlooking?

here is the PDO section of the code including the faulty line:

```<code>102    protected function dsn_options($dsn)
103    {
104    $result = array();
105
106    if (!empty($dsn['key'])) {
107        $result[PDO::MYSQL_ATTR_KEY] = $dsn['key'];
108    }
109
110    if (!empty($dsn['cipher'])) {
111        $result[PDO::MYSQL_ATTR_CIPHER] = $dsn['cipher'];
112    }
113
114    if (!empty($dsn['cert'])) {
115        $result[PDO::MYSQL_ATTR_SSL_CERT] = $dsn['cert'];
116    }
117
118    if (!empty($dsn['capath'])) {
119        $result[PDO::MYSQL_ATTR_SSL_CAPATH] = $dsn['capath'];
120    }
121
122    if (!empty($dsn['ca'])) {
123        $result[PDO::MYSQL_ATTR_SSL_CA] = $dsn['ca'];
124    }
125
126    // Always return matching (not affected only) rows count
127    $result[PDO::MYSQL_ATTR_FOUND_ROWS] = true;
</code>```

答:
Just spent a few hours chasing this down. I am using PHP 5.3.3 with MySQL 15.1 (10.0.31 MariaDB) on Centos 6.5

For me, the fix was to obtain the mySQL-pdo so file. Fixed by performing yum install php-mysql-5.3.3-49.el6.x86_64. That package was chosen by performing yum whatprovides phppdo*.so

I was led down this path by:
PHP 7 RC3: How to install missing MySQL PDO

This may be overkill - and please let me know if it is, but I also specified the extension in /etc/php.ini (line 925)
extension=/usr/lib64/php/modules/pdo_mysql.so

Body:
I'm installing Roundcube 0.9.0 on a shared host server.

I have PHP 5.3.8 with PDO activated however when i'm installing roundcube, this is what response I get:

Check DB config
Fatal error: Undefined class constant 'MYSQL_ATTR_FOUND_ROWS' in /home/neuas/domains/anthonysalvador.info/public_html/webmail/program/lib/Roundcube/rcube_db_mysql.php on line 127

I have contacted my host, they turned me away. I contacted Roundcube, they turned me away. Is there something I could be overlooking?

here is the PDO section of the code including the faulty line:

102    protected function dsn_options($dsn)
103    {
104    $result = array();
105
106    if (!empty($dsn['key'])) {
107        $result[PDO::MYSQL_ATTR_KEY] = $dsn['key'];
108    }
109
110    if (!empty($dsn['cipher'])) {
111        $result[PDO::MYSQL_ATTR_CIPHER] = $dsn['cipher'];
112    }
113
114    if (!empty($dsn['cert'])) {
115        $result[PDO::MYSQL_ATTR_SSL_CERT] = $dsn['cert'];
116    }
117
118    if (!empty($dsn['capath'])) {
119        $result[PDO::MYSQL_ATTR_SSL_CAPATH] = $dsn['capath'];
120    }
121
122    if (!empty($dsn['ca'])) {
123        $result[PDO::MYSQL_ATTR_SSL_CA] = $dsn['ca'];
124    }
125
126    // Always return matching (not affected only) rows count
127    $result[PDO::MYSQL_ATTR_FOUND_ROWS] = true;


答:
When you make the request in python you're getting back a response object. You need to parse the body of that response instead. So

tree.parse(r.content)

Title: Parsing XML file in python

Body:
    import requests
    import xml.etree.ElementTree as ET

    def abc(area_code, office_code):
        args = area_code + office_code
     url = (described bellow)
     r = requests.get(url=url)
     tree=ET.ElementTree()
     parsed_data=tree.parse(r.content)
      return parsed_data

   abc('503', '402')

where url is

url="http://www.networksolutions.ds.adp.com/NSPhoneToolDB/template/GetBusRouteFilterExpressions.xml?"\
               "Telnum=" +args+ "&FilterNamePrefix=ORPORTCDK&ReturnResult=detail"

when i run this thing i am getting

<Element 'GetBusRouteFilterExpressions' at 0x7f2abf526f48>

as output instead of entire file.


问:
Matching a row number and value to a row on another sheet
As the title suggests, I am trying to create a system where a cell (which matches to a specific row) will search another sheet, find a number which matches its row number, and then puts in the paired value. I have attached a screenshot for a clearer picture.

This is what I have tried so far without any success.

IF(INDEX(A2:B8,2,2)=?,____,"")

I sort of understand the INDEX and MATCH function independently, but have no concrete understanding of how to incorporate the two for this problem. Also, I have already attempted to search google for help on this but have had difficulty even knowing what to enter as search terms, so help on that would be great as well for future problems.

Thanks in advance!

答:
Use the following in A2:

```<code>=IFERROR(INDEX(Sheet1!$B$2:$B$8,SMALL(IF(Sheet1!$A$2:$B$8=ROW(),ROW(Sheet1!$A$2:$A$8),999999),COLUMN(A1))-1),"")
</code>```

Array formula press Ctrl+Shift+Enter at the same time instead of Enter

Drag the formula in the same row and down.

Sheet1!$A$2:$A$8, Sheet1!$B$2:$B$8 are Row and Value column

If() will test each value in A2:A8 for the Row() in the new sheet and return the Row number in sheet1

99999 to have a maximum value if no Row() match (false part of the If)

Column(A1) to return small( ,1)

It will become Column(B1) when you drag in the same row (for multiple value of same Row Number)

Iferror will return "" empty if no number

Sheet1

```<code>    A    B
    Row Value
    5   20
    2   30
    7   40
    8   50
    2   60
    3   70
    2   100
</code>```

Sheet2 result

```<code>Row/Col   A     B    C
 1
 2        30    60  100
 3        70
 4
 5        20
 6
 7        40
 8        50
</code>```

Body:
Use the following in A2:

=IFERROR(INDEX(Sheet1!$B$2:$B$8,SMALL(IF(Sheet1!$A$2:$B$8=ROW(),ROW(Sheet1!$A$2:$A$8),999999),COLUMN(A1))-1),"")

Array formula press Ctrl+Shift+Enter at the same time instead of Enter

Drag the formula in the same row and down.

Sheet1!$A$2:$A$8, Sheet1!$B$2:$B$8 are Row and Value column

If() will test each value in A2:A8 for the Row() in the new sheet and return the Row number in sheet1

99999 to have a maximum value if no Row() match (false part of the If)

Column(A1) to return small( ,1)

It will become Column(B1) when you drag in the same row (for multiple value of same Row Number)

Iferror will return "" empty if no number

Sheet1

    A    B
    Row Value
    5   20
    2   30
    7   40
    8   50
    2   60
    3   70
    2   100

Sheet2 result

Row/Col   A     B    C
 1
 2        30    60  100
 3        70
 4
 5        20
 6
 7        40
 8        50


问:
How handle large amount of data in Magento 2
I have 17 store, 40K product, 100 category, 1000 attribute. Is Magento 2 support this much of data.? I need to speed up the website. </p>

答:
Follow Listed Things

Enable Flat Category

Enable Flat Product

Enable Cache

Minify CSS

Minify JS

Bundle JS

Use CDN if possible

Try to use much less external jQuery

Do image optimization if needed.

Do leverage Browser Caching from .htaccess

off eTag from .htaccess

enable gzip from .htaccess

Hope this topics will increase your website speed.


问:
Swift perform segue without clicking button
I'm making a small game in SpriteKit where I have a bool value stored that checks if it's the first time the user plays my game. If it is, I want the app to redirect him to another viewcontroller where he enters his character-name.

However, I'm having trouble getting my app to do so.

In my "GameViewController.swift" I have this code:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    checkGame()

    if let view = self.view as! SKView? {

        // Load the SKScene from 'GameScene.sks'
        if let scene = SKScene(fileNamed: "GameScene") {
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            // Present the scene
            view.presentScene(scene)
        }

        view.ignoresSiblingOrder = true

        view.showsFPS = true
        view.showsNodeCount = true
    }
}

func checkGame() {
    //Check game
    let firstPlay:Bool = appData.bool(forKey: "\(GameData.firstPlay)")
    print(firstPlay)

    if firstPlay == false {
        print("Heading for setup")
        self.performSegue(withIdentifier: "GoToSetup", sender: nil)
    }
}
</code>```

However, the "setup viewcontroller" isn't loaded. I can manage to tricker the segue with a button-click, but that's not what I want. I want it to happen as soon as the view is loaded.

Any ideas?

答: As it was said, in viewDidLoad stage UIViewController can't be done any UI-interaction, and performSegue to, because view is not at the view hierarchy yet. You can do this at viewDidAppear(animated:Bool).

Body:
I'm making a small game in SpriteKit where I have a bool value stored that checks if it's the first time the user plays my game. If it is, I want the app to redirect him to another viewcontroller where he enters his character-name.

However, I'm having trouble getting my app to do so.

In my "GameViewController.swift" I have this code:

override func viewDidLoad() {
    super.viewDidLoad()

    checkGame()

    if let view = self.view as! SKView? {

        // Load the SKScene from 'GameScene.sks'
        if let scene = SKScene(fileNamed: "GameScene") {
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            // Present the scene
            view.presentScene(scene)
        }

        view.ignoresSiblingOrder = true

        view.showsFPS = true
        view.showsNodeCount = true
    }
}

func checkGame() {
    //Check game
    let firstPlay:Bool = appData.bool(forKey: "\(GameData.firstPlay)")
    print(firstPlay)

    if firstPlay == false {
        print("Heading for setup")
        self.performSegue(withIdentifier: "GoToSetup", sender: nil)
    }
}

However, the "setup viewcontroller" isn't loaded. I can manage to tricker the segue with a button-click, but that's not what I want. I want it to happen as soon as the view is loaded.

Any ideas?


问:
How do I add a vertex in between 0 and 1 such that there exists an edge from 0 to 0.5(the new vertex, say) and 0.5 to 1 using Boost Graph Library?
I have a boost graph:

```<code>Graph g(2);
</code>```

indices of which I access like:

```<code>g[0]; g[1];
</code>```

I draw an edge

```<code>add_edge(0, 1, g);
</code>```

Problem:

I want to add a vertex in between 0 and 1 such that there exists an edge from 0 to 0.5 (the new vertex, say) and 0.5 to 1.

What should be my approach?

答:
Given an edge-descriptor of the original edge:

```<code>template <typename Edge, typename Graph>
auto split_edge(Edge edge, Graph& g) {
    auto v = source(edge, g);
    auto u = target(edge, g);

    auto n = add_vertex(g);

    add_edge(v, n, g);
    add_edge(n, u, g);
    return n;
}
</code>```

Returns the descriptor for the newly added vertex.

Sample Program

Live On Coliru

```<code>#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>

using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS>;

template <typename Edge, typename Graph>
auto split_edge(Edge edge, Graph& g) -> typename Graph::vertex_descriptor {
    auto v = source(edge, g);
    auto u = target(edge, g);

    auto n = add_vertex(g);

    add_edge(v, n, g);
    add_edge(n, u, g);
    return n;
}

int main() {
    Graph g(2);
    auto original = add_edge(0, 1, g).first;
    print_graph(g);

    auto v_half = split_edge(original, g);

    print_graph(g);
}
</code>```

Prints

```<code>0 --> 1
1 -->
0 --> 1 2
1 -->
2 --> 1
</code>```

Body:
I have a boost graph:

Graph g(2);

indices of which I access like:

g[0]; g[1];

I draw an edge

add_edge(0, 1, g);

Problem:

I want to add a vertex in between 0 and 1 such that there exists an edge from 0 to 0.5 (the new vertex, say) and 0.5 to 1.

What should be my approach?

Body:
Given an edge-descriptor of the original edge:

template <typename Edge, typename Graph>
auto split_edge(Edge edge, Graph& g) {
    auto v = source(edge, g);
    auto u = target(edge, g);

    auto n = add_vertex(g);

    add_edge(v, n, g);
    add_edge(n, u, g);
    return n;
}

Returns the descriptor for the newly added vertex.

Sample Program

Live On Coliru

#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>

using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS>;

template <typename Edge, typename Graph>
auto split_edge(Edge edge, Graph& g) -> typename Graph::vertex_descriptor {
    auto v = source(edge, g);
    auto u = target(edge, g);

    auto n = add_vertex(g);

    add_edge(v, n, g);
    add_edge(n, u, g);
    return n;
}

int main() {
    Graph g(2);
    auto original = add_edge(0, 1, g).first;
    print_graph(g);

    auto v_half = split_edge(original, g);

    print_graph(g);
}

Prints

0 --> 1
1 -->
0 --> 1 2
1 -->
2 --> 1


问:
Access array content through loop
I have a mysql query result which I have turned into an array with:

```<code>$row = customfunction_fetch_array($results);
</code>```

This is how the $row array looks:

```<code>Array(
  [0]=> Array ([Fruit]=> apple [Count]=>4 [Season]=>Summer
  [1]=> Array ([Fruit]=> grape [Count]=>1 [Season]=>Fall
  [2]=> Array ([Fruit]=> apple [Count]=>3 [Season]=>Winter
  [3]=> Array ([Fruit]=> orange [Count]=>5 [Season]=>Spring
  [4]=> Array ([Fruit]=> apple [Count]=>45 [Season]=>All
)
</code>```

What I'm trying to do is loop through the unique values of a specific field and save them to a new array.

```<code>$newArray =[];
foreach( $row["Fruit"] as $myFruits){
  $newArray[] = $myFruits;
}
</code>```

I get a warning of:

"Invalid argument supplied for foreach()"

答:
Given the array that you posted, there is no $row['Fruit'], there is $row[0]['Fruit'], $row[1]['Fruit'] etc...

```<code>foreach($row as $values){
    $newArray[] = $values['Fruit'];
}
</code>```

However, to get all the Fruits you can simply do this:

```<code>$newArray = array_column($row, 'Fruit');
</code>```

Title: Access array content through loop

Body:
I have a mysql query result which I have turned into an array with:

$row = customfunction_fetch_array($results);

This is how the $row array looks:

Array(
  [0]=> Array ([Fruit]=> apple [Count]=>4 [Season]=>Summer
  [1]=> Array ([Fruit]=> grape [Count]=>1 [Season]=>Fall
  [2]=> Array ([Fruit]=> apple [Count]=>3 [Season]=>Winter
  [3]=> Array ([Fruit]=> orange [Count]=>5 [Season]=>Spring
  [4]=> Array ([Fruit]=> apple [Count]=>45 [Season]=>All
)

What I'm trying to do is loop through the unique values of a specific field and save them to a new array.

$newArray =[];
foreach( $row["Fruit"] as $myFruits){
  $newArray[] = $myFruits;
}

I get a warning of:

"Invalid argument supplied for foreach()"

Body:
Given the array that you posted, there is no $row['Fruit'], there is $row[0]['Fruit'], $row[1]['Fruit'] etc...

foreach($row as $values){
    $newArray[] = $values['Fruit'];
}

However, to get all the Fruits you can simply do this:

$newArray = array_column($row, 'Fruit');


问:
zoom level with satellite imagery using google maps api v3
I am having a problem where if I fit bounds to a single marker there is often no satellite imagery.

Is there a way I can set the map to the closest zoom level that still has satellite imagery?

I am using Google Maps API V3.

答: getMaxZoomAtLatLng is how you could do it in V2.  Strangely it does not seem to be implemented in V3, as documented here</p>