问:
Error when try to update text in French/English to mysql db
I have one page to edit data. In this case, I will show the page to edit French data. The problem is that, when I paste the text in French and click to edit and update, it assumes mysql_error. This just happens with French and English, I can do it right in Portuguese. I'm using only this tree languages.

I've tried some ways, but nothing happened...
What is commented is that what I tried.

When I press the button, that is what happens : "Ocorreu um erro, tente de novo! You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ont forcé à travailler comme apprenti à l'usine d'orfèvrerie de son ' at line 1"

```<code><?php
    session_start();
    $cookie_name = "loggedin";
    if (isset($_COOKIE[$cookie_name])){
        $cookie_value = $_COOKIE[$cookie_name];
    }else {
        echo "O seu tempo expirou, inicie sessão novamente!";
        header("Refresh:2; url=/estagio/admin/login.php");
    }

    ini_set ('default_charset', 'UTF-8');

    mysql_set_charset('utf8');

    //header ("content-type: text/html; charset=utf-8");

    //mysql_query("SET NAMES 'utf8'");
    //mysql_query("SET character_set_connection=utf8");
    //mysql_query("SET character_set_client=utf8");
    //mysql_query("SET character_set_results=utf8");

    mysql_connect ("localhost", "root", "") or die ("Erro na conexão " .mysql_error());
    mysql_select_db ("casadoadro") or die ("Erro na seleção da base de dados " .mysql_error());

    $editid = $_GET['eid'];

    if (!isset($_GET['eid']) || empty($_GET['eid'])){
        header ("location: admin_biografia.php");
    }

    $editquery = mysql_query("select * from tb_biografia where id='{$editid}'") or die (mysql_error());
    $editdata = mysql_fetch_row($editquery);

    if ($_POST)
    {
        $id = htmlspecialchars ($_POST['id']);
        $title_fr = htmlspecialchars ($_POST['title_fr']);
        $subtitle_fr = htmlspecialchars ($_POST['subtitle_fr']);
        $text_fr = htmlspecialchars ($_POST['text_fr']);

        $q = mysql_query ("UPDATE tb_biografia SET title_fr='{$title_fr}', subtitle_fr='{$subtitle_fr}', text_fr='{$text_fr}'  WHERE id='{$id}'") or die ("Ocorreu um erro, tente de novo! " .mysql_error());

        if($q){
            echo "<script>alert ('Editado com sucesso'); window.location='admin_biografia.php'</script>";
        }
    }
?>

<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
        <link rel="stylesheet" type="text/css" href="/estagio/css/styles.css">
        <title>Casa do adro</title>
    </head>
    <body>
        <div class="col-2"></div>
        <div class="col-8">
                <div class="col-12 w3-card-4 nopadding">
                    <form method="post" class="w3-container w3margin" enctype="multipart/form-data">
                        <input type="hidden" name="size" value="10000000" />
                        <div class="w3-row mtb">
                            <div class="w3-col" style="width:150px">ID</div>
                            <div class="w3-rest">
                                <?php echo $editdata[0]; ?>
                                <input class="w3-input w3-border" type="hidden" name="id"  value="<?php echo $editdata[0]; ?>">
                            </div>
                        </div>
                        <div class="w3-row mtb">
                            <div class="w3-col" style="width:150px">Título FR</div>
                            <div class="w3-rest">
                                <input class="w3-input w3-border" type="text" name="title_fr"  value="<?php echo $editdata[2]; ?>">
                            </div>
                        </div>
                        <div class="w3-row mtb">
                            <div class="w3-col" style="width:150px">Legenda FR</div>
                            <div class="w3-rest">
                                <input class="w3-input w3-border" type="text" name="subtitle_fr"  value="<?php echo $editdata[6]; ?>">
                            </div>
                        </div>
                        <div class="w3-row mtb">
                            <div class="w3-col" style="width:150px">Texto FR</div>
                            <div class="w3-rest">
                                <div class="w3-rest">
                                <textarea class="w3-input w3-border" rows="1" type="text" name="text_fr"><?php echo $editdata[9]; ?></textarea>
                            </div>
                            </div>
                        </div>

                        <button class="btnfbform w3-block mtb w3-ripple  w3-input w3-border" type="submit" name="upload"> Editar texto</button>
                    </form>
                </div>
            </div>
            <div class="col-2"></div>
        </body>
</html>
</code>```

答:
You are passing the value like '{$title_fr}' which will produce an error

just change this

```<code>title_fr='{$title_fr}'
</code>```

with

```<code>title_fr='".$title_fr."'
</code>```

it will work.

Body:
I have one page to edit data. In this case, I will show the page to edit French data. The problem is that, when I paste the text in French and click to edit and update, it assumes mysql_error. This just happens with French and English, I can do it right in Portuguese. I'm using only this tree languages.

I've tried some ways, but nothing happened...
What is commented is that what I tried.

When I press the button, that is what happens : "Ocorreu um erro, tente de novo! You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ont forcé à travailler comme apprenti à l'usine d'orfèvrerie de son ' at line 1"

<?php
    session_start();
    $cookie_name = "loggedin";
    if (isset($_COOKIE[$cookie_name])){
        $cookie_value = $_COOKIE[$cookie_name];
    }else {
        echo "O seu tempo expirou, inicie sessão novamente!";
        header("Refresh:2; url=/estagio/admin/login.php");
    }

    ini_set ('default_charset', 'UTF-8');

    mysql_set_charset('utf8');

    //header ("content-type: text/html; charset=utf-8");

    //mysql_query("SET NAMES 'utf8'");
    //mysql_query("SET character_set_connection=utf8");
    //mysql_query("SET character_set_client=utf8");
    //mysql_query("SET character_set_results=utf8");

    mysql_connect ("localhost", "root", "") or die ("Erro na conexão " .mysql_error());
    mysql_select_db ("casadoadro") or die ("Erro na seleção da base de dados " .mysql_error());

    $editid = $_GET['eid'];

    if (!isset($_GET['eid']) || empty($_GET['eid'])){
        header ("location: admin_biografia.php");
    }

    $editquery = mysql_query("select * from tb_biografia where id='{$editid}'") or die (mysql_error());
    $editdata = mysql_fetch_row($editquery);

    if ($_POST)
    {
        $id = htmlspecialchars ($_POST['id']);
        $title_fr = htmlspecialchars ($_POST['title_fr']);
        $subtitle_fr = htmlspecialchars ($_POST['subtitle_fr']);
        $text_fr = htmlspecialchars ($_POST['text_fr']);

        $q = mysql_query ("UPDATE tb_biografia SET title_fr='{$title_fr}', subtitle_fr='{$subtitle_fr}', text_fr='{$text_fr}'  WHERE id='{$id}'") or die ("Ocorreu um erro, tente de novo! " .mysql_error());

        if($q){
            echo "";
        }
    }
?>

        <meta charset="UTF-8">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
        <link rel="stylesheet" type="text/css" href="/estagio/css/styles.css">
        <title>Casa do adro</title>

                    <form method="post" class="w3-container w3margin" enctype="multipart/form-data">
                        <input type="hidden" name="size" value="10000000" />

ID

                                <?php echo $editdata[0]; ?>
                                <input class="w3-input w3-border" type="hidden" name="id"  value="<?php echo $editdata[0]; ?>">

Título FR

                                <input class="w3-input w3-border" type="text" name="title_fr"  value="<?php echo $editdata[2]; ?>">

Legenda FR

                                <input class="w3-input w3-border" type="text" name="subtitle_fr"  value="<?php echo $editdata[6]; ?>">

Texto FR

                                <textarea class="w3-input w3-border" rows="1" type="text" name="text_fr"><?php echo $editdata[9]; ?></textarea>

                        <button class="btnfbform w3-block mtb w3-ripple  w3-input w3-border" type="submit" name="upload"> Editar texto</button>
                    </form>

Body:
You are passing the value like '{$title_fr}' which will produce an error

just change this

title_fr='{$title_fr}'

with

title_fr='".$title_fr."'

it will work.


来源: stackexchange

问:
How to get respected column data with count(*)
I have a table which gives count of rows on selected condtion from database table in view
like this.

The table data 3 in bellow are count of rows on condition of 'a' and 'e'.

Like bellow query

```<code>    select count(*) from table1 where col1="a" and col2="e";
</code>```

When I click on 3 I want to get all 3 id's and count as 3 with out put as single row

Bellow, I want id's 1,5,7 on click table data 3

```<code>                 #  | a | b | c | d |
                ----|---|---|---|---|---
                 e  | 3 |   |   |   |
                ----|---|---|---|---|---
                 f  |   | 0 | 1 |   |
                ----|---|---|---|---|---
                 g  |   |   |   |   |
                ----|---|---|---|---|---
</code>```

My database table is

```<code>                id |col1 |col2|
                 1 |  a  | e  |
                 2 |  b  | g  |
                 3 |  a  | f  |
                 4 |  c  | f  |
                 5 |  a  | e  |
                 6 |  b  | f  |
                 7 |  a  | e  |
</code>```

I want id's with count

答:
Use query as:
SELECT id,count(*) as countRow FROM table1 WHERE col1="a" AND col2="e"</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a table which gives count of rows on selected condtion from database table in view
like this.

The table data 3 in bellow are count of rows on condition of 'a' and 'e'.

Like bellow query

    select count(*) from table1 where col1="a" and col2="e";

When I click on 3 I want to get all 3 id's and count as 3 with out put as single row

Bellow, I want id's 1,5,7 on click table data 3

                 #  | a | b | c | d |
                ----|---|---|---|---|---
                 e  | 3 |   |   |   |
                ----|---|---|---|---|---
                 f  |   | 0 | 1 |   |
                ----|---|---|---|---|---
                 g  |   |   |   |   |
                ----|---|---|---|---|---

My database table is

                id |col1 |col2|
                 1 |  a  | e  |
                 2 |  b  | g  |
                 3 |  a  | f  |
                 4 |  c  | f  |
                 5 |  a  | e  |
                 6 |  b  | f  |
                 7 |  a  | e  |

I want id's with count


问:
Handler.postDelayed with delayMillis taken from XML file
Wanting to transfer the numeric constants of my application to a file under res/value/integers.xml.

I encounter a confusing problem. It concerns the function Handler.postDelayed:
the code in Activity_A:

```<code>new Handler().postDelayed(new Thread() {
@Override
public void run() {
            Intent i_activity_b = new Intent(Activity_A.this, Activity_B.class);
            Activity_A.this.startActivity(i_activity_b);
            Activity_A.this.finish();
            getApplicationContext().stopService(some_service);;
        }
}, Data.GAME_THREAD_DELAY);
</code>```

This piece of code is supposed to run Activite_A, as well as some_service for some time (GAME_THREAD_DELAY).

Stop, stop some_service and start Activity_B.

Results

As long as the parameter GAME_THREAD_DELAY is taken from a class (Data.GAME_THREAD_DELAY) everything is ok. If I take it from an xml file (@ integer / GAME_THREAD_DELAY), it does not work (Activity_B does not start) !!

Could someone help me?

Here is more details :
MainActivity :

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    final Intent musicIntent = new Intent(this, Music.class);
    musicIntent.putExtra("musicToPlay", Data.SPLASH_MUSIC);
    startService(musicIntent);

    Data.display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Data.context = getApplicationContext();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageView title_img = (ImageView) findViewById(R.id.title);
    Animation title_animation = AnimationUtils.loadAnimation(this, R.anim.rotate);
    title_img.startAnimation(title_animation);

    new Handler().postDelayed(new Thread() {
        @Override
        public void run() {
            Intent mainMenu = new Intent(MainActivity.this, MenuActivity.class);
            MainActivity.this.startActivity(mainMenu);
            MainActivity.this.finish();
            getApplicationContext().stopService(musicIntent);;
        }
    }, Data.GAME_THREAD_DELAY);
}}
</code>```

MenuActivity :

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    final Intent musicIntent = new Intent(this, Music.class);
    musicIntent.putExtra("musicToPlay", Data.Menu_MUSIC);
    startService(musicIntent);

    Data.context = getApplicationContext();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);
}}
</code>```

service :

```<code>public class Music extends Service {
public static boolean isRunning = false;
MediaPlayer player;

public SolarisMusic() {
}

public int onStartCommand(Intent intent, int SoundFile, int startId) {
    private static final String TAG = "Music";
    super.onStartCommand(intent, SoundFile, startId);
    Bundle extras = intent.getExtras();
    if(extras == null) {
        Log.d(TAG,"null");
    } else {
        int from = extras.getInt("musicToPlay");
        if(from == Data.SPLASH_MUSIC){
            player = MediaPlayer.create(Data.context, Data.SPLASH_MUSIC);
            player.setLooping(Data.LOOP_BACKGROUND_MUSIC);
            player.setVolume(Data.R_VOLUME, Data.L_VOLUME);
            player.start();
        }
        else{
            player = MediaPlayer.create(Data.context, Data.Menu_MUSIC);
            player.setLooping(Data.LOOP_BACKGROUND_MUSIC);
            player.setVolume(Data.R_VOLUME, Data.L_VOLUME);
            player.start();
        }
    }
    return 1;
}
@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}
public IBinder onUnBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}
public void onStop() {
    isRunning = false;
}
public void onPause() { }
@Override
public void onCreate() {
    super.onCreate();
}
@Override
public void onDestroy() {
    player.stop();
    player.release();
}
@Override
public void onLowMemory() {
    player.stop();
}}
</code>```

答:
According to your comment below your question, you're trying to pass the ID of the integer resource as the delay (instead of the value of that resource).

The correct code should look something like this (assuming the name of your integer resource is GAME_THREAD_DELAY):

```<code>new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        Intent mainMenu = new Intent(MainActivity.this, MenuActivity.class);
        startActivity(mainMenu);
        stopService(musicIntent);
        finish();
    }
}, getResources().getInteger(R.integer.GAME_THREAD_DELAY));
</code>```

Body:
Wanting to transfer the numeric constants of my application to a file under res/value/integers.xml.

I encounter a confusing problem. It concerns the function Handler.postDelayed:
the code in Activity_A:

new Handler().postDelayed(new Thread() {
@Override
public void run() {
            Intent i_activity_b = new Intent(Activity_A.this, Activity_B.class);
            Activity_A.this.startActivity(i_activity_b);
            Activity_A.this.finish();
            getApplicationContext().stopService(some_service);;
        }
}, Data.GAME_THREAD_DELAY);

This piece of code is supposed to run Activite_A, as well as some_service for some time (GAME_THREAD_DELAY).

Stop, stop some_service and start Activity_B.

Results

As long as the parameter GAME_THREAD_DELAY is taken from a class (Data.GAME_THREAD_DELAY) everything is ok. If I take it from an xml file (@ integer / GAME_THREAD_DELAY), it does not work (Activity_B does not start) !!

Could someone help me?

Here is more details :
MainActivity :

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    final Intent musicIntent = new Intent(this, Music.class);
    musicIntent.putExtra("musicToPlay", Data.SPLASH_MUSIC);
    startService(musicIntent);

    Data.display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Data.context = getApplicationContext();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageView title_img = (ImageView) findViewById(R.id.title);
    Animation title_animation = AnimationUtils.loadAnimation(this, R.anim.rotate);
    title_img.startAnimation(title_animation);

    new Handler().postDelayed(new Thread() {
        @Override
        public void run() {
            Intent mainMenu = new Intent(MainActivity.this, MenuActivity.class);
            MainActivity.this.startActivity(mainMenu);
            MainActivity.this.finish();
            getApplicationContext().stopService(musicIntent);;
        }
    }, Data.GAME_THREAD_DELAY);
}}

MenuActivity :

public class MenuActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    final Intent musicIntent = new Intent(this, Music.class);
    musicIntent.putExtra("musicToPlay", Data.Menu_MUSIC);
    startService(musicIntent);

    Data.context = getApplicationContext();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);
}}

service :

public class Music extends Service {
public static boolean isRunning = false;
MediaPlayer player;

public SolarisMusic() {
}

public int onStartCommand(Intent intent, int SoundFile, int startId) {
    private static final String TAG = "Music";
    super.onStartCommand(intent, SoundFile, startId);
    Bundle extras = intent.getExtras();
    if(extras == null) {
        Log.d(TAG,"null");
    } else {
        int from = extras.getInt("musicToPlay");
        if(from == Data.SPLASH_MUSIC){
            player = MediaPlayer.create(Data.context, Data.SPLASH_MUSIC);
            player.setLooping(Data.LOOP_BACKGROUND_MUSIC);
            player.setVolume(Data.R_VOLUME, Data.L_VOLUME);
            player.start();
        }
        else{
            player = MediaPlayer.create(Data.context, Data.Menu_MUSIC);
            player.setLooping(Data.LOOP_BACKGROUND_MUSIC);
            player.setVolume(Data.R_VOLUME, Data.L_VOLUME);
            player.start();
        }
    }
    return 1;
}
@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}
public IBinder onUnBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}
public void onStop() {
    isRunning = false;
}
public void onPause() { }
@Override
public void onCreate() {
    super.onCreate();
}
@Override
public void onDestroy() {
    player.stop();
    player.release();
}
@Override
public void onLowMemory() {
    player.stop();
}}

Body:
According to your comment below your question, you're trying to pass the ID of the integer resource as the delay (instead of the value of that resource).

The correct code should look something like this (assuming the name of your integer resource is GAME_THREAD_DELAY):

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        Intent mainMenu = new Intent(MainActivity.this, MenuActivity.class);
        startActivity(mainMenu);
        stopService(musicIntent);
        finish();
    }
}, getResources().getInteger(R.integer.GAME_THREAD_DELAY));


问:
comparing strings of different lengths
I'm trying to compare strings in Python that can be different lengths. This is to do a simple version check.
Here are the examples: 1.2.3, 1.2.15, 1.2.2a

I need to compare to find which one is bigger so taking example above 1.2.2a < 1.2.3 < 1.2.15. If there were only number than it would be pretty simple but the added character messes things as it is not always present. I thought that converting to base64 which makes string the same length will solve the problem but with base64 1.2.15 becomes less than 1.2.2a and 1.2.3.
Maybe there is a module that already does that.
Thank you.

答: The version numbers you are using appear to confirm with the semantic versioning standard. There are libraries available to handle this for you - take a look at semver or semantic_version.

Title: comparing strings of different lengths


问:
":" Used in Matching
I am trying to do something like this. If a university choice is not on a drop down list, the user selects "Other" Now when he selects other he moves over to a textbox and enters the name of the University.

Code looks like this

```<code>                        <?php
                        if(isset($_POST['work_exp'])){
                        $inst_name = $_POST['inst_name'];
                        $inst_name2 = $_POST['inst_name2'];

                        if($inst_name =='Other')
                        {
                            $inst_name2:$inst_name;
                            echo $inst_name;
                        }

                            }
                        ?>
</code>```

Now the Challenge i have is that its returning an Error Here like this

```<code>Parse error: syntax error, unexpected ':' in C:\xampp\htdocs\seekweb\brWeb.php on line 229
</code>```

Any ideas? Code works very well here

```<code><!doctype html>
<html>
<head></head>
<title>test for dropdown</title>
<body>
<form name="school_form" id="school_form" method="post" action="test_form.php" />
<h1>Drop down Box test</h1>
School name :<select name="school" id="school" />
         <option selected="selected">Please Select School</option>
         <option>Catania School of Medicine</option>
         <option>J.M Hart University</option>
        <option>Beulah College of Business</option>
        <option>Crownay University</option>
        <option>Other</option>
        </select></br></p>
If Other, Please Enter Institution name : <input type="text" name="otherschool" id="otherschool" /></br></p>
<input type="submit" name="submit" value="Add School" />
</form>
</body>
</html>

<?php

if(isset($_POST['submit'])){
    $school = $_POST['school'];
    $otherschool = $_POST['otherschool'];

    if($school =="Other")
    {
        $otherschool:$school;
        echo $school;
    }

}

?>
</code>```

答:
Here Is Your Working Code !!

```<code><script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">

<!-- Modal -->

    <div class="form-group">

     <select name="school" id='type'>
     <option selected="selected" disabled="disabled">Please Select School</option>
     <option>Catania School of Medicine</option>
     <option>J.M Hart University</option>
     <option>Beulah College of Business</option>
     <option>Crownay University</option>
     <option value='Other'>Other</option>
     </select>

    <div id="myModal" class="modal fade" role="dialog">
      <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Please Enter Institution name : </h4>
          </div>
          <div class="modal-body">
            <input type="text" class="form-control" id="name" name="otherschool" placeholder="Enter Name">
          </div>
          <div class="modal-footer">
            <button type="button" name="submit" class="btn btn-primary" data-dismiss="modal">Save</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
        <!-- Modal content-->

      </div>
    </div>

   </div>

<button type="submit" name="submit" class="btn btn-primary" data-dismiss="modal">Sumbit</button>
</form>

<?php

if(isset($_POST['submit'])){
    $school = $_POST['school'];
    $otherschool = $_POST['otherschool'];

    if($school === "Other")
    {
        echo $otherschool;
        // insert code of other

    }
    else{

      echo $school;

    }

}

?>

<script type="text/javascript">

  $("#type").on("change", function () {
      $modal = $('#myModal');
      if($(this).val() === 'Other'){
        $modal.modal('show');
    }
 });

</script>
</code>```

Download Working File and Run in your server : https://ufile.io/taj8x

  $("#type").on("change", function () {
      $modal = $('#myModal');
      if($(this).val() === 'Other'){
        $modal.modal('show');
    }
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">

<!-- Modal -->

    <div class="form-group">

     <select name="school" id='type'>
     <option selected="selected" disabled="disabled">Please Select School</option>
     <option>Catania School of Medicine</option>
     <option>J.M Hart University</option>
     <option>Beulah College of Business</option>
     <option>Crownay University</option>
     <option value='Other'>Other</option>
     </select>

    <div id="myModal" class="modal fade" role="dialog">
      <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Please Enter Institution name : </h4>
          </div>
          <div class="modal-body">
            <input type="text" class="form-control" id="name" name="otherschool" placeholder="Enter Name">
          </div>
          <div class="modal-footer">
            <button type="button" name="submit" class="btn btn-primary" data-dismiss="modal">Save</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
        <!-- Modal content-->

      </div>
    </div>

   </div>

<button type="submit" name="submit" class="btn btn-primary" data-dismiss="modal">Sumbit</button>
</form>

<?php

if(isset($_POST['submit'])){
    $school = $_POST['school'];
    $otherschool = $_POST['otherschool'];

    if($school === "Other")
    {
        echo $otherschool;
        // insert code of other

    }
    else{

      echo $school;

    }

}

?></code>```

Title: ":" Used in Matching

Body:
I am trying to do something like this. If a university choice is not on a drop down list, the user selects "Other" Now when he selects other he moves over to a textbox and enters the name of the University.

Code looks like this

                        <?php
                        if(isset($_POST['work_exp'])){
                        $inst_name = $_POST['inst_name'];
                        $inst_name2 = $_POST['inst_name2'];

                        if($inst_name =='Other')
                        {
                            $inst_name2:$inst_name;
                            echo $inst_name;
                        }

                            }
                        ?>

Now the Challenge i have is that its returning an Error Here like this

Parse error: syntax error, unexpected ':' in C:\xampp\htdocs\seekweb\brWeb.php on line 229

Any ideas? Code works very well here

<!doctype html>

<title>test for dropdown</title>

<form name="school_form" id="school_form" method="post" action="test_form.php" />

Drop down Box test

School name :<select name="school" id="school" />
         <option selected="selected">Please Select School</option>
         <option>Catania School of Medicine</option>
         <option>J.M Hart University</option>
        <option>Beulah College of Business</option>
        <option>Crownay University</option>
        <option>Other</option>
        </select>

If Other, Please Enter Institution name : <input type="text" name="otherschool" id="otherschool" />

<input type="submit" name="submit" value="Add School" />
</form>

<?php

if(isset($_POST['submit'])){
    $school = $_POST['school'];
    $otherschool = $_POST['otherschool'];

    if($school =="Other")
    {
        $otherschool:$school;
        echo $school;
    }

}

?>

Body:
Here Is Your Working Code !!

<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">

<!-- Modal -->

    <div class="form-group">

     <select name="school" id='type'>
     <option selected="selected" disabled="disabled">Please Select School</option>
     <option>Catania School of Medicine</option>
     <option>J.M Hart University</option>
     <option>Beulah College of Business</option>
     <option>Crownay University</option>
     <option value='Other'>Other</option>
     </select>

    <div id="myModal" class="modal fade" role="dialog">
      <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Please Enter Institution name : </h4>
          </div>
          <div class="modal-body">
            <input type="text" class="form-control" id="name" name="otherschool" placeholder="Enter Name">
          </div>
          <div class="modal-footer">
            <button type="button" name="submit" class="btn btn-primary" data-dismiss="modal">Save</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
        <!-- Modal content-->

      </div>
    </div>

   </div>

<button type="submit" name="submit" class="btn btn-primary" data-dismiss="modal">Sumbit</button>
</form>

<?php

if(isset($_POST['submit'])){
    $school = $_POST['school'];
    $otherschool = $_POST['otherschool'];

    if($school === "Other")
    {
        echo $otherschool;
        // insert code of other

    }
    else{

      echo $school;

    }

}

?>

<script type="text/javascript">

  $("#type").on("change", function () {
      $modal = $('#myModal');
      if($(this).val() === 'Other'){
        $modal.modal('show');
    }
 });

</script>

Download Working File and Run in your server : https://ufile.io/taj8x

  $("#type").on("change", function () {
      $modal = $('#myModal');
      if($(this).val() === 'Other'){
        $modal.modal('show');
    }
 });

<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">

<!-- Modal -->

    <div class="form-group">

     <select name="school" id='type'>
     <option selected="selected" disabled="disabled">Please Select School</option>
     <option>Catania School of Medicine</option>
     <option>J.M Hart University</option>
     <option>Beulah College of Business</option>
     <option>Crownay University</option>
     <option value='Other'>Other</option>
     </select>

    <div id="myModal" class="modal fade" role="dialog">
      <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Please Enter Institution name : </h4>
          </div>
          <div class="modal-body">
            <input type="text" class="form-control" id="name" name="otherschool" placeholder="Enter Name">
          </div>
          <div class="modal-footer">
            <button type="button" name="submit" class="btn btn-primary" data-dismiss="modal">Save</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
        <!-- Modal content-->

      </div>
    </div>

   </div>

<button type="submit" name="submit" class="btn btn-primary" data-dismiss="modal">Sumbit</button>
</form>

<?php

if(isset($_POST['submit'])){
    $school = $_POST['school'];
    $otherschool = $_POST['otherschool'];

    if($school === "Other")
    {
        echo $otherschool;
        // insert code of other

    }
    else{

      echo $school;

    }

}

?>


问:
Image is always NULL on upload form
I'm trying to upload image on user registration via ajax. This is how it's look like the form + some fields for name, password and email which are working good.

```<code><form method="post" class="registerForm" enctype="multipart/form-data" id="login-form">
    <div class="form-group">
        <label><b>Profile Image <span class="required">*</span></b></label>
        <input accept="image/*" type="file" id="picture" name="picture" required>
    </div>
    <div class="clearfix">
        <button type="submit" id="login" class="signupbtn">Sign Up</button>
    </div>
</form>
</code>```

I have found on another thread here on SO that I need to put this on my ajax script

```<code>    var data = $("#login-form").serialize();
    var form = new FormData(document.getElementById('picture'));
    //append files
    var file = document.getElementById('picture').files[0];
    if (file) {
        form.append('picture', file);
    }
</code>```

And this is whole ajax

```<code>function submitForm()
{
    var data = $("#login-form").serialize();
    var form = new FormData(document.getElementById('picture'));
    //append files
    var file = document.getElementById('picture').files[0];
    if (file) {
        form.append('picture', file);
    }
    $.ajax({

        type : 'POST',
        url  : 'registration.php',
        data : data,
        beforeSend: function()
        {
            $("#error").fadeOut();
            $("#login").html('<span class="glyphicon glyphicon-transfer"></span>   sending ...');
        },
        success :  function(data)
        {
            if(data=="registered")
            {
            }
        }
    });
    return false;
}
</code>```

And the server side for the picture part and the query

```<code>if(!empty($_FILES['picture']) && $_FILES['picture']['size']  >0  ){

    $profilePic = $randomString. basename($_FILES['picture']['name']);
    $uploadfile = $uploaddir .$randomString. basename($_FILES['picture']['name']);

    if (move_uploaded_file($_FILES['picture']['tmp_name'], $uploadfile)) {
    } else {
        $error = "error\n";
    }
}else{
    $error ='Please add your Picture!';
}
var_dump($_FILES['picture']);
try
{
    $stmt = $db_con->prepare("SELECT * FROM users WHERE email=:email");
    $stmt->execute(array(":email"=>$email));
    $count = $stmt->rowCount();

    if($count==0){
        $stmt = $db_con->prepare("INSERT INTO users (picture) VALUES (:picture)");
        $stmt->bindParam(":picture",$profilePic);

        if($stmt->execute()) {
            echo "registered";
        }
        else { echo "Query could not execute !"; }
    }
    else{ echo "1"; }
}
catch(PDOException $e){
    echo $e->getMessage();
}
</code>```

I've removed other fields in order keep the code simple as much as possible. All fields got inserted and saved in database except the image name.

What can be the problem? No errors at all. I've got registered on the console and NULL for var_dump($_FILES['picture'])

答:
You must set the contentType option to false, so jQuery won't add a Content-Type heade also set processData flag set to false otherwise jQuery will try to convert your FormData into a string, which will fail.

So ajax code will look like

```<code>    $(".signupbtn").click(function(e){
    e.preventDefault();
    var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
    form.append('picture', file);
}

    $.ajax({

        type : 'POST',
        url  : 'registration.php',
        data : form,
        contentType: false,
        processData: false,
        success :  function(data){}
    });
});
</code>```

Title: Image is always NULL on upload form

Body:
I'm trying to upload image on user registration via ajax. This is how it's look like the form + some fields for name, password and email which are working good.

<form method="post" class="registerForm" enctype="multipart/form-data" id="login-form">

        Profile Image *
        <input accept="image/*" type="file" id="picture" name="picture" required>

        <button type="submit" id="login" class="signupbtn">Sign Up</button>

</form>

I have found on another thread here on SO that I need to put this on my ajax script

    var data = $("#login-form").serialize();
    var form = new FormData(document.getElementById('picture'));
    //append files
    var file = document.getElementById('picture').files[0];
    if (file) {
        form.append('picture', file);
    }

And this is whole ajax

function submitForm()
{
    var data = $("#login-form").serialize();
    var form = new FormData(document.getElementById('picture'));
    //append files
    var file = document.getElementById('picture').files[0];
    if (file) {
        form.append('picture', file);
    }
    $.ajax({

        type : 'POST',
        url  : 'registration.php',
        data : data,
        beforeSend: function()
        {
            $("#error").fadeOut();
            $("#login").html('   sending ...');
        },
        success :  function(data)
        {
            if(data=="registered")
            {
            }
        }
    });
    return false;
}

And the server side for the picture part and the query

if(!empty($_FILES['picture']) && $_FILES['picture']['size']  >0  ){

    $profilePic = $randomString. basename($_FILES['picture']['name']);
    $uploadfile = $uploaddir .$randomString. basename($_FILES['picture']['name']);

    if (move_uploaded_file($_FILES['picture']['tmp_name'], $uploadfile)) {
    } else {
        $error = "error\n";
    }
}else{
    $error ='Please add your Picture!';
}
var_dump($_FILES['picture']);
try
{
    $stmt = $db_con->prepare("SELECT * FROM users WHERE email=:email");
    $stmt->execute(array(":email"=>$email));
    $count = $stmt->rowCount();

    if($count==0){
        $stmt = $db_con->prepare("INSERT INTO users (picture) VALUES (:picture)");
        $stmt->bindParam(":picture",$profilePic);

        if($stmt->execute()) {
            echo "registered";
        }
        else { echo "Query could not execute !"; }
    }
    else{ echo "1"; }
}
catch(PDOException $e){
    echo $e->getMessage();
}

I've removed other fields in order keep the code simple as much as possible. All fields got inserted and saved in database except the image name.

What can be the problem? No errors at all. I've got registered on the console and NULL for var_dump($_FILES['picture'])

Body:
You must set the contentType option to false, so jQuery won't add a Content-Type heade also set processData flag set to false otherwise jQuery will try to convert your FormData into a string, which will fail.

So ajax code will look like

    $(".signupbtn").click(function(e){
    e.preventDefault();
    var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
    form.append('picture', file);
}

    $.ajax({

        type : 'POST',
        url  : 'registration.php',
        data : form,
        contentType: false,
        processData: false,
        success :  function(data){}
    });
});


问:
Kms request automatically increasing on AWS
KMS requests are continuously increasing on my AWS account. I am on Free Tier package. My monthly quota is 20,000 requests, but in first 7 days, I've used 45 % of it (9000 requests).

Please tell me how to control this number I have no instance running at the time still the requests are increasing. No instance, no KMS keys, no web apps, no deployments, and I don't know why this is happening to me. I tried a lot to search on Google but couldn't find anything helpful.

EDIT:
First I created an instance and deployed a Django project. After 3 days I terminated that instance. Now I have no services running. In last 2 days, KMS requests count has been increased by 10%.

答:
KMS is used by a number of other AWS services, and there is also a default key. Some examples of where this can be used:

Encrypting data of any type

AWS Certification Manager SSL certs in an ELB/CloudFront

As for encryption, there's encrypted EBS volumes, RedShift data, S3 bucket data, parameters in EC2 Parameter Store, etc. If you still haven't got any idea what is causing the KMS allocation hits you might want to use CloudTrail to log calls. Note that CloudTrail itself can encrypt data and essentially kill your KMS allocations, and the logs it stores in S3 count against your S3 allocations.


问:
How to convert epoch to gregorian datetime in haskell
Let's say I have an integer representing Epoch time, for example epoch = 1499055085, and I want to convert it to UTCTime in Haskell.
How can I do this?

In other languages this is a very trivial task, why is it so difficult in haskell?

答:
Who says it is difficult?

You can simply use fromIntegral :: (Integral a, Num b) => a -> b to convert the epoch (an integer) to POSIXTime.

Next we can use posixSecondsToUTCTime :: POSIXTime -> UTCTime to obtain the UTCTime, and finally we use the utctDay :: UTCTime -> Day to get the day part of the UTCTime.

In case you want a (year,month,day) tuple, we can use the toGregorian :: Day -> (Integer,Int,Int) method.

So we can use the following method:

```<code>import Data.Time.Calendar(toGregorian)
import Data.Time.Clock(utctDay,UTCTime)
import Data.Time.Clock.POSIX(posixSecondsToUTCTime)

epochToUTC :: Integral a => a -> UTCTime
epochToUTC = posixSecondsToUTCTime . fromIntegral

epochToGregorian :: Integral a => a -> (Integer,Int,Int)
epochToGregorian = toGregorian . utctDay . epochToUTC
</code>```

And then for instance:

```<code>Main> epochToGregorian 1234567
(1970,1,15)
Main> epochToGregorian 123456789
(1973,11,29)
Main> epochToGregorian 1234567890
(2009,2,13)
</code>```

Body:
Who says it is difficult?

You can simply use fromIntegral :: (Integral a, Num b) => a -> b to convert the epoch (an integer) to POSIXTime.

Next we can use posixSecondsToUTCTime :: POSIXTime -> UTCTime to obtain the UTCTime, and finally we use the utctDay :: UTCTime -> Day to get the day part of the UTCTime.

In case you want a (year,month,day) tuple, we can use the toGregorian :: Day -> (Integer,Int,Int) method.

So we can use the following method:

import Data.Time.Calendar(toGregorian)
import Data.Time.Clock(utctDay,UTCTime)
import Data.Time.Clock.POSIX(posixSecondsToUTCTime)

epochToUTC :: Integral a => a -> UTCTime
epochToUTC = posixSecondsToUTCTime . fromIntegral

epochToGregorian :: Integral a => a -> (Integer,Int,Int)
epochToGregorian = toGregorian . utctDay . epochToUTC

And then for instance:

Main> epochToGregorian 1234567
(1970,1,15)
Main> epochToGregorian 123456789
(1973,11,29)
Main> epochToGregorian 1234567890
(2009,2,13)


问:
How to check if a big decimal number can be divided by 2^x or 5^x
I have a big decimal number N (up to 100.000 digits) and I need to check if N can be divided by 2^X or 5^X ( 0 < X < 5 ).

```<code>bignumber % (2^x) == 0
</code>```

Can I get a tip? I don't have any idea.

答:
https://www.mathsisfun.com/divisibility-rules.html

There should be listed when a number is divisible or not. It's for all numbers, no matter how large.

Body:
I have a big decimal number N (up to 100.000 digits) and I need to check if N can be divided by 2^X or 5^X ( 0 < X < 5 ).

bignumber % (2^x) == 0

Can I get a tip? I don't have any idea.


问:
It lags when i am using android studio
my laptop is i7 4510U , 4GB ram , Intel HD graphics 2gb , Nvidia GeForce 840m 4GB
why it's so laggy when Iam using android studio?</p>

答:
I also had problems but then i disabled some plugins and tried to build gradle offline, you can find detailed answer here :
http://stackoverflow.com/questions/30817871/android-studio-is-slow-how-to-speed-up</p>

Title: It lags when i am using android studio


问:
Choosing a simple web application framework
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages. </p>

<p>I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail. </p>

答:
You may want to step back and really consider which language you enjoy coding in the most, regardless of your level of expertise in each.  That will definitely narrow down your choices.  I think it's kind of hard to choose a framework without choosing a language first.  For instance, what if you end up doing your project in ASP.NET MVC, and find yourself not even liking C#/.NET too much to begin with.

Also ask yourself why you need a framework, or how a framework would help you with your hobby project. (Unless the hobby project is just for the sake of learning a framework.)

OwnerDisplayName: nagul

ContentLicense: CC BY-SA 2.5

Body:
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages.

I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail.

LastEditorDisplayName: Marko Dumic

OwnerDisplayName: felideon


问:
Universal library for C++ strings
Please recommend me universal library for C++ strings. I want to manipulate ascii text and unicode text in one build without making two versions of builds for std::string/char and for std::wstring/wchar; Also I want to convert them to each other (where it is possible);

Thank you very much!!!

答: Boost String Algorithms Library can be used for many text operations on both string and wstring.</p>

Title: Universal library for C++ strings


问:
How to change the background color of UIStackView?
I tried to change the UIStackView background from clear to white in Storyboard inspector, but when simulating, the background color of the stack view still has a clear color.

How can I change the background color of a UIStackView?

答:
You could do it like this:

```<code>stackView.backgroundColor = UIColor.blue
</code>```

By providing an extension to override the backgroundColor:

```<code>extension UIStackView {

    override open var backgroundColor: UIColor? {

        get {
            return super.backgroundColor
        }

        set {

            super.backgroundColor = newValue

            let tag = -9999
            for view in subviews where view.tag == tag {
                view.removeFromSuperview()
            }

            let subView = UIView()
            subView.tag = tag
            subView.backgroundColor = newValue
            subView.translatesAutoresizingMaskIntoConstraints = false
            self.addSubview(subView)
            subView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
            subView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
            subView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
            subView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        }

    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You could do it like this:

stackView.backgroundColor = UIColor.blue

By providing an extension to override the backgroundColor:

extension UIStackView {

    override open var backgroundColor: UIColor? {

        get {
            return super.backgroundColor
        }

        set {

            super.backgroundColor = newValue

            let tag = -9999
            for view in subviews where view.tag == tag {
                view.removeFromSuperview()
            }

            let subView = UIView()
            subView.tag = tag
            subView.backgroundColor = newValue
            subView.translatesAutoresizingMaskIntoConstraints = false
            self.addSubview(subView)
            subView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
            subView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
            subView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
            subView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        }

    }

}


问:
android.app.RemoteServiceException Bad notification posted
Sometimes my application get this kind of exception:

```<code>Fatal Exception: android.app.RemoteServiceException: Bad notification posted from package com.packagename: Couldn't expand RemoteViews for: StatusBarNotification(pkg=com.packagename user=UserHandle{0} id=136094146 tag=null score=0: Notification(pri=0 contentView=com.packagename/0x109007e vibrate=default sound=default defaults=0xffffffff flags=0x11 kind=[null]))
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:149)
   at android.app.ActivityThread.main(ActivityThread.java:5257)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:515)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
   at dalvik.system.NativeStart.main(NativeStart.java)
</code>```

Code creating notification:

```<code>PendingIntent intent = PendingIntent.getActivities(this, id,
        notificationIntents, PendingIntent.FLAG_UPDATE_CURRENT);

int color = ContextCompat.getColor(this, R.color.notif_background);

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        .setContentText(description)
        .setSmallIcon(getSmallIcon())
        .setLargeIcon(getLargeIcon())
        .setColor(color)
        .setDefaults(NotificationCompat.DEFAULT_ALL)
        .setAutoCancel(true)
        .setStyle(new NotificationCompat.BigPictureStyle().bigLargeIcon(largeIcon))
        .setContentIntent(intent);

if (title != null) {
    notificationBuilder.setContentTitle(title)
            .setTicker(title)
            .setStyle(new NotificationCompat.BigTextStyle()
                    .setBigContentTitle(title).bigText(description));
} else {
    notificationBuilder.setStyle(new NotificationCompat.BigTextStyle()
            .bigText(description));
}

if (image != null) {
    notificationBuilder
            .setStyle(new NotificationCompat.BigPictureStyle()
                    .bigPicture(image).setSummaryText(description));
}
android.app.Notification notification = notificationBuilder.build();
notificationManager.notify(id, notification);
</code>```

I have seen almost all the solution on stack overflow and it shows that this issue is regarding custom layout. But I didn't use custom layout. I couldn't understand what is the exact issue. Can anyone help?

答:
I had the same issuee when I used notification icons in .webp
Be sure that you use icons in .png for devices with KitKat and below.

Body:
Sometimes my application get this kind of exception:

Fatal Exception: android.app.RemoteServiceException: Bad notification posted from package com.packagename: Couldn't expand RemoteViews for: StatusBarNotification(pkg=com.packagename user=UserHandle{0} id=136094146 tag=null score=0: Notification(pri=0 contentView=com.packagename/0x109007e vibrate=default sound=default defaults=0xffffffff flags=0x11 kind=[null]))
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:149)
   at android.app.ActivityThread.main(ActivityThread.java:5257)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:515)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
   at dalvik.system.NativeStart.main(NativeStart.java)

Code creating notification:

PendingIntent intent = PendingIntent.getActivities(this, id,
        notificationIntents, PendingIntent.FLAG_UPDATE_CURRENT);

int color = ContextCompat.getColor(this, R.color.notif_background);

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        .setContentText(description)
        .setSmallIcon(getSmallIcon())
        .setLargeIcon(getLargeIcon())
        .setColor(color)
        .setDefaults(NotificationCompat.DEFAULT_ALL)
        .setAutoCancel(true)
        .setStyle(new NotificationCompat.BigPictureStyle().bigLargeIcon(largeIcon))
        .setContentIntent(intent);

if (title != null) {
    notificationBuilder.setContentTitle(title)
            .setTicker(title)
            .setStyle(new NotificationCompat.BigTextStyle()
                    .setBigContentTitle(title).bigText(description));
} else {
    notificationBuilder.setStyle(new NotificationCompat.BigTextStyle()
            .bigText(description));
}

if (image != null) {
    notificationBuilder
            .setStyle(new NotificationCompat.BigPictureStyle()
                    .bigPicture(image).setSummaryText(description));
}
android.app.Notification notification = notificationBuilder.build();
notificationManager.notify(id, notification);

I have seen almost all the solution on stack overflow and it shows that this issue is regarding custom layout. But I didn't use custom layout. I couldn't understand what is the exact issue. Can anyone help?


问:
Get proper checkbox value using form.serialize
We are currently using $('form').serialize() to get all form information

This will return any checkbox values as "On" or "Off".

Is there any way to get a 1/0 or true/false value using this same method?

答:
If we have multiple checkboxed in our page like :

```<code>  <input id="reminder" name="Check1" value="false" type="checkbox" />

  <input id="alarm" name="Check2" value="false" type="checkbox" />
</code>```

we have to bind the change event of these checkboxes and set its value to true or false.

```<code> $('input[type=checkbox]').on('change', function(){
    var name =    $(this).attr('name');
    if($(this).is(':checked')){
    $('input[name= "' +name +'"]').val(true);
        $(this).val(true);
    }
    else{
       $(this).val(false);
       $('input[name= "' +name +'"]').val(false);
    }
});
</code>```

By default, checkbox value doesn't appear in $('form').serializeArray(), It appears when it is checked.

We have to keep one hidden field for each checkbox like :

```<code><input type="hidden" value="false" name="Check1" />
<input type="hidden" value="false" name="Check2" />
</code>```

Now when we serialize the form now, we get the correct value like :
    Check1=true
    Check2=false

Body:
If we have multiple checkboxed in our page like :

  <input id="reminder" name="Check1" value="false" type="checkbox" />

  <input id="alarm" name="Check2" value="false" type="checkbox" />

we have to bind the change event of these checkboxes and set its value to true or false.

 $('input[type=checkbox]').on('change', function(){
    var name =    $(this).attr('name');
    if($(this).is(':checked')){
    $('input[name= "' +name +'"]').val(true);
        $(this).val(true);
    }
    else{
       $(this).val(false);
       $('input[name= "' +name +'"]').val(false);
    }
});

By default, checkbox value doesn't appear in $('form').serializeArray(), It appears when it is checked.

We have to keep one hidden field for each checkbox like :

<input type="hidden" value="false" name="Check1" />
<input type="hidden" value="false" name="Check2" />

Now when we serialize the form now, we get the correct value like :
    Check1=true
    Check2=false


问:
Put onReceive on wait until the started activity finishes
In the onReceive(), I want to create a new Intent and start a new Activity. After the activity finishes, I want to get back to the same line from where I left for the activity. I know that I cannot use BroadcastReceiver class for achieving this. How can this be achieved? Below is the onReceive() code:

```<code>final BroadcastReceiver mPairingRequestRecevier = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(intent.getAction()))
        {
            final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR);

            if (type == BluetoothDevice.PAIRING_VARIANT_PIN)
            {
                abortBroadcast();
                String passkey="hey";
                Intent passkeyIntent = new Intent(context.getApplicationContext(),TestActivity.class);
                passkeyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                passkeyIntent.putExtra("passkey",passkey);
                context.startActivity(passkeyIntent);
                Log.d("after returning...",passkey);

            }
            else
            {
                Log.d("Unexpected pairingtype:" , type+"");
            }
        }
    }
};
</code>```

Any idea that can achieve this would be appreciated.

答:
You can use startActivityFor result instead of startActivity to start an activity..make it perform some task and return the result to previous activity
Look at this: How to manage `startActivityForResult` on Android?</p>

Body:
In the onReceive(), I want to create a new Intent and start a new Activity. After the activity finishes, I want to get back to the same line from where I left for the activity. I know that I cannot use BroadcastReceiver class for achieving this. How can this be achieved? Below is the onReceive() code:

final BroadcastReceiver mPairingRequestRecevier = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(intent.getAction()))
        {
            final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR);

            if (type == BluetoothDevice.PAIRING_VARIANT_PIN)
            {
                abortBroadcast();
                String passkey="hey";
                Intent passkeyIntent = new Intent(context.getApplicationContext(),TestActivity.class);
                passkeyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                passkeyIntent.putExtra("passkey",passkey);
                context.startActivity(passkeyIntent);
                Log.d("after returning...",passkey);

            }
            else
            {
                Log.d("Unexpected pairingtype:" , type+"");
            }
        }
    }
};

Any idea that can achieve this would be appreciated.


问:
Android Studio Failed to load platform rendering library
I have a project started from scratch on Android Studio. The layout editor was working fine. After adding the Google Play Services library, now when I open my layout XML file I get the following error in the Design tab:
"Rendering Problems: Failed to load platform rendering library"

In the Text tab, all the attributes for my TextView components have a warning "Unknown attribute android:[...]" where [...] is the attribute being declared.

Anybody know how to fix this issue?

答:
Studio version needs to be updated. Studio 2.1 supports till API 23 for rendering.
However for debugging it allows SDK version upto 26+.

For rendering you will have to use higher version Android Studio.


问:
Javascript EJS string literal
I am trying to pull a graphviz format string from my database and pass to a javascript function on my browser front end. I am using NodeJS and EJS as the view engine. The following code is on my index.ejs to take the array of graph formats, graph_format and send to the viz.js function:

```<code>    <script>
window.onload=function(){
  console.log("converting ejs to javascrpt")

  var jscgraph=[];
  <% graph_formats.forEach(function(graph){%>
    for(var i=0;i<graph_formats.length;i++){
      var r = "";
      r=r.concat("\"");
      r=r.concat(<%- graph%>;
      r=r.concat("\"");
      document.body.innerHTML += Viz(r);
    }
  <%
  })
  %>

  console.log("now printing javascript variable 1"+jscgraph[1])
}
</script>
</code>```

However, I get a "SyntaxError: missing ) after argument list[Learn More]  graphviz:206:24" error in the console of my browser and the lines "
      console.log("converting ejs to javascrpt")" and
      "console.log("now printing javascript variable 1"+jscgraph[1])" do not run.

When I go to the browser debugger at line 206 as per error message, I see the following:

```<code><script>
window.onload=function(){
  console.log("converting ejs to javascrpt")

  var jscgraph=[];

    for(var i=0;i<graph_formats.length;i++){
      var r = "";
      r=r.concat("\"");
      r=r.concat(digraph{
});
      r=r.concat("\"");
      document.body.innerHTML += Viz(r);
    }
</code>```

Where 206 is the line r=r.concat(digraph{});

He is the graph_format array copied and pasted from the nodejs console for completeness:

[ 'digraph{\n}\n\n\n\n\n\n',
  'digraph{\n0 [label="PUSH4", style=filled, color=antiquewhite]\n1 [label="PUSH1", style=filled, color=antiquewhite]\n2 [label="PUSH1", style=filled, color=antiquewhite]\n3 [label="EXP", style=filled, color=coral4]\n1 -> 3 [label="00000000000000000000000000000000000000000000000000000000000000e0", fontcolor=antiquewhite]\n2 -> 3 [label="0000000000000000000000000000000000000000000000000000000000000002", fontcolor=antiquewhite]\n4 [label="PUSH1", style=filled, color=antiquewhite]\n5 [label="CALLDATALOAD", style=filled, color=darkorchid4]\n4 -> 5 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n6 [label="DIV", style=filled, color=chocolate3]\n3 -> 6 [label="0000000100000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n5 -> 6 [label="1896f70a8851b17a825ca0cfde09020276ebce9c64cb69476c3b2e27299ccc88", fontcolor=antiquewhite]\n7 [label="EQ", style=filled, color=gold4]\n0 -> 7 [label="000000000000000000000000000000000000000000000000000000000178b8bf", fontcolor=antiquewhite]\n6 -> 7 [label="000000000000000000000000000000000000000000000000000000001896f70a", fontcolor=antiquewhite]\n8 [label="ISZERO", style=filled, color=goldenrod]\n7 -> 8 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n9 [label="PUSH2", style=filled, color=antiquewhite]\n10 [label="JUMPI", style=filled, color=burlywood1]\n8 -> 10 [label="0000000000000000000000000000000000000000000000000000000000000001", fontcolor=antiquewhite]\n9 -> 10 [label="0000000000000000000000000000000000000000000000000000000000000023", fontcolor=antiquewhite]\n11 [label="JUMPDEST", style=filled, color=magenta]\n12 [label="PUSH4", style=filled, color=antiquewhite]\n13 [label="PUSH1", style=filled, color=antiquewhite]\n14 [label="PUSH1", style=filled, color=antiquewhite]\n15 [label="EXP", style=filled, color=coral4]\n13 -> 15 [label="00000000000000000000000000000000000000000000000000000000000000e0", fontcolor=antiquewhite]\n14 -> 15 [label="0000000000000000000000000000000000000000000000000000000000000002", fontcolor=antiquewhite]\n16 [label="PUSH1", style=filled, color=antiquewhite]\n17 [label="CALLDATALOAD", style=filled, color=darkorchid4]\n16 -> 17 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n18 [label="DIV", style=filled, color=chocolate3]\n15 -> 18 [label="0000000100000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n17 -> 18 [label="1896f70a8851b17a825ca0cfde09020276ebce9c64cb69476c3b2e27299ccc88", fontcolor=antiquewhite]\n19 [label="EQ", style=filled, color=gold4]\n12 -> 19 [label="0000000000000000000000000000000000000000000000000000000002571be3", fontcolor=antiquewhite]\n18 -> 19 [label="000000000000000000000000000000000000000000000000000000001896f70a", fontcolor=antiquewhite]\n20 [label="ISZERO", style=filled, color=goldenrod]\n19 -> 20 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n21 [label="PUSH2", style=filled, color=antiquewhite]\n22 [label="JUMPI", style=filled, color=burlywood1]\n20 -> 22 [label="0000000000000000000000000000000000000000000000000000000000000001", fontcolor=antiquewhite]\n21 -> 22 [label="0000000000000000000000000000000000000000000000000000000000000047", fontcolor=antiquewhite]\n23 [label="JUMPDEST", style=filled, color=magenta]\n24 [label="PUSH4", style=filled, color=antiquewhite]\n25 [label="PUSH1", style=filled, color=antiquewhite]\n26 [label="PUSH1", style=filled, color=antiquewhite]\n27 [label="EXP", style=filled, color=coral4]\n25 -> 27 [label="00000000000000000000000000000000000000000000000000000000000000e0", fontcolor=antiquewhite]\n26 -> 27 [label="0000000000000000000000000000000000000000000000000000000000000002", fontcolor=antiquewhite]\n28 [label="PUSH1", style=filled, color=antiquewhite]\n29 [label="CALLDATALOAD", style=filled, color=darkorchid4]\n28 -> 29 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n30 [label="DIV", style=filled, color=chocolate3]\n27 -> 30 [label="0000000100000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n29 -> 30 [label="1896f70a8851b17a825ca0cfde09020276ebce9c64cb69476c3b2e27299ccc88", fontcolor=antiquewhite]\n31 [label="EQ", style=filled, color=gold4]\n24 -> 31 [label="0000000000000000000000000000000000000000000000000000000016a25cbd", fontcolor=antiquewhite]\n30 -> 31 [label="000000000000000000000000000000000000000000000000000000001896f70a", fontcolor=antiquewhite]\n32 [label="ISZERO", style=filled, color=goldenrod]\n31 -> 32 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n33 [label="PUSH2", style=filled, color=antiquewhite]\n34 [label="JUMPI", style=filled, color=burlywood1]\n32 -> 34 [label="0000000000000000000000000000000000000000000000000000000000000001", fontcolor=antiquewhite]\n33 -> 34 [label="000000000000000000000000000000000000000000000000000000000000006b", fontcolor=antiquewhite]\n35 [label="JUMPDEST", style=filled, color=magenta]\n36 [label="PUSH4", style=filled, color=antiquewhite]\n37 [label="PUSH1", style=filled, color=antiquewhite]\n38 [label="PUSH1", style=filled, color=antiquewhite]\n39 [label="EXP", style=filled, color=coral4]\n37 -> 39 [label="00000000000000000000000000000000000000000000000000000000000000e0", fontcolor=antiquewhite]\n38 -> 39 [label="0000000000000000000000000000000000000000000000000000000000000002", fontcolor=antiquewhite]\n40 [label="PUSH1", style=filled, color=antiquewhite]\n41 [label="CALLDATALOAD", style=filled, color=darkorchid4]\n40 -> 41 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n42 [label="DIV", style=filled, color=chocolate3]\n39 -> 42 [label="0000000100000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n41 -> 42 [label="1896f70a8851b17a825ca0cfde09020276ebce9c64cb69476c3b2e27299ccc88", fontcolor=antiquewhite]\n43 [label="EQ", style=filled, color=gold4]\n36 -> 43 [label="000000000000000000000000000000000000000000000000000000005b0fc9c3", fontcolor=antiquewhite]\n42 -> 43 [label="000000000000000000000000000000000000000000000000000000001896f70a", fontcolor=antiquewhite]\n44 [label="ISZERO", style=filled, color=goldenrod]\n43 -> 44 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n45 [label="PUSH2", style=filled, color=antiquewhite]\n46 [label="JUMPI", style=filled, color=burlywood1]\n44 -> 46 [label="0000000000000000000000000000000000000000000000000000000000000001", fontcolor=antiquewhite]\n45 -> 46 [label="00000000000000000000000000000000000000000000000000000000000000b8", fontcolor=antiquewhite]\n47 [label="JUMPDEST", style=filled, color=magenta]\n48 [label="PUSH4", style=filled, color=antiquewhite]\n49 [label="PUSH1", style=filled, color=antiquewhite]\n50 [label="PUSH1", style=filled, color=antiquewhite]\n51 [label="EXP", style=filled, color=coral4]\n49 -> 51 [label="00000000000000000000000000000000000000000000000000000000000000e0", fontcolor=antiquewhite]\n50 -> 51 [label="0000000000000000000000000000000000000000000000000000000000000002", fontcolor=antiquewhite]\n52 [label="PUSH1", style=filled, color=antiquewhite]\n53 [label="CALLDATALOAD", style=filled, color=darkorchid4]\n52 -> 53 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n54 [label="DIV", style=filled, color=chocolate3]\n51 -> 54 [label="0000000100000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n53 -> 54 [label="1896f70a8851b17a825ca0cfde09020276ebce9c64cb69476c3b2e27299ccc88", fontcolor=antiquewhite]\n55 [label="EQ", style=filled, color=gold4]\n48 -> 55 [label="0000000000000000000000000000000000000000000000000000000006ab5923", fontcolor=antiquewhite]\n54 -> 55 [label="000000000000000000000000000000000000000000000000000000001896f70a", fontcolor=antiquewhite]\n56 [label="ISZERO", style=filled, color=goldenrod]\n55 -> 56 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n57 [label="PUSH2", style=filled, color=antiquewhite]\n58 [label="JUMPI", style=filled, color=burlywood1]\n56 -> 58 [label="0000000000000000000000000000000000000000000000000000000000000001", fontcolor=antiquewhite]\n57 -> 58 [label="0000000000000000000000000000000000000000000000000000000000000116", fontcolor=antiquewhite]\n59 [label="JUMPDEST", style=filled, color=magenta]\n60 [label="PUSH4", style=filled, color=antiquewhite]\n61 [label="PUSH1", style=filled, color=antiquewhite]\n62 [label="PUSH1", style=filled, color=antiquewhite]\n63 [label="EXP", style=filled, color=coral4]\n61 -> 63 [label="00000000000000000000000000000000000000000000000000000000000000e0", fontcolor=antiquewhite]\n62 -> 63 [label="0000000000000000000000000000000000000000000000000000000000000002", fontcolor=antiquewhite]\n64 [label="PUSH1", style=filled, color=antiquewhite]\n65 [label="CALLDATALOAD", style=filled, color=darkorchid4]\n64 -> 65 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n66 [label="DIV", style=filled, color=chocolate3]\n63 -> 66 [label="0000000100000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n65 -> 66 [label="1896f70a8851b17a825ca0cfde09020276ebce9c64cb69476c3b2e27299ccc88", fontcolor=antiquewhite]\n67 [label="EQ", style=filled, color=gold4]\n60 -> 67 [label="000000000000000000000000000000000000000000000000000000001896f70a", fontcolor=antiquewhite]\n66 -> 67 [label="000000000000000000000000000000000000000000000000000000001896f70a", fontcolor=antiquewhite]\n68 [label="ISZERO", style=filled, color=goldenrod]\n67 -> 68 [label="0000000000000000000000000000000000000000000000000000000000000001", fontcolor=antiquewhite]\n69 [label="PUSH2", style=filled, color=antiquewhite]\n70 [label="JUMPI", style=filled, color=burlywood1]\n68 -> 70 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n69 -> 70 [label="0000000000000000000000000000000000000000000000000000000000000163", fontcolor=antiquewhite]\n71 [label="PUSH1", style=filled, color=antiquewhite]\n72 [label="PUSH1", style=filled, color=antiquewhite]\n73 [label="CALLDATALOAD", style=filled, color=darkorchid4]\n72 -> 73 [label="0000000000000000000000000000000000000000000000000000000000000004", fontcolor=antiquewhite]\n74 [label="ADD", style=filled, color=chocolate]\n71 -> 74 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n73 -> 74 [label="8851b17a825ca0cfde09020276ebce9c64cb69476c3b2e27299ccc88f650c575", fontcolor=antiquewhite]\n75 [label="SLOAD", style=filled, color=chartreuse]\n74 -> 75 [label="8851b17a825ca0cfde09020276ebce9c64cb69476c3b2e27299ccc88f650c575", fontcolor=antiquewhite]\n76 [label="CALLER", style=filled, color=darkorchid2]\n77 [label="EQ", style=filled, color=gold4]\n75 -> 77 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n76 -> 77 [label="00000000000000000000000065ddc3a1f2762f3d0669bbeea44e16b2b38090a5", fontcolor=antiquewhite]\n78 [label="ISZERO", style=filled, color=goldenrod]\n77 -> 78 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n79 [label="ISZERO", style=filled, color=goldenrod]\n78 -> 79 [label="0000000000000000000000000000000000000000000000000000000000000001", fontcolor=antiquewhite]\n80 [label="PUSH2", style=filled, color=antiquewhite]\n81 [label="JUMPI", style=filled, color=burlywood1]\n79 -> 81 [label="0000000000000000000000000000000000000000000000000000000000000000", fontcolor=antiquewhite]\n80 -> 81 [label="000000000000000000000000000000000000000000000000000000000000013d", fontcolor=antiquewhite]\n82 [label="PUSH1", style=filled, color=antiquewhite]\n83 [label="JUMP", style=filled, color=burlywood1]\n82 -> 83 [label="0000000000000000000000000000000000000000000000000000000000000002", fontcolor=antiquewhite]\n84 [label="JUMP", style=filled, color=burlywood1]\n}\n\n\n\n\n\n' ]```

Can someone please tell me what I need to do to get the viz.js function to accept this string? It accepts strings in the form of result = Viz("digraph { a -> b; }"); as per https://www.npmjs.com/package/viz.js

Thanks

答:
i think here is error:-

```<code>r=r.concat(<%- graph%>;
</code>```

you need to make it :-

```<code>r=r.concat(<%- graph%>);
</code>```

check in your code.

Title: Javascript EJS string literal

Body:
I am trying to pull a graphviz format string from my database and pass to a javascript function on my browser front end. I am using NodeJS and EJS as the view engine. The following code is on my index.ejs to take the array of graph formats, graph_format and send to the viz.js function:

However, I get a "SyntaxError: missing ) after argument list[Learn More]  graphviz:206:24" error in the console of my browser and the lines "
      console.log("converting ejs to javascrpt")" and
      "console.log("now printing javascript variable 1"+jscgraph[1])" do not run.

When I go to the browser debugger at line 206 as per error message, I see the following:

Body:
i think here is error:-

r=r.concat(<%- graph%>;

you need to make it :-

r=r.concat(<%- graph%>);

check in your code.


答:
Your template outputs some invalid JavaScript syntax:

```<code>digraph{
}
</code>```

You need to output r.concat("digraph{ }").

You could wrap your output in double quotes:

```<code>r=r.concat('"' + <%- graph%> + '"');
</code>```

But this will fail because graph contains a new line character. JavaScript strings literals with single or double quotes don't allow that.

If you don't need to support older browsers you could use backticks instead:

```<code>r=r.concat('`' + <%- graph%> + '`');
</code>```

This is a "template literal" string, which can have multi-line contents.

It works in all modern browsers, but not any version of Internet Explorer. See browser compatibility to decide if you'll be able to use it.

If you do need to support older browsers, you'll need to remove any newlines from graph. If it's a string:

```<code>var cleanGraph = graph.replace(/\n/g, " ")
r=r.concat('"' + <%- cleanGraph%> + '"')
</code>```

Title: Javascript EJS string literal

Body:
Your template outputs some invalid JavaScript syntax:

digraph{
}

You need to output r.concat("digraph{ }").

You could wrap your output in double quotes:

r=r.concat('"' + <%- graph%> + '"');

But this will fail because graph contains a new line character. JavaScript strings literals with single or double quotes don't allow that.

If you don't need to support older browsers you could use backticks instead:

r=r.concat('`' + <%- graph%> + '`');

This is a "template literal" string, which can have multi-line contents.

It works in all modern browsers, but not any version of Internet Explorer. See browser compatibility to decide if you'll be able to use it.

If you do need to support older browsers, you'll need to remove any newlines from graph. If it's a string:

var cleanGraph = graph.replace(/\n/g, " ")
r=r.concat('"' + <%- cleanGraph%> + '"')


问:
How to make button's "pushed" effect?
I have 3 buttons that represents 3 states. I'd like when I push some of them that button stays in visual "push" state and other 2 are in normal non-pushed state.

Here's the code I use:

if (itemType === 'default') {
  document.getElementById("defaultMode").classList.remove('non-pushed');
  document.getElementById("defaultMode").classList.add('pushed');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pushed {
  border-style: inset;
}

.non-pushed {
  border-style: solid;
}</code>```

<button id="defaultMode" class="non-pushed" onclick="setMode('link', 'default');">Default</button>
<button id="orthoMode" onclick="setMode('link', 'ortho');">Ortho</button>
<button id="cornerMode" onclick="setMode('link', 'corner');">Corner</button>```

But, it's not working.

答:
This one way of how you can do what you want

When you click on a button you remove the class pushed from all buttons and then you add that class to the clicked button.

function setMode(e, itemType) {

  var els = document.getElementsByClassName("pushed");

  Array.prototype.forEach.call(els, function(el) {
    el.classList.remove('pushed');
  });

  document.getElementById(itemType).classList.add('pushed');

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pushed {
  border-style: inset;
}

button {
  outline: none;
}</code>```

<button id="defaultMode" onclick="setMode('link', 'defaultMode');">Default</button>
<button id="orthoMode" onclick="setMode('link', 'orthoMode');">Ortho</button>
<button id="cornerMode" onclick="setMode('link', 'cornerMode');">Corner</button>```

Title: How to make button's "pushed" effect?

Body:
I have 3 buttons that represents 3 states. I'd like when I push some of them that button stays in visual "push" state and other 2 are in normal non-pushed state.

Here's the code I use:

if (itemType === 'default') {
  document.getElementById("defaultMode").classList.remove('non-pushed');
  document.getElementById("defaultMode").classList.add('pushed');
}

.pushed {
  border-style: inset;
}

.non-pushed {
  border-style: solid;
}

<button id="defaultMode" class="non-pushed" onclick="setMode('link', 'default');">Default</button>
<button id="orthoMode" onclick="setMode('link', 'ortho');">Ortho</button>
<button id="cornerMode" onclick="setMode('link', 'corner');">Corner</button>

But, it's not working.

Body:
This one way of how you can do what you want

When you click on a button you remove the class pushed from all buttons and then you add that class to the clicked button.

function setMode(e, itemType) {

  var els = document.getElementsByClassName("pushed");

  Array.prototype.forEach.call(els, function(el) {
    el.classList.remove('pushed');
  });

  document.getElementById(itemType).classList.add('pushed');

}

.pushed {
  border-style: inset;
}

button {
  outline: none;
}

<button id="defaultMode" onclick="setMode('link', 'defaultMode');">Default</button>
<button id="orthoMode" onclick="setMode('link', 'orthoMode');">Ortho</button>
<button id="cornerMode" onclick="setMode('link', 'cornerMode');">Corner</button>


答:
If you want to convert between UTF8 string and UTF16 wstring on Windows, you can use thin wrappers around WideCharToMultiByte and MultiByteToWideChar WIN32 API functions:</p>

```<code>std::string wstring_to_string(const std::wstring& in)
{
    int len = WideCharToMultiByte(CP_UTF8, 0, in.c_str(), -1, 0, 0, 0, 0);
    std::vector<char> buf(len);

    WideCharToMultiByte(CP_UTF8, 0, in.c_str(), -1, &buf[0], len, 0, 0);
    return std::string(buf.begin(), buf.end());
}

std::wstring string_to_wstring(const std::string& in)
{
    int len = MultiByteToWideChar(CP_UTF8, 0, in.c_str(), -1, 0, 0);
    std::vector<wchar_t> buf(len);

    MultiByteToWideChar(CP_UTF8, 0, in.c_str(), -1, &buf[0], len);
    return std::wstring(buf.begin(), buf.end());
}
</code>```

Title: Universal library for C++ strings

Body:
Please recommend me universal library for C++ strings. I want to manipulate ascii text and unicode text in one build without making two versions of builds for std::string/char and for std::wstring/wchar; Also I want to convert them to each other (where it is possible);

Thank you very much!!!

Body:
If you want to convert between UTF8 string and UTF16 wstring on Windows, you can use thin wrappers around WideCharToMultiByte and MultiByteToWideChar WIN32 API functions:

std::string wstring_to_string(const std::wstring& in)
{
    int len = WideCharToMultiByte(CP_UTF8, 0, in.c_str(), -1, 0, 0, 0, 0);
    std::vector<char> buf(len);

    WideCharToMultiByte(CP_UTF8, 0, in.c_str(), -1, &buf[0], len, 0, 0);
    return std::string(buf.begin(), buf.end());
}

std::wstring string_to_wstring(const std::string& in)
{
    int len = MultiByteToWideChar(CP_UTF8, 0, in.c_str(), -1, 0, 0);
    std::vector<wchar_t> buf(len);

    MultiByteToWideChar(CP_UTF8, 0, in.c_str(), -1, &buf[0], len);
    return std::wstring(buf.begin(), buf.end());
}


问:
Add css to 1 page using scss and ReactJS and redux
I am using ReactJS with redux.
I using scss.
lets say my path is:
http://localhost:3000/login
I need to add to this page:
html:{ overflow:hidden}

and on other pages i want to remove this attribute.

Anyone have a clue?

答:
I don't know how is your project architecture, but you can add a class (className) into your HTML tag in differently ways.

If you want, you can also use your redux state.
You check if you are in X page, if it's ok, pass a boolean at true and if it's true, put your css.

I prefer the first solution.


问:
Unlist column in data frame with listed
I have a list with multiple levels that I would like to the data level into a data frame, where the variable chr is collapsed into single strings.

```<code> myList <- list(total_reach = list(4),
                   data = list(list(reach = 2,
                              chr = list("A", "B", "C"),
                              nr = 3,
                              company = "Company A"),
                   list(reach = 2,
                        chr = list("A", "B", "C"),
                        nr = 3,
                        company = "Company B")))
</code>```

I would like to transform this into a data frame that looks like this:

```<code>  reach     chr nr   company
1     2 A, B, C  3 Company A
2     2 A, B, C  3 Company B
</code>```

Using dplyr and data.table I've come this far.

```<code>library(data.table)
library(dplyr)
df <- data.frame(rbindlist(myList[2])) %>% t() %>% as.data.frame()

colnames(df) <- names(myList$data[[1]])
rownames(df) <- c(1:nrow(df))

df$chr <- as.character(df$chr)

df <- df %>%
  mutate_all(funs(unlist(.recursive = F, use.names = F)))
</code>```

However, chr column contains strings with "list()" wrapped around it.

```<code>  reach                 chr nr   company
1     2 list("A", "B", "C")  3 Company A
2     2 list("A", "B", "C")  3 Company B
</code>```

A) Is there a better way to unlist this kind of list and turn it into a data frame?

B) How do I collapse the lists in chr to strings or factors?

答:
I'm using rbind to put everything together, then I reformat the chr column with sapply

```<code>library(magrittr)
myList$data %>%
  do.call(rbind,.) %>%
  transform(chr %<>% sapply(paste,collapse=","))
#   reach   chr nr   company
# 1     2 A,B,C  3 Company A
# 2     2 A,B,C  3 Company B
</code>```

EDIT a few months later:

One line longer but a more idiomatic tidyverse variation:

```<code>library(tidyverse)
myList$data %>%
  map_df(as_tibble)    %>%
  group_by(reach,nr,company) %>%
  summarize_at("chr",paste,collapse=",")
</code>```

Title: Unlist column in data frame with listed

Body:
I have a list with multiple levels that I would like to the data level into a data frame, where the variable chr is collapsed into single strings.

 myList <- list(total_reach = list(4),
                   data = list(list(reach = 2,
                              chr = list("A", "B", "C"),
                              nr = 3,
                              company = "Company A"),
                   list(reach = 2,
                        chr = list("A", "B", "C"),
                        nr = 3,
                        company = "Company B")))

I would like to transform this into a data frame that looks like this:

  reach     chr nr   company
1     2 A, B, C  3 Company A
2     2 A, B, C  3 Company B

Using dplyr and data.table I've come this far.

library(data.table)
library(dplyr)
df <- data.frame(rbindlist(myList[2])) %>% t() %>% as.data.frame()

colnames(df) <- names(myList$data[[1]])
rownames(df) <- c(1:nrow(df))

df$chr <- as.character(df$chr)

df <- df %>%
  mutate_all(funs(unlist(.recursive = F, use.names = F)))

However, chr column contains strings with "list()" wrapped around it.

  reach                 chr nr   company
1     2 list("A", "B", "C")  3 Company A
2     2 list("A", "B", "C")  3 Company B

A) Is there a better way to unlist this kind of list and turn it into a data frame?

B) How do I collapse the lists in chr to strings or factors?

Body:
I'm using rbind to put everything together, then I reformat the chr column with sapply

library(magrittr)
myList$data %>%
  do.call(rbind,.) %>%
  transform(chr %<>% sapply(paste,collapse=","))
#   reach   chr nr   company
# 1     2 A,B,C  3 Company A
# 2     2 A,B,C  3 Company B

EDIT a few months later:

One line longer but a more idiomatic tidyverse variation:

library(tidyverse)
myList$data %>%
  map_df(as_tibble)    %>%
  group_by(reach,nr,company) %>%
  summarize_at("chr",paste,collapse=",")


问:
One-time database shrinking with SQL Server
How can we decrease the DB files size when removing lots of outdated data?

We have an application that has data collected over many years. Now one customer has left the project and theirs data can be dropped. This customer alone stands for 75% of the data in the database.

The disk usage is very high, and running in a virtualized cloud service where the pricing is VERY high. Changing to another provider is not an option, and buying more disk is not popular since we have in practice 75% less data in use.

In my opinion it would be great if we could get rid of this customer data, shrink the files and be safe for years to come for reaching this disk usage level again.

I have seen many threads warning for performance decrease due to index fragmentation.

So, how can we drop this customer's data (stored in the same tables that other customers use, indexed on customer id among other things) without causing any considerable drawbacks?

Is these steps the way to go, or are there better ways?

Delete this customer's data

DBCC SHRINKDATABASE (database,30)

ALTER DATABASE database SET RECOVERY SIMPLE

DBCC SHRINKFILE (database_Log, 50)

ALTER DATABASE database SET RECOVERY FULL

DBCC INDEXDEFRAG

答:
Only step 1 is required. Deleting data will free space within the database which can be reused for new data. You should also execute ALTER INDEX...REORGANIZE or ALTER INDEX...REORGANIZE 1 to compact indexes and distribute free space evenly throughout the indexes.

EDIT:

Since your cloud provider charges for disk space used, you'll need to shrink files to release space back to the OS and avoid incurring charges. Below are some tweaks to the steps you proposed, which can be customized according to your RPO requirements.

ALTER DATABASE ... SET RECOVERY SIMPLE (or BULK_LOGGED)

Delete this customer's data

DBCC SHRINKFILE (database_Data, 30) --repeat for each file to the desired size

DBCC SHRINKFILE (database_Log, 50)

REORGANIZE (or REBUILD) indexes

ALTER DATABASE ... SET RECOVERY FULL

BACKUP DATABASE ...


问:
How to install trusted CA certificate on Android device?
I have created my own CA certificate and now I want to install it on my Android Froyo device (HTC Desire Z), so that the device trusts my certificate.

Android stores CA certificates in its Java keystore in /system/etc/security/cacerts.bks. I copied the file to my computer, added my certificate using portecle 1.5 and pushed it back to the device.

Now, Android does not seem to reload the file automatically. I have read in several blog posts that I need to restart the device. Doing so results in the file being overwritten with the original one again.

My next try was to install the certificate from SD card by copying it and using the according option from the settings menu. The device tells me that the certificate has been installed, but apparently it does not trust the certificate. Moreover, when I try to copy the keystore to my computer, I still find the original stock cacerts.bks.

So, what is the right way to install my own root CA certificate on an Android 2.2 device as a trusted certificate? Is there a way to do it programmatically?

答:
If you need your certificate for HTTPS connections you can add the .bks file as a raw resource to your application and extend DefaultHttpConnection so your certificates are used for HTTPS connections.</p>

```<code>public class MyHttpClient extends DefaultHttpClient {

    private Resources _resources;

    public MyHttpClient(Resources resources) {
        _resources = resources;
    }

    @Override
    protected ClientConnectionManager createClientConnectionManager() {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory
            .getSocketFactory(), 80));
        if (_resources != null) {
            registry.register(new Scheme("https", newSslSocketFactory(), 443));
        } else {
            registry.register(new Scheme("https", SSLSocketFactory
                .getSocketFactory(), 443));
        }
        return new SingleClientConnManager(getParams(), registry);
    }

    private SSLSocketFactory newSslSocketFactory() {
        try {
            KeyStore trusted = KeyStore.getInstance("BKS");
            InputStream in = _resources.openRawResource(R.raw.mystore);
            try {
                trusted.load(in, "pwd".toCharArray());
            } finally {
                in.close();
            }
            return new SSLSocketFactory(trusted);
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
}
</code>```

Body:
If you need your certificate for HTTPS connections you can add the .bks file as a raw resource to your application and extend DefaultHttpConnection so your certificates are used for HTTPS connections.

public class MyHttpClient extends DefaultHttpClient {

    private Resources _resources;

    public MyHttpClient(Resources resources) {
        _resources = resources;
    }

    @Override
    protected ClientConnectionManager createClientConnectionManager() {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory
            .getSocketFactory(), 80));
        if (_resources != null) {
            registry.register(new Scheme("https", newSslSocketFactory(), 443));
        } else {
            registry.register(new Scheme("https", SSLSocketFactory
                .getSocketFactory(), 443));
        }
        return new SingleClientConnManager(getParams(), registry);
    }

    private SSLSocketFactory newSslSocketFactory() {
        try {
            KeyStore trusted = KeyStore.getInstance("BKS");
            InputStream in = _resources.openRawResource(R.raw.mystore);
            try {
                trusted.load(in, "pwd".toCharArray());
            } finally {
                in.close();
            }
            return new SSLSocketFactory(trusted);
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
}


问:
regex to match the string more than one time
I have a string as follows

```<code>"SampleFilter('x','y','z') AND TestFilter('a','b','c') AND SampleFilter('d','e','f')"
</code>```

Here I want a regex to match the occurrence of SampleFilter so i want output to return all the occurrence of SampleFilter

I have tried below pattern

```<code>".*SampleFilter\\((.*?)\\).*"
</code>```

But I have captured group 1 and it is returning only last occurrence

答:
You can't retrieve your data with a simple match; you need to iterate:</p>

```<code>    String text = "SampleFilter('x','y','z') AND TestFilter('a','b','c')"
            + " AND SampleFilter('d','e','f')";
    Pattern re = Pattern.compile("SampleFilter\\((.*?)\\)");
    Matcher matcher = re.matcher(text);
    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }
</code>```

Body:
I have a string as follows

"SampleFilter('x','y','z') AND TestFilter('a','b','c') AND SampleFilter('d','e','f')"

Here I want a regex to match the occurrence of SampleFilter so i want output to return all the occurrence of SampleFilter

I have tried below pattern

".*SampleFilter\\((.*?)\\).*"

But I have captured group 1 and it is returning only last occurrence

Body:
You can't retrieve your data with a simple match; you need to iterate:

    String text = "SampleFilter('x','y','z') AND TestFilter('a','b','c')"
            + " AND SampleFilter('d','e','f')";
    Pattern re = Pattern.compile("SampleFilter\\((.*?)\\)");
    Matcher matcher = re.matcher(text);
    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }


问:
JavaScript replace all ignoring case sensitivity
I am trying to replace all the occurences of a value in a string and with another value

what I have so far is

var result = "Cooker Works"
var searchterm = "cooker wor";

searchterm.split(" ").forEach(function (item) {
   result = result.replace(new RegExp(item, 'g'), "" + item + "");
});

console.log(result)```
</div>
</div>
</p>

<p>The result I am after should look like</p>

```result = "Cooker Wors";
```

I am having problems handling the case, Is there any way I can ignore this and still get the result I am after

答:
You will get the result you want using capture groups and the i (ignoreCase) modifier. You can reference the capture group with $1.

var result = "Cooker Works";
var searchterm = "cooker wor";

searchterm.split(" ").forEach(function(item) {
    result = result.replace(new RegExp(`(${item})`, 'ig'), "$1");
});

console.log(result)```

See MDN for more details:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter

Body:
I am trying to replace all the occurences of a value in a string and with another value

what I have so far is

var result = "Cooker Works"
var searchterm = "cooker wor";

searchterm.split(" ").forEach(function (item) {
   result = result.replace(new RegExp(item, 'g'), "" + item + "");
});

console.log(result)

The result I am after should look like

result = "Cooker Wors";

I am having problems handling the case, Is there any way I can ignore this and still get the result I am after

Body:
You will get the result you want using capture groups and the i (ignoreCase) modifier. You can reference the capture group with $1.

var result = "Cooker Works";
var searchterm = "cooker wor";

searchterm.split(" ").forEach(function(item) {
    result = result.replace(new RegExp(`(${item})`, 'ig'), "<strong>$1</strong>");
});

console.log(result)

See MDN for more details:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter