问:
How to insert radio button value which is have multiple radio name in codeigniter?
I'm trying to making online quiz with codeigniter where there is a dynamic quiz with some subject. User can add the question and the multiple choice answer in each question. How can i get the value of each answer in each multiple choice answer on every question?

```<code><?php echo form_open_multipart('c_kuis/addKuisAnswer'); ?>
       <?php foreach($soalKuis as $row){?>
            <?php $jawab_array = array($row->pil_a,$row->pil_b,$row->pil_c,$row->pil_d);
            ?>
            <p><?=$row->soal?></p>
            <input type="radio" name="jawaban<?=$row->id_soal?>" value="A">A.<?=$jawab_array[0]?></input><br>
            <input type="radio" name="jawaban<?=$row->id_soal?>" value="B">B.<?=$jawab_array[1]?></input><br>
            <input type="radio" name="jawaban<?=$row->id_soal?>" value="C">C.<?=$jawab_array[2]?></input><br>
            <input type="radio" name="jawaban<?=$row->id_soal?>" value="D">D.<?=$jawab_array[3]?></input><br>
            <input type="hidden" name="id_soal_kuis" value="<?=$row->id_soal?>"></input>
            <br><br>
       <?php } ?>
        <button class="btn btn-primary" type="submit">Submit</button>
      <?php form_close(); ?>
</code>```

and this is the code looks like when i try to inspect :

```<code>            <input type="radio" name="jawaban1" value="A">A.Hamster</input><br>
            <input type="radio" name="jawaban1" value="B">B.Tiger</input><br>
            <input type="radio" name="jawaban1" value="C">C.Shark</input><br>
            <input type="radio" name="jawaban1" value="D">D.Lion</input><br>
            <br><br>

            <input type="radio" name="jawaban2" value="A">A.was</input><br>
            <input type="radio" name="jawaban2" value="B">B.have</input><br>
            <input type="radio" name="jawaban2" value="C">C.am</input><br>
            <input type="radio" name="jawaban2" value="D">D.is</input><br>
            <br><br>
                <button class="btn btn-primary" type="submit">Submit</button>
</code>```

Here is my Controller looks like :

```<code>public function addKuisAnswer(){
    if($this->session->userdata('data_user')->level != 1){
        redirect('/c_user/login');
    }
    $id_soal_kuis = $_POST['id_soal_kuis'];
    $id_user = $this->session->userdata('data_user')->id_user;
    $answer = $_POST['jawaban']; //The Problem's here... I should put jawaban with id_soal. Because the answer named 'jawaban1','jawaban2' etc it will follow the id_soal. How can i insert it?
    $this->load->model('m_kuis');
    $this->m_kuis->createAnswerKuis($id_soal_kuis, $id_user, $answer);
     echo " <script>
                    alert('Jawaban Tugas Tersimpan!');
                    history.go(-2);
                    </script>";

}
</code>```

Here is my model :

```<code>public function createAnswerKuis($id_soal_kuis, $id_user, $answer){
    $data = array(
        'id_soal_kuis'=>$id_soal_kuis,
        'id_user' => $id_user,
        'jawaban_kuis' => $answer
    );
    $this->db->set('tgl_jawab', 'NOW()', FALSE);
    $this->db->insert('jawab_kuis', $data);
}
</code>```

I want the table looks like this :This is the picture of database table i made.I want to insert the data like this.

The problem is in Controller. How can my Controller post the value of radio button name="jawaban<?=$row->id_soal?>"in database?

答:
i hope this little change will helps you

```<code> public function addKuisAnswer(){
        if($this->session->userdata('data_user')->level != 1){
            redirect('/c_user/login');
        }
        $id_soal_kuis = $_POST['id_soal_kuis'];
        $id_user = $this->session->userdata('data_user')->id_user;

        $this->load->model('m_kuis');
        $i=1;
    while(isset($_POST['jawaban'.$i]))
    {
         $answer = $_POST['jawaban'.$i];
//         var_dump($answer);
 $this->m_kuis->createAnswerKuis($id_soal_kuis, $id_user, $answer);
         $i++;
    }

         echo " <script>
                        alert('Jawaban Tugas Tersimpan!');
                        history.go(-2);
                        </script>";

    }
</code>```

you can change radio button name in sequential order(because there is no need of id appending in radio button)

```<code> <?php
$i=1;
    foreach($soalKuis as $row){?>
            <?php $jawab_array = array($row->pil_a,$row->pil_b,$row->pil_c,$row->pil_d);
            ?>
            <p><?=$row->soal?>
    <input type="hidden" value=<?php echo $row->id_soal?> name='id_soal'<?= $i ?>/></p>
            <input type="radio" name="jawaban<?=$i?>" value="A">A.<?=$jawab_array[0]?></input><br>
            <input type="radio" name="jawaban<?=$i?>" value="B">B.<?=$jawab_array[1]?></input><br>
            <input type="radio" name="jawaban<?=$i?>" value="C">C.<?=$jawab_array[2]?></input><br>
            <input type="radio" name="jawaban<?=$i?>" value="D">D.<?=$jawab_array[3]?></input><br>
            <input type="hidden" name="id_soal_kuis" value="<?=$row->id_soal?>"></input>
            <br><br>
       <?php $i++;} ?>
</code>```

Body:
I'm trying to making online quiz with codeigniter where there is a dynamic quiz with some subject. User can add the question and the multiple choice answer in each question. How can i get the value of each answer in each multiple choice answer on every question?

<?php echo form_open_multipart('c_kuis/addKuisAnswer'); ?>
       <?php foreach($soalKuis as $row){?>
            <?php $jawab_array = array($row->pil_a,$row->pil_b,$row->pil_c,$row->pil_d);
            ?>

<?=$row->soal?>

            <input type="radio" name="jawaban<?=$row->id_soal?>" value="A">A.<?=$jawab_array[0]?></input>

            <input type="radio" name="jawaban<?=$row->id_soal?>" value="B">B.<?=$jawab_array[1]?></input>

            <input type="radio" name="jawaban<?=$row->id_soal?>" value="C">C.<?=$jawab_array[2]?></input>

            <input type="radio" name="jawaban<?=$row->id_soal?>" value="D">D.<?=$jawab_array[3]?></input>

            <input type="hidden" name="id_soal_kuis" value="<?=$row->id_soal?>"></input>

       <?php } ?>
        <button class="btn btn-primary" type="submit">Submit</button>
      <?php form_close(); ?>

and this is the code looks like when i try to inspect :

            <input type="radio" name="jawaban1" value="A">A.Hamster</input>

            <input type="radio" name="jawaban1" value="B">B.Tiger</input>

            <input type="radio" name="jawaban1" value="C">C.Shark</input>

            <input type="radio" name="jawaban1" value="D">D.Lion</input>

            <input type="radio" name="jawaban2" value="A">A.was</input>

            <input type="radio" name="jawaban2" value="B">B.have</input>

            <input type="radio" name="jawaban2" value="C">C.am</input>

            <input type="radio" name="jawaban2" value="D">D.is</input>

                <button class="btn btn-primary" type="submit">Submit</button>

Here is my Controller looks like :

public function addKuisAnswer(){
    if($this->session->userdata('data_user')->level != 1){
        redirect('/c_user/login');
    }
    $id_soal_kuis = $_POST['id_soal_kuis'];
    $id_user = $this->session->userdata('data_user')->id_user;
    $answer = $_POST['jawaban']; //The Problem's here... I should put jawaban with id_soal. Because the answer named 'jawaban1','jawaban2' etc it will follow the id_soal. How can i insert it?
    $this->load->model('m_kuis');
    $this->m_kuis->createAnswerKuis($id_soal_kuis, $id_user, $answer);
     echo " ";

}

Here is my model :

public function createAnswerKuis($id_soal_kuis, $id_user, $answer){
    $data = array(
        'id_soal_kuis'=>$id_soal_kuis,
        'id_user' => $id_user,
        'jawaban_kuis' => $answer
    );
    $this->db->set('tgl_jawab', 'NOW()', FALSE);
    $this->db->insert('jawab_kuis', $data);
}

I want the table looks like this :This is the picture of database table i made.I want to insert the data like this.

The problem is in Controller. How can my Controller post the value of radio button name="jawaban<?=$row->id_soal?>"in database?

Body:
i hope this little change will helps you

 public function addKuisAnswer(){
        if($this->session->userdata('data_user')->level != 1){
            redirect('/c_user/login');
        }
        $id_soal_kuis = $_POST['id_soal_kuis'];
        $id_user = $this->session->userdata('data_user')->id_user;

        $this->load->model('m_kuis');
        $i=1;
    while(isset($_POST['jawaban'.$i]))
    {
         $answer = $_POST['jawaban'.$i];
//         var_dump($answer);
 $this->m_kuis->createAnswerKuis($id_soal_kuis, $id_user, $answer);
         $i++;
    }

         echo " <script>
                        alert('Jawaban Tugas Tersimpan!');
                        history.go(-2);
                        </script>";

    }

you can change radio button name in sequential order(because there is no need of id appending in radio button)

 <?php
$i=1;
    foreach($soalKuis as $row){?>
            <?php $jawab_array = array($row->pil_a,$row->pil_b,$row->pil_c,$row->pil_d);
            ?>
            <p><?=$row->soal?>
    <input type="hidden" value=<?php echo $row->id_soal?> name='id_soal'<?= $i ?>/></p>
            <input type="radio" name="jawaban<?=$i?>" value="A">A.<?=$jawab_array[0]?></input><br>
            <input type="radio" name="jawaban<?=$i?>" value="B">B.<?=$jawab_array[1]?></input><br>
            <input type="radio" name="jawaban<?=$i?>" value="C">C.<?=$jawab_array[2]?></input><br>
            <input type="radio" name="jawaban<?=$i?>" value="D">D.<?=$jawab_array[3]?></input><br>
            <input type="hidden" name="id_soal_kuis" value="<?=$row->id_soal?>"></input>
            <br><br>
       <?php $i++;} ?>


来源: stackexchange

问:
How to get values of two columns only when both column values are present using bash script
1

2

3   5

4   6

9

I have two columns, if 2nd column contain no values then skip the row  else I want result like two column values only  when both column values are present

sample output

3 5

4 6

答:
If a solution using grep is acceptable:

```<code>grep -v " " input
grep -E '[[:digit:]]+ [[:digit:]]+' input
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If a solution using grep is acceptable:

grep -v " " input
grep -E '[[:digit:]]+ [[:digit:]]+' input


问:
Create my own local and remote branch and pull from a remote branch only once
So in our repository we currently have the following branches:

```<code>Master
Dev1
</code>```

I would like to create my own local and remote branch called Dev2 and would like it to initially pull from the remote Dev1 instead of Master (since Dev1 is the most up-to-date and hasn't merged into the Master branch yet). When I then push to my remote branch I want to be pushin to Dev2 which should be a completely detached and independent branch from Dev1.

How could I do this? I am new to using Git, if you couldn't tell :)

答:
You can use below commands to meet your requirement:</p>

```<code>git checkout origin/Dev1
git checkout --orphan Dev2
# make some changes and commit them if have
git push -u origin Dev2
</code>```

Body:
So in our repository we currently have the following branches:

Master
Dev1

I would like to create my own local and remote branch called Dev2 and would like it to initially pull from the remote Dev1 instead of Master (since Dev1 is the most up-to-date and hasn't merged into the Master branch yet). When I then push to my remote branch I want to be pushin to Dev2 which should be a completely detached and independent branch from Dev1.

How could I do this? I am new to using Git, if you couldn't tell :)

Body:
You can use below commands to meet your requirement:

git checkout origin/Dev1
git checkout --orphan Dev2
# make some changes and commit them if have
git push -u origin Dev2


问:
How can JavaScript check if element is a specific color?
I have a piece of code that needs to check if an element matches a color, and if it does, change it. Otherwise it is set to a default color.

var caps = $("#caps");
if (caps.css('background-color') == "rgb(225, 0, 0)") {
  $('body').on('click', '#caps', function(event) {
    $('.clight').css({
      'background-color': 'red',
      'box-shadow': '0px 0px 20px yellow'
    });
    $('#l2').css({
      'background-color': 'red',
      'box-shadow': '0px 0px 20px yellow'
    });
    event.preventDefault();
  } else {
    $('.clight').css('background-color', 'white');
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.caps {
  /* Caps button CSS */
  width: 70px;
  font-size: 12px;
  line-height: 12px;
}

.clight {
  /* Caps button light CSS */
  width: 10px;
  height: 10px;
  top: 10px;
  margin-left: 1px;
  background-color: grey;
  position: relative;
  border-radius: 50%;
}</code>```

 Caps
Lock

```

It doesn't work however. All I am trying to do is to switch on the caps lock light when you click, and switch it back of if you click it again, almost like a toggle.

答:
Note: Just noticed that you have some javascript error in your code as the closing of your click event is getting closed at wrong place.

Well there is no concrete method to do such things as different browser have different settings for color codes some uses rgb() some hex etc.

I would rather suggest you to create some classes and look for them instead like:

```<code>.bg-red{ background-color:red; }

$('body').on('click', '#caps', function(event){
  if ($(this).hasClass('bg-red')) {
      $('.clight, #l2').css({
         'background-color' : 'red',
         'box-shadow' :  '0px 0px 20px yellow'
      });
      event.preventDefault();
  } else {
      $('.clight').css('background-color' , 'white');
  }
});
</code>```

Body:
I have a piece of code that needs to check if an element matches a color, and if it does, change it. Otherwise it is set to a default color.

var caps = $("#caps");
if (caps.css('background-color') == "rgb(225, 0, 0)") {
  $('body').on('click', '#caps', function(event) {
    $('.clight').css({
      'background-color': 'red',
      'box-shadow': '0px 0px 20px yellow'
    });
    $('#l2').css({
      'background-color': 'red',
      'box-shadow': '0px 0px 20px yellow'
    });
    event.preventDefault();
  } else {
    $('.clight').css('background-color', 'white');
  });

.caps {
  /* Caps button CSS */
  width: 70px;
  font-size: 12px;
  line-height: 12px;
}

.clight {
  /* Caps button light CSS */
  width: 10px;
  height: 10px;
  top: 10px;
  margin-left: 1px;
  background-color: grey;
  position: relative;
  border-radius: 50%;
}

 Caps
Lock

It doesn't work however. All I am trying to do is to switch on the caps lock light when you click, and switch it back of if you click it again, almost like a toggle.

Body:
Note: Just noticed that you have some javascript error in your code as the closing of your click event is getting closed at wrong place.

Well there is no concrete method to do such things as different browser have different settings for color codes some uses rgb() some hex etc.

I would rather suggest you to create some classes and look for them instead like:

.bg-red{ background-color:red; }

$('body').on('click', '#caps', function(event){
  if ($(this).hasClass('bg-red')) {
      $('.clight, #l2').css({
         'background-color' : 'red',
         'box-shadow' :  '0px 0px 20px yellow'
      });
      event.preventDefault();
  } else {
      $('.clight').css('background-color' , 'white');
  }
});


问:
magento top link changes
I am new to Magento. I have downloaded a theme in Magento and trying to change the top links. I couldn't track the files. How do i change the toplinks in Magento theme.

答:
you can modify it by edit reference name="top.links" block in
  following .xml files

app/design/frontend/Your_theme/default/layout/checkout.xml

app/design/frontend/Your_theme/default/layout/customer.xml

Check this following post

For information please visit this URL :-https://www.templatemonster.com/help/magento-how-to-edit-header-links-2.html#gref

Title: magento top link changes


问:
body on load function not getting called if the script tag is end of the body
the code is somewhat like

```<code><body onload="testFunc();">
    <div></div>

    <script type="text/javascript" src="/js/test.js"></script>
</body>
</code>```

and the testFunc is inside test.js
and sometimes its not getting called

答:
The onload attribute fires when an object has been loaded.

onload is most often used within the  element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

<!DOCTYPE html>

body loaded!

```

Body:
the code is somewhat like

and the testFunc is inside test.js
and sometimes its not getting called

Body:
The onload attribute fires when an object has been loaded.

onload is most often used within the  element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
    alert("body loaded");
}
</script>
</head>

<body onload="myFunction()">
<h1>body loaded!</h1>
</body>

</html>


问:
Unable to set Assignee to second user task in activiti in spring boot
I am new to activiti in spring boot. I have created the process i.e

Start---> User Task---> User Task---->End.

Now I have to assigned the dynamically Assignee to both user task. I have sent the Assignee to first user task by using this:

```<code>ProcessInstance process = runtimeService.startProcessInstanceByKey('process', variables);

Task task = taskService.createTaskQuery().processInstanceId(process.getId()).singleResult();
task.setAssignee("charnjeet");
taskService.saveTask(task);
</code>```

Now when I have completed the task from http://localhost:8080/activiti-explorer/ui/ then Listener, Service task expression is working. Can any one help me here. I want to assigned both user task to "charnjeet".

答:
These are some ways to save your time, to be used in XML as  activiti:assignee="${assingee}":

1.) Create a start-form to select the ${assignee}(a text field) who is going to get assigned for both of the task.

2.) Create an execution listener at end of each task to set ${assignee} for next task.

3.) As explained by Mr. Arjun.

Body:
I am new to activiti in spring boot. I have created the process i.e

Start---> User Task---> User Task---->End.

Now I have to assigned the dynamically Assignee to both user task. I have sent the Assignee to first user task by using this:

ProcessInstance process = runtimeService.startProcessInstanceByKey('process', variables);

Task task = taskService.createTaskQuery().processInstanceId(process.getId()).singleResult();
task.setAssignee("charnjeet");
taskService.saveTask(task);

Now when I have completed the task from http://localhost:8080/activiti-explorer/ui/ then Listener, Service task expression is working. Can any one help me here. I want to assigned both user task to "charnjeet".


问:
Change side of the navigation pane in Outlook 2010
I have a question regarding Microsoft Outlook. One person in my team said that it is possible to change side of the navigation pane (pane including favourites, inbox, etc.) from left to right side.

Is it really possible? I checked the documentation and didn't find the answer.

Thank you for any response.

答: I've just received an official answer that it is not possible in Outlook 2010.</p>


问:
Exception: Required option not passed: access_token
I am getting this error while trying to login with Google in Codeigniter only at first attempt

```<code>Fatal error: Uncaught exception 'Exception' with message ' in ..../application/libraries/OAuth2/Token/Access.php on line 44
Exception: Required option not passed: access_token in ..../application/libraries/OAuth2/Token/Access.php on line 44
</code>```

答:
Try to change your access.php file and change __construct method. </p>

```<code>public function __construct(array $options = null)
{
    echo "```";
    $new_options = array();
    foreach($options as  $key => $value)
    {
         $new_options = json_decode($key,true);
    }

    if ( ! isset($new_options['access_token']))
    {
        throw new Exception('Required option not passed: access_token'.PHP_EOL.print_r($new_options, true));
    }

    // if ( ! isset($options['expires_in']) and ! isset($options['expires']))
    // {
    //  throw new Exception('We do not know when this access_token will expire');
    // }

    $this->access_token = $new_options['access_token'];

    // Some providers (not many) give the uid here, so lets take it
    isset($new_options['uid']) and $this->uid = $new_options['uid'];

    //Vkontakte uses user_id instead of uid
    isset($new_options['user_id']) and $this->uid = $new_options['user_id'];

    //Mailru uses x_mailru_vid instead of uid
    isset($new_options['x_mailru_vid']) and $this->uid = $new_options['x_mailru_vid'];

    // We need to know when the token expires, add num. seconds to current time
    isset($new_options['expires_in']) and $this->expires = time() + ((int) $new_options['expires_in']);

    // Facebook is just being a spec ignoring jerk
    isset($new_options['expires']) and $this->expires = time() + ((int) $new_options['expires']);

    // Grab a refresh token so we can update access tokens when they expires
    isset($new_options['refresh_token']) and $this->refresh_token = $new_options['refresh_token'];
}
</code>```

Body:
I am getting this error while trying to login with Google in Codeigniter only at first attempt

Fatal error: Uncaught exception 'Exception' with message ' in ..../application/libraries/OAuth2/Token/Access.php on line 44
Exception: Required option not passed: access_token in ..../application/libraries/OAuth2/Token/Access.php on line 44

Body:
Try to change your access.php file and change __construct method.

public function __construct(array $options = null)
{
    echo "<pre>";
    $new_options = array();
    foreach($options as  $key => $value)
    {
         $new_options = json_decode($key,true);
    }

    if ( ! isset($new_options['access_token']))
    {
        throw new Exception('Required option not passed: access_token'.PHP_EOL.print_r($new_options, true));
    }

    // if ( ! isset($options['expires_in']) and ! isset($options['expires']))
    // {
    //  throw new Exception('We do not know when this access_token will expire');
    // }

    $this->access_token = $new_options['access_token'];

    // Some providers (not many) give the uid here, so lets take it
    isset($new_options['uid']) and $this->uid = $new_options['uid'];

    //Vkontakte uses user_id instead of uid
    isset($new_options['user_id']) and $this->uid = $new_options['user_id'];

    //Mailru uses x_mailru_vid instead of uid
    isset($new_options['x_mailru_vid']) and $this->uid = $new_options['x_mailru_vid'];

    // We need to know when the token expires, add num. seconds to current time
    isset($new_options['expires_in']) and $this->expires = time() + ((int) $new_options['expires_in']);

    // Facebook is just being a spec ignoring jerk
    isset($new_options['expires']) and $this->expires = time() + ((int) $new_options['expires']);

    // Grab a refresh token so we can update access tokens when they expires
    isset($new_options['refresh_token']) and $this->refresh_token = $new_options['refresh_token'];
}


问:
PHP snippet always shows in the top of page in wordpress
I'm currently using a database search in wordpress wherein I show the results in the result page via snippets.
The problem is the results always get displayed in the top of page. I do understand php executes first before html, but is there a way to get the results displayed where I want?

Code:

```<code>Wordpress: [xyz-ips snippet="industry"]
</code>```

Php:

```<code>$com=$_GET['company'];
$sql2 = "SELECT count(1) i from data where sector= (SELECT sector from data where company like '$com%')";
$rows2 = $wpdb->get_results($sql2 );
echo ' '.$rows2[0]->i.' ';
</code>```

答:
Thanks to the intelligent community here, they are more curious to downvote than to help fellow mate.!
I discovered after much search that the php version caused this. I downgraded (from the current 5.6) to 5.5 and that solved the issue.
This might help someone who is searching for a similar answer.</p>

Body:
I'm currently using a database search in wordpress wherein I show the results in the result page via snippets.
The problem is the results always get displayed in the top of page. I do understand php executes first before html, but is there a way to get the results displayed where I want?

Code:

Wordpress: [xyz-ips snippet="industry"]

Php:

$com=$_GET['company'];
$sql2 = "SELECT count(1) i from data where sector= (SELECT sector from data where company like '$com%')";
$rows2 = $wpdb->get_results($sql2 );
echo ' '.$rows2[0]->i.' ';


问:
Hover button that shows text html/css
I'm learning HTML & CSS. Now I am trying to make a hover button that shows some text just like the tooltip feature makes. How can I make that happen from here:

```<code><title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=2">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
    /*TEST HERE*/
    .w3-button {width:800px;}
    .w3-button {height:800px;} `
</style>
<div class="w3-container">
    <h2>TITULO AQUI</h2>
    <p>
        <button class="w3-button w3-light-blue">Hover in here</button>
    </p>
</div>
/*<div id="button1"></div>*/
</code>```

答:
just use the title attribute</p>

```<code><button class="w3-button w3-light-blue" title="this is a title">Hover in here</button>
</code>```

Title: Hover button that shows text html/css

Body:
I'm learning HTML & CSS. Now I am trying to make a hover button that shows some text just like the tooltip feature makes. How can I make that happen from here:

<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=2">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

TITULO AQUI

        <button class="w3-button w3-light-blue">Hover in here</button>

/*

*/

Body:
just use the title attribute

<button class="w3-button w3-light-blue" title="this is a title">Hover in here</button>


问:
Data Movement SQL Server
In SQL Server 2008 R2, I have two tables Table_A & Table_B.

Table_A has 20 million records & Table_B is empty with same structure of Table_A. I want to move the records from Table_A to Table_B with condition (90 days previous records,  15 million records) without any performance issue. What would be the best solution to move the data?

Data has to be deleted from Table_A once it got moved to Table_B.

答:
Try to think in plain SQL:</p>

```<code>INSERT INTO target
    SELECT as_is_col1, as_is_col2,
    FROM source
    WHERE wanted_col BETWEEN 0 AND 200000000;
</code>```

Title: Data Movement SQL Server

Body:
Try to think in plain SQL:

INSERT INTO target
    SELECT as_is_col1, as_is_col2,
    FROM source
    WHERE wanted_col BETWEEN 0 AND 200000000;


问:
How do I disable END blocks in child processes?
I frequently use fork in programs that also have END { ... } blocks:

```<code>...
END { &some_cleanup_code }
...
my $pid = fork();
if (defined($pid) && $pid==0) {
    &run_child_code;
    exit 0;
}
</code>```

The child process executes the END {} block as it is exiting, but usually I don't want that to happen. Is there a way to prevent a child process from calling the END block at exit? Barring that, is there a way for a program to "know" that it is a child process, so I could say something like

```<code>END { unless (i_am_a_child_process()) { &some_cleanup_code } }
</code>```

?

答: I know this isn't very helpful to you, but I'll say it anyway: Don't use END blocks. There's usually a better way.</p>

ContentLicense: CC BY-SA 2.5

Body:
I frequently use fork in programs that also have END { ... } blocks:

...
END { &some_cleanup_code }
...
my $pid = fork();
if (defined($pid) && $pid==0) {
    &run_child_code;
    exit 0;
}

The child process executes the END {} block as it is exiting, but usually I don't want that to happen. Is there a way to prevent a child process from calling the END block at exit? Barring that, is there a way for a program to "know" that it is a child process, so I could say something like

END { unless (i_am_a_child_process()) { &some_cleanup_code } }

?


问:
Kafka not able to consume without reading from beginning -Java
I am new to kafka and trying to build a producer - consumer app using kafka. Here I am able to produce messages to kalka but when I try to consume it back using a consumer, it is returning 0 records.

I check offset for my consumer group, I can see that offset is equals to log length are same (1M in my case - same as number of records).

If I use this config property while creating my consumer, its reading from beginning.

configProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

But my requirement is, if I restart consumer, it should start from the previous end point like AMQ.

Is there anything I am missing here. I think offset should change only after a consumer polls. Why is it set to max records length in the beginning itself ?

答:
As the link describes there are couple of scenarios you need to consider:

starting a new consumer (new group.id): for this case, there will be no committed offset, and thus the consumer start to read according to parameter setting auto.offset.reset

restarting a consumer (reuse of group.id): for this case, the consumer will resume where it left off. Parameter setting auto.offset.reset is ignored.

Thus, for scenario (1) you can just "configure" you starting position. For scenario (2), you starting position is "fixed" (ie, always last committed offset) and this cannot be change via a config. However, you can alway do a .seekToBeginning() or .seekToEnd() before you first call to poll() and either read the whole topic or start at the end of the topic. A call to .seekXX() will "overwrite" the last committed offset and allow you to start consuming at any offset you like. Note, there is also seek() that take on "offset parameter" so you can specify any offset you want to start consuming from.


问:
Error saying Conversion failed when converting date and/or time from character string
I use the following query:

```<code>SELECT
    CONVERT(DATETIME, (RIGHT(b.dob, 4) + '-' +
                       SUBSTRING(b.dob, 3, 2) + '-' +
                       LEFT (b.dob, 2)), 111)
FROM [Load].[123_Qualification] AS b
</code>```

The Dob is a nvarchar column, and I want to convert it to a DateTime datatype, but I am  getting an error:

Conversion failed when converting date and/or time from character string.

答:
Use STUFF and CONVERT methods :</p>

```<code> SELECT CONVERT(DATETIME,STUFF(STUFF(13051971, 3, 0, '/'), 6, 0, '/'),103)
</code>```

Body:
I use the following query:

SELECT
    CONVERT(DATETIME, (RIGHT(b.dob, 4) + '-' +
                       SUBSTRING(b.dob, 3, 2) + '-' +
                       LEFT (b.dob, 2)), 111)
FROM [Load].[123_Qualification] AS b

The Dob is a nvarchar column, and I want to convert it to a DateTime datatype, but I am  getting an error:

Conversion failed when converting date and/or time from character string.

Body:
Use STUFF and CONVERT methods :

 SELECT CONVERT(DATETIME,STUFF(STUFF(13051971, 3, 0, '/'), 6, 0, '/'),103)


问:
How to load string.xml for indian languages in android?
I am trying to load strings.xml files for following Indian languages:

Oriya (values-or)

Bengali (values-bn)

Punjabi (values-pa)

Gujarati (values-gu)

Marathi (values-mr)

Malayalam (values-ml)

Telugu (values-te)

Tamil (values-ta)

Kannada (values-kn)

and tried with values-or-rIN,..etc as well. and using following code to load locale:

```<code>public void changeLang(String lang) {
        Configuration config = getBaseContext().getResources().getConfiguration();
        if (!"".equals(lang) && !config.locale.getLanguage().equals(lang)) {

            SharedPreferences.Editor ed = PreferenceManager.getDefaultSharedPreferences(this).edit();
            ed.putString(getString(R.string.locale_lang), lang);
            ed.commit();

            locale = new Locale(lang);
            Locale.setDefault(locale);
            Configuration conf = new Configuration(config);
            conf.locale = locale;
            getBaseContext().getResources().updateConfiguration(conf, getBaseContext().getResources().getDisplayMetrics());
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(this.getString(R.string.locale_lang), lang);
            editor.commit();
        }
    }
</code>```

Above code is working for all international languages. but not for above-mentioned languages. I saw many answers, as per them we need to load fonts ttf files of the corresponding language. But I don't want to load fonts (TypeFace). I want to load strings.xml.

Could anyone suggest how to load strings.xml of Indian languages? Is it possible? or Should I go for fonts ttf for above-mentioned languages??

答:
like this for Gujarati language:

```<code>        Locale myLocale = new Locale("gu");
        Resources res =  getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);
</code>```

Change "gu" with other language name
I am using Gujarati in my app. This working perfectly

Body:
I am trying to load strings.xml files for following Indian languages:

Oriya (values-or)

Bengali (values-bn)

Punjabi (values-pa)

Gujarati (values-gu)

Marathi (values-mr)

Malayalam (values-ml)

Telugu (values-te)

Tamil (values-ta)

Kannada (values-kn)

and tried with values-or-rIN,..etc as well. and using following code to load locale:

public void changeLang(String lang) {
        Configuration config = getBaseContext().getResources().getConfiguration();
        if (!"".equals(lang) && !config.locale.getLanguage().equals(lang)) {

            SharedPreferences.Editor ed = PreferenceManager.getDefaultSharedPreferences(this).edit();
            ed.putString(getString(R.string.locale_lang), lang);
            ed.commit();

            locale = new Locale(lang);
            Locale.setDefault(locale);
            Configuration conf = new Configuration(config);
            conf.locale = locale;
            getBaseContext().getResources().updateConfiguration(conf, getBaseContext().getResources().getDisplayMetrics());
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(this.getString(R.string.locale_lang), lang);
            editor.commit();
        }
    }

Above code is working for all international languages. but not for above-mentioned languages. I saw many answers, as per them we need to load fonts ttf files of the corresponding language. But I don't want to load fonts (TypeFace). I want to load strings.xml.

Could anyone suggest how to load strings.xml of Indian languages? Is it possible? or Should I go for fonts ttf for above-mentioned languages??

Body:
like this for Gujarati language:

        Locale myLocale = new Locale("gu");
        Resources res =  getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);

Change "gu" with other language name
I am using Gujarati in my app. This working perfectly


问:
How to validate an input field if value is not null in Laravel
I am trying to create and update users with laravel 5.4

This is the validation added for create user. It works.

```<code>$this->validate($request, [
    'name' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users',
    'password' => 'required|min:6|confirmed',
]);
</code>```

On update the password field is not required. But validate the min:6 and confirmed rule if the password field is not null. Tried with sometimes.. but not working..

```<code>$this->validate($request, [
    'name' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users,email,'.$id,
    'password' => 'sometimes|min:6|confirmed',
]);
</code>```

答:
try using nullable as a rule

```<code>'password' => 'nullable|min:6|confirmed',
</code>```

see https://laravel.com/docs/5.8/validation#a-note-on-optional-fields

Body:
I am trying to create and update users with laravel 5.4

This is the validation added for create user. It works.

$this->validate($request, [
    'name' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users',
    'password' => 'required|min:6|confirmed',
]);

On update the password field is not required. But validate the min:6 and confirmed rule if the password field is not null. Tried with sometimes.. but not working..

$this->validate($request, [
    'name' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users,email,'.$id,
    'password' => 'sometimes|min:6|confirmed',
]);

Body:
try using nullable as a rule

'password' => 'nullable|min:6|confirmed',

see https://laravel.com/docs/5.8/validation#a-note-on-optional-fields

ContentLicense: CC BY-SA 4.0


问:
AspectJ, Can it be used for large scale loggin
I am adding logging into existing source code (large source code) to give a detailed logging, we decided the backend for logging (using face book scribe, and tested ). I am thinking of using Aspect oriented ways to add logging calls into all the functions (to start with)

Is this a good approach to use AspectJ to handle log collection, will it have any impact on the performance of the system.

Mani

答:
Performance overhead added by AspectJ itself will be negligible (assuming you will use build-time weaving). Obviously, the logging will have its own performance impact that will depend on how wide (number of join points) and deep (information logged) is your logging.

In other words, performance difference between logging added through AspectJ and equivalent manually implemented code will be negligible.


问:
Removing Duplicates in a linked list recursively
I am trying to write a recursive function that removes all adjacent duplicates in a linked list. However, my function is not working properly.

This is my attempt:

```<code>class Node:
    """Node in a linked list"""

    def __init__(self: 'Node', value: object = None, next: 'Node' = None) -> None:
        """Create Node self with data value and successor next."""
        self.value, self.next = value, next

def remove_dup(lnk):
    if not lnk or lnk.next:
        return lnk
    if lnk.value == lnk.next.value:
        lnk.next = lnk.next.next
    else:
        return remove_dup(lnk.next)
</code>```

答:
not has precedence over or, so you need to either repeat the not, or put the or expression as an and in parentheses:

```<code>if not (lnk and lnk.next):
</code>```

Also, when you find a duplicate, you should not stop the process, as the duplicate might occur more than twice, and there might be other duplicates as well.

So it could look like this (with a function for representing lists as string):

```<code>class Node:
    """Node in a linked list"""

    def __init__(self: 'Node', value: object = None, next: 'Node' = None) -> None:
        """Create Node self with data value and successor next."""
        self.value, self.next = value, next

    def __repr__(self):
        return str(self.value) + ('->' + str(self.next) if self.next else '')

def remove_dup(lnk):
    if not (lnk and lnk.next):
        return lnk
    if lnk.value == lnk.next.value:
        lnk.next = lnk.next.next
        return remove_dup(lnk) # there might be more duplicates...
    else:
        return remove_dup(lnk.next)

# Sample data and test
lst = Node(1, Node(3, Node(3, Node(3, Node(4, Node(4, Node(5)))))))
print (lst) # 1->3->3-3->4->4->5
remove_dup(lst)
print (lst) # 1->3->4->5
</code>```

See it run on repl.it

Some other improvements

The function remove_dup is a good candidate for being a method of Node.

And it would be nice if you could read and write a linked list as a standard list. A class method could be useful to create a linked list from a list of values, while the __iter__ method could make your class iterable.

Then it could look like this:

```<code>class Node:
    """Node in a linked list"""

    def __init__(self: 'Node', value: object = None, next: 'Node' = None) -> None:
        """Create Node self with data value and successor next."""
        self.value, self.next = value, next

    def __iter__(self):
        yield self.value
        if self.next:
            yield from iter(self.next) # this needs Python 3.4+

    def __repr__(self):
        return '->'.join(map(str, list(self))) # uses __iter__

    def remove_dup(self):
        if not self.next:
            return self
        if self.value == self.next.value:
            self.next = self.next.next
            return self.remove_dup() # there might be more duplicates...
        else:
            return self.next.remove_dup()

    @classmethod
    def from_list(cls, values):
        head = None
        for value in reversed(values):
            head = cls(value, head)
        return head

lst = Node.from_list([1, 3, 3, 3, 4, 4, 5])
print (lst) # 1->3->3->3->4->4->5
lst.remove_dup()
print (lst) # 1->3->4->5
print(list(lst)) # [1, 3, 4, 5]
</code>```

On repl.it

Body:
I am trying to write a recursive function that removes all adjacent duplicates in a linked list. However, my function is not working properly.

This is my attempt:

class Node:
    """Node in a linked list"""

    def __init__(self: 'Node', value: object = None, next: 'Node' = None) -> None:
        """Create Node self with data value and successor next."""
        self.value, self.next = value, next

def remove_dup(lnk):
    if not lnk or lnk.next:
        return lnk
    if lnk.value == lnk.next.value:
        lnk.next = lnk.next.next
    else:
        return remove_dup(lnk.next)

Body:
not has precedence over or, so you need to either repeat the not, or put the or expression as an and in parentheses:

if not (lnk and lnk.next):

Also, when you find a duplicate, you should not stop the process, as the duplicate might occur more than twice, and there might be other duplicates as well.

So it could look like this (with a function for representing lists as string):

class Node:
    """Node in a linked list"""

    def __init__(self: 'Node', value: object = None, next: 'Node' = None) -> None:
        """Create Node self with data value and successor next."""
        self.value, self.next = value, next

    def __repr__(self):
        return str(self.value) + ('->' + str(self.next) if self.next else '')

def remove_dup(lnk):
    if not (lnk and lnk.next):
        return lnk
    if lnk.value == lnk.next.value:
        lnk.next = lnk.next.next
        return remove_dup(lnk) # there might be more duplicates...
    else:
        return remove_dup(lnk.next)

# Sample data and test
lst = Node(1, Node(3, Node(3, Node(3, Node(4, Node(4, Node(5)))))))
print (lst) # 1->3->3-3->4->4->5
remove_dup(lst)
print (lst) # 1->3->4->5

See it run on repl.it

Some other improvements

The function remove_dup is a good candidate for being a method of Node.

And it would be nice if you could read and write a linked list as a standard list. A class method could be useful to create a linked list from a list of values, while the __iter__ method could make your class iterable.

Then it could look like this:

class Node:
    """Node in a linked list"""

    def __init__(self: 'Node', value: object = None, next: 'Node' = None) -> None:
        """Create Node self with data value and successor next."""
        self.value, self.next = value, next

    def __iter__(self):
        yield self.value
        if self.next:
            yield from iter(self.next) # this needs Python 3.4+

    def __repr__(self):
        return '->'.join(map(str, list(self))) # uses __iter__

    def remove_dup(self):
        if not self.next:
            return self
        if self.value == self.next.value:
            self.next = self.next.next
            return self.remove_dup() # there might be more duplicates...
        else:
            return self.next.remove_dup()

    @classmethod
    def from_list(cls, values):
        head = None
        for value in reversed(values):
            head = cls(value, head)
        return head

lst = Node.from_list([1, 3, 3, 3, 4, 4, 5])
print (lst) # 1->3->3->3->4->4->5
lst.remove_dup()
print (lst) # 1->3->4->5
print(list(lst)) # [1, 3, 4, 5]

On repl.it


问:
Orientation lock in UINavigationController with UITabbar
I want to lock orientation in few UIViewcontroller

1) Loginview (support portrait Only ) UIViewcontroller having login button

2) On login button i call UITabbarController from storyboard, having 3tabs all tab are embedded UINavigationControllers.(Tab1,Tab2,Tab3)

3) On Tab1 (support both landscape and portrait )having button button1, from which i am push a UIViewcontroller Demo(support portrait Only ). like below

```<code> Demo *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"Demo"];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
</code>```

The Demo is loaded successfully , but i want to lock its rotation to portrait so i create a Category of UINavigationController, but it still rotating.

```<code>#import <UIKit/UIKit.h>

@interface UINavigationController (Orientation)

@end
</code>```

//==========

```<code>#import "UINavigationController+Orientation.h"
@implementation UINavigationController (Orientation)
-(BOOL)shouldAutorotate
{

    return YES;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortraitUpsideDown;;
}
@end
</code>```

//------- Inside my Demo uiviewcontroller i but below code but it never called --------

```<code>-(BOOL)shouldAutorotate
{
    return NO;
}
-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}
</code>```

I read many post but non of them help ,Please Help me out how do i do it?

答:
Initial set orientation as Portrait only in Targets -> General -> Deployment Info (See Image Below)

In AppDelegate.h declare property:

```<code>@property (assign, nonatomic) BOOL shouldRotate;
</code>```

In AppDelegate.m define

```<code>-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.shouldRotate)
        return UIInterfaceOrientationMaskAllButUpsideDown;
    else
        return UIInterfaceOrientationMaskPortrait;
}
</code>```

In UIViewController Implemenatation set shouldRotate value like:

If you want to rotate then set YES

```<code>-(void) viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
        [(AppDelegate *)[[UIApplication sharedApplication] delegate] setShouldRotate:YES];
    }
</code>```

else set NO

```<code>-(void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [(AppDelegate *)[[UIApplication sharedApplication] delegate] setShouldRotate:NO];
}
</code>```

Note: setShouldRotate:  always call in viewDidAppear:. So, whenever you switch the UIViewController it will work properly.

Hope this will work for you. All the best :)

Body:
I want to lock orientation in few UIViewcontroller

1) Loginview (support portrait Only ) UIViewcontroller having login button

2) On login button i call UITabbarController from storyboard, having 3tabs all tab are embedded UINavigationControllers.(Tab1,Tab2,Tab3)

3) On Tab1 (support both landscape and portrait )having button button1, from which i am push a UIViewcontroller Demo(support portrait Only ). like below

 Demo *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"Demo"];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];

The Demo is loaded successfully , but i want to lock its rotation to portrait so i create a Category of UINavigationController, but it still rotating.

#import <UIKit/UIKit.h>

@interface UINavigationController (Orientation)

@end

//==========

#import "UINavigationController+Orientation.h"
@implementation UINavigationController (Orientation)
-(BOOL)shouldAutorotate
{

    return YES;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortraitUpsideDown;;
}
@end

//------- Inside my Demo uiviewcontroller i but below code but it never called --------

-(BOOL)shouldAutorotate
{
    return NO;
}
-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

I read many post but non of them help ,Please Help me out how do i do it?

Body:
Initial set orientation as Portrait only in Targets -> General -> Deployment Info (See Image Below)

In AppDelegate.h declare property:

@property (assign, nonatomic) BOOL shouldRotate;

In AppDelegate.m define

-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.shouldRotate)
        return UIInterfaceOrientationMaskAllButUpsideDown;
    else
        return UIInterfaceOrientationMaskPortrait;
}

In UIViewController Implemenatation set shouldRotate value like:

If you want to rotate then set YES

-(void) viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
        [(AppDelegate *)[[UIApplication sharedApplication] delegate] setShouldRotate:YES];
    }

else set NO

-(void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [(AppDelegate *)[[UIApplication sharedApplication] delegate] setShouldRotate:NO];
}

Note: setShouldRotate:  always call in viewDidAppear:. So, whenever you switch the UIViewController it will work properly.

Hope this will work for you. All the best :)


问:
Size parameter in elastic search
It may be a beginner question, but I have some doubts related to size.
As per elastic search specs, the maximum value of size can be 10000, I want to validate my understandings below:

Sample Query:

```<code>GET testindex-2016.04.14/_search
{
  "size": 10000,
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "type": "TEST"
          }
        }
      ]
    }
  },
  "aggs": {
    "testAggs": {
      "terms": {
        "field": "type",
        "size": 0
      },
      "aggs": {
        "innerAggs": {
          "max": {
            "field": "Value"
          }
        }
      }
    }
  }
}
</code>```

Response:

```<code>{
  "took": 6,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 26949,
    "max_score": 0,
    "hits": [
       .....10000 records
     ]
  },
  "aggregations": {
    "test": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "TEST",
          "doc_count": 26949,
          "innerAggs": {
            "value": 150
          }
        }
      ]
    }
  }
}
</code>```

1 - If size is set to 10000, and we have more than 200000 records in elastic search satisfying the query, So in query result, I will get the no. of hits to 10000, but the "total" : 200000.

2 - How many records will be available for further aggregations - the no. of hits or the "total" value.

3 - If we set "size" : 0, in this case, we get hits = 0, but how many records will be available for aggregations ?

Please clarify my understanding, and put comments in any doubt in question . Thanks.

答:
The size parameter only tells how many hits should be returned in the response, so if you specify size: 10000 and 200000 records match, you'll get 10000 matching documents in the result hits, but total will state 200000

aggregations are always computed on the full set of results, so the total value.

See 2

Title: Size parameter in elastic search

Body:
It may be a beginner question, but I have some doubts related to size.
As per elastic search specs, the maximum value of size can be 10000, I want to validate my understandings below:

Sample Query:

GET testindex-2016.04.14/_search
{
  "size": 10000,
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "type": "TEST"
          }
        }
      ]
    }
  },
  "aggs": {
    "testAggs": {
      "terms": {
        "field": "type",
        "size": 0
      },
      "aggs": {
        "innerAggs": {
          "max": {
            "field": "Value"
          }
        }
      }
    }
  }
}

Response:

{
  "took": 6,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 26949,
    "max_score": 0,
    "hits": [
       .....10000 records
     ]
  },
  "aggregations": {
    "test": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "TEST",
          "doc_count": 26949,
          "innerAggs": {
            "value": 150
          }
        }
      ]
    }
  }
}

1 - If size is set to 10000, and we have more than 200000 records in elastic search satisfying the query, So in query result, I will get the no. of hits to 10000, but the "total" : 200000.

2 - How many records will be available for further aggregations - the no. of hits or the "total" value.

3 - If we set "size" : 0, in this case, we get hits = 0, but how many records will be available for aggregations ?

Please clarify my understanding, and put comments in any doubt in question . Thanks.


问:
Forcing UTF-8 over cp1252 (Python3)
I've written some code that makes use of the Biopython Entrez wrapper. Code was working fine on my previous Win10 laptop (Python 3.5.1), but I've just ported the code to a new Win10 laptop with the same versions of every package and Python installed and I'm now getting a decode error.

The traceback error leads to a function that fetches text - it's attempting to decode the text using cp1252 when it should be using UTF-8. I know that similar questions have been asked, but none have dealt with this problem happening inside a package (Biopython in my case). Copying the UTF-8 encoding file in Python/lib and renaming it to cp1252.py solves the problem, but this obviously is not a long term solution.

```<code>File "C:\Users\arjun\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 21715: character maps to <undefined>
</code>```

答:
Use the io module for reading if you're using Python 3.x (https://docs.python.org/2/library/io.html#io.open).
By default, it will use the encoding specified on its running platform. You can also specify your own encoding as explained in the docs.

Title: Forcing UTF-8 over cp1252 (Python3)

Body:
I've written some code that makes use of the Biopython Entrez wrapper. Code was working fine on my previous Win10 laptop (Python 3.5.1), but I've just ported the code to a new Win10 laptop with the same versions of every package and Python installed and I'm now getting a decode error.

The traceback error leads to a function that fetches text - it's attempting to decode the text using cp1252 when it should be using UTF-8. I know that similar questions have been asked, but none have dealt with this problem happening inside a package (Biopython in my case). Copying the UTF-8 encoding file in Python/lib and renaming it to cp1252.py solves the problem, but this obviously is not a long term solution.

File "C:\Users\arjun\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 21715: character maps to <undefined>


问:
SQL MAX of multiple columns?
How do you return 1 value per row of the max of several columns:

TableName

```<code>[Number, Date1, Date2, Date3, Cost]
</code>```

I need to return something like this:

```<code>[Number, Most_Recent_Date, Cost]
</code>```

Query?

答:
```<code>SELECT
    CASE
        WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1
        WHEN Date2 >= Date3 THEN Date2
        ELSE Date3
    END AS MostRecentDate
</code>```

This is slightly easier to write out and skips evaluation steps as the case statement is evaluated in order.

OwnerDisplayName: BenBruscella

Title: SQL MAX of multiple columns?

Body:
How do you return 1 value per row of the max of several columns:

TableName

[Number, Date1, Date2, Date3, Cost]

I need to return something like this:

[Number, Most_Recent_Date, Cost]

Query?

LastEditorDisplayName: Nigel Campbell

Body:
SELECT
    CASE
        WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1
        WHEN Date2 >= Date3 THEN Date2
        ELSE Date3
    END AS MostRecentDate

This is slightly easier to write out and skips evaluation steps as the case statement is evaluated in order.


问:
Copy Row over to another sheet with multiple criteria in multiple ranges VBA Excel
I am trying to copy rows from one sheet to another using VBA, I need it to check cell in column a if it contains value X and if column C excludes Value Y.

I have come as far to copy it with the first criteria, but not the second.

This is what I have and it won't work...

```<code>Sub Copy_2016()
'
'Run Sub Copy_2016()
'
Sheets("Working - 2016").Select
Range("A3:AO6304").ClearContents

For Each Cell In Sheets("Working - Data").Range("A1:A6304,C3:C6304")
    If Cell.Value = "2016" And If Not Cell.Value = "HI" Then
         matchRow = Cell.Row
         Rows(matchRow & ":" & matchRow).Select
         Selection.Copy

         Sheets("Working - 2016").Select
         ActiveSheet.Rows(matchRow).Select
         ActiveSheet.Paste
         Sheets("Working - Data").Select
    End If
Next

End Sub
</code>```

答:
One thing @chris neilsen answer is missing, is that the pasted sheet ("Working - 2016") will have blank rows in the middle (since not all rows will be copied), that's why I added the RowDest variable.

Also, if all you do is paste the values, you can use Worksheets("Working - 2016").Rows(RowDest).value = Cell.EntireRow.value instead of Copy and PasteSpecial in 2 code lines.

Code

```<code>Option Explicit

Sub Copy_2016()

    Dim Cell As Range
    Dim RowDest As Long

    With Worksheets("Working - 2016")
        .Range("A3:AO6304").ClearContents
    End With

    RowDest = 3 ' first paste row , since you are clearing the sheet's contents
    With Worksheets("Working - Data")
        For Each Cell In .Range("A1:A6304")
            If Cell.value Like "2016" And Not Cell.Offset(0, 2).value Like "HI" Then
                Worksheets("Working - 2016").Rows(RowDest).value = Cell.EntireRow.value
                RowDest = RowDest + 1
            End If
        Next Cell
    End With

End Sub
</code>```

Body:
I am trying to copy rows from one sheet to another using VBA, I need it to check cell in column a if it contains value X and if column C excludes Value Y.

I have come as far to copy it with the first criteria, but not the second.

This is what I have and it won't work...

Sub Copy_2016()
'
'Run Sub Copy_2016()
'
Sheets("Working - 2016").Select
Range("A3:AO6304").ClearContents

For Each Cell In Sheets("Working - Data").Range("A1:A6304,C3:C6304")
    If Cell.Value = "2016" And If Not Cell.Value = "HI" Then
         matchRow = Cell.Row
         Rows(matchRow & ":" & matchRow).Select
         Selection.Copy

         Sheets("Working - 2016").Select
         ActiveSheet.Rows(matchRow).Select
         ActiveSheet.Paste
         Sheets("Working - Data").Select
    End If
Next

End Sub

Body:
One thing @chris neilsen answer is missing, is that the pasted sheet ("Working - 2016") will have blank rows in the middle (since not all rows will be copied), that's why I added the RowDest variable.

Also, if all you do is paste the values, you can use Worksheets("Working - 2016").Rows(RowDest).value = Cell.EntireRow.value instead of Copy and PasteSpecial in 2 code lines.

Code

Option Explicit

Sub Copy_2016()

    Dim Cell As Range
    Dim RowDest As Long

    With Worksheets("Working - 2016")
        .Range("A3:AO6304").ClearContents
    End With

    RowDest = 3 ' first paste row , since you are clearing the sheet's contents
    With Worksheets("Working - Data")
        For Each Cell In .Range("A1:A6304")
            If Cell.value Like "2016" And Not Cell.Offset(0, 2).value Like "HI" Then
                Worksheets("Working - 2016").Rows(RowDest).value = Cell.EntireRow.value
                RowDest = RowDest + 1
            End If
        Next Cell
    End With

End Sub


问:
need some help understanding an aspect of this code
Please refer the code below

```<code>import java.util.Scanner;

public class Reverse {

public static void main(String[] args) {

    String words = "";
    String output = "";

    Scanner scan = new Scanner(System.in);
    while (scan.hasNextLine()) {
        words = scan.nextLine();

        for (int i = 0; i < words.length(); i++) {
            output += words.charAt(words.length() - i - 1);
        }
        output += "\n";
    }
    System.out.print(output);

 }
}
</code>```

First of all, sorry for the vague title but I didn't know how to put it any other way. I am new to Java and for uni, we were given a task that read standard input until the end of file and then outputs the reverse of each line.

I was wondering how

```<code>String output
</code>```

is able to output multiple strings at the end. Shouldn't it only be able to hold one string? Sorry if this question doesn't make much sense.

答: output does not hold more than one string. A string can have multiple lines as denoted by the \n in your code. When you print \n, you are printing a new line. This is still one string, just with multiple lines.

Body:
Please refer the code below

import java.util.Scanner;

public class Reverse {

public static void main(String[] args) {

    String words = "";
    String output = "";

    Scanner scan = new Scanner(System.in);
    while (scan.hasNextLine()) {
        words = scan.nextLine();

        for (int i = 0; i < words.length(); i++) {
            output += words.charAt(words.length() - i - 1);
        }
        output += "\n";
    }
    System.out.print(output);

 }
}

First of all, sorry for the vague title but I didn't know how to put it any other way. I am new to Java and for uni, we were given a task that read standard input until the end of file and then outputs the reverse of each line.

I was wondering how

String output

is able to output multiple strings at the end. Shouldn't it only be able to hold one string? Sorry if this question doesn't make much sense.


问:
Retrieve and save the Dynamic added control in WPF Xaml?
I have added the template based on this link

I have an Add button - when I click on it through Command I add it to a collection.

```<code> <ItemsControl ItemsSource="{Binding Collection}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Grid DataContext="{StaticResource VieWModel}">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="15*"/>
                                <ColumnDefinition Width="40*"/>
                            </Grid.ColumnDefinitions>
                            <Label Content="GH" Grid.Row="0" Grid.Column="0" VerticalContentAlignment="Center"></Label>
                            <tk:RadComboBox Grid.Row="0" Grid.Column="0" Margin="10" IsFilteringEnabled="True" Width="150" DisplayMemberPath="D"  IsEditable="True" ItemsSource="{Binding GK}"  SelectedItem="{Binding SK, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                                <i:Interaction.Triggers>
                                    <i:EventTrigger EventName="SelectionChanged">
                                        <i:InvokeCommandAction Command="{Binding SelectionChangedCommand}" CommandParameter="{Binding}"/>
                                    </i:EventTrigger>
                                </i:Interaction.Triggers>
                            </tk:RadComboBox>
                            <Label Content="HB" Grid.Row="0" Grid.Column="1" VerticalContentAlignment="Center"></Label>
                            <tk:RadComboBox  Grid.Row="0" Grid.Column="1" Margin="10" IsFilteringEnabled="True" Name="cb"  Width="350" IsEditable="True" DisplayMemberPath="D"  ItemsSource="{Binding VR}" SelectedItem="{Binding VR1,Mode=TwoWay}">
                            </tk:RadComboBox>
                        </Grid>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
</code>```

ViewModel sample code:

```<code>     // Property for selected Item in combox1
            Public ValBase  SK{get;set;}

        //Property off combobox1 binding
        Public ValBase GK{get;set;}

        // Property ofor selected Item in combox2
        Public ValBase VR1{get; set;}

        //Property ofr combobox2 binding
        Public ValBase VR{get;set;}

        Public void AddButton(object obj)
        {
          var item =new collectionbase();
          Collection.Add(item)
        }
</code>```

Whenever I click the Add Button this itemplate will be added.

MyRequirement :

When I Click Add Button for the first time ,template should get added

When I click Add Button for the second time Previous generated controls Must have contain the values,only then controls should be added to a collection and then new controls should be created

And I dont know how to save those values dynamically created in a collection

I am running out of Ideas how to achieve this can anyone help . MVVM pattern

答: Using Selector Class.I have used CurrentInstance To Bind the Collection its working fine now</p>

Body:
I have added the template based on this link

I have an Add button - when I click on it through Command I add it to a collection.

 <ItemsControl ItemsSource="{Binding Collection}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Grid DataContext="{StaticResource VieWModel}">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="15*"/>
                                <ColumnDefinition Width="40*"/>
                            </Grid.ColumnDefinitions>

                            <tk:RadComboBox Grid.Row="0" Grid.Column="0" Margin="10" IsFilteringEnabled="True" Width="150" DisplayMemberPath="D"  IsEditable="True" ItemsSource="{Binding GK}"  SelectedItem="{Binding SK, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">

                            </tk:RadComboBox>

                            <tk:RadComboBox  Grid.Row="0" Grid.Column="1" Margin="10" IsFilteringEnabled="True" Name="cb"  Width="350" IsEditable="True" DisplayMemberPath="D"  ItemsSource="{Binding VR}" SelectedItem="{Binding VR1,Mode=TwoWay}">
                            </tk:RadComboBox>
                        </Grid>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

ViewModel sample code:

     // Property for selected Item in combox1
            Public ValBase  SK{get;set;}

        //Property off combobox1 binding
        Public ValBase GK{get;set;}

        // Property ofor selected Item in combox2
        Public ValBase VR1{get; set;}

        //Property ofr combobox2 binding
        Public ValBase VR{get;set;}

        Public void AddButton(object obj)
        {
          var item =new collectionbase();
          Collection.Add(item)
        }

Whenever I click the Add Button this itemplate will be added.

MyRequirement :

When I Click Add Button for the first time ,template should get added

When I click Add Button for the second time Previous generated controls Must have contain the values,only then controls should be added to a collection and then new controls should be created

And I dont know how to save those values dynamically created in a collection

I am running out of Ideas how to achieve this can anyone help . MVVM pattern


问:
Understanding reference counting with Cocoa and Objective-C
I'm just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I'm reasonably comfortable with C's malloc and free concept, but Cocoa's references counting scheme has me rather confused. I'm told it's very elegant once you understand it, but I'm just not over the hump yet.

How do release, retain and autorelease work and what are the conventions about their use?

(Or failing that, what did you read which helped you get it?)

答:
My usual collection of Cocoa memory management articles:

cocoa memory management

LastEditorDisplayName: Paul


问:
How to get the value of an ASP.net variable into a javascript textbox
I'm writing some Javascript code for an ASP.net page.

I have the string "foo" assigned to a string variable myString.

I would like to assign the value of myString to a JavaScript variable, so I write in my ASP.net code:

```<code><script type='txt/javascript' language='javascript'>
    var stringFromDotNet = '<%=myString%>';
</script>
</code>```

This works fine as long as myString does not contain quotation marks or line-breaks, but as as soon as I try to assign something with quotation marks or line-breaks, all hell breaks loose and my code doesn't work.  As a matter of fact, I can see that this code is vulnerable to all sort of injection attacks.

So... What can I do get the value of myString assigned to a variable in JavaScript?

Update:  I've tried creating a page with just an ASP:Hidden field.  It looks like the values inside are html encoded.

答:
You could use JavaScriptSerializer and that's guaranteed to be safe against XSS:

```<code><script type="text/javascript">
    var stringFromDotNet = <%= new JavaScriptSerializer().Serialize(myString) %>;
</script>
</code>```

This approach also allows you to pass complex objects and not just plain strings:

```<code><script type="text/javascript">
    var complexObjectFromDotNet = <%= new JavaScriptSerializer().Serialize(new { id = 123, name = "foo\"' <bar>" }) %>;
    alert(complexObjectFromDotNet.name);
</script>
</code>```

Body:
I'm writing some Javascript code for an ASP.net page.

I have the string "foo" assigned to a string variable myString.

I would like to assign the value of myString to a JavaScript variable, so I write in my ASP.net code:

This works fine as long as myString does not contain quotation marks or line-breaks, but as as soon as I try to assign something with quotation marks or line-breaks, all hell breaks loose and my code doesn't work.  As a matter of fact, I can see that this code is vulnerable to all sort of injection attacks.

So... What can I do get the value of myString assigned to a variable in JavaScript?

Update:  I've tried creating a page with just an ASP:Hidden field.  It looks like the values inside are html encoded.

Body:
You could use JavaScriptSerializer and that's guaranteed to be safe against XSS:

<script type="text/javascript">
    var stringFromDotNet = <%= new JavaScriptSerializer().Serialize(myString) %>;
</script>

This approach also allows you to pass complex objects and not just plain strings:

<script type="text/javascript">
    var complexObjectFromDotNet = <%= new JavaScriptSerializer().Serialize(new { id = 123, name = "foo\"' <bar>" }) %>;
    alert(complexObjectFromDotNet.name);
</script>


问:
PHP Paypal API: How to Capture Authorized Payment Partially?
I'm able to Authorize & Capture Payment.

https://developer.paypal.com/docs/api/payments/#authorization_capture

My Order's Authorize Amount Is: 100

```<code>$data = '{
            "amount": {
            "currency": "USD",
            "total": "10"
            },
            "is_final_capture": false
          }';
</code>```

Below API i'm using

```<code>https://api.sandbox.paypal.com/v1/payments/authorization/<authorizationId>/capture
</code>```

I'm only Capturing 10 USD & Marking is_final_capture as false. It mark as Completed Order.

When I run again with 90 USD it says

```<code>stdClass Object
(
    [name] => PAYMENT_ALREADY_DONE
    [message] => Payment has been done already for this cart.
    [information_link] => https://developer.paypal.com/docs/api/payments/#errors
    [debug_id] => ce22df5392497
)
</code>```

On Sandbox it mark as order Completed

How to Capture Pending 90 USD?

答:
Thanks to @Tejas & it works

1st Time you can Capture with below ones

```<code>$data = '{
            "amount": {
            "currency": "USD",
            "total": "10"
            }
          }';
</code>```

2nd Time you can Capture with below ones

```<code>$data = '{
            "amount": {
            "currency": "USD",
            "total": "90"
            },
           "is_final_capture": true
          }';
</code>```

On above way you can Capture Authorized Payment Partially

Body:
I'm able to Authorize & Capture Payment.

https://developer.paypal.com/docs/api/payments/#authorization_capture

My Order's Authorize Amount Is: 100

$data = '{
            "amount": {
            "currency": "USD",
            "total": "10"
            },
            "is_final_capture": false
          }';

Below API i'm using

https://api.sandbox.paypal.com/v1/payments/authorization/<authorizationId>/capture

I'm only Capturing 10 USD & Marking is_final_capture as false. It mark as Completed Order.

When I run again with 90 USD it says

stdClass Object
(
    [name] => PAYMENT_ALREADY_DONE
    [message] => Payment has been done already for this cart.
    [information_link] => https://developer.paypal.com/docs/api/payments/#errors
    [debug_id] => ce22df5392497
)

On Sandbox it mark as order Completed

How to Capture Pending 90 USD?

Body:
Thanks to @Tejas & it works

1st Time you can Capture with below ones

$data = '{
            "amount": {
            "currency": "USD",
            "total": "10"
            }
          }';

2nd Time you can Capture with below ones

$data = '{
            "amount": {
            "currency": "USD",
            "total": "90"
            },
           "is_final_capture": true
          }';

On above way you can Capture Authorized Payment Partially


问:
Retrieve data from json using Python
I am trying to retrieve the urls from the sub elements given comp1 and comp2 as input to the python script

```<code>{
  "main1": {
    "comp1": {
      "url": [
        "http://kcdclcm.com",
        "http://dacklsd.com"
       ]
    },
    "comp2": {
      "url": [
           "http://dccmsdlkm.com",
           "http://clsdmcsm.com"
        ]
    }
  },
  "main2": {
    "comp3": {
      "url": [
        "http://csdc.com",
        "http://uihjkn.com"
       ]
    },
    "comp4": {
      "url": [
           "http://jkll.com",
           "http://ackjn.com"
        ]
    }
  }
}
</code>```

Following is the snippet of the python function, I am trying to use to grab the urls

```<code>import json
data = json.load(open('test.json'))
def geturl(comp):
    if comp in data[comp]:
        for url in data[comp]['url']:
            print url
geturl('comp1')
geturl('comp2')
</code>```

I totally understand the error is in the 4th and 5th line of the script, since i am trying to grab the url information from the second element of the json data without passing the first element 'main1' or 'main2'. Same script works fine if I replace the 4th and 5th line as below:

```<code>if comp in data['main1']:
    for url in data['main1'][comp]['url']:
</code>```

In my case, i would not know main1 and main2 as the user would just pass comp1, comp2, comp3 and comp4 part as input to the script. Is there a way to find the url information given that only the second element is known

Any inputs would be highly appreciated.

答:
If you want to search the urls with only comp key in every main, you just need to do it like this:</p>

```<code>import json
data = json.load(open('test.json'))
def geturl(comp):
    for mainKey in data:
        main = data[mainKey]
        if comp in main:
            urls = main[comp]['url']
            for url in urls:
                print url

geturl('comp1')
geturl('comp2')
</code>```

Title: Retrieve data from json using Python

Body:
I am trying to retrieve the urls from the sub elements given comp1 and comp2 as input to the python script

{
  "main1": {
    "comp1": {
      "url": [
        "http://kcdclcm.com",
        "http://dacklsd.com"
       ]
    },
    "comp2": {
      "url": [
           "http://dccmsdlkm.com",
           "http://clsdmcsm.com"
        ]
    }
  },
  "main2": {
    "comp3": {
      "url": [
        "http://csdc.com",
        "http://uihjkn.com"
       ]
    },
    "comp4": {
      "url": [
           "http://jkll.com",
           "http://ackjn.com"
        ]
    }
  }
}

Following is the snippet of the python function, I am trying to use to grab the urls

import json
data = json.load(open('test.json'))
def geturl(comp):
    if comp in data[comp]:
        for url in data[comp]['url']:
            print url
geturl('comp1')
geturl('comp2')

I totally understand the error is in the 4th and 5th line of the script, since i am trying to grab the url information from the second element of the json data without passing the first element 'main1' or 'main2'. Same script works fine if I replace the 4th and 5th line as below:

if comp in data['main1']:
    for url in data['main1'][comp]['url']:

In my case, i would not know main1 and main2 as the user would just pass comp1, comp2, comp3 and comp4 part as input to the script. Is there a way to find the url information given that only the second element is known

Any inputs would be highly appreciated.

Body:
If you want to search the urls with only comp key in every main, you just need to do it like this:

import json
data = json.load(open('test.json'))
def geturl(comp):
    for mainKey in data:
        main = data[mainKey]
        if comp in main:
            urls = main[comp]['url']
            for url in urls:
                print url

geturl('comp1')
geturl('comp2')


问:
Hot to make jackson to use snake_case / camelCase on demand in a Spring Boot REST API?
I want to support both snake_case and camelCase in the json interface of my rest API.

Jackson uses camelCase by default. I know there are many ways of making Jackson to use snake_case:

Annotating properties individually: @JsonProperty("first_name")

Annotating classes with: @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

Applying it to the whole application inside application.properties:
spring.jackson.property-naming-strategy=SNAKE_CASE

But I haven't found information about how to allow the consumer to request the desired case. For example by using content negotiation (Accepts, Content-Type headers)

Lets suppose we have the following example:

```<code>@RequestMapping("/my-resource")
public interface ApiController {
    @RequestMapping(method = RequestMethod.POST, produces = {"application/json"})
    MyResource createResource(@RequestBody MyResource myResource);

    @GetMapping(value="/{resourceId}", produces = {"application/json"})
    MyResource readResource(@PathVariable String resourceId);
}
</code>```

So one use case could be to use custom json media-type and provide content negotiation headers like:

Accepts: application/vnd.snake+json

and let the default application/json to use camelCase.

But I cannot find the way of making jackson to use two different Mapper configurations based on the content negotiation.

答:
Good question, I would suggest to take a look into content negotiation and http message converter topics.

It seems you can configure two instances of MappingJackson2HttpMessageConverter
to produce application/vnd.snake+json or application/json.
Set it with specific media type and differently configured ObjectMapper

Code modification can looks like:

```<code>MyMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter
{
  public MyMappingJackson2HttpMessageConverter(ObjectMapper objectMapper, MediaType mediaType)
  {
     super(objectMapper, mediaType);
  }
}
</code>```

Configuration can looks like:

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void configureMessageConverters(
    List<HttpMessageConverter<?>> converters) {
      converters.add(new MyMappingJackson2HttpMessageConverter(snake, new MediaType("application", "vnd.snake+json")));
      converters.add(new MappingJackson2HttpMessageConverter(camel, MediaType.APPLICATION_JSON));
      super.configureMessageConverters(converters);
}
...
```

Body:
I want to support both snake_case and camelCase in the json interface of my rest API.

Jackson uses camelCase by default. I know there are many ways of making Jackson to use snake_case:

Annotating properties individually: @JsonProperty("first_name")

Annotating classes with: @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

Applying it to the whole application inside application.properties:
spring.jackson.property-naming-strategy=SNAKE_CASE

But I haven't found information about how to allow the consumer to request the desired case. For example by using content negotiation (Accepts, Content-Type headers)

Lets suppose we have the following example:

@RequestMapping("/my-resource")
public interface ApiController {
    @RequestMapping(method = RequestMethod.POST, produces = {"application/json"})
    MyResource createResource(@RequestBody MyResource myResource);

    @GetMapping(value="/{resourceId}", produces = {"application/json"})
    MyResource readResource(@PathVariable String resourceId);
}

So one use case could be to use custom json media-type and provide content negotiation headers like:

Accepts: application/vnd.snake+json

and let the default application/json to use camelCase.

But I cannot find the way of making jackson to use two different Mapper configurations based on the content negotiation.

Body:
Good question, I would suggest to take a look into content negotiation and http message converter topics.

It seems you can configure two instances of MappingJackson2HttpMessageConverter
to produce application/vnd.snake+json or application/json.
Set it with specific media type and differently configured ObjectMapper

Code modification can looks like:

MyMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter
{
  public MyMappingJackson2HttpMessageConverter(ObjectMapper objectMapper, MediaType mediaType)
  {
     super(objectMapper, mediaType);
  }
}

Configuration can looks like:

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void configureMessageConverters(
    List<HttpMessageConverter<?>> converters) {
      converters.add(new MyMappingJackson2HttpMessageConverter(snake, new MediaType("application", "vnd.snake+json")));
      converters.add(new MappingJackson2HttpMessageConverter(camel, MediaType.APPLICATION_JSON));
      super.configureMessageConverters(converters);
}
...


问:
Codeigniter Image upload issue
I'm using codeigniter upload library to upload multiple images. Mostly it is working fine, but in some cases the image is not uploading.

Function:

```<code>    function do_upload_img()
    {
        if(isset($_FILES['portfolioimg']['size']) != 0){
           $name_array = array();
           $files = $_FILES;
           $cpt = count($_FILES['portfolioimg']['name']);

           // $config['source_image'] = ''; //get original image
           $config['wm_type'] = 'overlay';
           $config['wm_overlay_path'] = './assets/img/watermark.png';
           $config['quality'] = 50;
           $config['wm_vrt_alignment'] = 'middle';
           $config['wm_hor_alignment'] = 'center';
           $this->load->library('image_lib', $config);

           for($i=0; $i<=$cpt-1; $i++)
           {
               $_FILES['userfile']['name']= $files['portfolioimg']['name'][$i];
               $_FILES['userfile']['type']= $files['portfolioimg']['type'][$i];
               $_FILES['userfile']['tmp_name']= $files['portfolioimg']['tmp_name'][$i];
               $_FILES['userfile']['error']= $files['portfolioimg']['error'][$i];
               $_FILES['userfile']['size']= $files['portfolioimg']['size'][$i];

               $imgnam = rand(10,1000000).time();
               $ext = pathinfo($files['portfolioimg']['name'][$i], PATHINFO_EXTENSION);
               if($this->upload->initialize($this->set_upload_options($imgnam))){
                      $data = $this->upload->do_upload();
                      $config['source_image'] = './assets/portfolio_img/' . 'Rookie_'.$imgnam.'.'.$ext;
                      $this->image_lib->initialize($config);
                      $this->image_lib->watermark();
                      $name_array[] = $this->upload->data('file_name');
                      $this->create_thumbnail('./assets/portfolio_img/',$imgnam,$ext);
               }else{
                   $this->session->set_flashdata('falsemsg','Only jpg, jpeg, png files are allowed to be uploaded.');
               }
           }
           return $name_array;
        }else{
          return false;
        }
    }
    private function set_upload_options($imgnam)
    {
            //upload an image options
        $config = array();
        $config['upload_path']   = './assets/portfolio_img/';
        $config['allowed_types'] = 'jpeg|jpg|png|JPEG|JPG|PNG';
        $config['max_size']      = '0';
        $config['overwrite']     = true;
        $config['file_name']     = 'Rookie_'.$imgnam;

        return $config;
    }
</code>```

This is the function that Im using to upload the images. I don't have any idea why it is not working sometimes. So please help me to figure out the error in my code. Thanks in advance.

答:
```<code>   $b='portfolioimg';
    $fileName = $_FILES[$b]['name'];
                $images = $fileName;
                $cpt = count($files);
                for($i=1; $i<=$cpt; $i++)
                {
                    $_FILES[$b]['name']= $files[$b]['name'][$i];
                    $_FILES[$b]['type']= $files[$b]['type'][$i];
                    $_FILES[$b]['tmp_name']= $files[$b]['tmp_name'][$i];
                    $_FILES[$b]['error']= $files[$b]['error'][$i];
                    $_FILES[$b]['size']= $files[$b]['size'][$i];
                    $uploadPath =  './assets/portfolio_img/';
                    $config['upload_path'] = $uploadPath;
                    $config['allowed_types'] = 'gif|jpg|png|ico';
                    $this->load->library('upload', $config);
                    $this->upload->initialize($config);

            if($this->upload->do_upload($b.$i)){
            $fileData = $this->upload->data();
            $uploadData[$i]['file_name'] = $fileData['file_name'];
            $im[$i]=$uploadData[$i]['file_name'];
            }
            }
        $tblValues = array(

        'image'=>$images, // change field name,

    );
    $this->db->insert('table_name', $tblValues);
</code>```

Title: Codeigniter Image upload issue

Body:
I'm using codeigniter upload library to upload multiple images. Mostly it is working fine, but in some cases the image is not uploading.

Function:

    function do_upload_img()
    {
        if(isset($_FILES['portfolioimg']['size']) != 0){
           $name_array = array();
           $files = $_FILES;
           $cpt = count($_FILES['portfolioimg']['name']);

           // $config['source_image'] = ''; //get original image
           $config['wm_type'] = 'overlay';
           $config['wm_overlay_path'] = './assets/img/watermark.png';
           $config['quality'] = 50;
           $config['wm_vrt_alignment'] = 'middle';
           $config['wm_hor_alignment'] = 'center';
           $this->load->library('image_lib', $config);

           for($i=0; $i<=$cpt-1; $i++)
           {
               $_FILES['userfile']['name']= $files['portfolioimg']['name'][$i];
               $_FILES['userfile']['type']= $files['portfolioimg']['type'][$i];
               $_FILES['userfile']['tmp_name']= $files['portfolioimg']['tmp_name'][$i];
               $_FILES['userfile']['error']= $files['portfolioimg']['error'][$i];
               $_FILES['userfile']['size']= $files['portfolioimg']['size'][$i];

               $imgnam = rand(10,1000000).time();
               $ext = pathinfo($files['portfolioimg']['name'][$i], PATHINFO_EXTENSION);
               if($this->upload->initialize($this->set_upload_options($imgnam))){
                      $data = $this->upload->do_upload();
                      $config['source_image'] = './assets/portfolio_img/' . 'Rookie_'.$imgnam.'.'.$ext;
                      $this->image_lib->initialize($config);
                      $this->image_lib->watermark();
                      $name_array[] = $this->upload->data('file_name');
                      $this->create_thumbnail('./assets/portfolio_img/',$imgnam,$ext);
               }else{
                   $this->session->set_flashdata('falsemsg','Only jpg, jpeg, png files are allowed to be uploaded.');
               }
           }
           return $name_array;
        }else{
          return false;
        }
    }
    private function set_upload_options($imgnam)
    {
            //upload an image options
        $config = array();
        $config['upload_path']   = './assets/portfolio_img/';
        $config['allowed_types'] = 'jpeg|jpg|png|JPEG|JPG|PNG';
        $config['max_size']      = '0';
        $config['overwrite']     = true;
        $config['file_name']     = 'Rookie_'.$imgnam;

        return $config;
    }

This is the function that Im using to upload the images. I don't have any idea why it is not working sometimes. So please help me to figure out the error in my code. Thanks in advance.


问:
elements of list in row
i have few polygons and distance of some points from those polygons. i tried to write in a csv by pandas where distance between each point and polygon will come in separate rows. i got this:

```<code>poly total inside outside dist
1000   2     0      2     [16015,5678]
1100   1     0      1     [5267]
</code>```

I wanted to get like:

```<code>poly total inside outside dist
1000   2    0       2     16015
1000   2    0       2     5678
1100   1    0       1     5267
</code>```

I tried the following after looking at this previous q [How to write nth value of list into csv file

```<code>distance =[]
for row in arcpy.da.SearchCursor(outSide, ["SHAPE@XY"]):
            px, py = row[0]
            zipPoint=point(px,py)
            Distance.append(int(zipPoint.calDist(PolyCenter)))
for i in distance:
    df.loc[polygon,"distance"]=distance
    df.loc[zipCode,"Total"]=count
    df.loc[zipCode,"Inside"]=insideNum
    df.loc[zipCode,"Outside"]=outsideNum
</code>```

But its giving me the same result in csv. any help is appreciated.

答:
Creating dataframe:

```<code>import pandas as pd
import numpy as np

df= pd.DataFrame({
        'poly':[1000,1100],
        'total':[2,1],
        'inside':[0,0],
        'outside':[2,1],
        'dist':[[16015,5678],[5267]]
        })

df = df[['poly','total','inside','outside','dist']]

df
Out[]:
   poly  total  inside  outside           dist
0  1000      2       0        2  [16015, 5678]
1  1100      1       0        1         [5267]
</code>```

Processing

```<code> new_df = pd.DataFrame({
         col:np.repeat(df[col].values, df['dist'].str.len())
         for col in df.columns.difference(['dist'])
     }).assign(**{'dist':np.concatenate(df['dist'].values)})[df.columns.tolist()]

new_df
Out[]:
   poly  total  inside  outside   dist
0  1000      2       0        2  16015
1  1000      2       0        2   5678
2  1100      1       0        1   5267
</code>```

Title: elements of list in row

Body:
i have few polygons and distance of some points from those polygons. i tried to write in a csv by pandas where distance between each point and polygon will come in separate rows. i got this:

poly total inside outside dist
1000   2     0      2     [16015,5678]
1100   1     0      1     [5267]

I wanted to get like:

poly total inside outside dist
1000   2    0       2     16015
1000   2    0       2     5678
1100   1    0       1     5267

I tried the following after looking at this previous q [How to write nth value of list into csv file

distance =[]
for row in arcpy.da.SearchCursor(outSide, ["SHAPE@XY"]):
            px, py = row[0]
            zipPoint=point(px,py)
            Distance.append(int(zipPoint.calDist(PolyCenter)))
for i in distance:
    df.loc[polygon,"distance"]=distance
    df.loc[zipCode,"Total"]=count
    df.loc[zipCode,"Inside"]=insideNum
    df.loc[zipCode,"Outside"]=outsideNum

But its giving me the same result in csv. any help is appreciated.

Body:
Creating dataframe:

import pandas as pd
import numpy as np

df= pd.DataFrame({
        'poly':[1000,1100],
        'total':[2,1],
        'inside':[0,0],
        'outside':[2,1],
        'dist':[[16015,5678],[5267]]
        })

df = df[['poly','total','inside','outside','dist']]

df
Out[]:
   poly  total  inside  outside           dist
0  1000      2       0        2  [16015, 5678]
1  1100      1       0        1         [5267]

Processing

 new_df = pd.DataFrame({
         col:np.repeat(df[col].values, df['dist'].str.len())
         for col in df.columns.difference(['dist'])
     }).assign(**{'dist':np.concatenate(df['dist'].values)})[df.columns.tolist()]

new_df
Out[]:
   poly  total  inside  outside   dist
0  1000      2       0        2  16015
1  1000      2       0        2   5678
2  1100      1       0        1   5267


问:
Running server for Ionic 2 app on Production
In dev/test environment, Ionic 2 app can be run using 'ionic serve'. However, when I deploy to i.e. Google Play or Apple Store does it need a special service to run the app to be able to fetch data from firebase?

Is it an additional service/hosting I need to purchase or it's taken care by the deployment and will just work when users download my app?

I can't find documentation on this. How does it work?

答:
Yes, You don't need to do any additional things for the firebase backend.B'cose firebase is a cloud-based platform.If you set all the settings properly before publishing it to google paly or Apple store then all will work when someone will install the app.In other words, if an app is working fine on the dev environment then it will work when you'll publish it too.B'cos you're using the same cloud-based firebase environment.

Note:

You can start Firebase for free.But when your app is scaled worldwide to millions of users then you have to pay only for what you use.

You can see Firebase Pricing plan here.


问:
Generate DataContract from XSD
I want to be able to generate a DataContract from a XSD file, preferably using the xsd.exe tool. What is the easiest way for it to auto generate the [DataContract] and [DataMember] on each of my items?

Or is there a better approach? I am trying to avoid having to recreate the data contract each time the XSD file is changed and regenerated.

答:
Use svcutil.exe instead of xsd.exe

How to Use ?
Go to Start Menu --> Microsoft Visual Studio 2008 --> Visual Studio Tools --> Visual Studio 2008 Command Prompt

and Change the directoy you want or change the directory to whre your xsd is there.

```<code>svcutil.exe /help
</code>```

it will list all the options.

one of the option I use to generate data contarct only is

```<code>svcutil.exe /target:code /n:*,[Your Company and Department].Common.DataTransferObjects /dataContractOnly /serializer:auto /importXmlTypes common.xsd /out:common.cs
</code>```

Keep coding hava good day!

Title: Generate DataContract from XSD

Body:
Use svcutil.exe instead of xsd.exe

How to Use ?
Go to Start Menu --> Microsoft Visual Studio 2008 --> Visual Studio Tools --> Visual Studio 2008 Command Prompt

and Change the directoy you want or change the directory to whre your xsd is there.

svcutil.exe /help

it will list all the options.

one of the option I use to generate data contarct only is

svcutil.exe /target:code /n:*,[Your Company and Department].Common.DataTransferObjects /dataContractOnly /serializer:auto /importXmlTypes common.xsd /out:common.cs

Keep coding hava good day!


答:
You can use str.len for get length of lists which are repeated by numpy.repeat with flattening lists and then join original columns:

```<code>from  itertools import chain

s = pd.Series(list(chain.from_iterable(df.dist)),
                   index=np.repeat(df.index.values, df.pop('dist').str.len())).rename('dist')
print (s)
0    16015
0     5678
1     5267
Name: dist, dtype: int64

print (df.join(s).reset_index(drop=True))
   poly  total  inside  outside   dist
0  1000      2       0        2  16015
1  1000      2       0        2   5678
2  1100      1       0        1   5267
</code>```

Another solution with MultiIndex:

```<code>names = ['poly','total', 'inside','outside']
df = df.set_index(names)
mux = pd.MultiIndex.from_tuples(np.repeat(df.index.values, df.dist.str.len()), names=names)
df2 = pd.DataFrame({'dist':list(chain.from_iterable(df.dist))}, index=mux).reset_index()
print (df2)
   poly  total  inside  outside   dist
0  1000      2       0        2  16015
1  1000      2       0        2   5678
2  1100      1       0        1   5267
</code>```

Title: elements of list in row

Body:
You can use str.len for get length of lists which are repeated by numpy.repeat with flattening lists and then join original columns:

from  itertools import chain

s = pd.Series(list(chain.from_iterable(df.dist)),
                   index=np.repeat(df.index.values, df.pop('dist').str.len())).rename('dist')
print (s)
0    16015
0     5678
1     5267
Name: dist, dtype: int64

print (df.join(s).reset_index(drop=True))
   poly  total  inside  outside   dist
0  1000      2       0        2  16015
1  1000      2       0        2   5678
2  1100      1       0        1   5267

Another solution with MultiIndex:

names = ['poly','total', 'inside','outside']
df = df.set_index(names)
mux = pd.MultiIndex.from_tuples(np.repeat(df.index.values, df.dist.str.len()), names=names)
df2 = pd.DataFrame({'dist':list(chain.from_iterable(df.dist))}, index=mux).reset_index()
print (df2)
   poly  total  inside  outside   dist
0  1000      2       0        2  16015
1  1000      2       0        2   5678
2  1100      1       0        1   5267