问:
multiple GPUs keras weird speedup
I did implement a similar code like the multi GPU code from keras
(multiGPU tutorial). When running this on a Server with 2 GPUs I have the following training times per epoch:

showing Keras only one GPU and setting variable gpus = 1 (only use one GPU), one epoch = 32s

showing Keras two GPUs, and gpus = 1, one epoch = 31 s

showing Keras two GPUs, and gpus = 2, one epoch = 37 s

the output looks a bit strange, while initializing the code seems to create multiple Tensorflow devices per GPU, I'm not sure if this is the correct behavior. But the most other examples I saw had just one such line per GPU.

first test (one GPU shown, gpus = 1):

```<code>2017-12-04 14:54:04.071549: I tensorflow/core/common_runtime/gpu/gpu_device.cc:955] Found device 0 with properties:
name: Tesla P100-PCIE-16GB
major: 6 minor: 0 memoryClockRate (GHz) 1.3285
pciBusID 0000:82:00.0
Total memory: 15.93GiB
Free memory: 15.64GiB
2017-12-04 14:54:04.071597: I tensorflow/core/common_runtime/gpu/gpu_device.cc:976] DMA: 0
2017-12-04 14:54:04.071605: I tensorflow/core/common_runtime/gpu/gpu_device.cc:986] 0:   Y
2017-12-04 14:54:04.071619: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
2017-12-04 14:54:21.531654: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
</code>```

second test (2 GPU shown, gpus = 1):

```<code>2017-12-04 14:48:24.881733: I tensorflow/core/common_runtime/gpu/gpu_device.cc:955] Found device 1 with properties:
...(same as earlier)
2017-12-04 14:48:24.882924: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
2017-12-04 14:48:24.882931: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:1) -> (device: 1, name: Tesla P100-PCIE-16GB, pci bus id: 0000:83:00.0)
2017-12-04 14:48:42.353807: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
2017-12-04 14:48:42.353851: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:1) -> (device: 1, name: Tesla P100-PCIE-16GB, pci bus id: 0000:83:00.0)
</code>```

and weirdly for example 3 (gpus = 2):

```<code>2017-12-04 14:41:35.906828: I tensorflow/core/common_runtime/gpu/gpu_device.cc:955] Found device 1 with properties:
...(same as earlier)
2017-12-04 14:41:35.907996: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
2017-12-04 14:41:35.908002: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:1) -> (device: 1, name: Tesla P100-PCIE-16GB, pci bus id: 0000:83:00.0)
2017-12-04 14:41:52.944335: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
2017-12-04 14:41:52.944377: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:1) -> (device: 1, name: Tesla P100-PCIE-16GB, pci bus id: 0000:83:00.0)
2017-12-04 14:41:53.709812: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
2017-12-04 14:41:53.709838: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:1) -> (device: 1, name: Tesla P100-PCIE-16GB, pci bus id: 0000:83:00.0)
</code>```

the code:

LSTM = keras.layers.CuDNNLSTM
model.add(LSTM(knots, input_shape=(timesteps, X_train.shape[-1]), return_sequences=True))
model.add(LSTM(knots))
model.add(Dense(3, activation='softmax'))

if gpus>=2:
    model_basic = model
    with tf.device("/cpu:0"):
        model = model_basic
    parallel_model = multi_gpu_model(model, gpus=gpus)
    model = parallel_model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
hist = model.fit(myParameter)
```

Is this a typical behavior? What is wrong with my code that the multiple devices per GPU are created. Thanks in advance.

答:
I tried the exact code of multiGPU tutorial.
It looks like its somehow the expected output. But to see the expected speed differences I had to increase the number of samples (20000) and needed to height and width to 100 (due to RAM limits).

I'm not completely sure why in my case I didn't see a speedup with two GPU. I expect it to be due to limits of the memory speed. Because my batch size is rather small and each sample is also small. This leads to the effect that the managing of the data needs more time than the actual calculation.
The distribution of the data gets even more time consuming when using 2 GPUs, while the actual runtime on each GPU decreases.
This effect could be proven if I could check the utilization of the graphics cards. Sadly I don't know how to do this.

If anyone has other ideas on this, let me know. Thanks

Title: multiple GPUs keras weird speedup

Body:
I did implement a similar code like the multi GPU code from keras
(multiGPU tutorial). When running this on a Server with 2 GPUs I have the following training times per epoch:

showing Keras only one GPU and setting variable gpus = 1 (only use one GPU), one epoch = 32s

showing Keras two GPUs, and gpus = 1, one epoch = 31 s

showing Keras two GPUs, and gpus = 2, one epoch = 37 s

the output looks a bit strange, while initializing the code seems to create multiple Tensorflow devices per GPU, I'm not sure if this is the correct behavior. But the most other examples I saw had just one such line per GPU.

first test (one GPU shown, gpus = 1):

2017-12-04 14:54:04.071549: I tensorflow/core/common_runtime/gpu/gpu_device.cc:955] Found device 0 with properties:
name: Tesla P100-PCIE-16GB
major: 6 minor: 0 memoryClockRate (GHz) 1.3285
pciBusID 0000:82:00.0
Total memory: 15.93GiB
Free memory: 15.64GiB
2017-12-04 14:54:04.071597: I tensorflow/core/common_runtime/gpu/gpu_device.cc:976] DMA: 0
2017-12-04 14:54:04.071605: I tensorflow/core/common_runtime/gpu/gpu_device.cc:986] 0:   Y
2017-12-04 14:54:04.071619: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
2017-12-04 14:54:21.531654: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)

second test (2 GPU shown, gpus = 1):

2017-12-04 14:48:24.881733: I tensorflow/core/common_runtime/gpu/gpu_device.cc:955] Found device 1 with properties:
...(same as earlier)
2017-12-04 14:48:24.882924: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
2017-12-04 14:48:24.882931: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:1) -> (device: 1, name: Tesla P100-PCIE-16GB, pci bus id: 0000:83:00.0)
2017-12-04 14:48:42.353807: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
2017-12-04 14:48:42.353851: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:1) -> (device: 1, name: Tesla P100-PCIE-16GB, pci bus id: 0000:83:00.0)

and weirdly for example 3 (gpus = 2):

2017-12-04 14:41:35.906828: I tensorflow/core/common_runtime/gpu/gpu_device.cc:955] Found device 1 with properties:
...(same as earlier)
2017-12-04 14:41:35.907996: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
2017-12-04 14:41:35.908002: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:1) -> (device: 1, name: Tesla P100-PCIE-16GB, pci bus id: 0000:83:00.0)
2017-12-04 14:41:52.944335: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
2017-12-04 14:41:52.944377: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:1) -> (device: 1, name: Tesla P100-PCIE-16GB, pci bus id: 0000:83:00.0)
2017-12-04 14:41:53.709812: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:82:00.0)
2017-12-04 14:41:53.709838: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:1) -> (device: 1, name: Tesla P100-PCIE-16GB, pci bus id: 0000:83:00.0)

the code:

LSTM = keras.layers.CuDNNLSTM
model.add(LSTM(knots, input_shape=(timesteps, X_train.shape[-1]), return_sequences=True))
model.add(LSTM(knots))
model.add(Dense(3, activation='softmax'))

if gpus>=2:
    model_basic = model
    with tf.device("/cpu:0"):
        model = model_basic
    parallel_model = multi_gpu_model(model, gpus=gpus)
    model = parallel_model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
hist = model.fit(myParameter)

Is this a typical behavior? What is wrong with my code that the multiple devices per GPU are created. Thanks in advance.


来源: stackexchange

问:
Facebook Page Tab Aplication external link
I have been creating one little facebook page tab for my company and I have encountered on problem.

I need to link to another website

```<code><a href="https://example.ly" class="btn btn-success">Visit my website</a>
</code>```

But facebook wont open linked webside, instead show empty page. Is there some trick how to do this? Some specific tag I need to add somewhere or how to do that?

Thanks

答:
Your page tab app is shown inside an iframe on facebook.com. Likely that other site sends an X-FRAME-OPTIONS header, forbidding the browser to display it in 3rd-party (i)frames.

But presumably you don’t want to display that page inside the iframe to begin with? Then simply add a target="_blank" to the link, to have it open in a new tab.

ContentLicense: CC BY-SA 3.0

Body:
I have been creating one little facebook page tab for my company and I have encountered on problem.

I need to link to another website

Visit my website

But facebook wont open linked webside, instead show empty page. Is there some trick how to do this? Some specific tag I need to add somewhere or how to do that?

Thanks


问:
jquery, to manage the next elements
I am new to jquery and need your help to solve an issue. I am using jQuery Validation plugin to validate my forms. By default what this plugin do is it creates a label with class "errorMessage" if validation happens. Since the input tags do not allow ::before / ::after in CSS therefore to style my form I require some HTML element right after the inputs.

PROBLEM:
The  Plugin pushes down that HTML tag so that it can create its own "error" label right after the input tag.

WHAT IS HAPPENING

```<code><input type="text" name="FirstName" class="inputField required">
<label class="errorMessage">Field is Required</label>
<div class="indicator"></div>
</code>```

WHAT I WANT

```<code><input type="text" name="FirstName" class="inputField required">
<div class="indicator"></div>
<label class="errorMessage">Field is Required</label>
</code>```

To solve this issue i tried some code but it just adds more than one 'indicator class' in different scenarios

MY SCRIPT

```<code>// On Document Ready
// I need this indicator on all inputs by default.
$(".inputField").each(function(i, obj) {
    $(this).after('<div class="indicator"></div>');
});

// On Input Focus Event
$(".inputField").focus(function(){
    if($(this).next().hasClass('errorMessage')) {
        $(this).after('<div class="indicator"></div>');
    }
});
</code>```

RESULTS

```<code><input type="text" name="FirstName" class="inputField required">
<div class="indicator"></div>
<label class="errorMessage">Field is Required</label>
<div class="indicator"></div>
</code>```

How to stop the duplication of the 'indicator div" and if there is a smart way to write this code so that it renders fast.

Any help is highly appreciated, Thanks in advance.

答:
Have you considered using the errorplacement callback?

The below should take the input element containing the validation error - element - and allow you to override where the error notification is created.

```<code>$("#id-of-your-form").validate({
  errorPlacement: function(error, element) {
    error.appendTo(element.next(".indicator"));
  }
});
</code>```

Then you can simply leave your HTML as:

```<code><input type="text" name="FirstName" class="inputField required">
<div class="indicator"></div>
</code>```

Title: jquery, to manage the next elements

Body:
I am new to jquery and need your help to solve an issue. I am using jQuery Validation plugin to validate my forms. By default what this plugin do is it creates a label with class "errorMessage" if validation happens. Since the input tags do not allow ::before / ::after in CSS therefore to style my form I require some HTML element right after the inputs.

PROBLEM:
The  Plugin pushes down that HTML tag so that it can create its own "error" label right after the input tag.

WHAT IS HAPPENING

<input type="text" name="FirstName" class="inputField required">
Field is Required

WHAT I WANT

<input type="text" name="FirstName" class="inputField required">

Field is Required

To solve this issue i tried some code but it just adds more than one 'indicator class' in different scenarios

MY SCRIPT

// On Document Ready
// I need this indicator on all inputs by default.
$(".inputField").each(function(i, obj) {
    $(this).after('

');
});

// On Input Focus Event
$(".inputField").focus(function(){
    if($(this).next().hasClass('errorMessage')) {
        $(this).after('

');
    }
});

RESULTS

<input type="text" name="FirstName" class="inputField required">

Field is Required

How to stop the duplication of the 'indicator div" and if there is a smart way to write this code so that it renders fast.

Any help is highly appreciated, Thanks in advance.

Body:
Have you considered using the errorplacement callback?

The below should take the input element containing the validation error - element - and allow you to override where the error notification is created.

$("#id-of-your-form").validate({
  errorPlacement: function(error, element) {
    error.appendTo(element.next(".indicator"));
  }
});

Then you can simply leave your HTML as:

<input type="text" name="FirstName" class="inputField required">
<div class="indicator"></div>


问:
Horizontal swipe in mobile web view using combination of appium and watir
I am using  combination of appium-android and watir-cucumber in our automation  framework.

In mobile emulator i am opening one site in chrome browser.

I want to do horizontal swipe for one of the slider images.

Let me know if anyone know any idea to swipe image from left to right or vice a versa?

I have tried Appium's touch action but no luck so far.

答:
@Manmohan_singh answer might work but swipe method is deprecated... So you should use TouchScreen

Python code:

```<code>screenSize = driver.get_window_size()
screenWidth = screenSize['width']
screenHeight = screenSize['height']

touchAction = TouchAction(driver)
#Move slider from left to right (finger movement simulation goes from right to left)
touchAction.press(None, screenWidth - (screenWidth/3), y).wait(500).move_to(None, (screenWidth/3), 0).release().perform()
</code>```

Hope it works

Body:
@Manmohan_singh answer might work but swipe method is deprecated... So you should use TouchScreen

Python code:

screenSize = driver.get_window_size()
screenWidth = screenSize['width']
screenHeight = screenSize['height']

touchAction = TouchAction(driver)
#Move slider from left to right (finger movement simulation goes from right to left)
touchAction.press(None, screenWidth - (screenWidth/3), y).wait(500).move_to(None, (screenWidth/3), 0).release().perform()

Hope it works


问:
How to pass a php variable from hidden input value to a php script?
I have this form INSIDE a table :

```<code>while($row=mysqli_fetch_array($result)){
    echo "<tr>";
        echo "<td>".$row['first_name'] . "</td>";
        echo "<td>" . $row['last_name'] . "</td>";
        <td>
            <form action="send_notification.php" method="POST">
                <input type="hidden" name="id" value="<?php echo $row['first_name']; ?>">
                <input type="submit" name="submit" value="request">
            </form>
       </td>
</code>```

Next to each row I have a button called "request" if I click on it I want
to pass the php variable $row['first_name'] to another PHP script .

How can I do that?
I tried to do this in the php file send_notification.php :

```<code><?php
session_start();
require("connect.php");

$id=$_GET['first_name'];

echo $id;
?>
</code>```

But it gave me this error:

Notice: Undefined index: first_name in path/send_notification.php on line 5

UPDATE ONE:

I change $_GET['first_name'] to $_POST['id'] , the output gave no error but it was a blank page. Should't it echo the $id?

答:
You are referring the wrong variable name.

When sending data via POST/GET, the name attribute will be considered as the variable name.

Also your form method is set to POST and you are checking the $_GET array.

Try fetching the value as mentioned below.

```<code>$id = $_POST['id'];
</code>```

Changed code

```<code><?php
session_start();
require("connect.php");

$id = $_POST['id'];

echo $id;

?>
</code>```

Body:
I have this form INSIDE a table :

while($row=mysqli_fetch_array($result)){
    echo "
";
        echo "".$row['first_name'] . "	";
        echo "" . $row['last_name'] . "	";

            <form action="send_notification.php" method="POST">
                <input type="hidden" name="id" value="<?php echo $row['first_name']; ?>">
                <input type="submit" name="submit" value="request">
            </form>

Next to each row I have a button called "request" if I click on it I want
to pass the php variable $row['first_name'] to another PHP script .

How can I do that?
I tried to do this in the php file send_notification.php :

<?php
session_start();
require("connect.php");

$id=$_GET['first_name'];

echo $id;
?>

But it gave me this error:

Notice: Undefined index: first_name in path/send_notification.php on line 5

UPDATE ONE:

I change $_GET['first_name'] to $_POST['id'] , the output gave no error but it was a blank page. Should't it echo the $id?

Body:
You are referring the wrong variable name.

When sending data via POST/GET, the name attribute will be considered as the variable name.

Also your form method is set to POST and you are checking the $_GET array.

Try fetching the value as mentioned below.

$id = $_POST['id'];

Changed code

<?php
session_start();
require("connect.php");

$id = $_POST['id'];

echo $id;

?>


问:
Problems with <select> filter
i coded an select filter for my website:

             Filter

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

                <select class="event-type-select" id="selection" >
                    <optgroup label="categorygroup1">
                        <option value="category1">category1</option>
                    </optgroup>
                    <optgroup label="categorygroup2">
                        <option value="category2">category2n</option>
                        <option value="category3">category3</option>
                    </optgroup>
                    <optgroup label="categorygroup3">
                        <option value="category4">category4</option>
                    </optgroup>
                </select>

        </div>

        <div class="row">

            <button type="submit" class="btn btn-default"> filter </button>

        </div>
    </form>
</code>```

before selecting anything in the "selection-window" on the website you read "category1". i guess thats default(?).

but if i selected a category (and that works: you can read in the "selection-window" e.g. category3) and then click on the "filter"-button the website refreshes but in the "selection-window" you again read "category1" and not the selected category e.g "category3". i guess the selection doesn't work right.

how can i solve this that when clicking the button you still read your selected category?

also i want to display the selected option on a different part of the website.

my current code for this:

```<code>    <script type='text/javascript'>
        var m = document.getElementById("selection").value;}
        document.write(m);

    </script>
</code>```

that as well doesn't work.

i hope you can understand what i mean, my english is pretty bad. sorry for that.

答:
First, the question essentially contains 2 questions packed into one, don't do that.

Second, you are simply missing the preselection of the <select> field.

the selection doesn't work

When submitting a form the values are sent to the server. The server processes the values and renders the page again. Therefore you have to adjust the rendering according to the selected value. Lets say you simply pass the selected value to the view as string the view code could look like this:

```<code>@model string

...

<select class="event-type-select" id="selection" >
    <optgroup label="categorygroup1">
        <option value="category1" @if (Model == "category1") {<text>selected</text>}>category1</option>
    </optgroup>
    <optgroup label="categorygroup2">
        <option value="category2" @if (Model == "category2") {<text>selected</text>}>category2n</option>

    ...
</select>
</code>```

also i want to display the selected option on a different part of the website.

Then store the selection somewhere (e.g. a DB), retrieve the selected value before the different part  is rendered and simply output it in the different part.

Title: Problems with <select> filter

Body:
i coded an select filter for my website:

             Filter

                <select class="event-type-select" id="selection" >
                    <optgroup label="categorygroup1">
                        <option value="category1">category1</option>
                    </optgroup>
                    <optgroup label="categorygroup2">
                        <option value="category2">category2n</option>
                        <option value="category3">category3</option>
                    </optgroup>
                    <optgroup label="categorygroup3">
                        <option value="category4">category4</option>
                    </optgroup>
                </select>

            <button type="submit" class="btn btn-default"> filter </button>

    </form>

before selecting anything in the "selection-window" on the website you read "category1". i guess thats default(?).

but if i selected a category (and that works: you can read in the "selection-window" e.g. category3) and then click on the "filter"-button the website refreshes but in the "selection-window" you again read "category1" and not the selected category e.g "category3". i guess the selection doesn't work right.

how can i solve this that when clicking the button you still read your selected category?

also i want to display the selected option on a different part of the website.

my current code for this:

that as well doesn't work.

i hope you can understand what i mean, my english is pretty bad. sorry for that.

Body:
First, the question essentially contains 2 questions packed into one, don't do that.

Second, you are simply missing the preselection of the <select> field.

the selection doesn't work

When submitting a form the values are sent to the server. The server processes the values and renders the page again. Therefore you have to adjust the rendering according to the selected value. Lets say you simply pass the selected value to the view as string the view code could look like this:

@model string

...

<select class="event-type-select" id="selection" >
    <optgroup label="categorygroup1">
        <option value="category1" @if (Model == "category1") {<text>selected</text>}>category1</option>
    </optgroup>
    <optgroup label="categorygroup2">
        <option value="category2" @if (Model == "category2") {<text>selected</text>}>category2n</option>

    ...
</select>

also i want to display the selected option on a different part of the website.

Then store the selection somewhere (e.g. a DB), retrieve the selected value before the different part  is rendered and simply output it in the different part.


问:
Spring Boot - Hibernate - Import Date from SQL Query
I am currently building a REST API with Spring Data (and Boot).
I have a sql Dumb from an h2database, which is accessed by hibernate.

My Application.yaml:

```<code>spring:
  profiles: "dev"
  datasource:
      data: classpath:/data_api.sql
  jpa:
    hibernate:
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
      ddl-auto: create-drop
</code>```

The sql query lools like this:

```<code>Insert into TABLE (name, number, date) values ("James", 123, to_date('28-JUL-17','DD-MON-RR'))
</code>```

Information.java looks like:

```<code>@Entity
@Table(name="TABLE")
@Data
public class Information {

    @Column(name="name")
    String name;

    @Column(name="number")
    Integer number;

    @Column(name="date")
    String date;
</code>```

When I try to run the API I got the following exception:
enter image description here

Caused by: org.h2.jdbc.JdbcSQLException: Function "TO_DATE": Invalid
  date format: " Tried to parse one of '[Jul, Feb, Apr, Jun, Aug, Mai,
  Nov, Jan, Dez, Okt, M├ñr, Sep]' but failed (may be an internal
  error?). Details:
      TO_DATE('16-MAR-17', 'DD-MON-RR')
                  ^      ,     ^ <-- Parsing failed at this point"; SQL statement

My guess is that hibernate takes some locale where the months are configured in german - does anybody know how to change that?
Another way would be to tell hibernate --> ignore the sql function to_date() and just read the field as string. I tried something like writing @org.hibernate.annotations.Type(type =“text“) over the @column annotation - but it doesn't work :(

EDIT: When changing the Monthname in the import queries to german --> like OCT --> OKT ; DEC --> DEZ.. it works. So it seems that Hibernate is using my local language settings for mapping. Is there a way to change this to english?

答:
If anybody else comes to this problem - I figuered it out. Hibernate reads the Locate settings. So with a simple code line in the Main Application this is done: </p>

```<code>Locale.setDefault(new Locale("en", "US"));
</code>```

Body:
I am currently building a REST API with Spring Data (and Boot).
I have a sql Dumb from an h2database, which is accessed by hibernate.

My Application.yaml:

spring:
  profiles: "dev"
  datasource:
      data: classpath:/data_api.sql
  jpa:
    hibernate:
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
      ddl-auto: create-drop

The sql query lools like this:

Insert into TABLE (name, number, date) values ("James", 123, to_date('28-JUL-17','DD-MON-RR'))

Information.java looks like:

@Entity
@Table(name="TABLE")
@Data
public class Information {

    @Column(name="name")
    String name;

    @Column(name="number")
    Integer number;

    @Column(name="date")
    String date;

When I try to run the API I got the following exception:
enter image description here

Caused by: org.h2.jdbc.JdbcSQLException: Function "TO_DATE": Invalid
  date format: " Tried to parse one of '[Jul, Feb, Apr, Jun, Aug, Mai,
  Nov, Jan, Dez, Okt, M├ñr, Sep]' but failed (may be an internal
  error?). Details:
      TO_DATE('16-MAR-17', 'DD-MON-RR')
                  ^      ,     ^ <-- Parsing failed at this point"; SQL statement

My guess is that hibernate takes some locale where the months are configured in german - does anybody know how to change that?
Another way would be to tell hibernate --> ignore the sql function to_date() and just read the field as string. I tried something like writing @org.hibernate.annotations.Type(type =“text“) over the @column annotation - but it doesn't work :(

EDIT: When changing the Monthname in the import queries to german --> like OCT --> OKT ; DEC --> DEZ.. it works. So it seems that Hibernate is using my local language settings for mapping. Is there a way to change this to english?

Body:
If anybody else comes to this problem - I figuered it out. Hibernate reads the Locate settings. So with a simple code line in the Main Application this is done:

Locale.setDefault(new Locale("en", "US"));


问:
Support with Logic Gate Simulation program in Python
I'm trying to create a logic gate simulation program in python so that a user can choose the type of logic gate they want to simulate. Once chosen, they can then enter the inputs and the program should return the value of the output from the chosen logic gate to the user.

This is what I have so far:

```<code>print ("Logic Gate Simulation")

def AND (a,b):

    if a == 1 and b == 1:
        return 1
    else:
        return 0

def NAND (a,b):
    if a == 1 and b == 1:
        return 0
    else:
        return 1

def OR(a,b):
    if a == 1:
        return 1
    elif b == 1:
        return 1
    else:
        return 0

def NOR (a,b):
    if a != b:
        return 1
    else:
        return 1

def Main():
    question = input("what type of gate do you want to simulate - OR, AND  or NAND?  ")

    if question == 'AND':
        a = input("enter value for input 1")
        b = input("enter value for input 2")
        x= AND(a,b)
        print (x)

    else:
        print ("")
Main()
</code>```

When I run the program and enter AND, inputs 1 and 1 it still returns 0 and I cant see why.

答:
This is my version of the code (I had to this for homework for AS Level, this may help you!) :</p>

```<code>print("Logic Gate Calculator")

def AND(a, b):  # AND Gate
    a = int(a)
    b = int(b)
    if a == 1 and b == 1:  # AND Gate logic
        return 1
    else:
        return 0

def NAND(a, b):  # NAND Gate
    a = int(a)
    b = int(b)
    if a == 1 and b == 1:  # NAND Gate logic
        return 0
    elif a == 1 and b == 0:
        return 0
    elif a == 0 and b == 1:
        return 0
    else:
        return 1

def OR(a, b):  # OR Gate
    a = int(a)
    b = int(b)
    if a == 1:  # OR Gate Logic
        return 1
    elif b == 1:
        return 1
    else:
        return 0

def NOR(a, b):  # NOR Gate
    a = int(a)
    b = int(b)
    if a == 1 and b == 0:  # NOR Gate Logic
        return 1
    elif a == 0 and b == 1:
        return 1
    elif a == 0 and b == 0:
        return 1
    else:
        return 0

def XOR(a, b):  # XOR Gate
    a = int(a)
    b = int(b)
    if a == 1 and b == 0:  # XOR Gate Logic
        return 1
    elif a == 1 and b == 1:
        return 1
    else:
        return 0

def main():  # The main program
    run = True
    while run:  # While loop
        question = input("What type of gate do you want to use OR, AND, NOR, or NAND or (Q)uit")  # Logic Gate chooser
        if question == "AND" or question == "and" or question == "And":  # If the user selects AND
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = AND(a, b)  # Calling the AND Function
            print("The output will be:", x)  # Output result
        elif question == "OR" or question == "or" or question == "Or":  # If the user selects OR
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = OR(a, b)  # Calling the OR Function
            print("The output will be:", x)  # Output result
        elif question == "NOR" or question == "nor" or question == "Nor":  # If the user selects NOR
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = NOR(a, b)  # Calling the NOR function
            print("The output will be:", x)  # Output result
        elif question == "NAND" or question == "nand" or question == "Nand":  # If the user selects NAND
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = NAND(a, b)  # Calling the NAND function
            print("The output will be:", x)  # Output result
        elif question == "XOR" or question == "xor" or question == "Xor":  # If the user selects XOR
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = XOR(a, b)  # Calling the XOR function
            print("The output will be:", x)  # Output result
        elif question == "Q" or question == "q":  # Quiting the program
            run = False
        else:
            print("Please enter one of the shown logic gates")  # Error handling

main()
</code>```

Body:
I'm trying to create a logic gate simulation program in python so that a user can choose the type of logic gate they want to simulate. Once chosen, they can then enter the inputs and the program should return the value of the output from the chosen logic gate to the user.

This is what I have so far:

print ("Logic Gate Simulation")

def AND (a,b):

    if a == 1 and b == 1:
        return 1
    else:
        return 0

def NAND (a,b):
    if a == 1 and b == 1:
        return 0
    else:
        return 1

def OR(a,b):
    if a == 1:
        return 1
    elif b == 1:
        return 1
    else:
        return 0

def NOR (a,b):
    if a != b:
        return 1
    else:
        return 1

def Main():
    question = input("what type of gate do you want to simulate - OR, AND  or NAND?  ")

    if question == 'AND':
        a = input("enter value for input 1")
        b = input("enter value for input 2")
        x= AND(a,b)
        print (x)

    else:
        print ("")
Main()

When I run the program and enter AND, inputs 1 and 1 it still returns 0 and I cant see why.

Body:
This is my version of the code (I had to this for homework for AS Level, this may help you!) :

print("Logic Gate Calculator")

def AND(a, b):  # AND Gate
    a = int(a)
    b = int(b)
    if a == 1 and b == 1:  # AND Gate logic
        return 1
    else:
        return 0

def NAND(a, b):  # NAND Gate
    a = int(a)
    b = int(b)
    if a == 1 and b == 1:  # NAND Gate logic
        return 0
    elif a == 1 and b == 0:
        return 0
    elif a == 0 and b == 1:
        return 0
    else:
        return 1

def OR(a, b):  # OR Gate
    a = int(a)
    b = int(b)
    if a == 1:  # OR Gate Logic
        return 1
    elif b == 1:
        return 1
    else:
        return 0

def NOR(a, b):  # NOR Gate
    a = int(a)
    b = int(b)
    if a == 1 and b == 0:  # NOR Gate Logic
        return 1
    elif a == 0 and b == 1:
        return 1
    elif a == 0 and b == 0:
        return 1
    else:
        return 0

def XOR(a, b):  # XOR Gate
    a = int(a)
    b = int(b)
    if a == 1 and b == 0:  # XOR Gate Logic
        return 1
    elif a == 1 and b == 1:
        return 1
    else:
        return 0

def main():  # The main program
    run = True
    while run:  # While loop
        question = input("What type of gate do you want to use OR, AND, NOR, or NAND or (Q)uit")  # Logic Gate chooser
        if question == "AND" or question == "and" or question == "And":  # If the user selects AND
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = AND(a, b)  # Calling the AND Function
            print("The output will be:", x)  # Output result
        elif question == "OR" or question == "or" or question == "Or":  # If the user selects OR
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = OR(a, b)  # Calling the OR Function
            print("The output will be:", x)  # Output result
        elif question == "NOR" or question == "nor" or question == "Nor":  # If the user selects NOR
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = NOR(a, b)  # Calling the NOR function
            print("The output will be:", x)  # Output result
        elif question == "NAND" or question == "nand" or question == "Nand":  # If the user selects NAND
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = NAND(a, b)  # Calling the NAND function
            print("The output will be:", x)  # Output result
        elif question == "XOR" or question == "xor" or question == "Xor":  # If the user selects XOR
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = XOR(a, b)  # Calling the XOR function
            print("The output will be:", x)  # Output result
        elif question == "Q" or question == "q":  # Quiting the program
            run = False
        else:
            print("Please enter one of the shown logic gates")  # Error handling

main()


问:
Multiple models in a view
I want to have 2 models in one view. The page contains both LoginViewModel and RegisterViewModel.

e.g.

```<code>public class LoginViewModel
{
    public string Email { get; set; }
    public string Password { get; set; }
}

public class RegisterViewModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}
</code>```

Do I need to make another ViewModel which holds these 2 ViewModels?

```<code>public BigViewModel
{
    public LoginViewModel LoginViewModel{get; set;}
    public RegisterViewModel RegisterViewModel {get; set;}
}
</code>```

I need the validation attributes to be brought forward to the view. This is why I need the ViewModels.

Isn't there another way such as (without the BigViewModel):

```<code> @model ViewModel.RegisterViewModel
 @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
 {
        @Html.TextBoxFor(model => model.Name)
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
 }

 @model ViewModel.LoginViewModel
 @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
 {
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
 }
</code>```

答:
There are lots of ways...

with your BigViewModel
you do:

```<code>@model BigViewModel
@using(Html.BeginForm()) {
    @Html.EditorFor(o => o.LoginViewModel.Email)
    ...
}
</code>```

you can create 2 additional views

Login.cshtml

```<code>@model ViewModel.LoginViewModel
@using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.Email)
    @Html.PasswordFor(model => model.Password)
}
</code>```

and register.cshtml same thing

after creation you have to render them in the main view and pass them the viewmodel/viewdata

so it could be like this:

```<code>@{Html.RenderPartial("login", ViewBag.Login);}
@{Html.RenderPartial("register", ViewBag.Register);}
</code>```

or

```<code>@{Html.RenderPartial("login", Model.LoginViewModel)}
@{Html.RenderPartial("register", Model.RegisterViewModel)}
</code>```

using ajax parts of your web-site become more independent

iframes, but probably this is not the case

ContentLicense: CC BY-SA 4.0

Title: Multiple models in a view

Body:
I want to have 2 models in one view. The page contains both LoginViewModel and RegisterViewModel.

e.g.

public class LoginViewModel
{
    public string Email { get; set; }
    public string Password { get; set; }
}

public class RegisterViewModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

Do I need to make another ViewModel which holds these 2 ViewModels?

public BigViewModel
{
    public LoginViewModel LoginViewModel{get; set;}
    public RegisterViewModel RegisterViewModel {get; set;}
}

I need the validation attributes to be brought forward to the view. This is why I need the ViewModels.

Isn't there another way such as (without the BigViewModel):

 @model ViewModel.RegisterViewModel
 @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
 {
        @Html.TextBoxFor(model => model.Name)
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
 }

 @model ViewModel.LoginViewModel
 @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
 {
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
 }

Body:
There are lots of ways...

with your BigViewModel
you do:

@model BigViewModel
@using(Html.BeginForm()) {
    @Html.EditorFor(o => o.LoginViewModel.Email)
    ...
}

you can create 2 additional views

Login.cshtml

@model ViewModel.LoginViewModel
@using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.Email)
    @Html.PasswordFor(model => model.Password)
}

and register.cshtml same thing

after creation you have to render them in the main view and pass them the viewmodel/viewdata

so it could be like this:

@{Html.RenderPartial("login", ViewBag.Login);}
@{Html.RenderPartial("register", ViewBag.Register);}

or

@{Html.RenderPartial("login", Model.LoginViewModel)}
@{Html.RenderPartial("register", Model.RegisterViewModel)}

using ajax parts of your web-site become more independent

iframes, but probably this is not the case


问:
Extract Value from XML having same tag name in SQL Server
I have XML variable defined below and its value.

I want to fetch the text defined between tag <TextNodeChild> in single query.

Kindly help.

```<code>Declare @XMLVariable =
'<?xml version="1.0"?>
 <root>
     <TextNodeParent>
         <TextNodeChild>12345</TextNodeChild>
         <TextNodeChild>67890</TextNodeChild>
         <TextNodeChild>12389</TextNodeChild>
     </TextNodeParent>
 </root>'
</code>```

I need output like this:

```<code>12345
67890
12389
</code>```

答:
@YogeshSharma's solution works - here - because you have nothing but <TextNodeChild> elements under your <TextNodeParent> node.

However, if you had various node, and you wanted to extract only the <TextNodeChild> ones and get their values (and ignore all others), you'd have to use something like this instead:

```<code>SELECT
    TextNodeParent = XC.value('.', 'INT')
FROM
    @XMLVariable.nodes('root/TextNodeParent/TextNodeChild') as XT(XC)
</code>```

Body:
I have XML variable defined below and its value.

I want to fetch the text defined between tag <TextNodeChild> in single query.

Kindly help.

Declare @XMLVariable =
'<?xml version="1.0"?>
 <root>
     <TextNodeParent>
         <TextNodeChild>12345</TextNodeChild>
         <TextNodeChild>67890</TextNodeChild>
         <TextNodeChild>12389</TextNodeChild>
     </TextNodeParent>
 </root>'

I need output like this:

12345
67890
12389

Body:
@YogeshSharma's solution works - here - because you have nothing but <TextNodeChild> elements under your <TextNodeParent> node.

However, if you had various node, and you wanted to extract only the <TextNodeChild> ones and get their values (and ignore all others), you'd have to use something like this instead:

SELECT
    TextNodeParent = XC.value('.', 'INT')
FROM
    @XMLVariable.nodes('root/TextNodeParent/TextNodeChild') as XT(XC)


问:
Python regex library can't match even though it should
My script:

```<code>#!/usr/bin/env python
import os
import re

def grep(filepath, regex):
    regObj = re.compile(regex)
    res = []
    with open(filepath) as f:
        for line in f:
            if regObj.match(line):
                res.append(line)
    return res

print(grep('/opt/conf/streaming.cfg', 'Port='))
</code>```

Supposed to loop through the lines in the file given and match the regex provided, if exists, append to res and eventually return res.

The content of /opt/conf/streaming.cfg contains a line:

```<code>SocketAcceptPort=8003
</code>```

Still prints []

How come?

答:
If you're looking for a list of ports, could you not use a string comparison instead:

```<code>#!/usr/bin/env python
import os
import re

def grep(filepath, substring):
    res = []
    with open(filepath) as f:
        for line in f:
            if substring in line:
                res.append(line.rsplit("\n")[0])
    return res

print(grep('/opt/conf/streaming.cfg', 'Port='))
</code>```

giving the result:

```<code>['SocketAcceptPort=8003']
</code>```

Body:
My script:

#!/usr/bin/env python
import os
import re

def grep(filepath, regex):
    regObj = re.compile(regex)
    res = []
    with open(filepath) as f:
        for line in f:
            if regObj.match(line):
                res.append(line)
    return res

print(grep('/opt/conf/streaming.cfg', 'Port='))

Supposed to loop through the lines in the file given and match the regex provided, if exists, append to res and eventually return res.

The content of /opt/conf/streaming.cfg contains a line:

SocketAcceptPort=8003

Still prints []

How come?

Body:
If you're looking for a list of ports, could you not use a string comparison instead:

#!/usr/bin/env python
import os
import re

def grep(filepath, substring):
    res = []
    with open(filepath) as f:
        for line in f:
            if substring in line:
                res.append(line.rsplit("\n")[0])
    return res

print(grep('/opt/conf/streaming.cfg', 'Port='))

giving the result:

['SocketAcceptPort=8003']


问:
Do I need to free in BinaryTree the root or the data?
I have a question... If I have a Binarytree like this:

```<code>typedef struct
{
   char* text;
   char* line;
   struct Node* left;
   struct Node* right;
}Node
</code>```

and have a start function:

```<code>Node *start(Node* ptr)
{
if(ptr == NULL)
{
 ptr = (Node*)malloc(sizeof(Node));
    ptr->text = "some text";
    ptr->line = "another text";
    ptr->left = NULL;
    ptr->right = NULL;
}
return (ptr);
}
</code>```

And a funtion to add left child in binarytree, if root is not empty and here I must give my text and line dynamic memory.

```<code>  Node* addNode(Node* ptr)
  {
    if(ptr != NULL)
    {
    Node* leftNode = (Node*)malloc(sizeof(zeiger));
    char* text = (char*) malloc(100*sizeof(char));
    char* line = (char*) malloc(100*sizeof(char));

    line = "some text 2";
    text = "another text";
    if(leftNode !=NULL)
    {
        leftNode->text = text;
        leftNode->line = line;
        leftNode->right = NULL;
        ptr->left = leftNode;
    }
    return leftNode;
}
return ptr;
</code>```

}

Now the problem ist I want to free everything in tree so I have a a function like this to call himself if left or right or root is not NULL. So i saw some codes that I should free the root and not the datas.

```<code>void freeTree(Node* root)
{
  while(1)
  {
   if(root == NULL)
  {
  break;
}
else if (root->left != NULL)
{
  freeTree(root->left);
  root->left = NULL;
}
else if (root->right) {
        freeTree(root->right);
  root->right = NULL;
}
else
  {
  free(root);
  }
 }
}
</code>```

Main.c

```<code>int main(int argc, char const *argv[]) {

Node* root = NULL;
root = start(root);
root = addNode(root);
freeTree(root);
return 0;
}
</code>```

答:
You shouldn't free memory that you didn't malloc.

Here the first node's pointers are pointing to a string literal. You shouldn't call free() on them.

You should allocate memory in the initial node also and then try to copy that string literal. Now every node is similar.

Now you free the memory of each node. Which node to do first? The post order traversal would be the one. First the children, then the parent will should be freed, otherwise you will have memory leak.

```<code>void freeTree(Node *root){
   if( root ){
     freeTree(root->left);
     freeTree(root->right);
     free(root->text); // root->text was allocated calling malloc
     free(root->line); // same for root->line
     free(root);
   }
}
</code>```

root->text was allocated calling malloc - You have to allocate dynamically to be able to call free on it. In your code the initial node's text is pointing to a string literal. You need to do it proper way as mentioned in answer - (allocate - and copy the string into newly allocated memory).

Body:
I have a question... If I have a Binarytree like this:

typedef struct
{
   char* text;
   char* line;
   struct Node* left;
   struct Node* right;
}Node

and have a start function:

Node *start(Node* ptr)
{
if(ptr == NULL)
{
 ptr = (Node*)malloc(sizeof(Node));
    ptr->text = "some text";
    ptr->line = "another text";
    ptr->left = NULL;
    ptr->right = NULL;
}
return (ptr);
}

And a funtion to add left child in binarytree, if root is not empty and here I must give my text and line dynamic memory.

  Node* addNode(Node* ptr)
  {
    if(ptr != NULL)
    {
    Node* leftNode = (Node*)malloc(sizeof(zeiger));
    char* text = (char*) malloc(100*sizeof(char));
    char* line = (char*) malloc(100*sizeof(char));

    line = "some text 2";
    text = "another text";
    if(leftNode !=NULL)
    {
        leftNode->text = text;
        leftNode->line = line;
        leftNode->right = NULL;
        ptr->left = leftNode;
    }
    return leftNode;
}
return ptr;

}

Now the problem ist I want to free everything in tree so I have a a function like this to call himself if left or right or root is not NULL. So i saw some codes that I should free the root and not the datas.

void freeTree(Node* root)
{
  while(1)
  {
   if(root == NULL)
  {
  break;
}
else if (root->left != NULL)
{
  freeTree(root->left);
  root->left = NULL;
}
else if (root->right) {
        freeTree(root->right);
  root->right = NULL;
}
else
  {
  free(root);
  }
 }
}

Main.c

int main(int argc, char const *argv[]) {

Node* root = NULL;
root = start(root);
root = addNode(root);
freeTree(root);
return 0;
}

Body:
You shouldn't free memory that you didn't malloc.

Here the first node's pointers are pointing to a string literal. You shouldn't call free() on them.

You should allocate memory in the initial node also and then try to copy that string literal. Now every node is similar.

Now you free the memory of each node. Which node to do first? The post order traversal would be the one. First the children, then the parent will should be freed, otherwise you will have memory leak.

void freeTree(Node *root){
   if( root ){
     freeTree(root->left);
     freeTree(root->right);
     free(root->text); // root->text was allocated calling malloc
     free(root->line); // same for root->line
     free(root);
   }
}

root->text was allocated calling malloc - You have to allocate dynamically to be able to call free on it. In your code the initial node's text is pointing to a string literal. You need to do it proper way as mentioned in answer - (allocate - and copy the string into newly allocated memory).


问:
Python - Getting a new print of progressbar every update

I am completely new to Python and would like to display a progress bar while copying data from one database to another (MongoDB). What I am trying to get is a single progressbar displaying the advancement (percentage) of the copy of a database to another. The copy is working just fine, the problem lies within the update of my progressbar, which gets reprinted every loop.

Here is the script :

```<code>    coll_names = db_in.collection_names()
    db_in_size = db_in.command('dbstats')['dataSize']

    bar = progressbar.ProgressBar(max_value=db_in_size).start()
    for X in X_list:
        for coll in coll_names:
          db_out_size = db_out.command('dbstats')['dataSize']
          bar.update(db_out_size)
          db_out[coll].delete_many({'X': X})
          data_in = db_in[coll].find({'X': X})
          if data_in.count() > 0:
                db_out[coll].insert_many(data_in)
    bar.finish()
</code>```

X_list contains strings.

This code is certainly not optimized nor formatted the right way to display a single progressbar, but please bear with me.

Expected result : Single progressbar on one line

Current result : One progressbar print for every iteration

Current result : tqdm

Thanks in advance for any input you may have.

答: Progress bars work by printing a "\r" character (a carriage return) which moves the cursor back to the start of the line. This works as long as the cursor stays on the current line. What is probably happening here is you are printing a newline to stderr somewhere else in the code. This essentially means the carriage return has no effect. Or maybe you are using a terminal which doesn't support carriage returns (some IDEs apparently).</p>

Body:
I am completely new to Python and would like to display a progress bar while copying data from one database to another (MongoDB). What I am trying to get is a single progressbar displaying the advancement (percentage) of the copy of a database to another. The copy is working just fine, the problem lies within the update of my progressbar, which gets reprinted every loop.

Here is the script :

    coll_names = db_in.collection_names()
    db_in_size = db_in.command('dbstats')['dataSize']

    bar = progressbar.ProgressBar(max_value=db_in_size).start()
    for X in X_list:
        for coll in coll_names:
          db_out_size = db_out.command('dbstats')['dataSize']
          bar.update(db_out_size)
          db_out[coll].delete_many({'X': X})
          data_in = db_in[coll].find({'X': X})
          if data_in.count() > 0:
                db_out[coll].insert_many(data_in)
    bar.finish()

X_list contains strings.

This code is certainly not optimized nor formatted the right way to display a single progressbar, but please bear with me.

Expected result : Single progressbar on one line

Current result : One progressbar print for every iteration

Current result : tqdm

Thanks in advance for any input you may have.


问:
Copy values and format in VBA macro excel
I am quite new to this stuff i.e. writing macros in excel. I need to modify a macro where content is copied from 1 sheet to another but here only values are being copied whereas I would like to copy cell formatting as well. I have searched on a number of forums and tried to copy their formats but still no luck. May be I missing out something in my code.

strActiveSheet - Sheet from which content is copied

res - Sheet on which content is being pasted

```<code>With Sheets(strActiveSheet)
    .Select
    .Range(.Cells(DataStartRow - 1, 1), .Cells(DataStartRow - 1, 4)).Select
    Selection.Copy
    End With

'Paste
 Sheets(res).Select
 Cells(9, 1).Select
 Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
</code>```

This code just copies the value. I have tried to use the following code but to no avail:

```<code>Sheets(res).Select
     Cells(9, 1).Select
     Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    .PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
</code>```

If I use the following code, this will just copy the formatting but omit the values:

```<code>Sheets(res).Select
         Cells(9, 1).Select
         Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
</code>```

May be I think I am not writing PasteSpecial code in correct format.

Can someone please help me to get the correct format for copying and pasting values as well as cell format from one sheet to another in VBA ?

Darren - I have edited my code and used as you have specified in your answer:

```<code>Dim wrkSht As Worksheet
Set wrkSht = ThisWorkbook.Worksheets("Sheet1")

Dim resSheet As Worksheet
Set resSheet = ThisWorkbook.Worksheets("Demo")

With wrkSht
    .Range(.Cells(DataStartRow - 1, 1), .Cells(DataStartRow - 1, 4)).Copy
End With

With resSheet
    .Cells(9, 1).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    .Cells(9, 1).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End With
</code>```

But still it is giving number as the format to my cells instead of the custom one that is assigned to cell in Sheet1.

Can you please help if I am missing out something in this code ?

答:
If you want to copy everything you can copy and paste to the destination in the same command.

```<code>Sub Test()

    Dim DataStartRow As Long
    DataStartRow = 2

    Dim wrkSht As Worksheet
    Set wrkSht = ThisWorkbook.Worksheets("Sheet1")

    Dim res As Worksheet
    Set res = ThisWorkbook.Worksheets("Sheet2")

    With wrkSht
        .Range(.Cells(DataStartRow - 1, 1), .Cells(DataStartRow - 1, 4)).Copy Destination:=res.Cells(9, 1)
    End With

'    Copy user selection
'    Selection.Copy Destination:=res.Cells(9, 1)

'    Paste to user selection
'    With wrkSht
'        .Range(.Cells(DataStartRow - 1, 1), .Cells(DataStartRow - 1, 4)).Copy Destination:=Selection
'    End With

End Sub
</code>```

If you only want the values and cell formatting then you can use two PasteSpecial commands:

```<code>Sub Test()

    Dim DataStartRow As Long
    DataStartRow = 2

    Dim wrkSht As Worksheet
    Set wrkSht = ThisWorkbook.Worksheets("Sheet1")

    Dim res As Worksheet
    Set res = ThisWorkbook.Worksheets("Sheet2")

    With wrkSht
        .Range(.Cells(DataStartRow - 1, 1), .Cells(DataStartRow - 1, 4)).Copy
    End With

    With res
        .Cells(9, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
        .Cells(9, 1).PasteSpecial Paste:=xlPasteFormats
    End With

'    Copy user selection
'    Selection.Copy

'    Paste to user selection
'    With Selection
'        .PasteSpecial Paste:=xlPasteValuesAndNumberFormats
'        .PasteSpecial Paste:=xlPasteFormats
'    End With

End Sub
</code>```

Note:  I haven't selected any cells in the code. You just have to reference them.

Body:
I am quite new to this stuff i.e. writing macros in excel. I need to modify a macro where content is copied from 1 sheet to another but here only values are being copied whereas I would like to copy cell formatting as well. I have searched on a number of forums and tried to copy their formats but still no luck. May be I missing out something in my code.

strActiveSheet - Sheet from which content is copied

res - Sheet on which content is being pasted

With Sheets(strActiveSheet)
    .Select
    .Range(.Cells(DataStartRow - 1, 1), .Cells(DataStartRow - 1, 4)).Select
    Selection.Copy
    End With

'Paste
 Sheets(res).Select
 Cells(9, 1).Select
 Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

This code just copies the value. I have tried to use the following code but to no avail:

Sheets(res).Select
     Cells(9, 1).Select
     Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    .PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

If I use the following code, this will just copy the formatting but omit the values:

Sheets(res).Select
         Cells(9, 1).Select
         Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

May be I think I am not writing PasteSpecial code in correct format.

Can someone please help me to get the correct format for copying and pasting values as well as cell format from one sheet to another in VBA ?

Darren - I have edited my code and used as you have specified in your answer:

Dim wrkSht As Worksheet
Set wrkSht = ThisWorkbook.Worksheets("Sheet1")

Dim resSheet As Worksheet
Set resSheet = ThisWorkbook.Worksheets("Demo")

With wrkSht
    .Range(.Cells(DataStartRow - 1, 1), .Cells(DataStartRow - 1, 4)).Copy
End With

With resSheet
    .Cells(9, 1).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    .Cells(9, 1).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End With

But still it is giving number as the format to my cells instead of the custom one that is assigned to cell in Sheet1.

Can you please help if I am missing out something in this code ?

Body:
If you want to copy everything you can copy and paste to the destination in the same command.

Sub Test()

    Dim DataStartRow As Long
    DataStartRow = 2

    Dim wrkSht As Worksheet
    Set wrkSht = ThisWorkbook.Worksheets("Sheet1")

    Dim res As Worksheet
    Set res = ThisWorkbook.Worksheets("Sheet2")

    With wrkSht
        .Range(.Cells(DataStartRow - 1, 1), .Cells(DataStartRow - 1, 4)).Copy Destination:=res.Cells(9, 1)
    End With

'    Copy user selection
'    Selection.Copy Destination:=res.Cells(9, 1)

'    Paste to user selection
'    With wrkSht
'        .Range(.Cells(DataStartRow - 1, 1), .Cells(DataStartRow - 1, 4)).Copy Destination:=Selection
'    End With

End Sub

If you only want the values and cell formatting then you can use two PasteSpecial commands:

Sub Test()

    Dim DataStartRow As Long
    DataStartRow = 2

    Dim wrkSht As Worksheet
    Set wrkSht = ThisWorkbook.Worksheets("Sheet1")

    Dim res As Worksheet
    Set res = ThisWorkbook.Worksheets("Sheet2")

    With wrkSht
        .Range(.Cells(DataStartRow - 1, 1), .Cells(DataStartRow - 1, 4)).Copy
    End With

    With res
        .Cells(9, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
        .Cells(9, 1).PasteSpecial Paste:=xlPasteFormats
    End With

'    Copy user selection
'    Selection.Copy

'    Paste to user selection
'    With Selection
'        .PasteSpecial Paste:=xlPasteValuesAndNumberFormats
'        .PasteSpecial Paste:=xlPasteFormats
'    End With

End Sub

Note:  I haven't selected any cells in the code. You just have to reference them.


问:
How to run adb shell?
I read an article about fix phone issue but they said run this code to fix.

```<code>adb shell am start -n com.google.android.setupwizard/.SetupWizardTestActivity
</code>```

From this Blog here

My device is LG G3 (android v5 OS)

So, is there any apk from playstore or google to download to run this command ?

答:
For Windows:

Open SDK folder

go to platform-tools

hold shift and right click

click open command window here

in command prompt run you commands

Title: How to run adb shell?

Body:
I read an article about fix phone issue but they said run this code to fix.

adb shell am start -n com.google.android.setupwizard/.SetupWizardTestActivity

From this Blog here

My device is LG G3 (android v5 OS)

So, is there any apk from playstore or google to download to run this command ?


问:
Div Not Showing Up : Rollover Image Link
Live Example Page:

http://newsite.702wedding.com/cheap-las-vegas-weddings.asp

I want the 3rd box on the right side to have a sprite image link in it. I cant seem to get the darn thing to show up.

The Image is : reserve-a-date-right.jpg

its 801px wide, with 401px viewable.

Thanks as Always,
Any Ideas would be helpful.

What am I missing? I have spent 3 hours trying to figure this out.

答:
Add in: display: block; to #package-right-box-promo a

It should show up, though you may have to adjust the top margin. (Looks like margin-top: 19px; centers it nicely, but that's in Firefox 3)

ContentLicense: CC BY-SA 2.5


问:
Adding Json Object into url
I want to be able to delete item based on the book_id.

```<code>tbody.insertAdjacentHTML('beforeend', '<tr><td>' + obj.book_id + '</td><td>' + <a href="delete_books?book_id=" + obj.book_id + >Delete</a> + '</td></tr>'
</code>```

I am not sure how to form the url. The link can't seem to work.
I want to be able to retrieve the id and delete in my  servlet file.

答: As Dane has mentioned, it is not advisable to expose parameters in the url. Using an AJAX POST/DELETE call would be a better option. Cheers! :)</p>

Title: Adding Json Object into url

Body:
I want to be able to delete item based on the book_id.

tbody.insertAdjacentHTML('beforeend', '
' + obj.book_id + '	' + Delete + '
'

I am not sure how to form the url. The link can't seem to work.
I want to be able to retrieve the id and delete in my  servlet file.


问:
OpenCV - Feature Matching vs Optical Flow
I am interested in making a motion tracking app using OpenCV, and there has been a wealth of information available online. However, I am a tad confused between feature matching and tracking features using a sparse optical flow algorithm such as Lucas-Kanade. With that in mind, I have the following questions:

What is the main difference between the two (feature matching and optical flow) if I have specified a region of pixels to track? I'm not interested in tracking in real time, if that helps clear up any assumptions.

In addition, since I'm not doing real time tracking, is it a better idea to use dense optical flow (Farneback) to keep track of the pixels in my specified region of interest?

Thank you.

答:
I would like to add a few thoughts about that theme since I found this a very interesting question too.
As said before Feature Matching is a technique that is based on:

A feature detection step which returns a set of so called feature points. These feature points are located at positions with salient image structures, e.g. edge-like structures when you are using FAST or blob like structures if you are using SIFT or SURF.

The second step is the matching. The association of feature points extracted from two different images. The matching is based on local visual descriptors, e.g. histogram of gradients or binary patterns, that are locally extracted around the feature positions. The descriptor is a feature vector and associated feature point pairs are pairs a minimal feature vector distances.

Most feature matching methods are scale and rotation invariant and are robust for changes in illuminations (e.g caused by shadow or different contrast). Thus these methods can be applied to image sequences but are more often used to align image pairs captured from different views or with different devices.The disadvantage of Feature Matching methods is the difficulty of defining where the feature matches are spawn and that the feature pair (which in a image sequence are motion vectors) are in general very sparse. In addition the subpixel accuracy of matching approaches are very limited as most detector are fine-graded to integer positions.

From my experience the main advantage of feature matching approaches is that they can compute very large motions/ displacements.

OpenCV offers some feature matching methods but there are a lot of more recent, faster and more accurate approaches available online e.g.:

DeepMatching which relies on deep learning and are often used to initialize optical flow methods to help them deal with long-range motions.

Stereoscann which is a very fast approach at its origin proposed for visual odometry.

Optical flow methods in contrast rely on the minimization of the brightness constancy and additional constrain e.g. smoothness etc. Thus they derive motion vector based on spatial and temporal image gradients of a sequence of consecutive frames. Thus they are more suited image sequences  rather than image pairs that are captured from very different view points. The main challenges in the estimation of motion with optical flow vectors  are large motions, occlusion, strong illumination changes and changes of the appearance of the objects and mostly the low runtime. However optical flow methods can be highly accurate and compute dense motion fields which respect to shared motion boundaries of the objects in a scene.

However, the accuracy of different optical flow methods is very different. Local methods such as the PLK (Lucas Kanade) are in general less accurate but allow to compute pre selected motion vectors only and can thus be very fast. (In the recent years we have done some research to improve the accuracy of the local approach, see here for further information).

The main OpenCV trunk offers global approaches such as the Farnback. But this is a quite outdated approach. Try the OpenCV contrib trunk which more recent methods. But to get an good overview of the most recent methods take a look at the public optical flow benchmarks. Here you will find code and implementations as well e.g.:

MPI-Sintel optical flow benchmark

KITTI 2012 optical flow benchmark. Both offer links e.g. to git's or source code for some newer methods. Such as FlowFields.

But from my point of view I would not on an early stage reject a specific approach matching or optical flow. Try as much as possible available online implementations and see what is the best for your application.


问:
parse value from JSON object with dynamic key in VBScript
Actually I want to get value from a JSON with Dynamic key in VBScript. I try to find similar question if any body asked already but nothing find for VBScript.

So below is a sample json:

```<code>{
    "assessmenttype": [{
        "id": "129666",
        "formattedvalue": "wT",
        "value": "WT"
    }],
    "jobid": "2017-2752",
    "jobtitle": "XYZ",
    "links": [{
        "rel": "self",
        "title": "The current profile being viewed.",
        "url": "https://dummyUrl.com/customers"
    }],
    "field33005": {
        "id": "C121",
        "formattedvalue": "XYZ",
        "value": "XYZ"
    }
}
</code>```

So in above JSON(which is client specific), as for one client node name is field33005 but for any other client this field name might be field38045 and so on.. so the challenge is to get the value of "value" sub field in this field33005 custom field.

please help me as I am not professional in JSON Parsing with VBScript.

Note: For json parsing I am using json2-min.js library

答:
To answer my own question I make one function in JavaScript as we can call a js function from VBSript in ASP.

```<code><script runat="server" language="javascript">

  function getJSONObject(targetJSONObject, propName)
  {

    for (var prop in targetJSONObject)
    {
      if (prop = propName)
      {
        return targetJSONObject[prop].value;
      }
    }
  return "";
  }
</script>
</code>```

In the above method we need to pass the actual Json and name of custom field then it will return the "value" sub node of that custom field.

Body:
Actually I want to get value from a JSON with Dynamic key in VBScript. I try to find similar question if any body asked already but nothing find for VBScript.

So below is a sample json:

{
    "assessmenttype": [{
        "id": "129666",
        "formattedvalue": "wT",
        "value": "WT"
    }],
    "jobid": "2017-2752",
    "jobtitle": "XYZ",
    "links": [{
        "rel": "self",
        "title": "The current profile being viewed.",
        "url": "https://dummyUrl.com/customers"
    }],
    "field33005": {
        "id": "C121",
        "formattedvalue": "XYZ",
        "value": "XYZ"
    }
}

So in above JSON(which is client specific), as for one client node name is field33005 but for any other client this field name might be field38045 and so on.. so the challenge is to get the value of "value" sub field in this field33005 custom field.

please help me as I am not professional in JSON Parsing with VBScript.

Note: For json parsing I am using json2-min.js library

Body:
To answer my own question I make one function in JavaScript as we can call a js function from VBSript in ASP.

<script runat="server" language="javascript">

  function getJSONObject(targetJSONObject, propName)
  {

    for (var prop in targetJSONObject)
    {
      if (prop = propName)
      {
        return targetJSONObject[prop].value;
      }
    }
  return "";
  }
</script>

In the above method we need to pass the actual Json and name of custom field then it will return the "value" sub node of that custom field.


问:
Azure SQL Sync Group Db Isolation Level Error
An error is given stating the database Isolation Level state is different between two databases when replicating between an Azure SQL database and an on-premise SQL database using the SQL Agent software installed on the on-premise server.

How do I fix this?

答:
View the isolation state using this sql:

select name, snapshot_isolation_state, is_read_committed_snapshot_on from sys.databases

You want these settings to be both ON like below and the same on both the Azure and on-premise database.

The sql below is used to change the settings:

ALTER DATABASE {name} SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE
GO

ALTER DATABASE {name} SET ALLOW_SNAPSHOT_ISOLATION ON
GO


问:
Building Abreviations Dictionary from Text file
I would like to build a dictionary of abreviations.

I have a text file with a lot of abreviations. The text file looks like this(after import)

```<code>with open('abreviations.txt') as ab:
    ab_words = ab.read().splitlines()
</code>```

An extract:

```<code>'ACE',
'Access Control Entry',
'ACK',
'Acknowledgement',
'ACORN',
'A Completely Obsessive Really Nutty person',
</code>```

Now I want to build the dictionnary, where I have every uneven line as a dictionary key and every even line as the dictionary value.

Hence I should be able to write at the end:

```<code>ab_dict['ACE']
</code>```

and get the result:

```<code>'Access Control Entry'
</code>```

Also, How can I make it case-insensitive ?

```<code>ab_dict['ace']
</code>```

should yield the same result

```<code>'Access Control Entry'
</code>```

In fact, it would be perfect, if the output would also be lower case:

```<code>'access control entry'
</code>```

Here is a link to the text file: https://www.dropbox.com/s/91afgnupk686p9y/abreviations.txt?dl=0

答:
Complete solution with custom ABDict class and Python's generator functionality:

```<code>class ABDict(dict):
    ''' Class representing a dictionary of abbreviations'''

    def __getitem__(self, key):
        v = dict.__getitem__(self, key.upper())
        return v.lower() if key.islower() else v

with open('abbreviations.txt') as ab:
    ab_dict = ABDict()

    while True:
        try:
            k = next(ab).strip()    # `key` line
            v = next(ab).strip()    # `value` line
            ab_dict[k] = v
        except StopIteration:
            break
</code>```

Now, testing (with case-relative access):

```<code>print(ab_dict['ACE'])
print(ab_dict['ace'])
print('*' * 10)
print(ab_dict['WYTB'])
print(ab_dict['wytb'])
</code>```

The output(consecutively):

```<code>Access Control Entry
access control entry
**********
Wish You The Best
wish you the best
</code>```

Body:
I would like to build a dictionary of abreviations.

I have a text file with a lot of abreviations. The text file looks like this(after import)

with open('abreviations.txt') as ab:
    ab_words = ab.read().splitlines()

An extract:

'ACE',
'Access Control Entry',
'ACK',
'Acknowledgement',
'ACORN',
'A Completely Obsessive Really Nutty person',

Now I want to build the dictionnary, where I have every uneven line as a dictionary key and every even line as the dictionary value.

Hence I should be able to write at the end:

ab_dict['ACE']

and get the result:

'Access Control Entry'

Also, How can I make it case-insensitive ?

ab_dict['ace']

should yield the same result

'Access Control Entry'

In fact, it would be perfect, if the output would also be lower case:

'access control entry'

Here is a link to the text file: https://www.dropbox.com/s/91afgnupk686p9y/abreviations.txt?dl=0

Body:
Complete solution with custom ABDict class and Python's generator functionality:

class ABDict(dict):
    ''' Class representing a dictionary of abbreviations'''

    def __getitem__(self, key):
        v = dict.__getitem__(self, key.upper())
        return v.lower() if key.islower() else v

with open('abbreviations.txt') as ab:
    ab_dict = ABDict()

    while True:
        try:
            k = next(ab).strip()    # `key` line
            v = next(ab).strip()    # `value` line
            ab_dict[k] = v
        except StopIteration:
            break

Now, testing (with case-relative access):

print(ab_dict['ACE'])
print(ab_dict['ace'])
print('*' * 10)
print(ab_dict['WYTB'])
print(ab_dict['wytb'])

The output(consecutively):

Access Control Entry
access control entry
**********
Wish You The Best
wish you the best


问:
Using command line arguments in Python: Understanding sys.argv
I'm currently going through Learn Python The Hard Way. I think this example might be out dated so I wanted to get feedback here on it.

I'm using Python 3.1

```<code>from sys import argv

script, first, second, third = argv

print("the script is called:", (script))
print("your first variable is:", (first))
print("your second variable is:", (second))
print("your third variable is:", (third))
</code>```

I'm getting this error:

```<code>Traceback (most recent call last):
  File "/path/ch13.py", line 3, in <module>
    script, first, second, third, bacon = argv
ValueError: need more than 1 value to unpack
</code>```

Any idea what's wrong?

答:
sys.arg is a list of command line parameters. You need to actually pass command line parameters to the script to populate this list. Do this either in your IDE's project settings or by running like this on the command line:

```<code>python script.py first second third
</code>```

Note that the first argument is always the script's name (python script.py in this case). Due to your usage of unpacking, you will get a ValueError whenever you pass fewer or more than 3 parameters. You can check the number before unpacking using len(argv)-1 and presenting a suitable error if not 3.

On a related note, look at getopt if you need to do more complex argument passing.

Body:
I'm currently going through Learn Python The Hard Way. I think this example might be out dated so I wanted to get feedback here on it.

I'm using Python 3.1

from sys import argv

script, first, second, third = argv

print("the script is called:", (script))
print("your first variable is:", (first))
print("your second variable is:", (second))
print("your third variable is:", (third))

I'm getting this error:

Traceback (most recent call last):
  File "/path/ch13.py", line 3, in <module>
    script, first, second, third, bacon = argv
ValueError: need more than 1 value to unpack

Any idea what's wrong?

Body:
sys.arg is a list of command line parameters. You need to actually pass command line parameters to the script to populate this list. Do this either in your IDE's project settings or by running like this on the command line:

python script.py first second third

Note that the first argument is always the script's name (python script.py in this case). Due to your usage of unpacking, you will get a ValueError whenever you pass fewer or more than 3 parameters. You can check the number before unpacking using len(argv)-1 and presenting a suitable error if not 3.

On a related note, look at getopt if you need to do more complex argument passing.


答:
If you work on windows os
open this path in your explorer C:\Users\YOUR_PC_NAME\AppData\Local\Android\sdk\platform-tools then press shift and right click. then choose open command window here. Also you have to enable usb debugging on your phone to work with adb commands.

Title: How to run adb shell?


问:
ConstraintLayout-Params are ignored
i want to create an calendar Day-View like the one Google has.
For that i want to create dynamically the timelines. Thats the way i do it right now:

```<code>TextView nextTime = new TextView(this);
View nextView = new View(this);
View nextLine = new View(this);

ConstraintLayout.LayoutParams lineParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
ConstraintLayout.LayoutParams timeParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
ConstraintLayout.LayoutParams viewParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);

viewParams.topToBottom = firstView.getId();
viewParams.leftToLeft = firstView.getId();
viewParams.height = Utils.changeDPItoPX(26, displayMetrics);
viewParams.width = Utils.changeDPItoPX(0, displayMetrics);
viewParams.setMargins(0, Utils.changeDPItoPX(16, displayMetrics),0,0);
nextView.setLayoutParams(viewParams);
constraintLayout.addView(nextView);

timeParams.topToTop = nextView.getId();
timeParams.bottomToBottom = nextView.getId();
timeParams.leftToLeft = nextView.getId();
timeParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
timeParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
timeParams.setMargins(Utils.changeDPItoPX(16, displayMetrics), 0,0,0);
nextTime.setLayoutParams(timeParams);
constraintLayout.addView(nextTime);

lineParams.height = Utils.changeDPItoPX(2, displayMetrics);
lineParams.bottomToBottom = nextTime.getId();
lineParams.endToEnd = nextView.getId();
lineParams.startToEnd = nextTime.getId();
lineParams.topToTop = nextTime.getId();
lineParams.setMargins(Utils.changeDPItoPX(8, displayMetrics), 0,
Utils.changeDPItoPX(8, displayMetrics), 0);
lineParams.width = Utils.changeDPItoPX(0, displayMetrics);
nextLine.setLayoutParams(lineParams);
constraintLayout.addView(nextLine);
</code>```

In my layout xml for the activity i already have the first timestamp. So this code should add the next one. And it looks like this:

|  00:00 --------------------------  |

|  01:--0--0 -----------------------|

The timeLine is over my time and it also goes to end of the screen.
But it should look like the timeStamp above.

What am i doing wrong? Why does it ignore the constraints?

答:
Use ConstraintSet instead of Layout params for adding the views to your ConstraintLayout.

You can refer the following link for the understanding how to use ConstraintSet

https://developer.android.com/reference/android/support/constraint/ConstraintSet.html

Title: ConstraintLayout-Params are ignored

Body:
i want to create an calendar Day-View like the one Google has.
For that i want to create dynamically the timelines. Thats the way i do it right now:

TextView nextTime = new TextView(this);
View nextView = new View(this);
View nextLine = new View(this);

ConstraintLayout.LayoutParams lineParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
ConstraintLayout.LayoutParams timeParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
ConstraintLayout.LayoutParams viewParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);

viewParams.topToBottom = firstView.getId();
viewParams.leftToLeft = firstView.getId();
viewParams.height = Utils.changeDPItoPX(26, displayMetrics);
viewParams.width = Utils.changeDPItoPX(0, displayMetrics);
viewParams.setMargins(0, Utils.changeDPItoPX(16, displayMetrics),0,0);
nextView.setLayoutParams(viewParams);
constraintLayout.addView(nextView);

timeParams.topToTop = nextView.getId();
timeParams.bottomToBottom = nextView.getId();
timeParams.leftToLeft = nextView.getId();
timeParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
timeParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
timeParams.setMargins(Utils.changeDPItoPX(16, displayMetrics), 0,0,0);
nextTime.setLayoutParams(timeParams);
constraintLayout.addView(nextTime);

lineParams.height = Utils.changeDPItoPX(2, displayMetrics);
lineParams.bottomToBottom = nextTime.getId();
lineParams.endToEnd = nextView.getId();
lineParams.startToEnd = nextTime.getId();
lineParams.topToTop = nextTime.getId();
lineParams.setMargins(Utils.changeDPItoPX(8, displayMetrics), 0,
Utils.changeDPItoPX(8, displayMetrics), 0);
lineParams.width = Utils.changeDPItoPX(0, displayMetrics);
nextLine.setLayoutParams(lineParams);
constraintLayout.addView(nextLine);

In my layout xml for the activity i already have the first timestamp. So this code should add the next one. And it looks like this:

|  00:00 --------------------------  |

|  01:--0--0 -----------------------|

The timeLine is over my time and it also goes to end of the screen.
But it should look like the timeStamp above.

What am i doing wrong? Why does it ignore the constraints?


问:
Setting some properties on "ismouseover"
we are trying to set some button's properties if the mouse is over the Button.
The strange thing is, that it works only for some properties.

We've created an blank WPF application and simply added these lines of code:

```<code><Button Content="{Binding IsMouseOver, RelativeSource={RelativeSource Self},Mode=OneWay}">
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" Value="True">
                    <Setter Property="Foreground" Value="Red" />
                    <Setter Property="Background" Value="Yellow" />
                    <Setter Property="BorderThickness" Value="5"></Setter>
                    <Setter Property="BorderBrush" Value="BurlyWood"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" Value="False">
                <Setter Property="Foreground" Value="Green" />
                <Setter Property="Background" Value="BlueViolet" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
</code>```

The "false"-Trigger works like a charme.
The "True"-Trigger only sets the BorderThickness and the Foreground.
Background and Borderbrush will get ignored.

Can anyone tell me how to solve this problem??

答:
This is the default behaviour of a button in order to change define your own template of a button see Control Template </p>

```<code><Button Content="{Binding IsMouseOver, RelativeSource={RelativeSource Self},Mode=OneWay}">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Border Background="{TemplateBinding Background}"
                                    BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="{TemplateBinding BorderThickness}"
                                    >
                                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" Value="True">
                        <Setter Property="Foreground" Value="Red" />
                        <Setter Property="Background" Value="Yellow" />
                        <Setter Property="BorderThickness" Value="5"></Setter>
                        <Setter Property="BorderBrush" Value="BurlyWood"></Setter>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" Value="False">
                        <Setter Property="Foreground" Value="Green" />
                        <Setter Property="Background" Value="BlueViolet" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</code>```

Body:
we are trying to set some button's properties if the mouse is over the Button.
The strange thing is, that it works only for some properties.

We've created an blank WPF application and simply added these lines of code:

<Button Content="{Binding IsMouseOver, RelativeSource={RelativeSource Self},Mode=OneWay}">
    <Button.Style>

        </Style>
    </Button.Style>
</Button>

The "false"-Trigger works like a charme.
The "True"-Trigger only sets the BorderThickness and the Foreground.
Background and Borderbrush will get ignored.

Can anyone tell me how to solve this problem??

Body:
This is the default behaviour of a button in order to change define your own template of a button see Control Template

<Button Content="{Binding IsMouseOver, RelativeSource={RelativeSource Self},Mode=OneWay}">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Border Background="{TemplateBinding Background}"
                                    BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="{TemplateBinding BorderThickness}"
                                    >
                                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" Value="True">
                        <Setter Property="Foreground" Value="Red" />
                        <Setter Property="Background" Value="Yellow" />
                        <Setter Property="BorderThickness" Value="5"></Setter>
                        <Setter Property="BorderBrush" Value="BurlyWood"></Setter>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" Value="False">
                        <Setter Property="Foreground" Value="Green" />
                        <Setter Property="Background" Value="BlueViolet" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>


问:
Using move semantics to avoid copying when pushing_back to a custom container does not avoid copying
I have implemented a  custom container (same vein as std::vector) and I am trying to make it so that its 'push_back' function would use leverage on move semantics to avoid creating a copy of whatever is being pushed back - specially when the object to be pushed into the container is returned by an external function.

After reading quite a bit about move semantics and custom containers, I still can't find why my approach is still generating a copy instead of just moving the passed object into the container's inner dynamic array.

Here is a simplified version of my container looks like:

```<code>template<class T>
class Constructor
{
private:
    size_t size = 0;
    size_t cap = 0;
    T *data = nullptr;

public:
Constructor()
{
    cap = 1;
    size = 0;
    data = static_cast<T*>(malloc(cap * sizeof(T)));
}

~Constructor()
{ delete[] data; }

template<typename U>
void push_back(U &&value)
{
    if (size + 1 >= cap)
    {
        size_t new_cap = (cap * 2);
        T* new_data = static_cast<T*>(malloc(new_cap * sizeof(T)));
        memmove(new_data, data, (size) * sizeof(T));
        for (size_t i = 0; i<cap; i++)
        {
            data[i].~T();
        }

        delete[] data;

        cap = new_cap;
        data = new_data;
        new(data + size) T(std::forward<U>(value));
    }
    else
    {
        new(data + size) T(std::forward<U>(value));
    }

    ++size;
}

const T& operator[](const size_t index) const //access [] overloading
{
    return data[index];
}
};
</code>```

Here is a custom class that will print messages when its instances are created, copied or moved, in order to help debugging:

```<code>class MyClass
{
size_t id;

public:
MyClass(const size_t new_id)
{
    id = new_id;
    std::cout << "new instance with id " << id << std::endl;
}
MyClass(const MyClass &passedEntity)
{
    id = passedEntity.id;
    std::cout << "copied instance" << std::endl;
}
MyClass(MyClass &&passedEntity)
{
    id = passedEntity.id;
    std::cout << "moved instance" << std::endl;
}

void printID() const
{
    std::cout << "this instance's id is " << id << std::endl;
}
};
</code>```

And here is the external function:

```<code>MyClass &foo(MyClass &passed)
{
    return passed;
}
</code>```

Lastly, here is the main function that runs a test case using the above function and classes to show the problem:

```<code>int main()
{
MyClass a(33);
std::cout << std::endl;

std::cout << "Using my custom container: " << std::endl;
Constructor<MyClass> myContainer;
myContainer.push_back(foo(a));
myContainer[0].printID();
std::cout << std::endl;

std::cout << "Using dinamic array: " << std::endl;
MyClass *dinArray = static_cast<MyClass*>(malloc(1 * sizeof(MyClass)));
dinArray = new(dinArray + 1) MyClass(std::forward<MyClass>(foo(a)));
dinArray[0].printID();
std::cout << std::endl;

system("Pause");
return 0;
}
</code>```

The output is:

```<code>new instance with id 33

Using my custom container:
copied instance
this instance's id is 33

Using dinamic array:
moved instance
this instance's id is 33
</code>```

As it can be seen, if the instance of MyClass is put directly into a dynamic array, then just the move conmstructor is called and not the copy constructor. However, if I push_back the yClass instance into an instance of Container, a copy constructor is still being called.

Could someone help me understand what exactly am I doing wrong here? How could I make it so that elements are pushed into the container without generating a copy?

答:
It is not safe to perform a memmove with objects in C++.
You can find more information here Will memcpy or memmove cause problems copying classes?

If this is C++11 onwards, then what you want to use is placement new and the move constructor.   (you could probably just bin the placement new though unless you really want to keep allocating memory yourself)

If this is any other version of C++ then you'll have to just accept that that either you're going to have to copy the object (like the rest of the stl) or that your object will have to implement a function like void moveTo(T& other)

Body:
I have implemented a  custom container (same vein as std::vector) and I am trying to make it so that its 'push_back' function would use leverage on move semantics to avoid creating a copy of whatever is being pushed back - specially when the object to be pushed into the container is returned by an external function.

After reading quite a bit about move semantics and custom containers, I still can't find why my approach is still generating a copy instead of just moving the passed object into the container's inner dynamic array.

Here is a simplified version of my container looks like:

template<class T>
class Constructor
{
private:
    size_t size = 0;
    size_t cap = 0;
    T *data = nullptr;

public:
Constructor()
{
    cap = 1;
    size = 0;
    data = static_cast<T*>(malloc(cap * sizeof(T)));
}

~Constructor()
{ delete[] data; }

template<typename U>
void push_back(U &&value)
{
    if (size + 1 >= cap)
    {
        size_t new_cap = (cap * 2);
        T* new_data = static_cast<T*>(malloc(new_cap * sizeof(T)));
        memmove(new_data, data, (size) * sizeof(T));
        for (size_t i = 0; i<cap; i++)
        {
            data[i].~T();
        }

        delete[] data;

        cap = new_cap;
        data = new_data;
        new(data + size) T(std::forward(value));
    }
    else
    {
        new(data + size) T(std::forward(value));
    }

    ++size;
}

const T& operator[](const size_t index) const //access [] overloading
{
    return data[index];
}
};

Here is a custom class that will print messages when its instances are created, copied or moved, in order to help debugging:

class MyClass
{
size_t id;

public:
MyClass(const size_t new_id)
{
    id = new_id;
    std::cout << "new instance with id " << id << std::endl;
}
MyClass(const MyClass &passedEntity)
{
    id = passedEntity.id;
    std::cout << "copied instance" << std::endl;
}
MyClass(MyClass &&passedEntity)
{
    id = passedEntity.id;
    std::cout << "moved instance" << std::endl;
}

void printID() const
{
    std::cout << "this instance's id is " << id << std::endl;
}
};

And here is the external function:

MyClass &foo(MyClass &passed)
{
    return passed;
}

Lastly, here is the main function that runs a test case using the above function and classes to show the problem:

int main()
{
MyClass a(33);
std::cout << std::endl;

std::cout << "Using my custom container: " << std::endl;
Constructor<MyClass> myContainer;
myContainer.push_back(foo(a));
myContainer[0].printID();
std::cout << std::endl;

std::cout << "Using dinamic array: " << std::endl;
MyClass *dinArray = static_cast<MyClass*>(malloc(1 * sizeof(MyClass)));
dinArray = new(dinArray + 1) MyClass(std::forward<MyClass>(foo(a)));
dinArray[0].printID();
std::cout << std::endl;

system("Pause");
return 0;
}

The output is:

new instance with id 33

Using my custom container:
copied instance
this instance's id is 33

Using dinamic array:
moved instance
this instance's id is 33

As it can be seen, if the instance of MyClass is put directly into a dynamic array, then just the move conmstructor is called and not the copy constructor. However, if I push_back the yClass instance into an instance of Container, a copy constructor is still being called.

Could someone help me understand what exactly am I doing wrong here? How could I make it so that elements are pushed into the container without generating a copy?