问:
Why does it get same value?? and how to attach currency sign after result?
Why does it get same value?? and how to attach currency sign after result?
also, How to make it more briefly? I want to amend the repeating code.

function changeSign() {
  var currencySelect = document.getElementById("CurrencyID").value;
}

function changeCurrency() {

  var inputVal = parseFloat(document.getElementById("inputMoney").value);
  var currencyVal = parseFloat(document.getElementById("inputMoney"));

  if (document.getElementById("Euro")) {

    if (document.getElementById("Us1")) {

      currencyVal = (inputVal * 1.08);

    } else if (document.getElementById("Uk1")) {

      currencyVal = (inputVal * 0.83);

    } else if (document.getElementById("Ja1")) {

      currencyVal = (inputVal * 118.88);

    } else if (document.getElementById("Ca1")) {

      currencyVal = (inputVal * 1.43);
    }
  }

  document.getElementById("demo").textContent = currencyVal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Choose Convert : </b><br><br>
<select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;" onchange="changeSign()">
  <option id="Euro" value="€">Euro (EUR)</option>
  <option id="Us" value="$">US Dollar (USD)</option>
  <option id="Uk" value="£">UK Pound Sterling (GBP)</option>
  <option id="Ja" value="¥">Japanese Yen (JPY)</option>
  <option id="Ca" value="$">Canadian Dollor (CAD)</option>
</select>
<br>

<b>Choose Convert : </b><br><br>
<select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;">
  <option id="Euro1" value="€">Euro (EUR)</option>
  <option id="Us1" value="$">US Dollar (USD)</option>
  <option id="Uk1" value="£">UK Pound Sterling (GBP)</option>
  <option id="Ja1" value="¥">Japanese Yen (JPY)</option>
  <option id="Ca1" value="$">Canadian Dollor (CAD)</option>
</select>
<br>

<label>
                <br>
                <input name="inputMoney" id="inputMoney" type="text" class="text ui-widget-content ui-corner-all"
                    style="width: 196px; height:22px;" oninput="changeCurrency()"
                    >
            </label><br><br>

</div>
</div>

<p>value: <span id="demo"></span></p></code>```

答:
I just wanted to give you a cleaner solution:

Note:
The CurrencyList object contains the implementation of the conversion for each respective currency to the other. So I have only worked out the Parsing of Euro to other currencies you've listed. So You might have to do this for every currency on the list.

var CurrencyList = {
  Euro: {
    sign: '€',
    Parse: function(value, desiredCurrency)
    {
      var result = 0;
      switch(desiredCurrency)
      {
        case 'Us': { result = value * 1.08 + CurrencyList[desiredCurrency].sign; }
          break;
        case 'Uk': { result = value * 0.83 + CurrencyList[desiredCurrency].sign; }
          break;
        case 'Ja': { result = value * 118.88 + CurrencyList[desiredCurrency].sign; }
          break;
        case 'Ca': { result = value * 1.43 + CurrencyList[desiredCurrency].sign; }
          break;
      }
      return result;
    }
  },
  Uk: {
    sign: '£'
  },
  Us: {
    sign: '$'
  },
  Ja: {
    sign: '¥'
  },
  Ca: {
    sign: '$'
  }
};

document.getElementById("fromCurrencyID").addEventListener('change',
  function()
  {
    document.querySelector(".text-field__label").innerHTML = CurrencyList[document.getElementById("fromCurrencyID").value].sign;
  }
);

document.getElementById("convertButton")
  .addEventListener('click',
  function()
  {
    var _fromCurrency = document.getElementById("fromCurrencyID").value;
    var _toCurrency = document.getElementById("toCurrencyID").value;

    if(_fromCurrency && _toCurrency)
    {

      document.getElementById("demo").innerHTML = CurrencyList[_fromCurrency].Parse(document.querySelector(".text-field__input").value,_toCurrency);
    }
  }
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.text-field{
  width: 218px;
  height: 32px;
  padding-left: 22px;
}

.text-field .text-field_part{
  position: relative;
  padding: 5px;
  box-sizing: border-box;
  border: thin solid #cdcdcd;
  display: block;
}

.text-field .text-field__label{
  position: absolute;
  width: 32px;
  height: 32px;
  text-align: center;
  background-color: #f5f5f5;
  left: 0;
  line-height: 20px;
}

.text-field .text-field__input {
  margin: 0;
}</code>```

Choose Convert :

<select name="CurrencyConverter" id="fromCurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;">
  <option value="Euro">Euro (EUR)</option>
  <option value="Us">US Dollar (USD)</option>
  <option value="Uk">UK Pound Sterling (GBP)</option>
  <option value="Ja">Japanese Yen (JPY)</option>
  <option value="Ca">Canadian Dollor (CAD)</option>
</select>

Choose Convert :

<select name="CurrencyConverter" id="toCurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;">
  <option value="Euro">Euro (EUR)</option>
  <option value="Us">US Dollar (USD)</option>
  <option value="Uk">UK Pound Sterling (GBP)</option>
  <option value="Ja">Japanese Yen (JPY)</option>
  <option value="Ca">Canadian Dollor (CAD)</option>
</select>

  <button class="text-field__label text-field_part"></button>
  <input name="inputMoney" class="text-field__input text-field_part" type="text"
    style="width: 196px; height:32px;" />

<button id="convertButton">Convert</button>

value:
```

Body:
Why does it get same value?? and how to attach currency sign after result?
also, How to make it more briefly? I want to amend the repeating code.

function changeSign() {
  var currencySelect = document.getElementById("CurrencyID").value;
}

function changeCurrency() {

  var inputVal = parseFloat(document.getElementById("inputMoney").value);
  var currencyVal = parseFloat(document.getElementById("inputMoney"));

  if (document.getElementById("Euro")) {

    if (document.getElementById("Us1")) {

      currencyVal = (inputVal * 1.08);

    } else if (document.getElementById("Uk1")) {

      currencyVal = (inputVal * 0.83);

    } else if (document.getElementById("Ja1")) {

      currencyVal = (inputVal * 118.88);

    } else if (document.getElementById("Ca1")) {

      currencyVal = (inputVal * 1.43);
    }
  }

  document.getElementById("demo").textContent = currencyVal;
}

Choose Convert :

<select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;" onchange="changeSign()">
  <option id="Euro" value="€">Euro (EUR)</option>
  <option id="Us" value="$">US Dollar (USD)</option>
  <option id="Uk" value="£">UK Pound Sterling (GBP)</option>
  <option id="Ja" value="¥">Japanese Yen (JPY)</option>
  <option id="Ca" value="$">Canadian Dollor (CAD)</option>
</select>

Choose Convert :

<select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;">
  <option id="Euro1" value="€">Euro (EUR)</option>
  <option id="Us1" value="$">US Dollar (USD)</option>
  <option id="Uk1" value="£">UK Pound Sterling (GBP)</option>
  <option id="Ja1" value="¥">Japanese Yen (JPY)</option>
  <option id="Ca1" value="$">Canadian Dollor (CAD)</option>
</select>

                <input name="inputMoney" id="inputMoney" type="text" class="text ui-widget-content ui-corner-all"
                    style="width: 196px; height:22px;" oninput="changeCurrency()"
                    >

value:

Body:
I just wanted to give you a cleaner solution:

Note:
The CurrencyList object contains the implementation of the conversion for each respective currency to the other. So I have only worked out the Parsing of Euro to other currencies you've listed. So You might have to do this for every currency on the list.

var CurrencyList = {
  Euro: {
    sign: '&euro;',
    Parse: function(value, desiredCurrency)
    {
      var result = 0;
      switch(desiredCurrency)
      {
        case 'Us': { result = value * 1.08 + CurrencyList[desiredCurrency].sign; }
          break;
        case 'Uk': { result = value * 0.83 + CurrencyList[desiredCurrency].sign; }
          break;
        case 'Ja': { result = value * 118.88 + CurrencyList[desiredCurrency].sign; }
          break;
        case 'Ca': { result = value * 1.43 + CurrencyList[desiredCurrency].sign; }
          break;
      }
      return result;
    }
  },
  Uk: {
    sign: '&pound;'
  },
  Us: {
    sign: '&dollar;'
  },
  Ja: {
    sign: '&yen;'
  },
  Ca: {
    sign: '&#36;'
  }
};

document.getElementById("fromCurrencyID").addEventListener('change',
  function()
  {
    document.querySelector(".text-field__label").innerHTML = CurrencyList[document.getElementById("fromCurrencyID").value].sign;
  }
);

document.getElementById("convertButton")
  .addEventListener('click',
  function()
  {
    var _fromCurrency = document.getElementById("fromCurrencyID").value;
    var _toCurrency = document.getElementById("toCurrencyID").value;

    if(_fromCurrency && _toCurrency)
    {

      document.getElementById("demo").innerHTML = CurrencyList[_fromCurrency].Parse(document.querySelector(".text-field__input").value,_toCurrency);
    }
  }
);

.text-field{
  width: 218px;
  height: 32px;
  padding-left: 22px;
}

.text-field .text-field_part{
  position: relative;
  padding: 5px;
  box-sizing: border-box;
  border: thin solid #cdcdcd;
  display: block;
}

.text-field .text-field__label{
  position: absolute;
  width: 32px;
  height: 32px;
  text-align: center;
  background-color: #f5f5f5;
  left: 0;
  line-height: 20px;
}

.text-field .text-field__input {
  margin: 0;
}

<b>Choose Convert : </b><br><br>
<select name="CurrencyConverter" id="fromCurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;">
  <option value="Euro">Euro (EUR)</option>
  <option value="Us">US Dollar (USD)</option>
  <option value="Uk">UK Pound Sterling (GBP)</option>
  <option value="Ja">Japanese Yen (JPY)</option>
  <option value="Ca">Canadian Dollor (CAD)</option>
</select>
<br>

<b>Choose Convert : </b><br><br>
<select name="CurrencyConverter" id="toCurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;">
  <option value="Euro">Euro (EUR)</option>
  <option value="Us">US Dollar (USD)</option>
  <option value="Uk">UK Pound Sterling (GBP)</option>
  <option value="Ja">Japanese Yen (JPY)</option>
  <option value="Ca">Canadian Dollor (CAD)</option>
</select>
<br>

<label>
<br>
<div class="text-field">
  <button class="text-field__label text-field_part"></button>
  <input name="inputMoney" class="text-field__input text-field_part" type="text"
    style="width: 196px; height:32px;" />
</div>
</label><br><br>
<button id="convertButton">Convert</button>

<p>value: <span id="demo"></span></p>


来源: stackexchange

问:
Accessing C++ std::vector object members before object initialization
I just realized that I can access object members of my empty object vector list.
I thought vector.reserve(nmb) just reserves the required memory (kind of nmb*sizeof(object)).

```<code>#include <iostream>
#include <vector>

class Car {

    public: int tires = 4;

    Car(void) {
        std::cout << "Constructor of Car" << std::endl;
    }
};

int main()
{
    std::vector<Car> carList;
    carList.reserve(20);
    std::cout << "Car tires: " << carList[0].tires << std::endl;
    std::cout << "Now comes the emplace_back:" << std::endl;
    carList.emplace_back();
    std::cout << "Car tires: " << carList[0].tires << std::endl;

    //Car carArray[20];
    //std::cout << "Car tires: " << carArray[0].tires << std::endl;

    return 0;
}
</code>```

gives me:

```<code>Car tires: 0
Now comes the emplace_back:
Constructor of Car
Car tires: 4

...Program finished with exit code 0
</code>```

Why can I access members of not yet initialized objects?
Thank you.

答:
Accessing elements of a std::vector outside its size (not its capacity) has undefined behavior.

Undefined behavior means that there is no guarantee that anything specific will happen in general. What exactly happens will depend on the particular implementation of the compiler and the standard library.

One likely behavior was mentioned by @ypnos, but (any) other behavior would also be permissible by the C++ standard and possible depending on how exactly the standard library implements std::vector and how exactly the compiler optimizes.

ContentLicense: CC BY-SA 4.0

Body:
I just realized that I can access object members of my empty object vector list.
I thought vector.reserve(nmb) just reserves the required memory (kind of nmb*sizeof(object)).

#include <iostream>
#include <vector>

class Car {

    public: int tires = 4;

    Car(void) {
        std::cout << "Constructor of Car" << std::endl;
    }
};

int main()
{
    std::vector<Car> carList;
    carList.reserve(20);
    std::cout << "Car tires: " << carList[0].tires << std::endl;
    std::cout << "Now comes the emplace_back:" << std::endl;
    carList.emplace_back();
    std::cout << "Car tires: " << carList[0].tires << std::endl;

    //Car carArray[20];
    //std::cout << "Car tires: " << carArray[0].tires << std::endl;

    return 0;
}

gives me:

Car tires: 0
Now comes the emplace_back:
Constructor of Car
Car tires: 4

...Program finished with exit code 0

Why can I access members of not yet initialized objects?
Thank you.


问:
Spark set driver memory config in Databricks
I'm working on Azure databricks. My driver node and worker  node specs are : 14.0 GB Memory, 4 Cores, 0.75 DBU Standard_DS3_v2.

My pyspark notebook fails with Java heap space error. I checked online and one suggestion was to increase driver memory. I'm trying to use following conf parameter in the notebook

```<code>spark.conf.get("spark.driver.memory")
</code>```

To get driver memory. But my notebook cell fails with error.

```<code>java.util.NoSuchElementException: spark.driver.memory
</code>```

Any idea how to check driver memory and change its value?

答:
You can set the spark config when you setup your cluster on Databricks. When you create a cluster and expand the "Advanced Options"-menu, you can see that there is a "Spark Config" section. In this field you can set the configurations you want.

For more information you can always check the documentation page of Azure Databricks.

Body:
I'm working on Azure databricks. My driver node and worker  node specs are : 14.0 GB Memory, 4 Cores, 0.75 DBU Standard_DS3_v2.

My pyspark notebook fails with Java heap space error. I checked online and one suggestion was to increase driver memory. I'm trying to use following conf parameter in the notebook

spark.conf.get("spark.driver.memory")

To get driver memory. But my notebook cell fails with error.

java.util.NoSuchElementException: spark.driver.memory

Any idea how to check driver memory and change its value?


问:
Spring webflux - file upload doesnt work it throws error when i hit it from postman
Hi I have a spring webflux application.  I wanted an API for uploading a file. I followed the instruction in  Spring Webflux 415 with MultipartFile

And wrote something like this

```<code>@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Mono<Void> save(@RequestPart("file") Mono<FilePart> file) {
        log.info("Storing a new file. Recieved by Controller");
        this.storageService.store(file);
        return Mono.empty();
    }
</code>```

But still i cannot test this, it fails with the below error in postman and swagger doesnt generate file browse button for this API.

```<code>org.springframework.web.server.UnsupportedMediaTypeStatusException: Response status 415 with reason "Content type 'image/png' not supported"
at org.springframework.web.reactive.result.method.annotation.AbstractMessageReaderArgumentResolver.readBody(AbstractMessageReaderArgumentResolver.java:206) ~[spring-webflux-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.web.reactive.result.method.annotation.AbstractMessageReaderArgumentResolver.readBody(AbstractMessageReaderArgumentResolver.java:124) ~[spring-webflux-5.0.4.RELEASE.jar:5.0.4.RELEASE]
</code>```

答:
could you try to set the content type to multipart/form-data in postman?
when sending following request, the upper configuration works for me

```<code>    POST /rest/upload HTTP/1.1
    Host: localhost:8083
    Content: multipart/form-data
    Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

     ----WebKitFormBoundary7MA4YWxkTrZu0gW
     Content-Disposition: form-data; name="file"; filename="image.png"
     Content-Type: image/png

     (data)
     ----WebKitFormBoundary7MA4YWxkTrZu0gW
</code>```

or curl:

```<code>curl --location --request POST 'http://localhost:8083/rest/upload' \
--header 'Content: multipart/form-data' \
--header 'Content-Type: multipart/form-data; boundary=--------------------------947246331766984894381774' \
--form 'file=@/Users/user/Documents/image.png'
</code>```

Body:
Hi I have a spring webflux application.  I wanted an API for uploading a file. I followed the instruction in  Spring Webflux 415 with MultipartFile

And wrote something like this

@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Mono<Void> save(@RequestPart("file") Mono<FilePart> file) {
        log.info("Storing a new file. Recieved by Controller");
        this.storageService.store(file);
        return Mono.empty();
    }

But still i cannot test this, it fails with the below error in postman and swagger doesnt generate file browse button for this API.

org.springframework.web.server.UnsupportedMediaTypeStatusException: Response status 415 with reason "Content type 'image/png' not supported"
at org.springframework.web.reactive.result.method.annotation.AbstractMessageReaderArgumentResolver.readBody(AbstractMessageReaderArgumentResolver.java:206) ~[spring-webflux-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.web.reactive.result.method.annotation.AbstractMessageReaderArgumentResolver.readBody(AbstractMessageReaderArgumentResolver.java:124) ~[spring-webflux-5.0.4.RELEASE.jar:5.0.4.RELEASE]

Body:
could you try to set the content type to multipart/form-data in postman?
when sending following request, the upper configuration works for me

    POST /rest/upload HTTP/1.1
    Host: localhost:8083
    Content: multipart/form-data
    Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

     ----WebKitFormBoundary7MA4YWxkTrZu0gW
     Content-Disposition: form-data; name="file"; filename="image.png"
     Content-Type: image/png

     (data)
     ----WebKitFormBoundary7MA4YWxkTrZu0gW

or curl:

curl --location --request POST 'http://localhost:8083/rest/upload' \
--header 'Content: multipart/form-data' \
--header 'Content-Type: multipart/form-data; boundary=--------------------------947246331766984894381774' \
--form 'file=@/Users/user/Documents/image.png'


问:
Parse short US date into yyyy-MM-dd, java
I want to parse the date "3/27/11" which I think is equal to US short date.

```<code>DateFormat df1 = new SimpleDateFormat("MM/dd/yy");
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date) df1.parseObject("03/27/11");
System.out.println("New date: " + df2.format(date));
</code>```

I found the code above in several java tutorials but it doesn't seem to work.
For some how I get,

```<code>Exception in thread "main" java.lang.AssertionError: Default directory must be absolute/non-UNC
</code>```

Here is what I want to achieve,

input: 3/27/11

(03/27/11 should also be a valid input)

output: 2011-03-27

Thanks in advance!

答:
When I run this it prints

```<code>New date: 2011-03-27
</code>```

I suspect your problem is nothing to do with this but rather you have a default directory for your application which is a UNC path. i.e. exactly what your error message says.

Try running this program from your C: drive or a path using a network drive letter.

ContentLicense: CC BY-SA 3.0

Body:
I want to parse the date "3/27/11" which I think is equal to US short date.

DateFormat df1 = new SimpleDateFormat("MM/dd/yy");
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date) df1.parseObject("03/27/11");
System.out.println("New date: " + df2.format(date));

I found the code above in several java tutorials but it doesn't seem to work.
For some how I get,

Exception in thread "main" java.lang.AssertionError: Default directory must be absolute/non-UNC

Here is what I want to achieve,

input: 3/27/11

(03/27/11 should also be a valid input)

output: 2011-03-27

Thanks in advance!

Body:
When I run this it prints

New date: 2011-03-27

I suspect your problem is nothing to do with this but rather you have a default directory for your application which is a UNC path. i.e. exactly what your error message says.

Try running this program from your C: drive or a path using a network drive letter.


问:
Can't setup swagger - Cannot read property 'parameters' of undefined
I am having a problem with setting up the swagger into my node.js application. I am using swagger-jsdoc and swagger-ui-express for creating documentation. Here are the versions

"swagger-jsdoc": "3.5.0", "swagger-ui-express": "4.1.3"

Below is the configs, which I pass to swagger-jsdoc.

```<code>openapi: 3.0.0
info:
  description: test
  version: 3.0.0
  title: U-CRM api documentation
  termsOfService: http://swagger.io/terms/
servers:
  - url: 'https://localhost:5000'
    description: Local server
tags:
- name: U-CRM
  description: CRM for university
components:
  parameters:
    $ref: 'components/parameters/index.yml'
  schemas:
    $ref: 'components/schemas/index.yml'
paths:
  $ref: '#/paths/index.yml'
</code>```

After all, I get an error

Cannot read property 'parameters' of undefined

Actually, it is surprising to me, as I read swagger docs carefully.
What could be the problem?

答:
OpenAPI does not support $ref everywhere. $ref can only be used in specific places where the OpenAPI Specification explicitly states that the value of a field can be a "Reference Object".

For example, $ref is not allowed directly under paths, under components/parameters and components/schemas - you can only reference individual paths, parameters and schemas.

The correct version of your example is:

paths:
  /foo:
    $ref: '#/paths/index.yml#/~1foo'  # $ref to root node `/foo` in `paths/index.yml`
  /bar:
    $ref: '#/paths/index.yml#/~1bar'  # $ref to root node `/bar` in `paths/index.yml`

components:
  parameters:
    param1:
      $ref: 'components/parameters/index.yml#/param1'
    param2:
      $ref: 'components/parameters/index.yml#/param2'
  schemas:
    schema1:
      $ref: 'components/schemas/index.yml#/schema1'
    schema2:
      $ref: 'components/schemas/index.yml#/schema2'
```

If you want to use $ref in random places, you'll have to pre-process your definition using a parser/tool that can resolve arbitrary $refs; this will give you a valid OpenAPI file that can be used with OpenAPI-compliant tools. One such pre-processing tool is json-refs, you can find an example of pre-processing here.

Body:
I am having a problem with setting up the swagger into my node.js application. I am using swagger-jsdoc and swagger-ui-express for creating documentation. Here are the versions

"swagger-jsdoc": "3.5.0", "swagger-ui-express": "4.1.3"

Below is the configs, which I pass to swagger-jsdoc.

openapi: 3.0.0
info:
  description: test
  version: 3.0.0
  title: U-CRM api documentation
  termsOfService: http://swagger.io/terms/
servers:
  - url: 'https://localhost:5000'
    description: Local server
tags:
- name: U-CRM
  description: CRM for university
components:
  parameters:
    $ref: 'components/parameters/index.yml'
  schemas:
    $ref: 'components/schemas/index.yml'
paths:
  $ref: '#/paths/index.yml'

After all, I get an error

Cannot read property 'parameters' of undefined

Actually, it is surprising to me, as I read swagger docs carefully.
What could be the problem?

Body:
OpenAPI does not support $ref everywhere. $ref can only be used in specific places where the OpenAPI Specification explicitly states that the value of a field can be a "Reference Object".

For example, $ref is not allowed directly under paths, under components/parameters and components/schemas - you can only reference individual paths, parameters and schemas.

The correct version of your example is:

paths:
  /foo:
    $ref: '#/paths/index.yml#/~1foo'  # $ref to root node `/foo` in `paths/index.yml`
  /bar:
    $ref: '#/paths/index.yml#/~1bar'  # $ref to root node `/bar` in `paths/index.yml`

components:
  parameters:
    param1:
      $ref: 'components/parameters/index.yml#/param1'
    param2:
      $ref: 'components/parameters/index.yml#/param2'
  schemas:
    schema1:
      $ref: 'components/schemas/index.yml#/schema1'
    schema2:
      $ref: 'components/schemas/index.yml#/schema2'

If you want to use $ref in random places, you'll have to pre-process your definition using a parser/tool that can resolve arbitrary $refs; this will give you a valid OpenAPI file that can be used with OpenAPI-compliant tools. One such pre-processing tool is json-refs, you can find an example of pre-processing here.


问:
Why does the Rust compiler complain that I use a moved value when I've replaced it with a new value?
I am working on two singly linked lists, named longer and shorter. The length of the longer one is guaranteed to be no less than the shorter one.

I pair the lists element-wise and do something to each pair. If the longer list has more unpaired elements, process the rest of them:

struct List {
    next: Option<Box<List>>,
}

fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
    // Pair the elements in the two lists.
    while let (Some(node1), Some(node2)) = (shorter, longer) {
        // Actual work elided.
        shorter = node1.next;
        longer = node2.next;
    }
    // Process the rest in the longer list.
    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }
}
```

<p>However, the compiler complains on the second while loop that</p>

```error[E0382]: use of moved value
  --> src/lib.rs:13:20
   |
5  | fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
   |                                                ---------- move occurs because `longer` has type `std::option::Option<std::boxed::Box<List>>`, which does not implement the `Copy` trait
6  |     // Pair the elements in the two lists.
7  |     while let (Some(node1), Some(node2)) = (shorter, longer) {
   |                                                      ------ value moved here
...
13 |     while let Some(node) = longer {
   |                    ^^^^ value used here after move
```

However, I do set a new value for shorter and longer at the end of the loop, so that I will never use a moved value of them.

How should I cater to the compiler?

答:
I think that the problem is caused by the tuple temporary in the first loop. Creating a tuple moves its components into the new tuple, and that happens even when the subsequent pattern matching fails.

First, let me write a simpler version of your code. This compiles fine:

```<code>struct Foo(i32);
fn main() {
    let mut longer = Foo(0);
    while let Foo(x) = longer {
        longer = Foo(x + 1);
    }
    println!("{:?}", longer.0);
}
</code>```

But if I add a temporary to the  while let then I'll trigger a compiler error similar to yours:

```<code>fn fwd<T>(t: T) -> T { t }
struct Foo(i32);
fn main() {
    let mut longer = Foo(0);
    while let Foo(x) = fwd(longer) {
        longer = Foo(x + 1);
    }
    println!("{:?}", longer.0);
    //        Error: ^ borrow of moved value: `longer`
}
</code>```

The solution is to add a local variable with the value to be destructured, instead of relying on a temporary. In your code:

```<code>struct List {
    next: Option<Box<List>>
}

fn drain_lists(shorter: Option<Box<List>>,
               longer: Option<Box<List>>) {
    // Pair the elements in the two lists.
    let mut twolists = (shorter, longer);
    while let (Some(node1), Some(node2)) = twolists {
        // Actual work elided.
        twolists = (node1.next, node2.next);
    }
    // Process the rest in the longer list.
    let (_, mut longer) = twolists;
    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }
}
</code>```

Body:
I am working on two singly linked lists, named longer and shorter. The length of the longer one is guaranteed to be no less than the shorter one.

I pair the lists element-wise and do something to each pair. If the longer list has more unpaired elements, process the rest of them:

struct List {
    next: Option<Box<List>>,
}

fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
    // Pair the elements in the two lists.
    while let (Some(node1), Some(node2)) = (shorter, longer) {
        // Actual work elided.
        shorter = node1.next;
        longer = node2.next;
    }
    // Process the rest in the longer list.
    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }
}

However, the compiler complains on the second while loop that

error[E0382]: use of moved value
  --> src/lib.rs:13:20
   |
5  | fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
   |                                                ---------- move occurs because `longer` has type `std::option::Option<std::boxed::Box<List>>`, which does not implement the `Copy` trait
6  |     // Pair the elements in the two lists.
7  |     while let (Some(node1), Some(node2)) = (shorter, longer) {
   |                                                      ------ value moved here
...
13 |     while let Some(node) = longer {
   |                    ^^^^ value used here after move

However, I do set a new value for shorter and longer at the end of the loop, so that I will never use a moved value of them.

How should I cater to the compiler?

Body:
I think that the problem is caused by the tuple temporary in the first loop. Creating a tuple moves its components into the new tuple, and that happens even when the subsequent pattern matching fails.

First, let me write a simpler version of your code. This compiles fine:

struct Foo(i32);
fn main() {
    let mut longer = Foo(0);
    while let Foo(x) = longer {
        longer = Foo(x + 1);
    }
    println!("{:?}", longer.0);
}

But if I add a temporary to the  while let then I'll trigger a compiler error similar to yours:

fn fwd<T>(t: T) -> T { t }
struct Foo(i32);
fn main() {
    let mut longer = Foo(0);
    while let Foo(x) = fwd(longer) {
        longer = Foo(x + 1);
    }
    println!("{:?}", longer.0);
    //        Error: ^ borrow of moved value: `longer`
}

The solution is to add a local variable with the value to be destructured, instead of relying on a temporary. In your code:

struct List {
    next: Option<Box<List>>
}

fn drain_lists(shorter: Option<Box<List>>,
               longer: Option<Box<List>>) {
    // Pair the elements in the two lists.
    let mut twolists = (shorter, longer);
    while let (Some(node1), Some(node2)) = twolists {
        // Actual work elided.
        twolists = (node1.next, node2.next);
    }
    // Process the rest in the longer list.
    let (_, mut longer) = twolists;
    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }
}


问:
How to select using multiple attribute selectors?
I am trying to disable multiple fields in a checkbox survey at the same time. Is it possible to select by multiple classes on same the div? I tried below but its not working. The code works with one class.</p>

```<code>function surveyInit(){
  $("div[class*='addressLine1', class*='addressLine2'] input"  ).attr('disabled', 'disabled');
}
</code>```

答:
you need comma as seperator and you can youse dot to select class instead of attribute selector</p>

```<code>function surveyInit(){
 $("div.addressLine1 input,div.addressLine2 input"  ).attr('disabled', 'disabled');

}
</code>```

Body:
I am trying to disable multiple fields in a checkbox survey at the same time. Is it possible to select by multiple classes on same the div? I tried below but its not working. The code works with one class.

function surveyInit(){
  $("div[class*='addressLine1', class*='addressLine2'] input"  ).attr('disabled', 'disabled');
}

Body:
you need comma as seperator and you can youse dot to select class instead of attribute selector

function surveyInit(){
 $("div.addressLine1 input,div.addressLine2 input"  ).attr('disabled', 'disabled');

}


问:
Handling paper documentation
After every new program written a lot of paper documentation remains.

Apart from the usual scribble notes from the programmers there usually is a nice heap of papers containing physical model explanations, calculations and so on (equations, tables, graphs, little pictures describing variables ...)

We usually do numerically intensive calculations in console applications, which are not released to the public (remain in the house, only results go out). Before each project is finished all those papers have to be packed somehow with the application, so that one day, when someone will be reusing parts of it, has some idea what is what in there.
So far, we've been using the 'dirty' solution of just scanning all of it, and packing it up on the disc with the application.

So I was wondering ... for all science guys here in a similar situation ... how do you handle project documentation which is needed, but not released to the public ?
(the one that does, goes to the dtp laddies, and they make it nice and shiny - not our problem anymore :)

答:
In the projects I've worked on we have done a lot of physics calculations in our programs and consequently we have a lot of whiteboard sessions with equations we are working on.

We keep a wiki for each major project and after each whiteboard session we physically photograph the whiteboard with a digital camera and upload/organize it within the wiki.  We also scan in paper documents from developers notebooks if it is important and include it in the wiki as well.

Then, we back up the wiki on disc for storage.  So our solution is pretty similar to yours, other than we use the project wiki for organization.

ContentLicense: CC BY-SA 2.5

Title: Handling paper documentation

OwnerDisplayName: Simucal


问:
building a parser with clang
I need to build an AST using clang and the only tutorials that I found are vague and two years out of date. Could anybody point me to an example?</p>

答:
There are several tutorial available that demonstrate the use of the Preprocessor class and how to build an AST:

A CLang tutorial (a bit outdated but with a lot of explanation)

Code samples

Title: building a parser with clang


问:
Possibility to modify 1 or 2 arguments from multiple list of arguments in keyword during creation test case in robotframework
I am curious if it's possible to modify some default argument when I try using following keyword during test case creation. See example below.

```<code>*** Keywords ***
Open URL With Custom Parameters
     [Arguments]     ${fe}=example.lan   ${be}=https://example.be.lan  ${reminderInterval}=5  ${licence}=default   ${flowId}=7349   ${name}=example    ${cur}=EUR   ${lang}=en
     ...             ${browser}=chrome
     Open Browser    https://${fe}/${name}/debug_index.html?&appsrv=${be}&currency=${cur}&lang=${lang}&reminderInterval=${reminderInterval}&fullscreen=yes&license=${licence}      ${browser}
</code>```

I would like to modify only 2 dedicated arguments e.g. Below doesn't work

```<code>*** Test Cases ***
Open browser and do sth
    Open URL With Custom Parameters         ${name}=development   ${be}=https://goodday.com`
</code>```

If is possible to change default argument from keyword in different order where is set it in keyword?

I would like to avoid adding all remains parameter to change only 1 or 2 arguments like below:

```<code>*** Test Cases ***
Open browser and do sth
    Open URL With Custom Parameters         ${fe}=https://development   ${be}=https://goodday3421.com
</code>```

....

答:
Yes, it's possible, just don't use the ${} around the arguments' names when calling the keyword:

```<code>Open URL With Custom Parameters         fe=https://development   be=https://goodday3421.com
</code>```

Body:
I am curious if it's possible to modify some default argument when I try using following keyword during test case creation. See example below.

*** Keywords ***
Open URL With Custom Parameters
     [Arguments]     ${fe}=example.lan   ${be}=https://example.be.lan  ${reminderInterval}=5  ${licence}=default   ${flowId}=7349   ${name}=example    ${cur}=EUR   ${lang}=en
     ...             ${browser}=chrome
     Open Browser    https://${fe}/${name}/debug_index.html?&appsrv=${be}&currency=${cur}&lang=${lang}&reminderInterval=${reminderInterval}&fullscreen=yes&license=${licence}      ${browser}

I would like to modify only 2 dedicated arguments e.g. Below doesn't work

*** Test Cases ***
Open browser and do sth
    Open URL With Custom Parameters         ${name}=development   ${be}=https://goodday.com`

If is possible to change default argument from keyword in different order where is set it in keyword?

I would like to avoid adding all remains parameter to change only 1 or 2 arguments like below:

*** Test Cases ***
Open browser and do sth
    Open URL With Custom Parameters         ${fe}=https://development   ${be}=https://goodday3421.com

....

Body:
Yes, it's possible, just don't use the ${} around the arguments' names when calling the keyword:

Open URL With Custom Parameters         fe=https://development   be=https://goodday3421.com


问:
why @UniqueConstraint doesn't work in hibernate?
I added unique constraint annotation but still I can insert duplicate entry.</p>

```<code>@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"firstName", "LastName"})})
public class Student {
    @Id
    @GeneratedValue(strategy =  GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String LastName;
    //getter and setter and no-arg constructor
</code>```

```<code> Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Student student1 = new Student("alireza", "rayani");
        Student student2 = new Student("alireza", "rayani");
        session.save(student1);
        session.save(student2);
        session.getTransaction().commit();
</code>```

答:
Finally ,I found out the problem ,I changed dialect  from  </p>

```<code>properties.put(Environment.DIALECT,"org.hibernate.dialect.MySQL5Dialect");
</code>```

<p>to </p>

```<code>properties.put(Environment.DIALECT, "org.hibernate.dialect.MySQL57Dialect");
</code>```

Body:
I added unique constraint annotation but still I can insert duplicate entry.

@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"firstName", "LastName"})})
public class Student {
    @Id
    @GeneratedValue(strategy =  GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String LastName;
    //getter and setter and no-arg constructor

 Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Student student1 = new Student("alireza", "rayani");
        Student student2 = new Student("alireza", "rayani");
        session.save(student1);
        session.save(student2);
        session.getTransaction().commit();

Body:
Finally ,I found out the problem ,I changed dialect  from

properties.put(Environment.DIALECT,"org.hibernate.dialect.MySQL5Dialect");

to

properties.put(Environment.DIALECT, "org.hibernate.dialect.MySQL57Dialect");


问:
how to save parent object containing child object using spring boot in @ManyToOne unidirectional mapping?
I am new in spring boot. I've two model classes Party(parent) and PartyCategory(child). PartyCategory stores data id, labelAr and labelEn successfully.

Now I am passing child id in json request and getting null values for labelAr and labelEn in json response as pasted below. Can someone please help what and doing wrong here.

I've pasted my code as well.

Json Request:

```<code>{

    "name": "Party A",
    "description": "Description of Party A",
    "category": {
        "id": 1
    }
}
</code>```

Json response;

```<code>{
    "id": 6,
    "name": "Party A",
    "description": "Description of Party A",
    "category": {
        "id": 1,
        "labelAr": null,
        "labelEn": null
    }
}
</code>```

Party.java:

```<code>   public class Party {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;
        private String name;
        private String description;
        @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
        @JoinColumn(name = "category_id")
        private PartyCategory category;

        ....setters and getters
   }
</code>```

PartyCategory.java:-

```<code>public class PartyCategory {

    @Id
    @GeneratedValue
    private Integer id;
    private String labelAr;
    private String labelEn;

    ...setters and getters..
</code>```

Repositories:

```<code>public interface PartyCategoryRepository extends JpaRepository<PartyCategory, Integer> {

}

public interface PartyRepository extends JpaRepository<Party, Integer> {

}
</code>```

Services:

```<code>public class PartyServiceImpl {
    @Autowired
    PartyRepository partyRepository;

public Party saveParty(Party party) {

        return partyRepository.save(party);
    }
</code>```

Controller:

```<code>@RestController
public class PartyController {

    @Autowired
    PartyServiceImpl partyServiceIml;

    @PostMapping(value = "/party/save")
    public Party saveParty(@RequestBody Party party ) {
        Party returnedParty = partyServiceIml.saveParty(party);
        return returnedParty;
    }
}
</code>```

答:
First of all, it's not a good practice to use the same entity for the database and also for the rest services. They should be separate entities, normally the entities for the rest services are called DTO (Data Access Objects).

Now, regarding your problem, it's normal what it's happening in your code, because you overwrite the PartyCategory labelAr and labelEn associated to the ID 1 with null values when you save your new Party, because you didn't provide any value for those two labels.

```<code>return partyRepository.save(party);
</code>```

If you want to avoid this problem you have to retrieve the PartyCategory data first from the database, set to the Party entity and after that to save it to the database. Something like this:

```<code>public class PartyServiceImpl {
    @Autowired
    PartyRepository partyRepository;

    @Autowired
    PartyCategoryRepository partyCategoryRepository;

    public Party saveParty(Party party) {
        PartyCategory partyCategory = partyCategoryRepository.findById(party.getPartyCategory().getId());

        party.setPartyCategory(partyCategory);

        return partyRepository.save(party);
    }
</code>```

Body:
I am new in spring boot. I've two model classes Party(parent) and PartyCategory(child). PartyCategory stores data id, labelAr and labelEn successfully.

Now I am passing child id in json request and getting null values for labelAr and labelEn in json response as pasted below. Can someone please help what and doing wrong here.

I've pasted my code as well.

Json Request:

{

    "name": "Party A",
    "description": "Description of Party A",
    "category": {
        "id": 1
    }
}

Json response;

{
    "id": 6,
    "name": "Party A",
    "description": "Description of Party A",
    "category": {
        "id": 1,
        "labelAr": null,
        "labelEn": null
    }
}

Party.java:

   public class Party {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;
        private String name;
        private String description;
        @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
        @JoinColumn(name = "category_id")
        private PartyCategory category;

        ....setters and getters
   }

PartyCategory.java:-

public class PartyCategory {

    @Id
    @GeneratedValue
    private Integer id;
    private String labelAr;
    private String labelEn;

    ...setters and getters..

Repositories:

public interface PartyCategoryRepository extends JpaRepository<PartyCategory, Integer> {

}

public interface PartyRepository extends JpaRepository<Party, Integer> {

}

Services:

public class PartyServiceImpl {
    @Autowired
    PartyRepository partyRepository;

public Party saveParty(Party party) {

        return partyRepository.save(party);
    }

Controller:

@RestController
public class PartyController {

    @Autowired
    PartyServiceImpl partyServiceIml;

    @PostMapping(value = "/party/save")
    public Party saveParty(@RequestBody Party party ) {
        Party returnedParty = partyServiceIml.saveParty(party);
        return returnedParty;
    }
}

Body:
First of all, it's not a good practice to use the same entity for the database and also for the rest services. They should be separate entities, normally the entities for the rest services are called DTO (Data Access Objects).

Now, regarding your problem, it's normal what it's happening in your code, because you overwrite the PartyCategory labelAr and labelEn associated to the ID 1 with null values when you save your new Party, because you didn't provide any value for those two labels.

return partyRepository.save(party);

If you want to avoid this problem you have to retrieve the PartyCategory data first from the database, set to the Party entity and after that to save it to the database. Something like this:

public class PartyServiceImpl {
    @Autowired
    PartyRepository partyRepository;

    @Autowired
    PartyCategoryRepository partyCategoryRepository;

    public Party saveParty(Party party) {
        PartyCategory partyCategory = partyCategoryRepository.findById(party.getPartyCategory().getId());

        party.setPartyCategory(partyCategory);

        return partyRepository.save(party);
    }


问:
Can the time to live (TTL) for a memcached key be set to infinite?
I have implemented memcache in my PHP-MySQL based app and it gets updated regularly from a backend process.

Due to this some data is conflicting with the expiration time and other backend processes, so I came up with a solution but for that I would have to make the TTL = infinite.

答:
As far as I know, if you don't set a ttl, it will never expire.

However, there are replacing policies for keys, about which you can read here


问:
Best way to set strongly typed dataset connection string at runtime?
My Windows Forms application uses a strongly typed dataset created using the designer in Visual Studio. At runtime I would like to be able to select either the live or test database.

What is the best way to programmatically set the connection string for the dataset at runtime?

答:
By default the Connection property is set to be internal. This can be changed in the DataSet's designer.

Right-click the TableAdapter.

Then change the ConnectionModifier property to public.

You can now access the Connection property in your project.

```<code>var loginsTableAdapter = new MyDataSetTableAdapters.LoginsTableAdapter();
loginsTableAdapter.Connection.ConnectionString = _myConnectionString;
</code>```

OwnerDisplayName: wethercotes

Body:
By default the Connection property is set to be internal. This can be changed in the DataSet's designer.

Right-click the TableAdapter.

Then change the ConnectionModifier property to public.

You can now access the Connection property in your project.

var loginsTableAdapter = new MyDataSetTableAdapters.LoginsTableAdapter();
loginsTableAdapter.Connection.ConnectionString = _myConnectionString;


问:
Disable past date in DatePickerDialog
I want to add code .getDatePicker().setMinDate(newDate.getTime() - (newDate.getTime()%(24*60*60*1000)))for disable the past date but suddenly .show() cannot be used.

Can someone teach me how to solve this kind of problem?

Code:

```<code>btnDate.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            selectDate();
                        }
                    });

private void selectDate()
{
    DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            String selectedDate = dateFormat.format(calendar.getTime());

            btnDate.setText(selectedDate);
            btnDate.setTextColor(getResources().getColor(colorPrimaryDark));
        }
    };

    Date newDate = calendar.getTime();

    new DatePickerDialog(TutorAddNewTimeSlotActivity.this,  dateSetListener,
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
}
</code>```

答:
You can simply do it like this

```<code>datePickerDialog.datePicker.minDate=Date().time
</code>```

You can create your own date picker class by inheriting the default one and define the min date like the below code

```<code>class DatePicker(var onDateSetListener: DatePickerDialog.OnDateSetListener): DialogFragment() {
var date: Date? = null

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    val c = Calendar.getInstance()
    val year = c.get(Calendar.YEAR)
    val month = c.get(Calendar.MONTH)
    val day = c.get(Calendar.DAY_OF_MONTH)
    val datePickerDialog= DatePickerDialog(activity!!,onDateSetListener, year, month, day)
    datePickerDialog.datePicker.minDate=Date().time
    return datePickerDialog
}
</code>```

}

Title: Disable past date in DatePickerDialog

Body:
I want to add code .getDatePicker().setMinDate(newDate.getTime() - (newDate.getTime()%(24*60*60*1000)))for disable the past date but suddenly .show() cannot be used.

Can someone teach me how to solve this kind of problem?

Code:

btnDate.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            selectDate();
                        }
                    });

private void selectDate()
{
    DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            String selectedDate = dateFormat.format(calendar.getTime());

            btnDate.setText(selectedDate);
            btnDate.setTextColor(getResources().getColor(colorPrimaryDark));
        }
    };

    Date newDate = calendar.getTime();

    new DatePickerDialog(TutorAddNewTimeSlotActivity.this,  dateSetListener,
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
}

Body:
You can simply do it like this

datePickerDialog.datePicker.minDate=Date().time

You can create your own date picker class by inheriting the default one and define the min date like the below code

class DatePicker(var onDateSetListener: DatePickerDialog.OnDateSetListener): DialogFragment() {
var date: Date? = null

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    val c = Calendar.getInstance()
    val year = c.get(Calendar.YEAR)
    val month = c.get(Calendar.MONTH)
    val day = c.get(Calendar.DAY_OF_MONTH)
    val datePickerDialog= DatePickerDialog(activity!!,onDateSetListener, year, month, day)
    datePickerDialog.datePicker.minDate=Date().time
    return datePickerDialog
}

}


问:
Removing specific value from cell of dataframe and shifting the value towards left
I'm working with the pandas data frame. I have unwanted data in some cells. I need to clear that data from specific cells and shift the whole row towards left by one cell. I have tried couple of things but it is not working for me. Here is the example dataframe

```<code>     userId             movieId  ratings  extra
0       1                 500      3.5
1       1                 600      4.5
2       1                www.abcd      700     2.0
3       2                1100      5.0
4       2                1200      4.0
5       3                 600      4.5
6       4                 600      5.0
7       4                1900      3.5
</code>```

Expected Outcome:

```<code>     userId             movieId  ratings   extra
0       1                 500      3.5
1       1                 600      4.5
2       1                 700      2.0
3       2                1100      5.0
4       2                1200      4.0
5       3                 600      4.5
6       4                 600      5.0
7       4                1900      3.5
</code>```

I have tried the following code but it is showing the following error.

```<code>raw = df[f['ratings'].str.contains('www')==True]

#Here I am trying to fix the specific cell value to empty but it shows the following error.
**AttributeError:** 'str' object has no attribute 'at'
df = df.at[raw, 'movieId'] = ' '

#code for shifting the cell value to left
df.iloc[raw,2:-1] = df.iloc[raw,2:-1].shift(-1,axis=1)

</code>```

答:
You can shift values by mask, but is realy important match types, it means if column movieId is filled by strings (because at leas one string) is necessary convert it to numeric by to_numeric for avoid data lost, because different types:

```<code>m = df['movieId'].str.contains('www')
df['movieId'] = pd.to_numeric(df['movieId'], errors='coerce')

#if want shift only missing values rows
#m = df['movieId'].isna()
df[m] = df[m].shift(-1, axis=1)
df['userId'] = df['userId'].ffill()
df = df.drop('extra', axis=1)
print (df)
   userId  movieId  ratings
0     1.0    500.0      3.5
1     1.0    600.0      4.5
2     1.0    700.0      2.0
3     2.0   1100.0      5.0
4     2.0   1200.0      4.0
5     3.0    600.0      4.5
6     4.0    600.0      5.0
7     4.0   1900.0      3.5
</code>```

If omit converting to numeric get missing value:

```<code>m = df['movieId'].str.contains('www')
df[m] = df[m].shift(-1, axis=1)
df['userId'] = df['userId'].ffill()
df = df.drop('extra', axis=1)
print (df)
   userId movieId  ratings
0     1.0     500      3.5
1     1.0     600      4.5
2     1.0     NaN      2.0
3     2.0    1100      5.0
4     2.0    1200      4.0
5     3.0     600      4.5
6     4.0     600      5.0
7     4.0    1900      3.5
</code>```

Body:
I'm working with the pandas data frame. I have unwanted data in some cells. I need to clear that data from specific cells and shift the whole row towards left by one cell. I have tried couple of things but it is not working for me. Here is the example dataframe

     userId             movieId  ratings  extra
0       1                 500      3.5
1       1                 600      4.5
2       1                www.abcd      700     2.0
3       2                1100      5.0
4       2                1200      4.0
5       3                 600      4.5
6       4                 600      5.0
7       4                1900      3.5

Expected Outcome:

     userId             movieId  ratings   extra
0       1                 500      3.5
1       1                 600      4.5
2       1                 700      2.0
3       2                1100      5.0
4       2                1200      4.0
5       3                 600      4.5
6       4                 600      5.0
7       4                1900      3.5

I have tried the following code but it is showing the following error.

raw = df[f['ratings'].str.contains('www')==True]

#Here I am trying to fix the specific cell value to empty but it shows the following error.
**AttributeError:** 'str' object has no attribute 'at'
df = df.at[raw, 'movieId'] = ' '

#code for shifting the cell value to left
df.iloc[raw,2:-1] = df.iloc[raw,2:-1].shift(-1,axis=1)

Body:
You can shift values by mask, but is realy important match types, it means if column movieId is filled by strings (because at leas one string) is necessary convert it to numeric by to_numeric for avoid data lost, because different types:

m = df['movieId'].str.contains('www')
df['movieId'] = pd.to_numeric(df['movieId'], errors='coerce')

#if want shift only missing values rows
#m = df['movieId'].isna()
df[m] = df[m].shift(-1, axis=1)
df['userId'] = df['userId'].ffill()
df = df.drop('extra', axis=1)
print (df)
   userId  movieId  ratings
0     1.0    500.0      3.5
1     1.0    600.0      4.5
2     1.0    700.0      2.0
3     2.0   1100.0      5.0
4     2.0   1200.0      4.0
5     3.0    600.0      4.5
6     4.0    600.0      5.0
7     4.0   1900.0      3.5

If omit converting to numeric get missing value:

m = df['movieId'].str.contains('www')
df[m] = df[m].shift(-1, axis=1)
df['userId'] = df['userId'].ffill()
df = df.drop('extra', axis=1)
print (df)
   userId movieId  ratings
0     1.0     500      3.5
1     1.0     600      4.5
2     1.0     NaN      2.0
3     2.0    1100      5.0
4     2.0    1200      4.0
5     3.0     600      4.5
6     4.0     600      5.0
7     4.0    1900      3.5


问:
Gym's box 2d (openAI) doesn't install successfully (pip error)
I'm trying to do the follow code with OpenAI:

import gym
env = gym.make('CarRacing-v0')
env.reset()

for _ in range(1000):
 env.render()
 env.step(env.action_space.sample())
```

<p>but it throws the error:</p>

<blockquote>
  <p>fn = getattr(mod, attr_name)
  AttributeError: module 'gym.envs.box2d' has no attribute 'CarRacing'</p>
</blockquote>

<p>And then I try to install box2d by pip install box2d-py throwing this error:</p>

```ERROR: Command errored out with exit status 1:
     command: 'C:\Users\Junior\Anaconda\envs\gym\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Junior\\AppData\\Local\\Temp\\pip-install-w8awn22p\\box2d-py\\setup.py'"'"'; __file__='"'"'C:\\Users\\Junior\\AppData\\Local\\Temp\\pip-install-w8awn22p\\box2d-py\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Junior\AppData\Local\Temp\pip-record-netg1nlq\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Junior\Anaconda\envs\gym\Include\box2d-py'
         cwd: C:\Users\Junior\AppData\Local\Temp\pip-install-w8awn22p\box2d-py\
    Complete output (16 lines):
    Using setuptools (version 45.2.0.post20200210).
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.7
    creating build\lib.win-amd64-3.7\Box2D
    copying library\Box2D\Box2D.py -> build\lib.win-amd64-3.7\Box2D
    copying library\Box2D\__init__.py -> build\lib.win-amd64-3.7\Box2D
    creating build\lib.win-amd64-3.7\Box2D\b2
    copying library\Box2D\b2\__init__.py -> build\lib.win-amd64-3.7\Box2D\b2
    running build_ext
    building 'Box2D._Box2D' extension
    swigging Box2D\Box2D.i to Box2D\Box2D_wrap.cpp
    swig.exe -python -c++ -IBox2D -small -O -includeall -ignoremissing -w201 -globals b2Globals -outdir library\Box2D -keyword -w511 -D_SWIG_KWARGS -o Box2D\Box2D_wrap.cpp Box2D\Box2D.i
    error: command 'swig.exe' failed: No such file or directory
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'C:\Users\Junior\Anaconda\envs\gym\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Junior\\AppData\\Local\\Temp\\pip-install-w8awn22p\\box2d-py\\setup.py'"'"'; __file__='"'"'C:\\Users\\Junior\\AppData\\Local\\Temp\\pip-install-w8awn22p\\box2d-py\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Junior\AppData\Local\Temp\pip-record-netg1nlq\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Junior\Anaconda\envs\gym\Include\box2d-py' Check the logs for full command output.
```

what I have to do to install it successfully?

答:
Windows support is at present moment experimental (source). That being said, on most of the occasions you will get it to work, but some of the functionality could be broken. Proceed with caution.

Here's what could work:

Install Anaconda.

Start Anaconda command line (it adds conda to the PATH).

conda create -c conda-forge -n gymenv swig pip - create base environment.

conda activate gymenv - activate it.

pip install Box2D gym - install base gym with Box2D.

(Optional) pip install gym[all] - install all components of Gym. You might run into errors.

If you get build errors on missing compilers, install Visual Studio Built Tools.

Depending on the component you're using, you might need e.g. pystan. Activate then the conda environment and install it, i.e. conda install pystan.

An alternative could be to try to install Gym directly through conda:

```<code>conda create -c conda-forge -c powerai -n gymenv gym swig pip pystan
</code>```

This will install gym from powerai channel. Might work, but mind that it's not the latest nor seems to be supported by devs.

Body:
I'm trying to do the follow code with OpenAI:

import gym
env = gym.make('CarRacing-v0')
env.reset()

for _ in range(1000):
 env.render()
 env.step(env.action_space.sample())

but it throws the error:

fn = getattr(mod, attr_name)
  AttributeError: module 'gym.envs.box2d' has no attribute 'CarRacing'

And then I try to install box2d by pip install box2d-py throwing this error:

ERROR: Command errored out with exit status 1:
     command: 'C:\Users\Junior\Anaconda\envs\gym\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Junior\\AppData\\Local\\Temp\\pip-install-w8awn22p\\box2d-py\\setup.py'"'"'; __file__='"'"'C:\\Users\\Junior\\AppData\\Local\\Temp\\pip-install-w8awn22p\\box2d-py\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Junior\AppData\Local\Temp\pip-record-netg1nlq\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Junior\Anaconda\envs\gym\Include\box2d-py'
         cwd: C:\Users\Junior\AppData\Local\Temp\pip-install-w8awn22p\box2d-py\
    Complete output (16 lines):
    Using setuptools (version 45.2.0.post20200210).
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.7
    creating build\lib.win-amd64-3.7\Box2D
    copying library\Box2D\Box2D.py -> build\lib.win-amd64-3.7\Box2D
    copying library\Box2D\__init__.py -> build\lib.win-amd64-3.7\Box2D
    creating build\lib.win-amd64-3.7\Box2D\b2
    copying library\Box2D\b2\__init__.py -> build\lib.win-amd64-3.7\Box2D\b2
    running build_ext
    building 'Box2D._Box2D' extension
    swigging Box2D\Box2D.i to Box2D\Box2D_wrap.cpp
    swig.exe -python -c++ -IBox2D -small -O -includeall -ignoremissing -w201 -globals b2Globals -outdir library\Box2D -keyword -w511 -D_SWIG_KWARGS -o Box2D\Box2D_wrap.cpp Box2D\Box2D.i
    error: command 'swig.exe' failed: No such file or directory
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'C:\Users\Junior\Anaconda\envs\gym\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Junior\\AppData\\Local\\Temp\\pip-install-w8awn22p\\box2d-py\\setup.py'"'"'; __file__='"'"'C:\\Users\\Junior\\AppData\\Local\\Temp\\pip-install-w8awn22p\\box2d-py\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Junior\AppData\Local\Temp\pip-record-netg1nlq\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Junior\Anaconda\envs\gym\Include\box2d-py' Check the logs for full command output.

what I have to do to install it successfully?

Body:
Windows support is at present moment experimental (source). That being said, on most of the occasions you will get it to work, but some of the functionality could be broken. Proceed with caution.

Here's what could work:

Install Anaconda.

Start Anaconda command line (it adds conda to the PATH).

conda create -c conda-forge -n gymenv swig pip - create base environment.

conda activate gymenv - activate it.

pip install Box2D gym - install base gym with Box2D.

(Optional) pip install gym[all] - install all components of Gym. You might run into errors.

If you get build errors on missing compilers, install Visual Studio Built Tools.

Depending on the component you're using, you might need e.g. pystan. Activate then the conda environment and install it, i.e. conda install pystan.

An alternative could be to try to install Gym directly through conda:

conda create -c conda-forge -c powerai -n gymenv gym swig pip pystan

This will install gym from powerai channel. Might work, but mind that it's not the latest nor seems to be supported by devs.


问:
error at javascript that connect to sql, asp.net c#
I have javascript timer countdown with the code:

```<code><script language="JavaScript">
TargetDate = "<% = TargetDate %>";
/*this is a property in code behind*/BackColor = "palegreen";
ForeColor = "navy";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
FinishMessage = "the auction end"
</script>
<script language="JavaScript" src="countdown.js"></script>
</script>
</code>```

the code behind:

```<code>public string TargetDate ()
{

    DataTable dataTable = new DataTable();
    using (SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True"))
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "select * from endTime";
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        dataTable.Load(reader); }
}
</code>```

i get the error:
't.TargetDate()': not all code paths return value.

when i tried to write return i got another error... what means that i dont know what to do :)

答:
First of all you must return the targetdate value as string according to your function specification.
You should read the datatable and return that. Something like this

```<code>public string TargetDate ()
{
    String tDate = "";
    DataTable dataTable = new DataTable();
    using (SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connection=True"))
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "select * from endTime";
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        dataTable.Load(reader);
         tDate = dataTable.Rows[0][0].toString(); // Expecting the first row and first column
 }
return tDate;
}
</code>```

Hope this helps.

Body:
I have javascript timer countdown with the code:

</script>

the code behind:

public string TargetDate ()
{

    DataTable dataTable = new DataTable();
    using (SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True"))
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "select * from endTime";
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        dataTable.Load(reader); }
}

i get the error:
't.TargetDate()': not all code paths return value.

when i tried to write return i got another error... what means that i dont know what to do :)

Body:
First of all you must return the targetdate value as string according to your function specification.
You should read the datatable and return that. Something like this

public string TargetDate ()
{
    String tDate = "";
    DataTable dataTable = new DataTable();
    using (SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connection=True"))
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "select * from endTime";
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        dataTable.Load(reader);
         tDate = dataTable.Rows[0][0].toString(); // Expecting the first row and first column
 }
return tDate;
}

Hope this helps.


问:
Angular 9 not producing app.module.ngfactory
I am doing an aot compile of angular 9(upgraded from 6) project but I see that no ngFactory files are bein produced. I have a reference of app.module.ngfactory in my main aot file. Something like this:

```<code>import { enableProdMode } from '@angular/core';
import { platformBrowser } from '@angular/platform-browser';
import { AppModuleNgFactory } from './app/app.module.ngfactory';

enableProdMode();

platformBrowser().bootstrapModuleFactory(AppModuleNgFactory).catch(err => {
});
</code>```

Any pointers on how to resolve the issue?
TIA

答: In Angular 9 and Ivy, there are no ngfactory files anymore, you should remove the main-aot.ts file</p>

Body:
I am doing an aot compile of angular 9(upgraded from 6) project but I see that no ngFactory files are bein produced. I have a reference of app.module.ngfactory in my main aot file. Something like this:

import { enableProdMode } from '@angular/core';
import { platformBrowser } from '@angular/platform-browser';
import { AppModuleNgFactory } from './app/app.module.ngfactory';

enableProdMode();

platformBrowser().bootstrapModuleFactory(AppModuleNgFactory).catch(err => {
});

Any pointers on how to resolve the issue?
TIA


问:
Get images from PHP server to Android
I am prototyping an android application and need to get images from a web server to Android ListView. I understand the android side of things (although am yet to implement and test) via this thread Lazy load of images in ListView

I need help with the PHP/server side of it. The particular images that need to be populated in a list view will be decided dynamically (those images that have a given tag). I am new to web applications but have managed to set up a web server which can run PHP scripts.

1) Android decides which tags to retrieve. Makes an HTTP connection and calls a PHP script with the given tag as a parameter.

2) The PHP script looks up the MySQL database for the tag, decides the ids of images to upload, which are stored in a folder.

3) [Here is where I am unclear how to implement] The PHP sends these images followed by meta-data associated with each image. The number of records to send will not be fixed beforehand and will be decided by the number of records returned by MySQL (only maximum will be fixed).

I would greatly appreciate any sample scripts, and pointers to where I could find more information to better understand the inner working. Also, if there are better frameworks to do what I want to, I am happy to learn about that (I am not married to PHP/MySQL).

答:
I guess you should use JSON to send data to your mobile device via HTTP connection. For low internet connect I don't prefer SOAP.

If you can not load images directly via HTTP URL you can send image data in JSON, and mime type as well and create image object through image data.

Title: Get images from PHP server to Android


问:
Generating Directed Graph With Parallel Labelled Edges/Vertices in Python
What is the best way to generate a Directed Graph With Parallel Labelled Edges/Vertices in Python like the one in the Image below??

I have already tried networkx but it does not work with parallel edges.

This is the code I'm using to generate the data for the Graph.

```<code>from forex_python.converter import CurrencyRates
import pandas as pd

chosen_currencies = ['GBP', 'EUR', 'USD']

c = CurrencyRates()

rates = []

for currency_index in range(len(chosen_currencies)):
    temp_list = []
    for second_index in range(len(chosen_currencies)):
        temp_list.append(c.get_rate(chosen_currencies[currency_index], chosen_currencies[second_index]))
    rates.append(temp_list)

df = (pd.DataFrame.from_records(rates)).transpose()
df.columns = chosen_currencies
</code>```

答:
You can use the dataframe to read the edges directly into a NetworkX graph using from_pandas_adjacency. In order to do that, lets set the index of the dataframe equal to chosen_currencies, to ensure that the edges are mapped correctly.

```<code>from forex_python.converter import CurrencyRates
import pandas as pd

chosen_currencies = ['GBP', 'EUR', 'USD']

c = CurrencyRates()

rates = []

for currency_index in range(len(chosen_currencies)):
    temp_list = []
    for second_index in range(len(chosen_currencies)):
        temp_list.append(c.get_rate(chosen_currencies[currency_index], chosen_currencies[second_index]))
    rates.append(temp_list)

df = (pd.DataFrame.from_records(rates)).transpose()
df.columns = chosen_currencies
#   GBP         EUR     USD
#0  1.000000    0.83238 0.768233
#1  1.201374    1.00000 0.922935
#2  1.301689    1.08350 1.000000
</code>```

Now set the index

```<code>df.set_index([pd.Index(chosen_currencies)], inplace=True)
#       GBP         EUR     USD
#GBP    1.000000    0.83238 0.768233
#EUR    1.201374    1.00000 0.922935
#USD    1.301689    1.08350 1.000000
</code>```

Now let's create the graph

```<code>import networkx as nx
import matplotlib.pyplot as plt

G = nx.from_pandas_adjacency(df, create_using=nx.DiGraph)

# Set the figure size
plt.figure(figsize=(8,8))

# Get the edge labels and round them to 3 decimal places
# for more clarity while drawing
edge_labels = dict([((u,v), round(d['weight'], 3))
             for u,v,d in G.edges(data=True)])

# Get the layout
pos = nx.spring_layout(G)

# Draw edge labels and graph
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels,
                             label_pos=0.15, font_size=10)
nx.draw(G, pos, with_labels=True,
        connectionstyle='arc3, rad = 0.15',
        node_size=800)

plt.show()
</code>```

Note: The number near the arrowhead is the edge weight.

You can also view this Google Colab Notebook with above working example.

You can adjust the font size, label position, etc. according to your requirements.

References:

Connection Style

Draw Edge Labels

Drawing multiple edge labels

Body:
What is the best way to generate a Directed Graph With Parallel Labelled Edges/Vertices in Python like the one in the Image below??

I have already tried networkx but it does not work with parallel edges.

This is the code I'm using to generate the data for the Graph.

from forex_python.converter import CurrencyRates
import pandas as pd

chosen_currencies = ['GBP', 'EUR', 'USD']

c = CurrencyRates()

rates = []

for currency_index in range(len(chosen_currencies)):
    temp_list = []
    for second_index in range(len(chosen_currencies)):
        temp_list.append(c.get_rate(chosen_currencies[currency_index], chosen_currencies[second_index]))
    rates.append(temp_list)

df = (pd.DataFrame.from_records(rates)).transpose()
df.columns = chosen_currencies

Body:
You can use the dataframe to read the edges directly into a NetworkX graph using from_pandas_adjacency. In order to do that, lets set the index of the dataframe equal to chosen_currencies, to ensure that the edges are mapped correctly.

from forex_python.converter import CurrencyRates
import pandas as pd

chosen_currencies = ['GBP', 'EUR', 'USD']

c = CurrencyRates()

rates = []

for currency_index in range(len(chosen_currencies)):
    temp_list = []
    for second_index in range(len(chosen_currencies)):
        temp_list.append(c.get_rate(chosen_currencies[currency_index], chosen_currencies[second_index]))
    rates.append(temp_list)

df = (pd.DataFrame.from_records(rates)).transpose()
df.columns = chosen_currencies
#   GBP         EUR     USD
#0  1.000000    0.83238 0.768233
#1  1.201374    1.00000 0.922935
#2  1.301689    1.08350 1.000000

Now set the index

df.set_index([pd.Index(chosen_currencies)], inplace=True)
#       GBP         EUR     USD
#GBP    1.000000    0.83238 0.768233
#EUR    1.201374    1.00000 0.922935
#USD    1.301689    1.08350 1.000000

Now let's create the graph

import networkx as nx
import matplotlib.pyplot as plt

G = nx.from_pandas_adjacency(df, create_using=nx.DiGraph)

# Set the figure size
plt.figure(figsize=(8,8))

# Get the edge labels and round them to 3 decimal places
# for more clarity while drawing
edge_labels = dict([((u,v), round(d['weight'], 3))
             for u,v,d in G.edges(data=True)])

# Get the layout
pos = nx.spring_layout(G)

# Draw edge labels and graph
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels,
                             label_pos=0.15, font_size=10)
nx.draw(G, pos, with_labels=True,
        connectionstyle='arc3, rad = 0.15',
        node_size=800)

plt.show()

Note: The number near the arrowhead is the edge weight.

You can also view this Google Colab Notebook with above working example.

You can adjust the font size, label position, etc. according to your requirements.

References:

Connection Style

Draw Edge Labels

Drawing multiple edge labels


问:
Content-length available in Curl, Wget, but not in Python Requests
I have an URL pointing to a binary file which I need to download after checking its size, because the download should only be (re-)executed if the local file size differs from the remote file size.

This is how it works with wget (anonymized host names and IPs):

```<code>$ wget <URL>
--2020-02-17 11:09:18--  <URL>
Resolving <URL> (<host>)... <IP>
Connecting to <host> (<host>)|<ip>|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 31581872 (30M) [application/x-gzip]
Saving to: ‘[...]’
</code>```

This also works fine with the --continue flag in order to resume a download, including skipping if the file was completely downloaded earlier.

I can do the same with curl, the content-length is also present:

```<code>$ curl -I <url>
HTTP/2 200
date: Mon, 17 Feb 2020 13:11:55 GMT
server: Apache/2.4.25 (Debian)
strict-transport-security: max-age=15768000
last-modified: Fri, 14 Feb 2020 15:42:29 GMT
etag: "[...]"
accept-ranges: bytes
content-length: 31581872
vary: Accept-Encoding
content-type: application/x-gzip
</code>```

In Python, I try to implement the same logic by checking the Content-length header using the requests library:

```<code>        with requests.get(url, stream=True) as response:
            total_size = int(response.headers.get("Content-length"))

            if not response.ok:
                logger.error(
                    f"Error {response.status_code} when downloading file from {url}"
                )
            elif os.path.exists(file) and os.stat(file).st_size == total_size:
                logger.info(f"File '{file}' already exists, skipping download.")
            else:
                [...] # download file
</code>```

It turns out that the Content-length header is never present, i.e. gets a None value here. I know that this should be worked around by passing a default value to the get() call, but for the purpose of debugging, this example consequently triggers an exception:

```<code>TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
</code>```

I can confirm manually that the Content-length header is not there:

```<code>requests.get(url, stream=True).headers
{'Date': '[...]', 'Server': '[...]', 'Strict-Transport-Security': '[...]', 'Upgrade': '[...]', 'Connection': 'Upgrade, Keep-Alive', 'Last-Modified': '[...]', 'ETag': ''[...]'', 'Accept-Ranges': 'bytes', 'Vary': 'Accept-Encoding', 'Content-Encoding': 'gzip', 'Keep-Alive': 'timeout=15, max=100', 'Transfer-Encoding': 'chunked', 'Content-Type': 'application/x-gzip'}
</code>```

This logic works fine though for other URLs, i.e. I do get the Content-length header.

When using requests.head(url) (omitting the stream=True), I get the same headers except for Transfer-Encoding.

I understand that a server does not have to send a Content-length header.
However, wget and curl clearly do get that header. What do they do differently from my Python implementation?

答:
Not really an answer to the question about the missing Content-length header, but a solution to the underlying problem:

Instead of checking the local file size vs the content length of the remote, I have ended up checking the Last-modified header and compare that to the mtime of the local file. This is also safer in (the unlikely) case that the remote file is updated, but still has the exact same size.

Body:
I have an URL pointing to a binary file which I need to download after checking its size, because the download should only be (re-)executed if the local file size differs from the remote file size.

This is how it works with wget (anonymized host names and IPs):

$ wget <URL>
--2020-02-17 11:09:18--  <URL>
Resolving <URL> (<host>)... <IP>
Connecting to <host> (<host>)|<ip>|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 31581872 (30M) [application/x-gzip]
Saving to: ‘[...]’

This also works fine with the --continue flag in order to resume a download, including skipping if the file was completely downloaded earlier.

I can do the same with curl, the content-length is also present:

$ curl -I <url>
HTTP/2 200
date: Mon, 17 Feb 2020 13:11:55 GMT
server: Apache/2.4.25 (Debian)
strict-transport-security: max-age=15768000
last-modified: Fri, 14 Feb 2020 15:42:29 GMT
etag: "[...]"
accept-ranges: bytes
content-length: 31581872
vary: Accept-Encoding
content-type: application/x-gzip

In Python, I try to implement the same logic by checking the Content-length header using the requests library:

        with requests.get(url, stream=True) as response:
            total_size = int(response.headers.get("Content-length"))

            if not response.ok:
                logger.error(
                    f"Error {response.status_code} when downloading file from {url}"
                )
            elif os.path.exists(file) and os.stat(file).st_size == total_size:
                logger.info(f"File '{file}' already exists, skipping download.")
            else:
                [...] # download file

It turns out that the Content-length header is never present, i.e. gets a None value here. I know that this should be worked around by passing a default value to the get() call, but for the purpose of debugging, this example consequently triggers an exception:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

I can confirm manually that the Content-length header is not there:

requests.get(url, stream=True).headers
{'Date': '[...]', 'Server': '[...]', 'Strict-Transport-Security': '[...]', 'Upgrade': '[...]', 'Connection': 'Upgrade, Keep-Alive', 'Last-Modified': '[...]', 'ETag': ''[...]'', 'Accept-Ranges': 'bytes', 'Vary': 'Accept-Encoding', 'Content-Encoding': 'gzip', 'Keep-Alive': 'timeout=15, max=100', 'Transfer-Encoding': 'chunked', 'Content-Type': 'application/x-gzip'}

This logic works fine though for other URLs, i.e. I do get the Content-length header.

When using requests.head(url) (omitting the stream=True), I get the same headers except for Transfer-Encoding.

I understand that a server does not have to send a Content-length header.
However, wget and curl clearly do get that header. What do they do differently from my Python implementation?


问:
loading data using ng-table issue
I am trying to display data set using, ng-table. but data is not loading. please check my sample service and controller

```<code>app.service('ContactService', function () {
    var bfLosses = [
        { idx: 0, uid: 'User 11', name: 'Name 11', area: 'Area 1'},
        { idx: 1, uid: 'User 12', name: 'Name 12', area: 'Area 1'},
        { idx: 2, uid: 'User 21', name: 'Name 21', area: 'Area 2'},
        { idx: 3, uid: 'User 22', name: 'Name 22', area: 'Area 2'}
    ];
}
</code>```

i need to access above array to populate table. my controller

```<code>app.controller("businessController", function ($scope,NgTableParams,ContactService){
    $scope.tableParams = new NgTableParams({
        group: "area"
      },{
        dataset:   $scope.bfLosses
    });
});
</code>```

when define array inside the controller , working well. but my requirement is accessing it inside the controller.

答:
You can also use 'this' in case of service not in case of factories

```<code>app.service('ContactService', function () {
this.bfLosses = [
    { idx: 0, uid: 'User 11', name: 'Name 11', area: 'Area 1'},
    { idx: 1, uid: 'User 12', name: 'Name 12', area: 'Area 1'},
    { idx: 2, uid: 'User 21', name: 'Name 21', area: 'Area 2'},
    { idx: 3, uid: 'User 22', name: 'Name 22', area: 'Area 2'}
  ];
});
</code>```

Controller:

```<code>app.controller("businessController", function ($scope,NgTableParams,ContactService){
  $scope.tableParams = new NgTableParams({
    group: "area"
  },{
    dataset:   ContactService.bfLosses
  });
});
</code>```

Title: loading data using ng-table issue

Body:
I am trying to display data set using, ng-table. but data is not loading. please check my sample service and controller

app.service('ContactService', function () {
    var bfLosses = [
        { idx: 0, uid: 'User 11', name: 'Name 11', area: 'Area 1'},
        { idx: 1, uid: 'User 12', name: 'Name 12', area: 'Area 1'},
        { idx: 2, uid: 'User 21', name: 'Name 21', area: 'Area 2'},
        { idx: 3, uid: 'User 22', name: 'Name 22', area: 'Area 2'}
    ];
}

i need to access above array to populate table. my controller

app.controller("businessController", function ($scope,NgTableParams,ContactService){
    $scope.tableParams = new NgTableParams({
        group: "area"
      },{
        dataset:   $scope.bfLosses
    });
});

when define array inside the controller , working well. but my requirement is accessing it inside the controller.

Body:
You can also use 'this' in case of service not in case of factories

app.service('ContactService', function () {
this.bfLosses = [
    { idx: 0, uid: 'User 11', name: 'Name 11', area: 'Area 1'},
    { idx: 1, uid: 'User 12', name: 'Name 12', area: 'Area 1'},
    { idx: 2, uid: 'User 21', name: 'Name 21', area: 'Area 2'},
    { idx: 3, uid: 'User 22', name: 'Name 22', area: 'Area 2'}
  ];
});

Controller:

app.controller("businessController", function ($scope,NgTableParams,ContactService){
  $scope.tableParams = new NgTableParams({
    group: "area"
  },{
    dataset:   ContactService.bfLosses
  });
});


问:
How to define a function with a parameter in it in Octave?
I am trying to define a function with a predefined variable, and Octave says that the variable was not defined. I am trying to run the following code in Octave,

q = 5;
function w = tointegrate(x)
  w = 2 * q * sin(x);
endfunction
[ans, ier, nfun, err] = quad("tointegrate", -10*q, 10*q);
ans
```

<p>Octave gives the error</p>

<blockquote>
```error: 'q' undefined near line 3 column 10
error: quad: evaluation of user-supplied function failed
```

How to fix this error?

答:
You are expecting 'commandline functions' in octave to have lexical scope, but this is simply not the case.

If all of this was inside a function, and you defined a nested function, it would work as you expect. But 'commandline functions' like this are treated as if they are in their own file, and have no knowledge of the workspace in which they've been defined.

In this particular case, since your function is effectively a one-liner, you can get the effect you want by making it a function handle instead, which 'does' capture the local workspace. I.e. this will work

```<code>q = 5;
tointegrate = @(x) 2 * q * sin(x);
[ans, ier, nfun, err] = quad("tointegrate",-10 *q ,10*q);
</code>```

Note, however, that 'q' will have the value it had at the time it was captured. I.e. if you update q dynamically, its value will not be updated in the function handle.

Otherwise, for more complex functions, the solution is really to pass it as a parameter (or to access it as a global etc).

Body:
I am trying to define a function with a predefined variable, and Octave says that the variable was not defined. I am trying to run the following code in Octave,

q = 5;
function w = tointegrate(x)
  w = 2 * q * sin(x);
endfunction
[ans, ier, nfun, err] = quad("tointegrate", -10*q, 10*q);
ans

Octave gives the error

error: 'q' undefined near line 3 column 10
error: quad: evaluation of user-supplied function failed

How to fix this error?

Body:
You are expecting 'commandline functions' in octave to have lexical scope, but this is simply not the case.

If all of this was inside a function, and you defined a nested function, it would work as you expect. But 'commandline functions' like this are treated as if they are in their own file, and have no knowledge of the workspace in which they've been defined.

In this particular case, since your function is effectively a one-liner, you can get the effect you want by making it a function handle instead, which 'does' capture the local workspace. I.e. this will work

q = 5;
tointegrate = @(x) 2 * q * sin(x);
[ans, ier, nfun, err] = quad("tointegrate",-10 *q ,10*q);

Note, however, that 'q' will have the value it had at the time it was captured. I.e. if you update q dynamically, its value will not be updated in the function handle.

Otherwise, for more complex functions, the solution is really to pass it as a parameter (or to access it as a global etc).


问:
How to delete all objects from a S3 folder of various sub folder with Specific name which are older than n days using AWS Ruby SDK
I have a requirement to delete files with prefix application.log which are older than 5 days in an S3 folder.

The file is present inside log-bucket/main-shell/apps/app-main-shell-55f79d74fc-4sx6c/helpkit.

Is there a way where we can list and delete files recursively using AWS Ruby SDK?

答:
Rather than writing your own code you can setup AWS3 life cycle with prefix by using RUBY SDK.
In life cycle mentioned after 5th day delete data from particular path.

Below are the reference Links to configure S3 cycle and Ruby SDK.

https://docs.aws.amazon.com/sdkforruby/api/Aws/S3/BucketLifecycle.html

https://docs.aws.amazon.com/AmazonS3/latest/dev/lifecycle-configuration-examples.html


问:
I am getting a run time error '429'. Trying to get Excel macro to send a email

Sub SendEmail()
'    SendEmail Macro
'
    Dim olApp As Outlook.Application
    Set olApp = CreateObject("Outlook.Application")

    Dim olMail As Outlook.MailItem
    Set olMail = olApp.CreateItem(olMailItem)

    olMail.To = ""
    olMail.CC = ""
    olMail.Subject = " There is a change to the EMR adjustment Form that Approval"
    olMail.Send
End Sub
```

答:
You are mixing up early and late binding,

Late binding uses either the Visual Basic GetObject function or the CreateObject function to initialize Outlook

Example

```<code>Dim olApp as Object
Set olApp = CreateObject("Outlook.Application")
</code>```

To use early binding, you first need to set a reference to the Outlook object library, Microsoft Outlook xx.x Object Library

Example

```<code>Dim olApp as Outlook.Application
Set olApp = New Outlook.Application
</code>```

Body:
You are mixing up early and late binding,

Late binding uses either the Visual Basic GetObject function or the CreateObject function to initialize Outlook

Example

Dim olApp as Object
Set olApp = CreateObject("Outlook.Application")

To use early binding, you first need to set a reference to the Outlook object library, Microsoft Outlook xx.x Object Library

Example

Dim olApp as Outlook.Application
Set olApp = New Outlook.Application


问:
Unable to download remote image with PHP CURL
Edit: I contact the support at scrapestack and confirmed that their api doesn't support image files.

I am trying to download a remote image using CURL with php. Below is my code. But whenever I try to open the downloaded image, I always get:

```<code>Cannot read this file. This is not a valid bitmap file, or its format is not currently supported.
</code>```

Anyone know what is wrong with my code? Thank you.

```<code>$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://i.imgur.com/Cbiu8Ef.png";
$imageName = pathinfo( $image, PATHINFO_BASENAME );
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $image );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTP_CONTENT_DECODING, false);
$source = curl_exec( $ch );
$info = curl_getinfo($ch);
curl_close( $ch );
file_put_contents( $imageName, $source );
</code>```

I am not able to open the file, when I tried to open it with sublime, it is stuck at Loading Image. When I open it with notepad, I got the following that looks like PNG image, but it is not a valid image. File starts with
    �PNG

```<code>IHDR       �   q�I�    IDATx�k�]�u�o��(��_�M��m�8:���_r�G
</code>```

You can see the file here: https://gofile.io/?c=cfsYf2

Looks like the problem is making the curl request through Scrapestack, because if I point the curl to image url directly, the image is downloaded correctly, like below:

```<code>$image ="https://i.imgur.com/Cbiu8Ef.png";
</code>```

答:
It looks like the response you get is a corrupt PNG image.

If you are using PHP with version prior of 5.1.3 you need to specify an additional option for binary data transfers, like images:

```<code>curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
</code>```

If the above options doesn't solve the issue you may try setting

```<code>curl_setopt($ch, CURLOPT_HTTP_CONTENT_DECODING, false);
</code>```

in case the response has the Content-Type header set wrong letting curl do unwanted decoding on the raw output.

Body:
Edit: I contact the support at scrapestack and confirmed that their api doesn't support image files.

I am trying to download a remote image using CURL with php. Below is my code. But whenever I try to open the downloaded image, I always get:

Cannot read this file. This is not a valid bitmap file, or its format is not currently supported.

Anyone know what is wrong with my code? Thank you.

$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://i.imgur.com/Cbiu8Ef.png";
$imageName = pathinfo( $image, PATHINFO_BASENAME );
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $image );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTP_CONTENT_DECODING, false);
$source = curl_exec( $ch );
$info = curl_getinfo($ch);
curl_close( $ch );
file_put_contents( $imageName, $source );

I am not able to open the file, when I tried to open it with sublime, it is stuck at Loading Image. When I open it with notepad, I got the following that looks like PNG image, but it is not a valid image. File starts with
    �PNG

IHDR       �   q�I�    IDATx�k�]�u�o��(��_�M��m�8:���_r�G

You can see the file here: https://gofile.io/?c=cfsYf2

Looks like the problem is making the curl request through Scrapestack, because if I point the curl to image url directly, the image is downloaded correctly, like below:

$image ="https://i.imgur.com/Cbiu8Ef.png";

Body:
It looks like the response you get is a corrupt PNG image.

If you are using PHP with version prior of 5.1.3 you need to specify an additional option for binary data transfers, like images:

curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);

If the above options doesn't solve the issue you may try setting

curl_setopt($ch, CURLOPT_HTTP_CONTENT_DECODING, false);

in case the response has the Content-Type header set wrong letting curl do unwanted decoding on the raw output.


问:
How to compile class.cpp and class.hpp to one .o file?
How to compile class.cpp and class.hpp to one .o file? If I can, please tell me how. If I can't, please tell me what should I do if I want to do something similar. These are the latest version of my classes(they're not completed yet.): OptionParser.cpp, OptionParser.hpp. </p>

答:
To do so you need to just include class.hpp to you class.cpp file.
It can be done like

#include "class.hpp"

So you just need to have both in same folder and after that you need to add above line in class.cpp and then just compile and run the executable.


问:
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float)
Im facing problem with this line of code in keras with backend Tensorflow 2.0:

loss_out = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,))([y_pred, Y_train, X_train_length, label_length])
```

Y_train, X_train_length are numpy.ndarrays
y_pred and label_length are class 'tensorflow.python.framework.ops.Tensor'

答:
You can use

```<code>        tf.convert_to_tensor()
</code>```

example,

```<code>        import tensorflow as tf
        import numpy as np

        loss = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,))
                       ([y_pred, Y_train, X_train_length, label_length])
        loss_np = np.asarray(loss, np.float32)

        loss_tf = tf.convert_to_tensor(loss_np, np.float32)

        sess = tf.InteractiveSession()
        print(loss_tf.eval())

        sess.close()
</code>```

Body:
Im facing problem with this line of code in keras with backend Tensorflow 2.0:

loss_out = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,))([y_pred, Y_train, X_train_length, label_length])

Y_train, X_train_length are numpy.ndarrays
y_pred and label_length are class 'tensorflow.python.framework.ops.Tensor'

Body:
You can use

        tf.convert_to_tensor()

example,

        import tensorflow as tf
        import numpy as np

        loss = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,))
                       ([y_pred, Y_train, X_train_length, label_length])
        loss_np = np.asarray(loss, np.float32)

        loss_tf = tf.convert_to_tensor(loss_np, np.float32)

        sess = tf.InteractiveSession()
        print(loss_tf.eval())

        sess.close()