问:
How to play and pause the audio by using the media player?
I want to perform the three functions by using the single play button.
  First process - when we click the play button the mediaplayer should play the audio.
  second process - when user click second time the play button the audio should be paused.
  Third process - when user click the third time play button the audio should resume from the paused song.

The tried the below code

```<code> if (!mediaPlayer.isPlaying()) {
                mediaPlayer.reset();
                try {
                    mediaPlayer.setDataSource(path);
                    //  mediaPlayer.setOnPreparedListener((MediaPlayer.OnPreparedListener) getActivity());
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaPlayer.start();

            }
           else if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }

            else if (!mediaPlayer.isPlaying() && mediaPlayer.getCurrentPosition() > 0) {
                long currentPosition = mediaPlayer.getCurrentPosition();
                mediaPlayer.seekTo((int) currentPosition);
                mediaPlayer.start();

            }
</code>```

The above code is not working ,please help me how to solve this.

答:
try this way

```<code>public class MainActivity extends Activity {
private Button btn;
/**
 * help to toggle between play and pause.
 */
private boolean playPause;
private MediaPlayer mediaPlayer;
/**
 * remain false till media is not completed, inside OnCompletionListener make it true.
 */
private boolean intialStage = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.button1);
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    btn.setOnClickListener(pausePlay);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

private OnClickListener pausePlay = new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub

        if (!playPause) {
            btn.setBackgroundResource(R.drawable.button_pause);
            if (intialStage)
                new Player()
                        .execute("http://www.virginmegastore.me/Library/Music/CD_001214/Tracks/Track1.mp3");
            else {
                if (!mediaPlayer.isPlaying())
                    mediaPlayer.start();
            }
            playPause = true;
        } else {
            btn.setBackgroundResource(R.drawable.button_play);
            if (mediaPlayer.isPlaying())
                mediaPlayer.pause();
            playPause = false;
        }
    }
};
/**
 * preparing mediaplayer will take sometime to buffer the content so prepare it inside the background thread and starting it on UI thread.
 * @author piyush
 *
 */

class Player extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog progress;

    @Override
    protected Boolean doInBackground(String... params) {
        // TODO Auto-generated method stub
        Boolean prepared;
        try {

            mediaPlayer.setDataSource(params[0]);

            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    intialStage = true;
                    playPause=false;
                    btn.setBackgroundResource(R.drawable.button_play);
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                }
            });
            mediaPlayer.prepare();
            prepared = true;
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            Log.d("IllegarArgument", e.getMessage());
            prepared = false;
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            prepared = false;
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            prepared = false;
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            prepared = false;
            e.printStackTrace();
        }
        return prepared;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        if (progress.isShowing()) {
            progress.cancel();
        }
        Log.d("Prepared", "//" + result);
        mediaPlayer.start();

        intialStage = false;
    }

    public Player() {
        progress = new ProgressDialog(MainActivity.this);
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        this.progress.setMessage("Buffering...");
        this.progress.show();

    }
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    if (mediaPlayer != null) {
        mediaPlayer.reset();
        mediaPlayer.release();
        mediaPlayer = null;
    }
}
</code>```

Body:
I want to perform the three functions by using the single play button.
  First process - when we click the play button the mediaplayer should play the audio.
  second process - when user click second time the play button the audio should be paused.
  Third process - when user click the third time play button the audio should resume from the paused song.

The tried the below code

 if (!mediaPlayer.isPlaying()) {
                mediaPlayer.reset();
                try {
                    mediaPlayer.setDataSource(path);
                    //  mediaPlayer.setOnPreparedListener((MediaPlayer.OnPreparedListener) getActivity());
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaPlayer.start();

            }
           else if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }

            else if (!mediaPlayer.isPlaying() && mediaPlayer.getCurrentPosition() > 0) {
                long currentPosition = mediaPlayer.getCurrentPosition();
                mediaPlayer.seekTo((int) currentPosition);
                mediaPlayer.start();

            }

The above code is not working ,please help me how to solve this.

Body:
try this way

public class MainActivity extends Activity {
private Button btn;
/**
 * help to toggle between play and pause.
 */
private boolean playPause;
private MediaPlayer mediaPlayer;
/**
 * remain false till media is not completed, inside OnCompletionListener make it true.
 */
private boolean intialStage = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.button1);
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    btn.setOnClickListener(pausePlay);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

private OnClickListener pausePlay = new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub

        if (!playPause) {
            btn.setBackgroundResource(R.drawable.button_pause);
            if (intialStage)
                new Player()
                        .execute("http://www.virginmegastore.me/Library/Music/CD_001214/Tracks/Track1.mp3");
            else {
                if (!mediaPlayer.isPlaying())
                    mediaPlayer.start();
            }
            playPause = true;
        } else {
            btn.setBackgroundResource(R.drawable.button_play);
            if (mediaPlayer.isPlaying())
                mediaPlayer.pause();
            playPause = false;
        }
    }
};
/**
 * preparing mediaplayer will take sometime to buffer the content so prepare it inside the background thread and starting it on UI thread.
 * @author piyush
 *
 */

class Player extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog progress;

    @Override
    protected Boolean doInBackground(String... params) {
        // TODO Auto-generated method stub
        Boolean prepared;
        try {

            mediaPlayer.setDataSource(params[0]);

            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    intialStage = true;
                    playPause=false;
                    btn.setBackgroundResource(R.drawable.button_play);
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                }
            });
            mediaPlayer.prepare();
            prepared = true;
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            Log.d("IllegarArgument", e.getMessage());
            prepared = false;
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            prepared = false;
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            prepared = false;
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            prepared = false;
            e.printStackTrace();
        }
        return prepared;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        if (progress.isShowing()) {
            progress.cancel();
        }
        Log.d("Prepared", "//" + result);
        mediaPlayer.start();

        intialStage = false;
    }

    public Player() {
        progress = new ProgressDialog(MainActivity.this);
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        this.progress.setMessage("Buffering...");
        this.progress.show();

    }
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    if (mediaPlayer != null) {
        mediaPlayer.reset();
        mediaPlayer.release();
        mediaPlayer = null;
    }
}


来源: stackexchange

问:
NHibernate mapping class properties to Rows not Columns
Is it possible to map a class with each property stored as a row in the table, not a column. The scenario is where we persist global options to the database. We store the options in an 'Options' class that has a property per option, i.e. "Expand Menu", "Save on Exit" etc.

Rather than store each option in its own table column, we would simply like to have a table with each of the class properties stored as a new row, identified by a Enum.

Is this possible?

(C# Winforms)

答:
Using NHibernate's EntityMode.Map might help solve this problem.  It does mean that you might have to put your global options in a Dictionary collection, but you can always implement an Option class that abstracts the underlying Dictionary.

NHibernate provides the ability to map a Dictionary dynamically to a table.  See NHibernate's reference on Dynamic Models

ContentLicense: CC BY-SA 2.5


问:
How to refer to a cell outside of cellForRowAtIndexPath
I am trying to update a label in a cell outside of

```<code>override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
</code>```

by using

```<code>let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell
</code>```

in another function. However, I keep getting errors. Therefore, I tried to refer to the cell by using let cell = Cell(), but I get the error unexpectedly found nil. Lastly, I tried

```<code>let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! Cell
</code>```

that does not return an error, but the label cell.time.text is not updated.

答:
If you want to use cell outside of the UITableView override method cellForRowAt indexPath then first of all, you need to fetch the indexPath of row and then using the indexPath of that row you can get the cell of UITableView.

Once, you get the cell then you can access their properties & methods outside of UITableView.

Try this:

In this code, i'm use a Custom Cell.

```<code>let indexPath = IndexPath.init(row: 0, section: 0)
let cell = tableView.cellForRow(at: indexPath) as! MembersCell
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to update a label in a cell outside of

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

by using

let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell

in another function. However, I keep getting errors. Therefore, I tried to refer to the cell by using let cell = Cell(), but I get the error unexpectedly found nil. Lastly, I tried

let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! Cell

that does not return an error, but the label cell.time.text is not updated.

Body:
If you want to use cell outside of the UITableView override method cellForRowAt indexPath then first of all, you need to fetch the indexPath of row and then using the indexPath of that row you can get the cell of UITableView.

Once, you get the cell then you can access their properties & methods outside of UITableView.

Try this:

In this code, i'm use a Custom Cell.

let indexPath = IndexPath.init(row: 0, section: 0)
let cell = tableView.cellForRow(at: indexPath) as! MembersCell


问:
Google Drive HTTP 403 "Access Not Configured" error with DrEdit
I'm attempting to install the DrEdit sample app for python onto GAE. The app runs, but saving or opening a file results in an HTTP 403 "Access Not Configured Error".

client.json has client_id and client_secret set per the API Access>Client ID for Drive SDK values. I have also attempted to use the values for API Access>Client ID for web applications.

The Google Drive SDK> OAuth Client ID has also been set variously to the Drive SDK and web app Client IDs.

What am I doing wrong?

答:
And your must also identify in your code the following

```<code>DriveService.Scope.DriveFile, DriveService.Scope.Drive
</code>```

good luck

Body:
And your must also identify in your code the following

DriveService.Scope.DriveFile, DriveService.Scope.Drive

good luck


问:
SQL query to get the count by applying group by
I want to get the below result:

source table :

```<code>Cnt  A    B
4   ABC YU/FGH
5   ABC YU/DFE
5   ABC KL
2   LKP BN/ER
4   JK  RE
</code>```

Result:

```<code>Cnt  A  B
9   ABC YU
5   ABC KL
2   LKP BN
4   JK  RE
</code>```

Here I want the count by grouping 'B' and want to display the 'B' record only till the special character (/)

答:
Basically, you will have to filter out the all the characters after the "/" symbol and then apply a SUM and a GROUP BY. You can see this below. The inner query filters out the unwanted string and the outer query does the SUM and the GROUP BY :

```<code>SELECT      SUM(t.Cnt), t.A, t.B
FROM        (
                SELECT      Cnt,
                            A,
                            CASE
                                WHEN CHARINDEX('/', B) > 0 THEN SUBSTRING(B, 0, CHARINDEX('/', B))
                            ELSE B
                            END AS B

                FROM        #Tab
            ) t
GROUP BY    t.A, t.B
ORDER BY    t.A
</code>```

You can see this working here -> http://rextester.com/IQJ79191

Hope this helps!!!

Body:
I want to get the below result:

source table :

Cnt  A    B
4   ABC YU/FGH
5   ABC YU/DFE
5   ABC KL
2   LKP BN/ER
4   JK  RE

Result:

Cnt  A  B
9   ABC YU
5   ABC KL
2   LKP BN
4   JK  RE

Here I want the count by grouping 'B' and want to display the 'B' record only till the special character (/)

Body:
Basically, you will have to filter out the all the characters after the "/" symbol and then apply a SUM and a GROUP BY. You can see this below. The inner query filters out the unwanted string and the outer query does the SUM and the GROUP BY :

SELECT      SUM(t.Cnt), t.A, t.B
FROM        (
                SELECT      Cnt,
                            A,
                            CASE
                                WHEN CHARINDEX('/', B) > 0 THEN SUBSTRING(B, 0, CHARINDEX('/', B))
                            ELSE B
                            END AS B

                FROM        #Tab
            ) t
GROUP BY    t.A, t.B
ORDER BY    t.A

You can see this working here -> http://rextester.com/IQJ79191

Hope this helps!!!


问:
Ruby gem mysql2 install error
I have the Ruby version ruby 1.9.2p0 (2010-08-18) [i386-mingw32] installed in Windows7.
and the gem vesion 1.3.7

When i tried to install mysql gem, it is showing Failed to build gem native extension error, why is this? my mysql version is 5.1.36(WampServer)

```<code>E:\RubyApps\test_app2>gem install mysql2
Building native extensions.  This could take a while...
ERROR:  Error installing mysql2:
        ERROR: Failed to build gem native extension.

E:/Ruby192/bin/ruby.exe extconf.rb
checking for rb_thread_blocking_region()... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=E:/Ruby192/bin/ruby
E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:368:in `try_do': The complier failed to genera
te an executable file. (RuntimeError)
You have to install development tools first.
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:435:in `try_link0'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:440:in `try_link'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:552:in `try_func'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:797:in `block in have_func'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:693:in `block in checking_for'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:280:in `block (2 levels) in postp
one'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:254:in `open'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:280:in `block in postpone'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:254:in `open'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:276:in `postpone'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:692:in `checking_for'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:796:in `have_func'
        from extconf.rb:9:in `<main>'

Gem files will remain installed in E:/Ruby192/lib/ruby/gems/1.9.1/gems/mysql2-0.
2.3 for inspection.
Results logged to E:/Ruby192/lib/ruby/gems/1.9.1/gems/mysql2-0.2.3/ext/mysql2/ge
m_make.out

E:\RubyApps\test_app2>
</code>```

答:
You can try </p>

```<code>gem install mysql2 -v '0.0.00' -- --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include
</code>```

Title: Ruby gem mysql2 install error

Body:
I have the Ruby version ruby 1.9.2p0 (2010-08-18) [i386-mingw32] installed in Windows7.
and the gem vesion 1.3.7

When i tried to install mysql gem, it is showing Failed to build gem native extension error, why is this? my mysql version is 5.1.36(WampServer)

E:\RubyApps\test_app2>gem install mysql2
Building native extensions.  This could take a while...
ERROR:  Error installing mysql2:
        ERROR: Failed to build gem native extension.

E:/Ruby192/bin/ruby.exe extconf.rb
checking for rb_thread_blocking_region()... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=E:/Ruby192/bin/ruby
E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:368:in `try_do': The complier failed to genera
te an executable file. (RuntimeError)
You have to install development tools first.
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:435:in `try_link0'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:440:in `try_link'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:552:in `try_func'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:797:in `block in have_func'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:693:in `block in checking_for'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:280:in `block (2 levels) in postp
one'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:254:in `open'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:280:in `block in postpone'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:254:in `open'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:276:in `postpone'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:692:in `checking_for'
        from E:/Ruby192/lib/ruby/1.9.1/mkmf.rb:796:in `have_func'
        from extconf.rb:9:in `'

Gem files will remain installed in E:/Ruby192/lib/ruby/gems/1.9.1/gems/mysql2-0.
2.3 for inspection.
Results logged to E:/Ruby192/lib/ruby/gems/1.9.1/gems/mysql2-0.2.3/ext/mysql2/ge
m_make.out

E:\RubyApps\test_app2>

Body:
You can try

gem install mysql2 -v '0.0.00' -- --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include


答:
I can suggest you to use a query like this:</p>

```<code>select
    sum(Cnt) Cnt,
    A,
    left(B, charindex('/',B+'/',0)-1) B    -- Using `+'\'` will do the trick
from
    t
group by
    A,
    left(B, charindex('/',B+'/',0)-1);
</code>```

Title: SQL query to get the count by applying group by

Body:
I can suggest you to use a query like this:

select
    sum(Cnt) Cnt,
    A,
    left(B, charindex('/',B+'/',0)-1) B    -- Using `+'\'` will do the trick
from
    t
group by
    A,
    left(B, charindex('/',B+'/',0)-1);


问:
Get ListView content height
How to get list-view content height(not list-view height). Is it possible to use the onLayout method for that?

答:
I figure it out. we can use the onContentSizeChange method to get list-view content height.

```<code><ListView
    ref={ref => this.listView = ref}
    onContentSizeChange={this.onContentSize}
/>

onContentSize(contentWidth, contentHeight) {
    console.log("<<<<<< content >>>>>>>>>", contentWidth, contentHeight);
}
</code>```

Title: Get ListView content height

Body:
I figure it out. we can use the onContentSizeChange method to get list-view content height.

<ListView
    ref={ref => this.listView = ref}
    onContentSizeChange={this.onContentSize}
/>

onContentSize(contentWidth, contentHeight) {
    console.log("<<<<<< content >>>>>>>>>", contentWidth, contentHeight);
}


问:
Detecting superfluous #includes in C/C++
I often find that the headers section of a file gets larger and larger all the time, but it never gets smaller. Throughout the life of a source file, classes may have moved and been refactored and it's very possible that there are quite a few #includes that don't need to be there and anymore. Leaving them there only prolong the compile time and adds unnecessary compilation dependencies. Trying to figure out which are still needed can be quite tedious.

Is there some kind of tool that can detect superfluous #include directives and suggest which ones I can safely remove?
Does lint do this maybe?

答:
There's two types of superfluous #include files:

A header file actually not needed by
the module(.c, .cpp) at all

A header file is need by the module
but being included more than once, directly, or indirectly.

There's 2 ways in my experience that works well to detecting it:

gcc -H or cl.exe /showincludes (resolve problem 2)

In real world,
you can export CFLAGS=-H before make,
if all the Makefile's not override
CFLAGS options.    Or as I used, you
can create a cc/g++ wrapper to add -H
options forcibly to each invoke of
$(CC) and $(CXX). and prepend the
wrapper's directory to $PATH
variable, then your make will all
uses you wrapper command instead. Of
course your wrapper should invoke the
real gcc compiler.    This tricks
need to change if your Makefile uses
gcc directly. instead of $(CC) or
$(CXX) or by implied rules.

You can also compile a single file by tweaking with the command line. But if you want to clean headers for the whole project. You can capture all the output by:

make clean

make 2>&1 | tee result.txt

PC-Lint/FlexeLint(resolve problem
both 1 and 2)

make sure add the +e766 options, this warning is about:
unused header files.

pclint/flint  -vf   ...

This will cause pclint output included header files, nested header files will be indented appropriately.

OwnerDisplayName: shoosh

ContentLicense: CC BY-SA 4.0


问:
AJAX request: Not enough or too many segments
I'm trying to do a POST request with AJAX and I'm getting the following error:

```<code>Error: Not enough or too many segments
</code>```

I have this function to send AJAX request:

```<code>function sendAjaxRequest(type, url, params, callback, returnType = 'json') {

    var token = token_admin;

    var request = $.ajax({
        url: url,
        method: type,
        data: params,
        beforeSend: function(xhr) {
            /* Authorization header */
            xhr.setRequestHeader("Authorization", "BEARER " + token);
            // xhr.setRequestHeader("X-Mobile", "false");
        },
        dataType: returnType,
        contentType: 'application/json'
    });
    request.done(function(res) {
        callback(res);
    });
    request.fail(function(jqXHR, textStatus) {
        console.error(jqXHR);
        callback({ err: true, message: "Request failed: " + textStatus });
    });

}
</code>```

And I'm using it like this:

```<code>var hostAPI = 'server_url';
var token_admin = 'some_token';

var params = {
    "criteria": {
        "lang.es_es.verb.parent": "abandonar"
    }
}

sendAjaxRequest("POST", hostAPI + 'words/getByCriteria', JSON.stringify(params), function(response) {
        console.log("------------");
        console.log(response);
        console.log("------------");
});
</code>```

But it's always returning me this error, the most weird thing is that I tested this webservice in Insomnia like this:

```<code>{
    "criteria": {
            "lang.es_es.verb.parent": "abandonar"
    }
}
</code>```

And it returns all data properly. I'm pretty new with AJAX and I have no idea of what's happening here, why it works in Insomnia and not with Javascript AJAX? What am I doing wrong?

Thank you very much for your answers.

答:
This error usually comes when your JWT token is malformed or invalid. Please note that you are passing it in headers

```<code>xhr.setRequestHeader("Authorization", "BEARER " + token);
</code>```

Please ensure that the token is valid, and the API is capable of accepting it. Also, please try to change BEARER to Bearer. The latter can be a cause if the API is not ignoring the case while checking for the header value.

Body:
I'm trying to do a POST request with AJAX and I'm getting the following error:

Error: Not enough or too many segments

I have this function to send AJAX request:

function sendAjaxRequest(type, url, params, callback, returnType = 'json') {

    var token = token_admin;

    var request = $.ajax({
        url: url,
        method: type,
        data: params,
        beforeSend: function(xhr) {
            /* Authorization header */
            xhr.setRequestHeader("Authorization", "BEARER " + token);
            // xhr.setRequestHeader("X-Mobile", "false");
        },
        dataType: returnType,
        contentType: 'application/json'
    });
    request.done(function(res) {
        callback(res);
    });
    request.fail(function(jqXHR, textStatus) {
        console.error(jqXHR);
        callback({ err: true, message: "Request failed: " + textStatus });
    });

}

And I'm using it like this:

var hostAPI = 'server_url';
var token_admin = 'some_token';

var params = {
    "criteria": {
        "lang.es_es.verb.parent": "abandonar"
    }
}

sendAjaxRequest("POST", hostAPI + 'words/getByCriteria', JSON.stringify(params), function(response) {
        console.log("------------");
        console.log(response);
        console.log("------------");
});

But it's always returning me this error, the most weird thing is that I tested this webservice in Insomnia like this:

{
    "criteria": {
            "lang.es_es.verb.parent": "abandonar"
    }
}

And it returns all data properly. I'm pretty new with AJAX and I have no idea of what's happening here, why it works in Insomnia and not with Javascript AJAX? What am I doing wrong?

Thank you very much for your answers.

Body:
This error usually comes when your JWT token is malformed or invalid. Please note that you are passing it in headers

xhr.setRequestHeader("Authorization", "BEARER " + token);

Please ensure that the token is valid, and the API is capable of accepting it. Also, please try to change BEARER to Bearer. The latter can be a cause if the API is not ignoring the case while checking for the header value.


问:
Cannot run android app using expo and genymotion

I am use genymotion along with expo to run my react-native app. I am not getting any errors with genymotion, but when i try to run it with expo, i get the following error:

Couldn't start project on Android: could not install smartsocket listener: cannot bind to 127.0.0.1:5037: Only one usage of each socket address (protocol/network address/port) is normally permitted. (10048)
could not read ok from ADB Server
* failed to start daemon *
error: cannot connect to daemon

I don't have vt-x enabled in my system so Android 5 and above versions are not working. This I am trying to run using Custom tablet 4.2.2-API 17 - 1536x2048.

Please guide me on how to proceed!

UPDATE : @dikaiosune here is the output of adb devices

答:
tns run android --emulator specifically targets the Android SDK emulator.
You have two options to use Genymotion:

Start the Genymotion virtual device and never close it. Then remove the --emulator parameter, like tns run android
use the --geny parameter, like: tns run android --emulator --geny . You can also use the shorter emulate command, like tns emulate android --geny
For more details, you can refer to our online help at any time using tns help run android.

Hope this helps!


问:
Setting a CSV filename as a variable in jmeter, based on date modified
I'm trying to set a variable from a CSV filename, specifically the file with the last date modified. The CSV files are based on data from my tests, so that file will be constantly changing. I've tried this code but I can't seem to get it to save as a variable.

```<code>public static File getLatestFilefromDir(String dirPath) {
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
    return null;
}

File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
   if (lastModifiedFile.lastModified() < files[i].lastModified()) {
       lastModifiedFile = files[i];
   }
}
return lastModifiedFile;
}

   String fileName = lastModifiedFile;

    vars.put("FILENAME", fileName);
</code>```

Thank you for your help.

答:
I would recommend using the following Groovy code to get the name of the newest file in the specified folder and save the result into the FILENAME JMeter Variable:

```<code>vars.put("FILENAME", new File('/path/to/the/folder/with/CSV/files').listFiles()?.sort { -it.lastModified() }?.head().getName())
</code>```

You can use this code with any of JSR223 Test Elements

See Apache Groovy - Why and How You Should Use It article for more details on using Groovy scripting in JMeter tests.

Body:
I'm trying to set a variable from a CSV filename, specifically the file with the last date modified. The CSV files are based on data from my tests, so that file will be constantly changing. I've tried this code but I can't seem to get it to save as a variable.

public static File getLatestFilefromDir(String dirPath) {
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
    return null;
}

File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
   if (lastModifiedFile.lastModified() < files[i].lastModified()) {
       lastModifiedFile = files[i];
   }
}
return lastModifiedFile;
}

   String fileName = lastModifiedFile;

    vars.put("FILENAME", fileName);

Thank you for your help.

Body:
I would recommend using the following Groovy code to get the name of the newest file in the specified folder and save the result into the FILENAME JMeter Variable:

vars.put("FILENAME", new File('/path/to/the/folder/with/CSV/files').listFiles()?.sort { -it.lastModified() }?.head().getName())

You can use this code with any of JSR223 Test Elements

See Apache Groovy - Why and How You Should Use It article for more details on using Groovy scripting in JMeter tests.


问:
Convert String Array to an Object in talend java code
I have created a context variable called srcCols of type Object

I am assigning a string array to the context variable using this code.
The following assignment is done in tJava component

```<code>String[] cols = { "This","is","test" };
context.SrcCols = cols;
</code>```

I am accessing the context variable in tJavaRow using the following code.

```<code>String[] Cols = (String[])context.SrcCols;
</code>```

but when i run the job i get the following error.

java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.String

What will be the solution for this problem

PS: This job is a Talend Bigdata Spark Job.

答:
You can try this with it (java 8)

```<code>Arrays.stream(objects).toArray(String[]::new);
</code>```

in your case

```<code>String[] Cols = Arrays.stream(context.SrcCols).toArray(String[]::new);
</code>```

Body:
I have created a context variable called srcCols of type Object

I am assigning a string array to the context variable using this code.
The following assignment is done in tJava component

String[] cols = { "This","is","test" };
context.SrcCols = cols;

I am accessing the context variable in tJavaRow using the following code.

String[] Cols = (String[])context.SrcCols;

but when i run the job i get the following error.

java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.String

What will be the solution for this problem

PS: This job is a Talend Bigdata Spark Job.

Body:
You can try this with it (java 8)

Arrays.stream(objects).toArray(String[]::new);

in your case

String[] Cols = Arrays.stream(context.SrcCols).toArray(String[]::new);


问:
unable to register node to hub in selenium
My hub is working successfully and running

```<code>    java -jar selenium-server-standalone-2.53.0.jar -role hub -port 5555
</code>```

my node command

```<code>  java -jar selenium-server-standalone-2.53.0.jar -role webdriver –hub http://localhost:5555/gridhost/register -port 7621
</code>```

but unable to  register my  node forbidden + for + proxy the hub is down or not responding

答:
Here is the Answer to your Question:

Assuming that you have a requirement to run the Selenium Grid Hub on port 5555, you have to consider the fact that by default Selenium Grid Node runs on port 5555. As you are setting up the Hub & Node both on your localhost and have started the Hub on port 5555, you have to consider configuring the node to run on some other port other than 5555. That will solve your issue.

If running the Selenium Grid Hub on port 5555 is not a mandatory requirement, then you can start the Selenium Grid Hub on the default port (port 4444) or any other port , e.g. port 5786

Here are the steps for your reference:

Start the Selenium Grid Server (on port 5786):

```<code>java -jar selenium-server-standalone-3.4.0.jar -role hub -port 5786
</code>```

The following logs confirms your Selenium Grid Hub is running properly:

```<code>2017-06-05 12:22:03.092:INFO:osjs.Server:main: Started @1917ms
12:22:03.093 INFO - Nodes should register to http://192.168.0.101:5786/grid/register/
12:22:03.094 INFO - Selenium Grid hub is up and running
</code>```

Access the Selenium Grid Console through the URL:

```<code>http://localhost:5786/grid/console
</code>```

Start the Selenium Grid Node:

```<code>java -jar selenium-server-standalone-3.4.0.jar -role node -hub http://localhost:5786/grid/register
</code>```

The following logs confirms your Selenium Grid Node is running properly:

```<code>12:49:46.805 INFO - Selenium Grid node is up and ready to register to the hub
12:49:46.927 INFO - Registering the node to the hub: http://localhost:5786/grid/register
12:49:47.166 INFO - The node is registered to the hub and ready to use
</code>```

Access the Selenium Grid Console through the console URL to see the registered Node:

```<code>http://localhost:5786/grid/console
</code>```

Let me know if this Answers your Question.

Body:
My hub is working successfully and running

    java -jar selenium-server-standalone-2.53.0.jar -role hub -port 5555

my node command

  java -jar selenium-server-standalone-2.53.0.jar -role webdriver –hub http://localhost:5555/gridhost/register -port 7621

but unable to  register my  node forbidden + for + proxy the hub is down or not responding

Body:
Here is the Answer to your Question:

Assuming that you have a requirement to run the Selenium Grid Hub on port 5555, you have to consider the fact that by default Selenium Grid Node runs on port 5555. As you are setting up the Hub & Node both on your localhost and have started the Hub on port 5555, you have to consider configuring the node to run on some other port other than 5555. That will solve your issue.

If running the Selenium Grid Hub on port 5555 is not a mandatory requirement, then you can start the Selenium Grid Hub on the default port (port 4444) or any other port , e.g. port 5786

Here are the steps for your reference:

Start the Selenium Grid Server (on port 5786):

java -jar selenium-server-standalone-3.4.0.jar -role hub -port 5786

The following logs confirms your Selenium Grid Hub is running properly:

2017-06-05 12:22:03.092:INFO:osjs.Server:main: Started @1917ms
12:22:03.093 INFO - Nodes should register to http://192.168.0.101:5786/grid/register/
12:22:03.094 INFO - Selenium Grid hub is up and running

Access the Selenium Grid Console through the URL:

http://localhost:5786/grid/console

Start the Selenium Grid Node:

java -jar selenium-server-standalone-3.4.0.jar -role node -hub http://localhost:5786/grid/register

The following logs confirms your Selenium Grid Node is running properly:

12:49:46.805 INFO - Selenium Grid node is up and ready to register to the hub
12:49:46.927 INFO - Registering the node to the hub: http://localhost:5786/grid/register
12:49:47.166 INFO - The node is registered to the hub and ready to use

Access the Selenium Grid Console through the console URL to see the registered Node:

http://localhost:5786/grid/console

Let me know if this Answers your Question.


问:
How to add different constraints depend on iPhone screen size?
This is my xib file viewed as iPhone6/iPhone7,it looks good.

but if i turn it into iPhoneSE,it becomes abnormal.

Becasue the space blank doesn't change when the device changes,and i can not change the space constraint adapting to device without code.

答:
you shouldn't have to add different constraints depend on iPhone screen size! since constraints works perfectly with any screen size

just make a simple fix in layout constraints:

The problem:
So what I am see that you have a problem with UIScrollView height it seems you set a fixed height constraint for UIScrollView

The Solution:
first you need to remove the height constraint for UIScrollView
second just add a height constraint to UISCrollView equal to parent screen height and give it a percentage

Note:
how to put percentage in constraint -> highlight the constraint and then from attributes inspector there is an attribute named Multiplier it takes value form 0.0 to 1


问:
JavaFx MVC Getter throws NullPointerException
I'm trying to build a simple MVC app with JavaFx. It takes the value of the left TextField (tf1) and copies it into the right one (tf2) when you hit button b. So, when I define what to do when Button b is clicked, eclipse doesn't show an error, but when I run the programme instead of returning the button a NullpointerException is thrown.

Do you have an idea about what I'm doing wrong?

Thanks in advance!

Model.java:

```<code>package mvc;

public class Model {
private String firsttext;
private String lasttext;

public String getFirsttext() {
    return firsttext;
}
public void setFirsttext(String firsttext) {
    this.firsttext = firsttext;
}
public String getLasttext() {
    return lasttext;
}
public void setLasttext(String lasttext) {
    this.lasttext = lasttext;
}

}
</code>```

View.java:

```<code>package mvc;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class View extends Application {
private TextField tf1;
private TextField tf2;
private Button b;

@Override
public void start(Stage stage) {
    tf1 = new TextField();
    tf2 = new TextField();
    b = new Button("Copy");

    FlowPane fp = new FlowPane();
    fp.getChildren().addAll(tf1, b, tf2);

    Scene scene = new Scene(fp, 600, 200);
    stage.setScene(scene);
    stage.show();
}

public void init(String args[]) {
    launch(args);
}

public TextField getTf1() {
    return tf1;
}

public void setTf1(TextField tf1) {
    this.tf1 = tf1;
}

public TextField getTf2() {
    return tf2;
}

public void setTf2(TextField tf2) {
    this.tf2 = tf2;
}

public Button getB() {
    return b;
}

public void setB(Button b) {
    this.b = b;
}
}
</code>```

Controller.java:

```<code>package mvc;

public class Controller {
private View view;
private Model model;

public Controller(View v, Model m) {
    view = v;
    model = m;
}

public void initController() {
    view.getB().setOnAction(evt -> {
        model.setFirsttext(view.getTf1().getText());
        model.setLasttext(model.getFirsttext());

        view.getTf2().setText(model.getLasttext());
    });

}
}
</code>```

App.java:

```<code>package mvc;

public class App {
public static void main(String[] args) {
    Model m = new Model();
    View v = new View();
    Controller c = new Controller(v, m);
    v.init(args);
    c.initController();
}
}
</code>```

答:
Look at sillyfly's comment. I made a new instance that was not passed on the controller.

Here are the corrected files:

Model.java -> didn't change, take a look above to see it

Controller.java -> didn't change, take a look above to see it

View.java:

```<code>package mvc;

import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;

public class View  {
private TextField tf1;
private TextField tf2;
private Button b;
private Scene scene;

public View() {
    tf1 = new TextField();
    tf2 = new TextField();
    b = new Button("Copy");

    FlowPane fp = new FlowPane();
    fp.getChildren().addAll(tf1, b, tf2);

    scene = new Scene(fp, 600, 200);
}

public Scene getScene() {
    return scene;
}

public void setScene(Scene scene) {
    this.scene = scene;
}

public TextField getTf1() {
    return tf1;
}

public void setTf1(TextField tf1) {
    this.tf1 = tf1;
}

public TextField getTf2() {
    return tf2;
}

public void setTf2(TextField tf2) {
    this.tf2 = tf2;
}

public Button getB() {
    return b;
}

public void setB(Button b) {
    this.b = b;
}
}
</code>```

App.java:

```<code>package mvc;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class App extends Application {
private Scene scene;
private Model m = new Model();
private View v = new View();
Controller c = new Controller(v, m);

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage stage) throws Exception {
    scene = v.getScene();
    stage.setScene(scene);
    stage.show();
    c.initController();
}
}
</code>```

Body:
I'm trying to build a simple MVC app with JavaFx. It takes the value of the left TextField (tf1) and copies it into the right one (tf2) when you hit button b. So, when I define what to do when Button b is clicked, eclipse doesn't show an error, but when I run the programme instead of returning the button a NullpointerException is thrown.

Do you have an idea about what I'm doing wrong?

Thanks in advance!

Model.java:

package mvc;

public class Model {
private String firsttext;
private String lasttext;

public String getFirsttext() {
    return firsttext;
}
public void setFirsttext(String firsttext) {
    this.firsttext = firsttext;
}
public String getLasttext() {
    return lasttext;
}
public void setLasttext(String lasttext) {
    this.lasttext = lasttext;
}

}

View.java:

package mvc;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class View extends Application {
private TextField tf1;
private TextField tf2;
private Button b;

@Override
public void start(Stage stage) {
    tf1 = new TextField();
    tf2 = new TextField();
    b = new Button("Copy");

    FlowPane fp = new FlowPane();
    fp.getChildren().addAll(tf1, b, tf2);

    Scene scene = new Scene(fp, 600, 200);
    stage.setScene(scene);
    stage.show();
}

public void init(String args[]) {
    launch(args);
}

public TextField getTf1() {
    return tf1;
}

public void setTf1(TextField tf1) {
    this.tf1 = tf1;
}

public TextField getTf2() {
    return tf2;
}

public void setTf2(TextField tf2) {
    this.tf2 = tf2;
}

public Button getB() {
    return b;
}

public void setB(Button b) {
    this.b = b;
}
}

Controller.java:

package mvc;

public class Controller {
private View view;
private Model model;

public Controller(View v, Model m) {
    view = v;
    model = m;
}

public void initController() {
    view.getB().setOnAction(evt -> {
        model.setFirsttext(view.getTf1().getText());
        model.setLasttext(model.getFirsttext());

        view.getTf2().setText(model.getLasttext());
    });

}
}

App.java:

package mvc;

public class App {
public static void main(String[] args) {
    Model m = new Model();
    View v = new View();
    Controller c = new Controller(v, m);
    v.init(args);
    c.initController();
}
}

Body:
Look at sillyfly's comment. I made a new instance that was not passed on the controller.

Here are the corrected files:

Model.java -> didn't change, take a look above to see it

Controller.java -> didn't change, take a look above to see it

View.java:

package mvc;

import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;

public class View  {
private TextField tf1;
private TextField tf2;
private Button b;
private Scene scene;

public View() {
    tf1 = new TextField();
    tf2 = new TextField();
    b = new Button("Copy");

    FlowPane fp = new FlowPane();
    fp.getChildren().addAll(tf1, b, tf2);

    scene = new Scene(fp, 600, 200);
}

public Scene getScene() {
    return scene;
}

public void setScene(Scene scene) {
    this.scene = scene;
}

public TextField getTf1() {
    return tf1;
}

public void setTf1(TextField tf1) {
    this.tf1 = tf1;
}

public TextField getTf2() {
    return tf2;
}

public void setTf2(TextField tf2) {
    this.tf2 = tf2;
}

public Button getB() {
    return b;
}

public void setB(Button b) {
    this.b = b;
}
}

App.java:

package mvc;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class App extends Application {
private Scene scene;
private Model m = new Model();
private View v = new View();
Controller c = new Controller(v, m);

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage stage) throws Exception {
    scene = v.getScene();
    stage.setScene(scene);
    stage.show();
    c.initController();
}
}


问:
Addressing Flask application launched from virtual machine
I have the following problem: I have OS xUbuntu and I run virtual machine with VirtualBox. The OS on my VM is Debian Wheezy. I have Flask application. What I want to do is, when I launch my application from the VM (which is on 127.0.0.1:5000), to run it on browser from my host machine (xUbuntu). </p>

<p>How do I do that? </p>

答:
This question is old, but googling the problem brought me here first.

I found this to work perfectly:

VBoxManage.exe modifyvm "VMnameInQuotes" --natpf1 "guestFlask,tcp,,5000,,5000"

Taken from http://dnfehren.github.io/blog/2012/07/20/use-python-flask-server-through-nat-virtualbox-guest/

Body:
I have the following problem: I have OS xUbuntu and I run virtual machine with VirtualBox. The OS on my VM is Debian Wheezy. I have Flask application. What I want to do is, when I launch my application from the VM (which is on 127.0.0.1:5000), to run it on browser from my host machine (xUbuntu).

How do I do that?


问:
How to run Node.js as a background process and never die?
I connect to the linux server via putty SSH. I tried to run it as a background process like this:

```<code>$ node server.js &
</code>```

However, after 2.5 hrs the terminal becomes inactive and the process dies.  Is there anyway I can keep the process alive even with the terminal disconnected?

Edit 1

Actually, I tried nohup, but as soon as I close the Putty SSH terminal or unplug my internet, the server process stops right away.

Is there anything I have to do in Putty?

Edit 2 (on Feb, 2012)

There is a node.js module, forever. It will run node.js server as daemon service.

答:
To run command as a system service on debian with sysv init:

Copy skeleton script and adapt it for your needs, probably all you have to do is to set some variables. Your script will inherit fine defaults from /lib/init/init-d-script, if something does not fits your needs - override it in your script. If something goes wrong you can see details in source /lib/init/init-d-script. Mandatory vars are DAEMON and NAME. Script will use start-stop-daemon to run your command, in START_ARGS you can define additional parameters of start-stop-daemon to use.

```<code>cp /etc/init.d/skeleton /etc/init.d/myservice
chmod +x /etc/init.d/myservice
nano /etc/init.d/myservice

/etc/init.d/myservice start
/etc/init.d/myservice stop
</code>```

That is how I run some python stuff for my wikimedia wiki:

```<code>...
DESC="mediawiki articles converter"
DAEMON='/home/mss/pp/bin/nslave'
DAEMON_ARGS='--cachedir /home/mss/cache/'
NAME='nslave'
PIDFILE='/var/run/nslave.pid'
START_ARGS='--background --make-pidfile --remove-pidfile --chuid mss --chdir /home/mss/pp/bin'

export PATH="/home/mss/pp/bin:$PATH"

do_stop_cmd() {
    start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 \
        $STOP_ARGS \
        ${PIDFILE:+--pidfile ${PIDFILE}} --name $NAME
    RETVAL="$?"
    [ "$RETVAL" = 2 ] && return 2
    rm -f $PIDFILE
    return $RETVAL
}
</code>```

Besides setting vars I had to override do_stop_cmd because of python substitutes the executable, so service did not stop properly.

Body:
I connect to the linux server via putty SSH. I tried to run it as a background process like this:

$ node server.js &

However, after 2.5 hrs the terminal becomes inactive and the process dies.  Is there anyway I can keep the process alive even with the terminal disconnected?

Edit 1

Actually, I tried nohup, but as soon as I close the Putty SSH terminal or unplug my internet, the server process stops right away.

Is there anything I have to do in Putty?

Edit 2 (on Feb, 2012)

There is a node.js module, forever. It will run node.js server as daemon service.

Body:
To run command as a system service on debian with sysv init:

Copy skeleton script and adapt it for your needs, probably all you have to do is to set some variables. Your script will inherit fine defaults from /lib/init/init-d-script, if something does not fits your needs - override it in your script. If something goes wrong you can see details in source /lib/init/init-d-script. Mandatory vars are DAEMON and NAME. Script will use start-stop-daemon to run your command, in START_ARGS you can define additional parameters of start-stop-daemon to use.

cp /etc/init.d/skeleton /etc/init.d/myservice
chmod +x /etc/init.d/myservice
nano /etc/init.d/myservice

/etc/init.d/myservice start
/etc/init.d/myservice stop

That is how I run some python stuff for my wikimedia wiki:

...
DESC="mediawiki articles converter"
DAEMON='/home/mss/pp/bin/nslave'
DAEMON_ARGS='--cachedir /home/mss/cache/'
NAME='nslave'
PIDFILE='/var/run/nslave.pid'
START_ARGS='--background --make-pidfile --remove-pidfile --chuid mss --chdir /home/mss/pp/bin'

export PATH="/home/mss/pp/bin:$PATH"

do_stop_cmd() {
    start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 \
        $STOP_ARGS \
        ${PIDFILE:+--pidfile ${PIDFILE}} --name $NAME
    RETVAL="$?"
    [ "$RETVAL" = 2 ] && return 2
    rm -f $PIDFILE
    return $RETVAL
}

Besides setting vars I had to override do_stop_cmd because of python substitutes the executable, so service did not stop properly.


问:
Send data with POST method, android studio singleton
I'm creating an app that include a login form, I'm using a singleton class, jsonobject request and volley library. Can someone tell me how to get email and password from the edit text in order to send them in post method to the URL?

Here's the login.java code:

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
//import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONObject;

public class Login extends AppCompatActivity {

private EditText email,password;
private Button login;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    email = (EditText) findViewById(R.id.email);
    password = (EditText) findViewById(R.id.password);
    login = (Button) findViewById(R.id.bLogin);
    //ip azienda
    //final String url = "http://192.168.10.59/mygymapi/Login.php";
    //ip casa mia
    final String url = "http://192.168.56.1/mygymapi/Login.php";
    login.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){

        JsonObjectRequest jsObjRequest = new JsonObjectRequest

                    (Request.Method.POST, url, null, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {

                            Toast.makeText(getBaseContext(),"Response: " + response.toString(), Toast.LENGTH_SHORT).show();
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // TODO Auto-generated method stub
                            VolleyLog.e("Error: ", error.getMessage());
                        }
                    });
            MySingleton.getInstance(getBaseContext()).addToRequestQueue(jsObjRequest);
        }
    });
}
}
</code>```

Singleton code:

```<code>import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.Request;
import com.android.volley.toolbox.Volley;

public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;

private MySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();

    mImageLoader = new ImageLoader(mRequestQueue,
            new ImageLoader.ImageCache() {
                private final LruCache<String, Bitmap>
                        cache = new LruCache<String, Bitmap>(20);

                @Override
                public Bitmap getBitmap(String url) {
                    return cache.get(url);
                }

                @Override
                public void putBitmap(String url, Bitmap bitmap) {
                    cache.put(url, bitmap);
                }
            });
}

public static synchronized MySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MySingleton(context);
    }
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}

public ImageLoader getImageLoader() {
    return mImageLoader;
}
}
</code>```

答:
Use this function to post data

```<code>StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                }
            });
</code>```

And add request to the request queue

```<code> RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
</code>```

Body:
I'm creating an app that include a login form, I'm using a singleton class, jsonobject request and volley library. Can someone tell me how to get email and password from the edit text in order to send them in post method to the URL?

Here's the login.java code:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
//import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONObject;

public class Login extends AppCompatActivity {

private EditText email,password;
private Button login;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    email = (EditText) findViewById(R.id.email);
    password = (EditText) findViewById(R.id.password);
    login = (Button) findViewById(R.id.bLogin);
    //ip azienda
    //final String url = "http://192.168.10.59/mygymapi/Login.php";
    //ip casa mia
    final String url = "http://192.168.56.1/mygymapi/Login.php";
    login.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){

        JsonObjectRequest jsObjRequest = new JsonObjectRequest

                    (Request.Method.POST, url, null, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {

                            Toast.makeText(getBaseContext(),"Response: " + response.toString(), Toast.LENGTH_SHORT).show();
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // TODO Auto-generated method stub
                            VolleyLog.e("Error: ", error.getMessage());
                        }
                    });
            MySingleton.getInstance(getBaseContext()).addToRequestQueue(jsObjRequest);
        }
    });
}
}

Singleton code:

import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.Request;
import com.android.volley.toolbox.Volley;

public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;

private MySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();

    mImageLoader = new ImageLoader(mRequestQueue,
            new ImageLoader.ImageCache() {
                private final LruCache<String, Bitmap>
                        cache = new LruCache<String, Bitmap>(20);

                @Override
                public Bitmap getBitmap(String url) {
                    return cache.get(url);
                }

                @Override
                public void putBitmap(String url, Bitmap bitmap) {
                    cache.put(url, bitmap);
                }
            });
}

public static synchronized MySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MySingleton(context);
    }
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}

public ImageLoader getImageLoader() {
    return mImageLoader;
}
}

Body:
Use this function to post data

StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                }
            });

And add request to the request queue

 RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);


问:
javascript Firebug error: Identifier starts immediately after numeric literal
I've got this error being reported in firebug, but I have no idea what it means:

Identifier starts immediately after numeric literal

Here is my webpage:
http://www.austintreeexperts.com/maps/optionUpdateMap.cfm?zoom=15

When the page and map loads, click on one of the blue or green markers.  Then click on one of the check boxes to get the error.  I have an onclick= for the input checkboxes.

答:
This message also appears if you've tried to name a variable starting with a numeral. eg.</p>

```<code>var 2ndString = 'abc';
</code>```

Body:
This message also appears if you've tried to name a variable starting with a numeral. eg.

var 2ndString = 'abc';


问:
Android - Preserve array value while moving to and returning from the another activity
I am having 2 activities:

1st Activity contains 2 arrays which are filled up with the data by making call to a webservice. And both the arrays are used to display data in ListView. On clicking on any List Item, i am opening new activity Activity-2, here i am posting data related with that selected List-item.

But i am facing trouble when i return from Activity-2 to Activity-1 , it agains goes to fetch data from Webservice into Array(Instead of, It should go for fetching data if there is anything posted from 2nd activity otherwise it should get preserved arrays value). So my question is how do i preserve value of both the arrays so that i remains preserve the same value. so it does not have to go for fetching again and again.

(I think i need to use the "Save activity state" kind of concept, but i didnt have implemented such concept yet, so please if you know such then pls let me know for the same.)

Update:

I have added "(Instead of, It should go for fetching data if there is anything posted from 2nd activity otherwise it should get preserved arrays value)"

答:
You can put them the values you retrieved in the Bundle passed to onSaveInstanceState:

```<code>@Override
protected void onSaveInstanceState(Bundle outState) {
    // Put your values into outState
    outState.putStringArray("my.project.str.array", stringArray);
    outState.putStringArrayList("my.proj.str.array.list", strArrayList);

    // read the documentation on Bundles to see complete
    //      list of values you can put in

    super.onSaveInstanceState(outState);
}
</code>```

And then you can retrieve them back via onRestoreInstanceState.

EDIT: You can put in more than one string array or string array list or whatever value, as long as the keys are different for each.

Body:
You can put them the values you retrieved in the Bundle passed to onSaveInstanceState:

@Override
protected void onSaveInstanceState(Bundle outState) {
    // Put your values into outState
    outState.putStringArray("my.project.str.array", stringArray);
    outState.putStringArrayList("my.proj.str.array.list", strArrayList);

    // read the documentation on Bundles to see complete
    //      list of values you can put in

    super.onSaveInstanceState(outState);
}

And then you can retrieve them back via onRestoreInstanceState.

EDIT: You can put in more than one string array or string array list or whatever value, as long as the keys are different for each.


问:
setTimeout for whole site, not just one page
How would I use setTimeout() - or any other javascript method - to call a function when the user had been on my website for 45 seconds.

I was using the below:

```<code>setTimeout(function(){ ....code.... }, 45000);
</code>```

But if the user navigated off the page and onto another page on the site before 45 seconds, the timer was reset.

I'd like the setTimeout to apply to the time the user landed on the first page, regardless of what page they are on now.

I will be including this javascript on every page on the site.

Thanks.

答:
You have to store the timestamp to localStorage when user comes to your page and start a timer using setTimeOut and listen to onbeforeUnlaod event when user goes from your site.

Again when user comes back query the localStorage for lastTime and reinit the timer.

Here is a fiddle

```<code>var your_delay = 5*1000;
window.init= function(){
    var start = localStorage.getItem('start');
    var end = new Date().getTime();
    if(start){
         if(end-start<your_delay)
           setTimeout(action,your_delay-(end-start));
    }else{
       setTimeout(action,your_delay);
    }
}
window.onbeforeunlaod = function(){
      /* Send the timer to server if you want it to be consistant across browser */
}

window.action = function(){
     alert("Hi");
}

init();
</code>```

Body:
How would I use setTimeout() - or any other javascript method - to call a function when the user had been on my website for 45 seconds.

I was using the below:

setTimeout(function(){ ....code.... }, 45000);

But if the user navigated off the page and onto another page on the site before 45 seconds, the timer was reset.

I'd like the setTimeout to apply to the time the user landed on the first page, regardless of what page they are on now.

I will be including this javascript on every page on the site.

Thanks.

Body:
You have to store the timestamp to localStorage when user comes to your page and start a timer using setTimeOut and listen to onbeforeUnlaod event when user goes from your site.

Again when user comes back query the localStorage for lastTime and reinit the timer.

Here is a fiddle

var your_delay = 5*1000;
window.init= function(){
    var start = localStorage.getItem('start');
    var end = new Date().getTime();
    if(start){
         if(end-start<your_delay)
           setTimeout(action,your_delay-(end-start));
    }else{
       setTimeout(action,your_delay);
    }
}
window.onbeforeunlaod = function(){
      /* Send the timer to server if you want it to be consistant across browser */
}

window.action = function(){
     alert("Hi");
}

init();


问:
How to use if statement within map in javascript/vuejs
I'm building a small application in Vuejs where I'm getting a response data and I'm mapping it to a variable, I've got few elements which has empty array, so while mapping I want to check the condition and map accordingly. Here is my code:

```<code>this.model = a.map(i => Object.assign({
    'id': i.id,
    'meeting_date': i.schedule,
    'meeting_call': i.type,
    'event_type': i.event_type,
    'venue': i.venue,
    'with_client': i.with_client
},{
    if(i.meeting.meeting_summaries)
    {
        'meeting_summaries': i.meeting_summaries.map(ms => ({
            client_name: ms.client_name,
            nature: ms.nature,
            action: ms.action,
            mention: ms.user_id,
            feedback: ms.feedback
        }))
    }

},
</code>```

答:
In your case you can just swap to ternary expression:

```<code>this.model = a.map(i => Object.assign({
    'id': i.id,
    'meeting_date': i.schedule,
    'meeting_call': i.type,
    'event_type': i.event_type,
    'venue': i.venue,
    'with_client': i.with_client
}, (i.meeting.meeting_summaries) ? { // if condition is met
    'meeting_summaries': i.meeting_summaries.map(ms => ({
        client_name: ms.client_name,
        nature: ms.nature,
        action: ms.action,
        mention: ms.user_id,
        feedback: ms.feedback
    }))
} : {} // otherwise don't do anything
</code>```

The idea is the following:

const a = [1, 2, 3, 4, 5];

const b = a.map(number => Object.assign({a: number},
  (number > 2) ? {b: ++number} : {}, // add 'b' for numbers > 2
  (number % 2 === 0) ? {c: number + ' is even'} : {} // add 'c' for even numbers
  ))

console.log(b)```

Body:
I'm building a small application in Vuejs where I'm getting a response data and I'm mapping it to a variable, I've got few elements which has empty array, so while mapping I want to check the condition and map accordingly. Here is my code:

this.model = a.map(i => Object.assign({
    'id': i.id,
    'meeting_date': i.schedule,
    'meeting_call': i.type,
    'event_type': i.event_type,
    'venue': i.venue,
    'with_client': i.with_client
},{
    if(i.meeting.meeting_summaries)
    {
        'meeting_summaries': i.meeting_summaries.map(ms => ({
            client_name: ms.client_name,
            nature: ms.nature,
            action: ms.action,
            mention: ms.user_id,
            feedback: ms.feedback
        }))
    }

},

Body:
In your case you can just swap to ternary expression:

this.model = a.map(i => Object.assign({
    'id': i.id,
    'meeting_date': i.schedule,
    'meeting_call': i.type,
    'event_type': i.event_type,
    'venue': i.venue,
    'with_client': i.with_client
}, (i.meeting.meeting_summaries) ? { // if condition is met
    'meeting_summaries': i.meeting_summaries.map(ms => ({
        client_name: ms.client_name,
        nature: ms.nature,
        action: ms.action,
        mention: ms.user_id,
        feedback: ms.feedback
    }))
} : {} // otherwise don't do anything

The idea is the following:

const a = [1, 2, 3, 4, 5];

const b = a.map(number => Object.assign({a: number},
  (number > 2) ? {b: ++number} : {}, // add 'b' for numbers > 2
  (number % 2 === 0) ? {c: number + ' is even'} : {} // add 'c' for even numbers
  ))

console.log(b)


问:
Likelihood of a sample prediction in machine learning
I know some machine learning algorithms can output the probability of predicted labels of an input sample.

For example, give a sample with three possible labels, a probability tuple (0.2,0.3,0.5) can be outputted through some probabilistic learning algorithms, such as logistic regression or probability estimate tree. Then the label with maximum probability (here 0.5) is outputted as the final prediction.

My question is, given a new sample having the predicted probability tuple (0.3,0.4,0.3), how can I quantitatively determine the likelihood of that the predicted label (here the second label) is correct?

Many thanks

答:
(This IMHO question doesn't belong here. It does belong to stat stack exchange)

The answer is freakingly simple: the probability/likelihood -- which is not exactly the same -- is 0.4, which is pretty low.

If you want to run a small experiment. Build/learn a model classify a few instances and compare it to the ground truth. In addition sum up the probability of the most likely label. You will see that the sum of probabilities matches the fraction of correctly classified instances
or:

your model is wrong

your sample set is to small


问:
i want to make 2 html select tags dependent. how do i do it?
I have 2 select tags which will get information from database. 1 takes from product_category table and other takes from product. I want to make the products select tag depend on the product_category select tag. For Example I have 2 categories of Medicines 1 is capsules and other is tablets. I want the product select tag to display me the names of the capsules when i select capsules in the product_category select tag. how do i make it dependent? here is the code for those select tags.</p>

```<code><div class="form-group" style="width:50%;">
        <label>Select Category</label>
        <select class="form-control" name="product_category" id="product_category" >
            <?php
            $query="SELECT * FROM product_category";
            $cat_result= mysqli_query($connection,$query);
            while($cat_row = mysqli_fetch_assoc($cat_result))
            {
              $ctg_id=$cat_row['category_id'];
              $ctg_name= $cat_row['category_name'];
              echo "<option value='$ctg_id'>$ctg_name</option>";
            }
            ?>
        </select>
    </div>
   <div class="form-group" style="width:50%;">
        <label>Select Product</label>
        <select class="form-control" name="product_name" id="product_name">
            <?php
            $query="SELECT product_id,product_name FROM product";
            $result= mysqli_query($connection,$query);
            while($row = mysqli_fetch_assoc($result))
            {
              $product_id=$row['product_id'];
              $product_name= $row['product_name'];
              echo "<option value='$product_id'>$product_name</option>";
            }
            ?>
        </select>
    </div>
</code>```

答:
Exactly, you need to use Ajax. When you select a product_category on success method you have to call the name of product_tag. This way you can use the ID of product_category to get the names of product tag .Use Jquery AJax ;)

http://api.jquery.com/jquery.ajax/

Firstly, fill the first select (Select Category). Create an event 'change' on this select and when the user select an option fill the other select with Ajax . Something like this:

```<code>$( "#product_category" ).change(function() {

 $.ajax({
    method: "POST",
    url: "some.php", /* The page you want */
    data: { id:  } /* here , you have to send the ID product category */
 }).success(data ) {
    /* Here you have to fill your new select with the info you have got it. If you selected capsules, the info you get it is the name of capsules*/
     $.each(data, function() { /* Iterator the object */
        $("#product_name").append("<option>" + data.value + "</option>")
     })

 })
});
</code>```

Body:
I have 2 select tags which will get information from database. 1 takes from product_category table and other takes from product. I want to make the products select tag depend on the product_category select tag. For Example I have 2 categories of Medicines 1 is capsules and other is tablets. I want the product select tag to display me the names of the capsules when i select capsules in the product_category select tag. how do i make it dependent? here is the code for those select tags.

        Select Category
        <select class="form-control" name="product_category" id="product_category" >
            <?php
            $query="SELECT * FROM product_category";
            $cat_result= mysqli_query($connection,$query);
            while($cat_row = mysqli_fetch_assoc($cat_result))
            {
              $ctg_id=$cat_row['category_id'];
              $ctg_name= $cat_row['category_name'];
              echo "<option value='$ctg_id'>$ctg_name</option>";
            }
            ?>
        </select>

        Select Product
        <select class="form-control" name="product_name" id="product_name">
            <?php
            $query="SELECT product_id,product_name FROM product";
            $result= mysqli_query($connection,$query);
            while($row = mysqli_fetch_assoc($result))
            {
              $product_id=$row['product_id'];
              $product_name= $row['product_name'];
              echo "<option value='$product_id'>$product_name</option>";
            }
            ?>
        </select>

Body:
Exactly, you need to use Ajax. When you select a product_category on success method you have to call the name of product_tag. This way you can use the ID of product_category to get the names of product tag .Use Jquery AJax ;)

http://api.jquery.com/jquery.ajax/

Firstly, fill the first select (Select Category). Create an event 'change' on this select and when the user select an option fill the other select with Ajax . Something like this:

$( "#product_category" ).change(function() {

 $.ajax({
    method: "POST",
    url: "some.php", /* The page you want */
    data: { id:  } /* here , you have to send the ID product category */
 }).success(data ) {
    /* Here you have to fill your new select with the info you have got it. If you selected capsules, the info you get it is the name of capsules*/
     $.each(data, function() { /* Iterator the object */
        $("#product_name").append("<option>" + data.value + "</option>")
     })

 })
});


问:
Encoding issue - 'ascii' codec can't decode byte 0xc3
I have an encoding issue in my Python code. I've tried different ways, but I don't get it to work.

value is ä

```<code>with open("result.txt", "a") as myfile:
    myfile.write(value.encode('utf-8'))
</code>```

The error is:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

答:
You can try codecs module, It is specifically designed for that only.
I am also hoping that value is unicode not string. If it's a unicode.

```<code>import codecs
value = u'ä'
with codecs.open("result.txt", "a", encoding="utf-8") as f:
    f.write(value)
</code>```

This should do it.

But looking at the error unicode decode it seems your value is string.
If its a string

```<code>f.write(value.decode("utf-8"))
</code>```

Always remember unicode is encoded to string, string decoded to unicode.
So in your case while writing you encode a string which is not true.
But python allows it. So it tries to decode the string to unicode So that it can be encoded further. But surely it would fail as decode would use by default ASCII encoding and ä doesn't fall into that.

Body:
I have an encoding issue in my Python code. I've tried different ways, but I don't get it to work.

value is ä

with open("result.txt", "a") as myfile:
    myfile.write(value.encode('utf-8'))

The error is:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Body:
You can try codecs module, It is specifically designed for that only.
I am also hoping that value is unicode not string. If it's a unicode.

import codecs
value = u'ä'
with codecs.open("result.txt", "a", encoding="utf-8") as f:
    f.write(value)

This should do it.

But looking at the error unicode decode it seems your value is string.
If its a string

f.write(value.decode("utf-8"))

Always remember unicode is encoded to string, string decoded to unicode.
So in your case while writing you encode a string which is not true.
But python allows it. So it tries to decode the string to unicode So that it can be encoded further. But surely it would fail as decode would use by default ASCII encoding and ä doesn't fall into that.


问:
Throwing Exceptions from Exception class in java
Ok ... So I am learning about exceptions in java and i am currently at throw statements. I throw an exception of Exception class, and then re-throw it from the catch block again to handle it in the main function. But whenever i throw it as Exception class, i always get an Error in the catch block(where i re-throw it to be handled in main).But as soon as i change the thrown and caught Exceptions to some particular Exceptions like NullPointerException, it works!

Error Code:

```<code>class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(Exception e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new Exception("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(Exception e) {
           System.out.println("Please handle the error");
           throw e; // It gives me an error here
       }
    }
}
</code>```

Working Code:

```<code>class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(NullPointerException e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new NullPointerException("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(NullPointerException e) {
           System.out.println("Please handle the error");
           throw e;
       }
    }
}
</code>```

Why doesn't it work with Exception class and worked with its subclass??

Note :-  The error i get in the error code is Unhandled exception type Exception

答:
It's because they are several Exception classes which are inherited from the class Exception. Each can be throwed, catched but they divide into two groups:

Checked and unchecked exceptions:

An unchecked exception doesn't need to be handled and the
NullPointerException which you tried is from that group, so you don't need to care about it technically.

A checked exception need to be handled every time or it won't
compile, these exceptions are like IOException.

Since the base Exception Object can be checked and unchecked as well the compiler cares about that it should be handled everytime.

If you give it a try and change the NullPointerException to IOException it won't compile either cause it is a Checked Exception. So it was just random, that you exactly find one type of Exception which your code can be work without compile error.

For more info visit my blog post about it:
http://www.zoltanraffai.com/blog/?p=93

Body:
Ok ... So I am learning about exceptions in java and i am currently at throw statements. I throw an exception of Exception class, and then re-throw it from the catch block again to handle it in the main function. But whenever i throw it as Exception class, i always get an Error in the catch block(where i re-throw it to be handled in main).But as soon as i change the thrown and caught Exceptions to some particular Exceptions like NullPointerException, it works!

Error Code:

class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(Exception e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new Exception("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(Exception e) {
           System.out.println("Please handle the error");
           throw e; // It gives me an error here
       }
    }
}

Working Code:

class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(NullPointerException e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new NullPointerException("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(NullPointerException e) {
           System.out.println("Please handle the error");
           throw e;
       }
    }
}

Why doesn't it work with Exception class and worked with its subclass??

Note :-  The error i get in the error code is Unhandled exception type Exception


问:
Div with text wont stay centered
I'm creating a simple image gallery. Above the images I name the place where the pictures were taken, but the second and every another row has issues - div with the name is being pushed to the right instead of staying centered. Here is how it looks: http://prntscr.com/fg10u4

@import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css);
.locationName {
  text-align: center;
  padding: 0px 0px 20px 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row" id="locations">

  <div class="locationName">
    City
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="1.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>
</div></code>```

Obviously the code is doubled inside the "row" div.

答:
Add a full 12 column grid to the locationName class so that it takes up the whole row and force a break between the other columns. As you currently have it, it is trying to be placed inline, which is after the longest image.

```<code><div class="row" id="locations">

  <div class="col-xs-12 locationName">
    City
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="1.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>
</div>
</code>```

Title: Div with text wont stay centered

Body:
I'm creating a simple image gallery. Above the images I name the place where the pictures were taken, but the second and every another row has issues - div with the name is being pushed to the right instead of staying centered. Here is how it looks: http://prntscr.com/fg10u4

@import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css);
.locationName {
  text-align: center;
  padding: 0px 0px 20px 20px;
}

    City

Obviously the code is doubled inside the "row" div.

Body:
Add a full 12 column grid to the locationName class so that it takes up the whole row and force a break between the other columns. As you currently have it, it is trying to be placed inline, which is after the longest image.

<div class="row" id="locations">

  <div class="col-xs-12 locationName">
    City
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="1.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>
</div>


问:
How do I get the runtime Class of a parameterized Type in a Scala trait
I'm trying to implement a Scala trait that handles the details of interfacing with a Java library that requires us to create

What I want to do is something like:

```<code>trait SomeTrait[A] extends JavaAPI {
  def foo = {
    callApi(classOf[A])
  }

  override def bar = {
    foo
  }
}
</code>```

Note that bar is actually overriding a method from a base class, so I can't change it's signature.

I've tried several variations with Manifests, etc., but can't quite get this to work. Is there a way to get the runtime class of a parameterized type?

答:
You have to get the manifest in there somehow, and traits have no constructor parameters.  Only you can say what tradeoff you want to make.  Here's another one.</p>

```<code>trait SomeTrait[A] {
  implicit def manifesto: Manifest[A]

  def foo = println(manifest[A].erasure)
}
object SomeTrait {
  def apply[A: Manifest] : SomeTrait[A] = new SomeTrait[A] { def manifesto = manifest[A] }
}
</code>```

Body:
I'm trying to implement a Scala trait that handles the details of interfacing with a Java library that requires us to create

What I want to do is something like:

trait SomeTrait[A] extends JavaAPI {
  def foo = {
    callApi(classOf[A])
  }

  override def bar = {
    foo
  }
}

Note that bar is actually overriding a method from a base class, so I can't change it's signature.

I've tried several variations with Manifests, etc., but can't quite get this to work. Is there a way to get the runtime class of a parameterized type?

Body:
You have to get the manifest in there somehow, and traits have no constructor parameters.  Only you can say what tradeoff you want to make.  Here's another one.

trait SomeTrait[A] {
  implicit def manifesto: Manifest[A]

  def foo = println(manifest[A].erasure)
}
object SomeTrait {
  def apply[A: Manifest] : SomeTrait[A] = new SomeTrait[A] { def manifesto = manifest[A] }
}


问:
R vector - return all items of vector if vector is defined by minimum/maximum
Let's say I have the following vector:

```<code>vector <- c(0, 5)
</code>```

0 here defines my minimum, 10 defines my my maximum.

```<code>min <- min(vector)
</code>```

now I want to return all values, that are between 0 and 5:

```<code>fullvector <- c(min, min+1, min+2, min+3, min+4)
</code>```

Of course that fails If the number of items changes, so what is a better way to write this?

答:
We can use range

```<code>Reduce(`:`, range(vector))
#[1] 0 1 2 3 4 5
</code>```

Body:
Let's say I have the following vector:

vector <- c(0, 5)

0 here defines my minimum, 10 defines my my maximum.

min <- min(vector)

now I want to return all values, that are between 0 and 5:

fullvector <- c(min, min+1, min+2, min+3, min+4)

Of course that fails If the number of items changes, so what is a better way to write this?

Body:
We can use range

Reduce(`:`, range(vector))
#[1] 0 1 2 3 4 5


问:
Removing dynamically an element from a list
My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

I am using a for .. in .. like in the following example:

```<code>def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test
</code>```

I am getting the following output:

```<code>[5]
</code>```

Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

Thank you very much.

答:
While you can't do a for in loop or a list comprehension while making modifications to that iterable. The simplest is to use a while loop</p>

```<code>while len(test):
    test.pop()
</code>```

Body:
My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

I am using a for .. in .. like in the following example:

def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test

I am getting the following output:

[5]

Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

Thank you very much.

Body:
While you can't do a for in loop or a list comprehension while making modifications to that iterable. The simplest is to use a while loop

while len(test):
    test.pop()


问:
How can I code correctly to keep unique attributes in separate objects
I have the following structure in user.java

```<code>public class User(){

    string fname;
    string lname;
    string email;

    public User(){
        this.fname = randomCharGenMethod();
        this.lname = randomCharGenMethod();
        this.email = randomCharGenMethod();
   }
}
</code>```

in another java class, I've created following objects.

```<code>static User user1 = new User();
static User user2 = new User();
</code>```

when I'm going forward with the objects created, they both have same fname, lname, and email.

Actually, I want them to have unique fname,lname and email as they were generated from a string generating method

答:
Is there any specific reason that the User1, User2 are declared static? When you are handling static variables, you should remember that they are loaded before the instance with their value.

Consider this code, as a simpler example:

```<code>public class User() {
static string fname;
static string lname;
static string email;

public User() {
    this.fname = randomCharGenMethod();
    this.lname = randomCharGenMethod();
    this.email = randomCharGenMethod();
 }
}
</code>```

any new instance of User will share the same value of fname, lname and email, because those are loaded before any instantiation.

Taking that into account, perhaps if user1, user2 are not static, they can hold values generated individually.

Body:
I have the following structure in user.java

public class User(){

    string fname;
    string lname;
    string email;

    public User(){
        this.fname = randomCharGenMethod();
        this.lname = randomCharGenMethod();
        this.email = randomCharGenMethod();
   }
}

in another java class, I've created following objects.

static User user1 = new User();
static User user2 = new User();

when I'm going forward with the objects created, they both have same fname, lname, and email.

Actually, I want them to have unique fname,lname and email as they were generated from a string generating method

Body:
Is there any specific reason that the User1, User2 are declared static? When you are handling static variables, you should remember that they are loaded before the instance with their value.

Consider this code, as a simpler example:

public class User() {
static string fname;
static string lname;
static string email;

public User() {
    this.fname = randomCharGenMethod();
    this.lname = randomCharGenMethod();
    this.email = randomCharGenMethod();
 }
}

any new instance of User will share the same value of fname, lname and email, because those are loaded before any instantiation.

Taking that into account, perhaps if user1, user2 are not static, they can hold values generated individually.