答:
Firstly you are shadowing your own variable

```<code>{% for user_equity in user_equity %}
</code>```

Instead of more convenient ( of course you should change context variable to plural also)

```<code>{% for user_equity in user_equities %}
</code>```

Secondly you are using .fields property which probably doesn't exist

```<code>  <p id="money_metrics_box_equity_figure">{{ user_equity.equity }}</p>
</code>```

Title: Value of Queryset doesn't populate template-tag in Django

Body:
Firstly you are shadowing your own variable

{% for user_equity in user_equity %}

Instead of more convenient ( of course you should change context variable to plural also)

{% for user_equity in user_equities %}

Secondly you are using .fields property which probably doesn't exist

  <p id="money_metrics_box_equity_figure">{{ user_equity.equity }}</p>


来源: stackexchange

问:
Correct setting of Python home and sys.prefix in an embedded environment
Current situation

I embedded Python into my C++ application. The application is installed into the common Application locations on Windows, macOS (C:\Program Files, /Applications/, ...) which require admin privileges to make modifications to these directories. My application also ships with its own Python installation. Here is an example for the packaging structure:

```<code>C:\Program Files\Foo\foo.exe
C:\Program Files\Foo\Lib
C:\Program Files\Foo\DLLs
C:\Program Files\Foo\python.exe
</code>```

The program also sets up an additional user-specific directory, which doesn't require any permissions and which is in sys.path:

```<code>C:\Users\username\AppData\Roaming\Foo\python\libs
</code>```

Problem

During initialization I call PySet_Path, Py_SetPythonHome and I set sys.prefix to Program Files\Foo (as required by the documentation)

If the user installs pip or a module through pip it ends up in this application directory which would requires elevated permissions rights of course. But there is pip install something --user to find a user friendly installation directory (which is the AppData dir in my case).

My question is, which values and combinations should I set to make use of --user? Is it recommended to set the Python home to the AppData directory, and sys.prefix to the Program Files directory?

Because, that would mean the user could use --user to control where certain files are installed to

```<code>C:\Program Files\Foo\python.exe -m pip install xyz --user
would go into the user directory

C:\Program Files\Foo\python.exe -m pip install xyz
would go into the Program Files directory
</code>```

Is this recommended, or am I overseeing any side-effects here?

答:
I previously embedded a python interpreter into a Java application.  I used Virtual Environments to manage things.  This gives a lot of control over packages and where things end up.

Essentially you can have things in the system and/or override them in the virtualenv.  And you can have virtualenv's for each user if needed.

See here for more about it:

https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

ContentLicense: CC BY-SA 4.0

Body:
Current situation

I embedded Python into my C++ application. The application is installed into the common Application locations on Windows, macOS (C:\Program Files, /Applications/, ...) which require admin privileges to make modifications to these directories. My application also ships with its own Python installation. Here is an example for the packaging structure:

C:\Program Files\Foo\foo.exe
C:\Program Files\Foo\Lib
C:\Program Files\Foo\DLLs
C:\Program Files\Foo\python.exe

The program also sets up an additional user-specific directory, which doesn't require any permissions and which is in sys.path:

C:\Users\username\AppData\Roaming\Foo\python\libs

Problem

During initialization I call PySet_Path, Py_SetPythonHome and I set sys.prefix to Program Files\Foo (as required by the documentation)

If the user installs pip or a module through pip it ends up in this application directory which would requires elevated permissions rights of course. But there is pip install something --user to find a user friendly installation directory (which is the AppData dir in my case).

My question is, which values and combinations should I set to make use of --user? Is it recommended to set the Python home to the AppData directory, and sys.prefix to the Program Files directory?

Because, that would mean the user could use --user to control where certain files are installed to

C:\Program Files\Foo\python.exe -m pip install xyz --user
would go into the user directory

C:\Program Files\Foo\python.exe -m pip install xyz
would go into the Program Files directory

Is this recommended, or am I overseeing any side-effects here?


问:
Centering rotated text in
How to vertically center "There is information text" here?

Better - without changing html.

Also why doesn't max-width: 15px!important limit the width of the first  (tall) to 15px? How to limit it without changing the general width parameter?

td {width: 60px}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="1">
    <tbody>
        <tr>
            <td style="max-width: 15px!important;" rowspan="12">
                <p style="transform: rotate(270deg); white-space: nowrap">There is information text</p>
            </td>
            <td>1</td>
        </tr>
        <tr>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
        </tr>
        <tr>
            <td>4</td>
        </tr>
        <tr>
            <td>5</td>
        </tr>
        <tr>
            <td>6</td>
        </tr>
        <tr>
            <td>7</td>
        </tr>
        <tr>
            <td>8</td>
        </tr>
        <tr>
            <td>9</td>
        </tr>
        <tr>
            <td>10</td>
        </tr>
        <tr>
            <td>11</td>
        </tr>
        <tr>
            <td>12</td>
        </tr>
    </tbody>
</table></code>```

It is need to center it so without rotation to make it work with:

Is it possible? It is the most interesting for me.

答:
Don't use rotation but adjust the writing-mode. The text will get centred and you no more need to force the width:

td:not([rowspan]) {
  width: 60px
}

p {
  margin:5px;
  writing-mode: vertical-lr;
  transform: scale(-1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="1">
  <tbody>
    <tr>
      <td rowspan="12">
        <p>There is information text</p>
      </td>
      <td>1</td>
    </tr>
    <tr>
      <td>2</td>
    </tr>
    <tr>
      <td>3</td>
    </tr>
    <tr>
      <td>4</td>
    </tr>
    <tr>
      <td>5</td>
    </tr>
    <tr>
      <td>6</td>
    </tr>
    <tr>
      <td>7</td>
    </tr>
    <tr>
      <td>8</td>
    </tr>
    <tr>
      <td>9</td>
    </tr>
    <tr>
      <td>10</td>
    </tr>
    <tr>
      <td>11</td>
    </tr>
    <tr>
      <td>12</td>
    </tr>
  </tbody>
</table></code>```

Or like below:

td:not([rowspan]) {
  width: 60px
}

p {
  margin:5px;
  white-space:nowrap;
  max-width:15px;
  display:flex;
  justify-content:center;
  transform:rotate(-90deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="1">
  <tbody>
    <tr>
      <td rowspan="12">
        <p>There is information text</p>
      </td>
      <td>1</td>
    </tr>
    <tr>
      <td>2</td>
    </tr>
    <tr>
      <td>3</td>
    </tr>
    <tr>
      <td>4</td>
    </tr>
    <tr>
      <td>5</td>
    </tr>
    <tr>
      <td>6</td>
    </tr>
    <tr>
      <td>7</td>
    </tr>
    <tr>
      <td>8</td>
    </tr>
    <tr>
      <td>9</td>
    </tr>
    <tr>
      <td>10</td>
    </tr>
    <tr>
      <td>11</td>
    </tr>
    <tr>
      <td>12</td>
    </tr>
  </tbody>
</table></code>```

Title: Centering rotated text in <td>

Body:
How to vertically center "There is information text" here?

Better - without changing html.

Also why doesn't max-width: 15px!important limit the width of the first  (tall) to 15px? How to limit it without changing the general width parameter?

td {width: 60px}

There is information text

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

It is need to center it so without rotation to make it work with:

Is it possible? It is the most interesting for me.

Body:
Don't use rotation but adjust the writing-mode. The text will get centred and you no more need to force the width:

td:not([rowspan]) {
  width: 60px
}

p {
  margin:5px;
  writing-mode: vertical-lr;
  transform: scale(-1);
}

<table border="1">
  <tbody>
    <tr>
      <td rowspan="12">
        <p>There is information text</p>
      </td>
      <td>1</td>
    </tr>
    <tr>
      <td>2</td>
    </tr>
    <tr>
      <td>3</td>
    </tr>
    <tr>
      <td>4</td>
    </tr>
    <tr>
      <td>5</td>
    </tr>
    <tr>
      <td>6</td>
    </tr>
    <tr>
      <td>7</td>
    </tr>
    <tr>
      <td>8</td>
    </tr>
    <tr>
      <td>9</td>
    </tr>
    <tr>
      <td>10</td>
    </tr>
    <tr>
      <td>11</td>
    </tr>
    <tr>
      <td>12</td>
    </tr>
  </tbody>
</table>

Or like below:

td:not([rowspan]) {
  width: 60px
}

p {
  margin:5px;
  white-space:nowrap;
  max-width:15px;
  display:flex;
  justify-content:center;
  transform:rotate(-90deg);
}

<table border="1">
  <tbody>
    <tr>
      <td rowspan="12">
        <p>There is information text</p>
      </td>
      <td>1</td>
    </tr>
    <tr>
      <td>2</td>
    </tr>
    <tr>
      <td>3</td>
    </tr>
    <tr>
      <td>4</td>
    </tr>
    <tr>
      <td>5</td>
    </tr>
    <tr>
      <td>6</td>
    </tr>
    <tr>
      <td>7</td>
    </tr>
    <tr>
      <td>8</td>
    </tr>
    <tr>
      <td>9</td>
    </tr>
    <tr>
      <td>10</td>
    </tr>
    <tr>
      <td>11</td>
    </tr>
    <tr>
      <td>12</td>
    </tr>
  </tbody>
</table>


问:
Can't make an output with a forEach function in a template string
```<code>const categoriesLght = document.querySelectorAll('#categories .item').length;
console.log(`There are ${categoriesLght} clasifications.`);
const h2s = document.querySelectorAll('h2');
const heading = h2s.forEach(element =>
  console.log(`Clasification: ${element.textContent}`),
);

const quantity = document.querySelectorAll('h2 + ul');
quantity.forEach(el =>
  console.log(`Quantity: ${el.childElementCount}`),
);
</code>```

Output:

```<code>There are 3 clasifications.
Clasification: Student
Clasification: Fish
Clasification: Rocket
Quantity: 3
Quantity: 5
Quantity: 6
</code>```

If I try to put a function in a template string, there will be an error. Trying to find a way to make it happen. Desired output is:

```<code>Clasification: Student
Quantity: 3
Clasification: Fish
Quantity: 5
Clasification: Rocket
Quantity: 6
</code>```

And I'm looking for a way how to put a result of ForEach method in a template string, to make happen something like that (I think I'm looking for some destructurization):

```<code>str = [h2s.forEach, quantity.forEach]([category, count])=> (console.log(`Clasification: ${category.textContent},
Quantity: ${count.childElementCount} `));
</code>```

答:
Loop over one and use the index to reference the other</p>

```<code>const h2s = document.querySelectorAll('h2');
const quantity = document.querySelectorAll('h2 + ul');

h2s.forEach((element, i) =>
  console.log(`Classification: ${element.textContent}, Quantity: ${quantity[i].childElementCount}`),
);
</code>```

Body:
const categoriesLght = document.querySelectorAll('#categories .item').length;
console.log(`There are ${categoriesLght} clasifications.`);
const h2s = document.querySelectorAll('h2');
const heading = h2s.forEach(element =>
  console.log(`Clasification: ${element.textContent}`),
);

const quantity = document.querySelectorAll('h2 + ul');
quantity.forEach(el =>
  console.log(`Quantity: ${el.childElementCount}`),
);

Output:

There are 3 clasifications.
Clasification: Student
Clasification: Fish
Clasification: Rocket
Quantity: 3
Quantity: 5
Quantity: 6

If I try to put a function in a template string, there will be an error. Trying to find a way to make it happen. Desired output is:

Clasification: Student
Quantity: 3
Clasification: Fish
Quantity: 5
Clasification: Rocket
Quantity: 6

And I'm looking for a way how to put a result of ForEach method in a template string, to make happen something like that (I think I'm looking for some destructurization):

str = [h2s.forEach, quantity.forEach]([category, count])=> (console.log(`Clasification: ${category.textContent},
Quantity: ${count.childElementCount} `));

Body:
Loop over one and use the index to reference the other

const h2s = document.querySelectorAll('h2');
const quantity = document.querySelectorAll('h2 + ul');

h2s.forEach((element, i) =>
  console.log(`Classification: ${element.textContent}, Quantity: ${quantity[i].childElementCount}`),
);


问:
I want to move a button to the far most top of a stack panel by clicking it
```<code><StackPanel Name="ButtonsStack" Width="250" >
    <Button Name="button1" Content="button 1" Height="30"/>
    <Button Name="button2" Content= "button 2" Height="30" MouseDown="button2_MouseDown"/>
</StackPanel>
</code>```

<p>"""I want button2 to move above button 1 when I click button2"""</p>

答:
Buttons are just ui elements, what you are concerned about is the content needs to switch. On the button click, simply switch the content as shown below in the pseudo code:</p>

```<code>bool IsButton2 { get; set; }

public void button2_MouseDown(...)
{
    IsButton2 = !IsButton2;
    button1.Content = (IsButton2) ? "Button 2" : "Button 1";
    button2.Content = (IsButton2) ? "Button 1" : "Button 2";
}
</code>```

Body:
<StackPanel Name="ButtonsStack" Width="250" >
    <Button Name="button1" Content="button 1" Height="30"/>
    <Button Name="button2" Content= "button 2" Height="30" MouseDown="button2_MouseDown"/>
</StackPanel>

"""I want button2 to move above button 1 when I click button2"""

Body:
Buttons are just ui elements, what you are concerned about is the content needs to switch. On the button click, simply switch the content as shown below in the pseudo code:

bool IsButton2 { get; set; }

public void button2_MouseDown(...)
{
    IsButton2 = !IsButton2;
    button1.Content = (IsButton2) ? "Button 2" : "Button 1";
    button2.Content = (IsButton2) ? "Button 1" : "Button 2";
}


问:
On printing webpage , it prints all the images of image slider
I have got a jquery image slider on my webpage , when i try to print that page all the  images of that slider are printed , I want to print the current slide image , how can i acheive that , Below is the website :
Duxbury Caravans</p>

答:
Probably because all images are visible on page load. The slider javascript is not executed for the print, so you're actually printing the non-js version of your page.

Show only the first image and hide the rest in CSS. Make them visible using javascript if the slider won't do that for you.

If that won't work either (can't imagine why), include only one image in your HTML, and add the rest in javascript before the image slider is initialized.

ContentLicense: CC BY-SA 3.0


问:
How can I merge two strings of comma-separated numbers in MySQL?
For example, there are three rooms.

```<code>1|gold_room|1,2,3

2|silver_room|1,2,3

3|brown_room|2,4,6

4|brown_room|3

5|gold_room|4,5,6
</code>```

Then, I'd like to get

```<code>gold_room|1,2,3,4,5,6

brown_room|2,3,4,6

silver_room|1,2,3
</code>```

How can I achieve this?

I've tried: select * from room group by name; And it only prints the first row.  And I know CONCAT() can combine two string values.

答:
Please use below query,

```<code>select col2, GROUP_CONCAT(col3) from data group by col2;
</code>```

Below is the Test case,

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=ab35e8d66ffe3ac6436c17faf97ee9af

Body:
For example, there are three rooms.

1|gold_room|1,2,3

2|silver_room|1,2,3

3|brown_room|2,4,6

4|brown_room|3

5|gold_room|4,5,6

Then, I'd like to get

gold_room|1,2,3,4,5,6

brown_room|2,3,4,6

silver_room|1,2,3

How can I achieve this?

I've tried: select * from room group by name; And it only prints the first row.  And I know CONCAT() can combine two string values.

Body:
Please use below query,

select col2, GROUP_CONCAT(col3) from data group by col2;

Below is the Test case,

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=ab35e8d66ffe3ac6436c17faf97ee9af


问:
Xampp Wordpress admin
I've justed moved my website to localhost using Xampp.
I changed some settings to increase speed and I can access every part of my site offline from localhost:8080, instead the wp-admin.
I can see the login page and I can enter my info to login, but when I hit enter it takes too much to load and I don't know even if it will be loaded or not, but when I connect to the internet, everything works well.
Currently, I can only see the pages and posts offline and WordPress doesn't respond.
What is wrong?

Update

I use localhost:8080 to access my site, so I edited wp-config.php and changed

```<code>/** MySQL hostname */
define('DB_HOST', 'localhost');
</code>```

to

```<code>/** MySQL hostname */
define('DB_HOST', 'localhost:8080');
</code>```

but I get the following error:

Fatal error: Uncaught Error: Call to undefined function
  nocache_headers() in C:\xampp\htdocs\mysite\wp-admin\admin.php:33
  Stack trace: #0 C:\xampp\htdocs\mysite\wp-admin\index.php(10):
  require_once() #1 {main} thrown in
  C:\xampp\htdocs\mysite\wp-admin\admin.php on line 33

Some of the changes I've made

changing Listen 127.0.0.1:80 to Listen 127.0.0.1:8080 in httpd.conf

答:
There were wp files in the web root which had file size of 0 bytes.

Uploading proper copies from the zip file resolved the problem.

The same cause of the problem has occurred to me quite a few times in the past, but I had forgotten it.

Title: Xampp Wordpress admin

Body:
I've justed moved my website to localhost using Xampp.
I changed some settings to increase speed and I can access every part of my site offline from localhost:8080, instead the wp-admin.
I can see the login page and I can enter my info to login, but when I hit enter it takes too much to load and I don't know even if it will be loaded or not, but when I connect to the internet, everything works well.
Currently, I can only see the pages and posts offline and WordPress doesn't respond.
What is wrong?

Update

I use localhost:8080 to access my site, so I edited wp-config.php and changed

/** MySQL hostname */
define('DB_HOST', 'localhost');

to

/** MySQL hostname */
define('DB_HOST', 'localhost:8080');

but I get the following error:

Fatal error: Uncaught Error: Call to undefined function
  nocache_headers() in C:\xampp\htdocs\mysite\wp-admin\admin.php:33
  Stack trace: #0 C:\xampp\htdocs\mysite\wp-admin\index.php(10):
  require_once() #1 {main} thrown in
  C:\xampp\htdocs\mysite\wp-admin\admin.php on line 33

Some of the changes I've made

changing Listen 127.0.0.1:80 to Listen 127.0.0.1:8080 in httpd.conf


问:
Unirest post with GZIPOutputStream not working with python Flask api
Getting following error while posting compressed payload from Java client (Unirest) to Flask Api.

[POST]>. Error 400 Bad Request: Failed to decode JSON object: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte while decompression. \",). in loads\n    s = s.decode(encoding)\nUnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte\n\nDuring handling of the above exception, another exception occurred

The payload is passed in compressed format. The post request works fine from python test code.

I have following java post request.

```<code>  public void PostData() throws Exception {
        String payload = "{\"FirstName\": \"ABC\", \"LastName\": \"XYZ\"}";
        ByteArrayOutputStream obj = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(obj);
        gzip.write(payload.getBytes("UTF-8"));
        gzip.close();
        HttpResponse<JsonNode> jsonResponse
                = Unirest.post("http://localhost:5000/service")
                .header("Accept-Encoding", "gzip")
                .body(obj.toByteArray())
                .asJson();
    }
</code>```

Following python code is receiving request.
modified code to make it bit simple. The code fails at .decode('utf8')

```<code>def post(self):
        payload = json.loads(gzip.decompress(request.data).decode('utf8')) if request.content_encoding is 'gzip' else request.get_json('data')

 return Response(payload, status=201)

</code>```

Following is working pyhton test code

```<code> def test_post(self):
     payload = {'FirstName': 'ABC', 'LastName': 'XYZ'}
     payload = gzip.compress(json.dumps(payload).encode())
     resp = self._client.post('/service', data=payload, headers={'Content-Encoding': 'gzip'})
</code>```

答:
header was different in both Java and python test cases.

Java header is "Accept-Encoding", "gzip"

python header is 'Content-Encoding': 'gzip'

There is check in post method   if request.content_encoding is 'gzip'. This condition was filing for Java code and causing issue. Made header same in both cases. The code works fine.

Body:
Getting following error while posting compressed payload from Java client (Unirest) to Flask Api.

[POST]>. Error 400 Bad Request: Failed to decode JSON object: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte while decompression. \",). in loads\n    s = s.decode(encoding)\nUnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte\n\nDuring handling of the above exception, another exception occurred

The payload is passed in compressed format. The post request works fine from python test code.

I have following java post request.

  public void PostData() throws Exception {
        String payload = "{\"FirstName\": \"ABC\", \"LastName\": \"XYZ\"}";
        ByteArrayOutputStream obj = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(obj);
        gzip.write(payload.getBytes("UTF-8"));
        gzip.close();
        HttpResponse<JsonNode> jsonResponse
                = Unirest.post("http://localhost:5000/service")
                .header("Accept-Encoding", "gzip")
                .body(obj.toByteArray())
                .asJson();
    }

Following python code is receiving request.
modified code to make it bit simple. The code fails at .decode('utf8')

def post(self):
        payload = json.loads(gzip.decompress(request.data).decode('utf8')) if request.content_encoding is 'gzip' else request.get_json('data')

 return Response(payload, status=201)

Following is working pyhton test code

 def test_post(self):
     payload = {'FirstName': 'ABC', 'LastName': 'XYZ'}
     payload = gzip.compress(json.dumps(payload).encode())
     resp = self._client.post('/service', data=payload, headers={'Content-Encoding': 'gzip'})


问:
Printing only when it is not an empty string
Assume that

```<code>type house = {first_name: string; last_name: string; nb_windows: int; nb_doors: int; nb_cars: int; nb_rooms: int};;
house1 = {first_name="John"; last_name="Doe; nb_windows = 10; nb_doors = 50; nb_cars = 3; nb_rooms= 10};;
</code>```

I want to print each element of record house1.

```<code>Full Name : John Doe
Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10
</code>```

A way I have define the function is

```<code>let test (lch: house) =
    begin
      print_string ("Full Name : " ^ lch.first_name ^ " " ^ lch.last_name "\n");
      print_string ("Number of windows : " ^ string_of_int lch.nb_windows ^ "\n");
      print_string ("Number of doors : " ^ string_of_int lch.nb_doors ^ "\n");
      print_string ("Number of car : " ^ string_of_int lch.nb_cars ^ "\n");
      print_string ("Number of rooms : " ^ string_of_int lch.nb_rooms ^ "\n\n");
    end;;

test house1;;
</code>```

However, that function is very limited. For instance, if I define

```<code>house2 = {first_name=""; last_name="" nb_windows=10; nb_doors = 50; nb_cars = 3; nb_rooms= 10}
</code>```

In that example, I don't want to print Full Name if first_name and last_name are emptied strings.

How can I modify the test function so that the line test house2;; will display only

```<code>Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10
</code>```

instead of

```<code>Full Name :
Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10
</code>```

Be aware that I have to use only the functional paradigm, so no while or for loops.

Beginning of an answer

I think I can use something like

```<code>let print_data x y = match x with
      | "" -> ()
      | x -> print_string y;;
</code>```

but I don't know how to move on

答:
```<code>let print_data a b =
  let has_empty_string list_strings = List.exists (fun x -> x = "") list_strings in
  match a with
  | [] -> ()
  | _ -> if not (has_empty_string a) then print_string b else ();;

print_data [lch.first_name, lch.last_name] ("Full Name : " ^ lch.first_name ^ " " ^ lch.last_name "\n");;
</code>```

This works, but lch.first_name and lch.last_name are repeated twich, which is a bit annoying.

Body:
Assume that

type house = {first_name: string; last_name: string; nb_windows: int; nb_doors: int; nb_cars: int; nb_rooms: int};;
house1 = {first_name="John"; last_name="Doe; nb_windows = 10; nb_doors = 50; nb_cars = 3; nb_rooms= 10};;

I want to print each element of record house1.

Full Name : John Doe
Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10

A way I have define the function is

let test (lch: house) =
    begin
      print_string ("Full Name : " ^ lch.first_name ^ " " ^ lch.last_name "\n");
      print_string ("Number of windows : " ^ string_of_int lch.nb_windows ^ "\n");
      print_string ("Number of doors : " ^ string_of_int lch.nb_doors ^ "\n");
      print_string ("Number of car : " ^ string_of_int lch.nb_cars ^ "\n");
      print_string ("Number of rooms : " ^ string_of_int lch.nb_rooms ^ "\n\n");
    end;;

test house1;;

However, that function is very limited. For instance, if I define

house2 = {first_name=""; last_name="" nb_windows=10; nb_doors = 50; nb_cars = 3; nb_rooms= 10}

In that example, I don't want to print Full Name if first_name and last_name are emptied strings.

How can I modify the test function so that the line test house2;; will display only

Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10

instead of

Full Name :
Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10

Be aware that I have to use only the functional paradigm, so no while or for loops.

Beginning of an answer

I think I can use something like

let print_data x y = match x with
      | "" -> ()
      | x -> print_string y;;

but I don't know how to move on

Body:
let print_data a b =
  let has_empty_string list_strings = List.exists (fun x -> x = "") list_strings in
  match a with
  | [] -> ()
  | _ -> if not (has_empty_string a) then print_string b else ();;

print_data [lch.first_name, lch.last_name] ("Full Name : " ^ lch.first_name ^ " " ^ lch.last_name "\n");;

This works, but lch.first_name and lch.last_name are repeated twich, which is a bit annoying.


问:
C# MySql ASP.NET Get items from rows in the database and put them in a gridview
I have a table in my database which contains the modules in a project. It is a many to many relationship with the module id which is a foreign to the modules table and the project key which is a foreign key to the projects table. I want to display the names for the modules associated with a project in a gridview. I have the first bit of code done but I don't know how to take in and store all the modules id and then how to get their names in the module table and put them in the gridview. Any help would be much appreciated.</p>

答:
1) Create a class Named MyClass
.ie</p>

```<code>public class MyClass
{
    public int MyModules{ get; set; }

}

2) Now in the Main Block
  List<MyClass> lstObj = new List<MyClass>();
// add the modules one by one
  MyClass obj = new MyClass();
  obj.MyModules= // your code to add modules
lstObj.add(obj);
// after your logic and filling the List.
gridView1.datasource = lstObj;
gridView1.databind();

its done now.
</code>```

Body:
1) Create a class Named MyClass
.ie

public class MyClass
{
    public int MyModules{ get; set; }

}

2) Now in the Main Block
  List<MyClass> lstObj = new List<MyClass>();
// add the modules one by one
  MyClass obj = new MyClass();
  obj.MyModules= // your code to add modules
lstObj.add(obj);
// after your logic and filling the List.
gridView1.datasource = lstObj;
gridView1.databind();

its done now.


问:
The best way to create signed certificate request and verify certificate from UEFI
I'm trying to create signed certificate request from C code in UEFI (I use edk2).

I know how to do it using openssl in Linux C code. I know there is CryptoPkg in edk2.
But I didn't find functions to create request and check certificate.

Is there any way to create X509_REQ and check X509 certificate using CryptoPkg? And how can I do it?

In the case if I can't do it: How can I create create request and check certificate? What is the best way to create my own openssl wrapper?

答:
Okay. I figured out that the best way for me is create my own wrapper in CryptoPkg.
So I created library in CryptoPkg\Library\MyCryptLib according to CryptoPkg\Library\BaseCryptLib, copy enviroment header and library paths to link.

So I've got openssl wrapper that I can expand and use


问:
Build error in Xcode on cloud-hosted Mac on VSTS
I'm getting following error while building my project on cloud

no such module 'RxCocoa' import RxCocoa

** BUILD FAILED **

The following build commands failed:

CompileSwift normal arm64

CompileSwiftSources normal arm64com.apple.xcode.tools.swift.compiler (2 failures) Error:
/usr/bin/xcodebuild failed with return code: 65

the reason is same as building on local machine when frameworks are not added in 'Link Binary With Libraries' then Xcode throw this error.

So my question is how to fix this issue in Xcode on cloud-hosted Mac?

Thanks in Advance

答:
I have faced another issue and fixed this issue after 4 days.

Please check your
    configuration: '$(configuration)'
    scheme: '$(scheme)'

Most of example tell you "configuration" as "Release" if you have custom configuration please use particular name.


问:
I can't delete user authentication
I am currently developing a user crud and the last step is missing, which is to delete the user's authentication account, but I am not able to do that. What's going wrong?

code:

```<code> deleteUserButton.addEventListener('click', function(){
     firebase
        .auth()
        .signInWithEmailAndPassword(email, password)
        .then(function(user){
            user.delete()
      })
})
</code>```

答:
For delete the user you need to use this method</p>

```<code>var user = firebase.auth().currentUser;
user.delete().then(function() {
  // User is deleted.
}).catch(function(error) {
  // if error occur
});

</code>```

Title: I can't delete user authentication

Body:
I am currently developing a user crud and the last step is missing, which is to delete the user's authentication account, but I am not able to do that. What's going wrong?

code:

 deleteUserButton.addEventListener('click', function(){
     firebase
        .auth()
        .signInWithEmailAndPassword(email, password)
        .then(function(user){
            user.delete()
      })
})

Body:
For delete the user you need to use this method

var user = firebase.auth().currentUser;
user.delete().then(function() {
  // User is deleted.
}).catch(function(error) {
  // if error occur
});


问:
Rails: Is it bad to have an irreversible migration?
When is it acceptable to raise an ActiveRecord::IrreversibleMigration exception in the self.down method of a migration?  When should you take the effort to actually implement the reverse of the migration?</p>

答:
If you are dealing with production-grade systems then yes, it is very bad.  If it is your own pet project, then anything is allowed (if nothing else, it will be a learning experience :) though chances are that sooner rather than later, even in a pet project, you will find yourself having put a cross over a reverse migration only to have to undo that migration a few days later, be it via rake or manually.)

In a production scenario, you should always make the effort to write and test a reversible migration in the eventuality that you go through it in production, then discover a bug which forces you to roll back (code and schema) to some previous revision (pending some non-trivial fix -- and an otherwise unusable production system.)

Reverse migrations range from mostly trivial (removing columns or tables that were added during migration, and/or changing column types, etc.) to somewhat more involved (execute of JOINed INSERTs or UPDATEs), but nothing is so complex as to justify "sweeping it under the rug".  If nothing else, forcing yourself to think of ways to achieve reverse migrations can give you new insight into the very problem that your forward migration is fixing.

You might occasionally run into a situation where a forward migration removes a feature, resulting in data being discarded from the database.  For obvious reasons, the reverse migration cannot resuscitate discarded data.  Although one could, in such cases,  recommend having the forward migration automatically save the data or keep it around in the eventuality of rollback as an alternative to outright failure (save to yml, copy/move to a special table, etc.), you don't have to, as the time required to test such an automated procedure could exceed the time required to restore the data manually (should the need arise.)  But even in such cases, instead of just failing, you can always make the reverse migration conditionally and temporarily fail pending some user action (i.e. test for the existence of some required table that has to be restored manually; if missing, output "I have failed because I cannot recreate table XYZ from nothingness; manually restore table XYZ from backup then run me again, and I will not fail you!")

OwnerDisplayName: Readonly

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Vlad Romascanu

LastEditorDisplayName: Vlad Romascanu


问:
How to acess spring data redis stored object at the expiration event?
I am storing a Cart in Redis using Spring Data Redis for a specific time. An expiration property annotated with @TimeToLive sets the time to live for the Cart object as described by the code below.
I have set KeyExpirationEventMessageListener type to listen to the expiration event in order to process additional work at the expiration event. I was able to fetch the key from the triggered event of the expiration object and I am trying to access it or its phantom object at the expiry time using the spring data repository but with no result.It returns an empty object which means that the original obeject is likely been deleted. I don't know if it is the proper way to do it.But, is there a way to fetch the expiry object at expiration or just before it gets deleted to process motre work?

```<code>@RedisHash("cart")
public class Cart implements Serializable {
    @Id
    @Indexed
    private String id;
    private long customerId;
    private Set<CartLine> lines = new HashSet<>();

    @TimeToLive
    private long expiration;

}

public interface ShoppingCartRepository extends CrudRepository<Cart, String> {

}

    @Component
    public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

        private RedisTemplate<?, ?> redisTemplate;
        private ShoppingCartRepository repository;
        public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer,
                                          RedisTemplate redisTemplate, ShoppingCartRepository repository) {
            super(listenerContainer);
            this.redisTemplate = redisTemplate;
            this.repository = repository;
        }

        @Override
        public void onMessage(Message message, byte[] pattern) {
            String key = new String(message.getBody());
            try {
                String id = extractId(key);
                Optional<ShoppingCart> cart = repository.findById(id);
            } catch(Exception e) {
                logger.info("something went wrong  ====>  " + e.getStackTrace());
            }
        }
        private String extractId(String key){
            String keyPrefix = ShoppingCart.class.getAnnotation(RedisHash.class).value();
            return key.substring((keyPrefix + ":").length());
        }
    }

</code>```

答:
There was once a use case in my scenario, you can actually use RedisKeyExpiredEvent,

RedisKeyExpiredEvent [0] is a Redis specific ApplicationEvent published
when a particular key in Redis expires. It can hold the value of the
expired key next to the key.

You can proceed with the following implementaion.

```<code>@SpringBootApplication
@EnableRedisRepositories(considerNestedRepositories = true, enableKeyspaceEvents = EnableKeyspaceEvents.ON_STARTUP)
static class Config {

    /**
     * An {@link ApplicationListener} that captures {@link RedisKeyExpiredEvent}s and just prints the value to the
     * console.
     *
     * @return
     */
    @Bean
    ApplicationListener<RedisKeyExpiredEvent<Person>> eventListener() {
        return event -> {
            System.out.println(String.format("Received expire event for key=%s with value %s.",
                    new String(event.getSource()), event.getValue()));
        };
    }
}
</code>```

You can find the sample implementation at [1].

[0] https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/RedisKeyExpiredEvent.html#getValue--

[1] https://github.com/christophstrobl/next-level-redis-with-spring/blob/master/src/test/java/org/example/repository/RepsoitoryTests.java#L57

Body:
I am storing a Cart in Redis using Spring Data Redis for a specific time. An expiration property annotated with @TimeToLive sets the time to live for the Cart object as described by the code below.
I have set KeyExpirationEventMessageListener type to listen to the expiration event in order to process additional work at the expiration event. I was able to fetch the key from the triggered event of the expiration object and I am trying to access it or its phantom object at the expiry time using the spring data repository but with no result.It returns an empty object which means that the original obeject is likely been deleted. I don't know if it is the proper way to do it.But, is there a way to fetch the expiry object at expiration or just before it gets deleted to process motre work?

@RedisHash("cart")
public class Cart implements Serializable {
    @Id
    @Indexed
    private String id;
    private long customerId;
    private Set<CartLine> lines = new HashSet<>();

    @TimeToLive
    private long expiration;

}

public interface ShoppingCartRepository extends CrudRepository<Cart, String> {

}

    @Component
    public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

        private RedisTemplate<?, ?> redisTemplate;
        private ShoppingCartRepository repository;
        public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer,
                                          RedisTemplate redisTemplate, ShoppingCartRepository repository) {
            super(listenerContainer);
            this.redisTemplate = redisTemplate;
            this.repository = repository;
        }

        @Override
        public void onMessage(Message message, byte[] pattern) {
            String key = new String(message.getBody());
            try {
                String id = extractId(key);
                Optional<ShoppingCart> cart = repository.findById(id);
            } catch(Exception e) {
                logger.info("something went wrong  ====>  " + e.getStackTrace());
            }
        }
        private String extractId(String key){
            String keyPrefix = ShoppingCart.class.getAnnotation(RedisHash.class).value();
            return key.substring((keyPrefix + ":").length());
        }
    }

Body:
There was once a use case in my scenario, you can actually use RedisKeyExpiredEvent,

RedisKeyExpiredEvent [0] is a Redis specific ApplicationEvent published
when a particular key in Redis expires. It can hold the value of the
expired key next to the key.

You can proceed with the following implementaion.

@SpringBootApplication
@EnableRedisRepositories(considerNestedRepositories = true, enableKeyspaceEvents = EnableKeyspaceEvents.ON_STARTUP)
static class Config {

    /**
     * An {@link ApplicationListener} that captures {@link RedisKeyExpiredEvent}s and just prints the value to the
     * console.
     *
     * @return
     */
    @Bean
    ApplicationListener<RedisKeyExpiredEvent<Person>> eventListener() {
        return event -> {
            System.out.println(String.format("Received expire event for key=%s with value %s.",
                    new String(event.getSource()), event.getValue()));
        };
    }
}

You can find the sample implementation at [1].

[0] https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/RedisKeyExpiredEvent.html#getValue--

[1] https://github.com/christophstrobl/next-level-redis-with-spring/blob/master/src/test/java/org/example/repository/RepsoitoryTests.java#L57


问:
discord.py : Sort message ID in a JSON file by user
I'm currently in the process of making a kind of ticket system. I want to do that through a reaction.

When a user clicks on the reaction, a message is sent to a specific channel. This message ID is saved in a JSON file and should be assigned to the user who clicked on the reaction. But if I save the user and the message individually in the JSON file, I don't know which user the message belongs to. How can I assign the message ID to a user?

My Code:

```<code>@client.event
async def on_raw_reaction_add(reaction):
    ticketmess = 716263100638035969
    ticketlog = client.get_channel(716265124771397662)
    user = client.get_user(reaction.user_id)

    if reaction.message_id == ticketmess and reaction.emoji.id == 680827797165572117:
        with open(r'./tickets.json', 'r')as f:
            ticketchannels = json.load(f)
        if not f"{reaction.user_id}" in ticketchannels:

            ticketmess = await ticketlog.send('Ein User braucht Hilfe!')

            with open(r'./tickets.json', 'r')as f:
                ticketmessages = json.load(f)

                ticketmessages[f"{reaction.user_id}"] = f'{user} in {ticketmess.id}'

                with open(r'./tickets.json', 'w') as f:
                    json.dump(ticketmessages, f, indent=4)

</code>```

答:
The code would look something like:

@client.event
async def on_raw_reaction_add(reaction):
    ticketmsg = 716263100638035969
    ticketlog = client.get_channel(716265124771397662)
    user = client.get_user(reaction.user_id)

    if reaction.message_id == ticketmsg and reaction.emoji.id == 680827797165572117:

        # you already have loaded it in once, you don't need to read it again
        with open("tickets.json", "r") as fp:
            data = json.load(fp)

        if f"{reaction.user_id}" not in data.keys():
            ticketmsg = await ticketlog.send("Ein User braucht Hilfe!")

            # you can just assign the message id to the user, no need for a string
            data[f"{reaction.user_id}"] = ticketmsg.id

            with open("tickets.json", "w+") as fp:
                json.dump(data, fp, sort_keys=True, indent=4) # kwargs are for beautification
```

<p>You don't need the <code>f"{user} in {ticketmsg.id}"</code> because you can get the user from the key. Besides, usernames can change, so putting it in the file would prove to be not very useful.<br>
If you wish to get the user's name, just load in the keys from the json and use <code>client.get_user(ID_HERE)</code>.</p>

<p>If you want to search for a user based off of a specific message ID, you can iterate through a dictionary like so:</p>

<pre class="lang-py prettyprint-override"><code>my_dict = {"key": "value", "foo": "bar"}

for k, v in my_dict.items():
    if v == "bar":
        print(k) # selecting the key based off of its value

# output:
# foo
</code>```

I'm hoping I understood your question correctly, if not, I'll be happy to edit my answer after some clarification.

Body:
I'm currently in the process of making a kind of ticket system. I want to do that through a reaction.

When a user clicks on the reaction, a message is sent to a specific channel. This message ID is saved in a JSON file and should be assigned to the user who clicked on the reaction. But if I save the user and the message individually in the JSON file, I don't know which user the message belongs to. How can I assign the message ID to a user?

My Code:

@client.event
async def on_raw_reaction_add(reaction):
    ticketmess = 716263100638035969
    ticketlog = client.get_channel(716265124771397662)
    user = client.get_user(reaction.user_id)

    if reaction.message_id == ticketmess and reaction.emoji.id == 680827797165572117:
        with open(r'./tickets.json', 'r')as f:
            ticketchannels = json.load(f)
        if not f"{reaction.user_id}" in ticketchannels:

            ticketmess = await ticketlog.send('Ein User braucht Hilfe!')

            with open(r'./tickets.json', 'r')as f:
                ticketmessages = json.load(f)

                ticketmessages[f"{reaction.user_id}"] = f'{user} in {ticketmess.id}'

                with open(r'./tickets.json', 'w') as f:
                    json.dump(ticketmessages, f, indent=4)

Body:
The code would look something like:

@client.event
async def on_raw_reaction_add(reaction):
    ticketmsg = 716263100638035969
    ticketlog = client.get_channel(716265124771397662)
    user = client.get_user(reaction.user_id)

    if reaction.message_id == ticketmsg and reaction.emoji.id == 680827797165572117:

        # you already have loaded it in once, you don't need to read it again
        with open("tickets.json", "r") as fp:
            data = json.load(fp)

        if f"{reaction.user_id}" not in data.keys():
            ticketmsg = await ticketlog.send("Ein User braucht Hilfe!")

            # you can just assign the message id to the user, no need for a string
            data[f"{reaction.user_id}"] = ticketmsg.id

            with open("tickets.json", "w+") as fp:
                json.dump(data, fp, sort_keys=True, indent=4) # kwargs are for beautification

You don't need the f"{user} in {ticketmsg.id}" because you can get the user from the key. Besides, usernames can change, so putting it in the file would prove to be not very useful.

If you wish to get the user's name, just load in the keys from the json and use client.get_user(ID_HERE).

If you want to search for a user based off of a specific message ID, you can iterate through a dictionary like so:

my_dict = {"key": "value", "foo": "bar"}

for k, v in my_dict.items():
    if v == "bar":
        print(k) # selecting the key based off of its value

# output:
# foo

I'm hoping I understood your question correctly, if not, I'll be happy to edit my answer after some clarification.


答:
You could try saving the values to variable first:</p>

```<code>const clarifications = [];
const quantities = [];

const h2s = document.querySelectorAll('h2');
const heading = h2s.forEach(element =>
    clarifications.push(element.textContent);
);

const quantity = document.querySelectorAll('h2 + ul');
quantity.forEach(el =>
    quantities.push(el.childElementCount);
);

clarifications.forEach((clarification, i) => {
    console.log('Clarification:', clarification);
    console.log('Quantity:', quantities[i]);
});
</code>```

Title: Can't make an output with a forEach function in a template string

Body:
const categoriesLght = document.querySelectorAll('#categories .item').length;
console.log(`There are ${categoriesLght} clasifications.`);
const h2s = document.querySelectorAll('h2');
const heading = h2s.forEach(element =>
  console.log(`Clasification: ${element.textContent}`),
);

const quantity = document.querySelectorAll('h2 + ul');
quantity.forEach(el =>
  console.log(`Quantity: ${el.childElementCount}`),
);

Output:

There are 3 clasifications.
Clasification: Student
Clasification: Fish
Clasification: Rocket
Quantity: 3
Quantity: 5
Quantity: 6

If I try to put a function in a template string, there will be an error. Trying to find a way to make it happen. Desired output is:

Clasification: Student
Quantity: 3
Clasification: Fish
Quantity: 5
Clasification: Rocket
Quantity: 6

And I'm looking for a way how to put a result of ForEach method in a template string, to make happen something like that (I think I'm looking for some destructurization):

str = [h2s.forEach, quantity.forEach]([category, count])=> (console.log(`Clasification: ${category.textContent},
Quantity: ${count.childElementCount} `));

Body:
You could try saving the values to variable first:

const clarifications = [];
const quantities = [];

const h2s = document.querySelectorAll('h2');
const heading = h2s.forEach(element =>
    clarifications.push(element.textContent);
);

const quantity = document.querySelectorAll('h2 + ul');
quantity.forEach(el =>
    quantities.push(el.childElementCount);
);

clarifications.forEach((clarification, i) => {
    console.log('Clarification:', clarification);
    console.log('Quantity:', quantities[i]);
});


问:
Join two arrays of different size with condition
i have two arrays of different sizes and i want them to joint in one only if first three elements match.

for exapmle:

```<code>A1 = [
    [1,8,9,8,2],
    [2,9,9,8,2],
    [1,7,7,8,2],
    [8,6,2,6,7]
]

A2 = [[2,9,9,30,60],
      [8,6,2,70,20]]

Result = [[2,9,9,8,2,30,60]
         [8,6,2,6,7,70,20]]
</code>```

I guess there is some numpy function for this but i couldn't find it.

答:
A general-purpose way to do this (e.g. if you might have arbitrary numbers of these lists) might be to use itertools.groupby:

```<code>result = []
for p, g in itertools.groupby(sorted(A1+A2), lambda arr: arr[:3]):
     group = list(g)
     if len(group) >= 2:
         result.append(p + [i for arr in group for i in arr[3:]])
</code>```

Body:
i have two arrays of different sizes and i want them to joint in one only if first three elements match.

for exapmle:

A1 = [
    [1,8,9,8,2],
    [2,9,9,8,2],
    [1,7,7,8,2],
    [8,6,2,6,7]
]

A2 = [[2,9,9,30,60],
      [8,6,2,70,20]]

Result = [[2,9,9,8,2,30,60]
         [8,6,2,6,7,70,20]]

I guess there is some numpy function for this but i couldn't find it.

Body:
A general-purpose way to do this (e.g. if you might have arbitrary numbers of these lists) might be to use itertools.groupby:

result = []
for p, g in itertools.groupby(sorted(A1+A2), lambda arr: arr[:3]):
     group = list(g)
     if len(group) >= 2:
         result.append(p + [i for arr in group for i in arr[3:]])


问:
Rotating image in WPF not respecting screen size
I am currently having trouble when rotating an image in WPF, using RotateTransform and LayoutTransform. When an image, that has a pixel height size greater than the monitors height and is rotated at 90º or 270º, the window size will be higher than the monitors screen resolution size.

Example screenshots:
Application running with image at 90º
Application running with image at 0º

I am using the code below (simplified), with mainWindow.img being a System.Windows.Control.Image:

```<code>static void Rotate(int degrees)
{
    var rt = new RotateTransform { Angle = degrees };
    mainWindow.img.LayoutTransform = rt;
}
</code>```

It is for a a picture viewer project, the full source code is available at https://github.com/Ruben2776/PicView

I have tried shifting the Width and Height values of the image, but it produces an undesired result (skewed proportion).

The sizing calculation, for the image size, is made based on the user's screen height, using the following trimmed code:

```<code>int interfaceHeight = 90;
double maxWidth = Math.Min(MonitorInfo.Width, width);
double maxHeight = Math.Min((MonitorInfo.Height - interfaceHeight), height);
double AspectRatio = Math.Min((maxWidth / width), (maxHeight / height));
mainWindow.img.Width = (width * AspectRatio);
mainWindow.img.Height = (height * AspectRatio);
</code>```

with height and width being the image's dimensions and MonitorInfo being a class that retrieves the current monitors resolution.

Update

Below is the minimal code for a sample WPF app illustrating the issue:

MainWindow.xaml

```<code><Window x:Class="RotateTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        SizeToContent="WidthAndHeight"
        Title="MainWindow" >
    <Grid>
        <Image x:Name="img" Stretch="Fill" Source="https://w.wallhaven.cc/full/nk/wallhaven-nkrwz1.jpg"/>
    </Grid>
</Window>
</code>```

MainWindow.xaml.cs

```<code>using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace RotateTest
{
    public partial class MainWindow : Window
    {
        int Degrees;

        public MainWindow()
        {
            InitializeComponent();
            ContentRendered += MainWindow_ContentRendered;
            KeyDown += MainWindow_KeyDown;
        }

        private void MainWindow_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Up:
                    Rotate(true);
                    break;
                case Key.Down:
                    Rotate(false);
                    break;

            }
        }

        private void MainWindow_ContentRendered(object sender, EventArgs e)
        {
            int interfaceHeight = 90;
            double maxWidth = Math.Min(SystemParameters.PrimaryScreenWidth, img.Source.Width);
            double maxHeight = Math.Min(SystemParameters.PrimaryScreenHeight - interfaceHeight, img.Source.Height);
            double AspectRatio = Math.Min((maxWidth / img.Source.Width), (maxHeight / img.Source.Height));
            img.Width = (img.Source.Width * AspectRatio);
            img.Height = (img.Source.Height * AspectRatio);
        }

        void Rotate(int degrees)
        {
            var rt = new RotateTransform { Angle = Degrees = degrees };
            img.LayoutTransform = rt;
        }

        void Rotate(bool right)
        {
            switch (Degrees)
            {
                case 0:
                    if (right)
                    {
                        Rotate(270);
                    }
                    else
                    {
                        Rotate(90);
                    }

                    break;

                case 90:
                    if (right)
                    {
                        Rotate(0);
                    }
                    else
                    {
                        Rotate(180);
                    }

                    break;

                case 180:
                    if (right)
                    {
                        Rotate(90);
                    }
                    else
                    {
                        Rotate(270);
                    }

                    break;

                case 270:
                    if (right)
                    {
                        Rotate(180);
                    }
                    else
                    {
                        Rotate(0);
                    }

                    break;
            }
        }
    }
}
</code>```

答:
The root of the problem is that you are only calculating your scaling ratios based on the the image's size when it's not rotated. Once you rotate the image, img.ActualHeight effectively becomes its width and img.ActualWidth effectively becomes its height, and your calculation from when the image was un-rotated is no longer correct.

Here are the changes and additions I made to your code:

```<code>private double normalRatio;
private double rotatedRatio;

private void MainWindow_ContentRendered(object sender, EventArgs e)
{
    double interfaceHeight = this.ActualHeight - img.ActualHeight;

    normalRatio = Math.Min(SystemParameters.WorkArea.Width / img.Source.Width, (SystemParameters.WorkArea.Height - interfaceHeight) / img.Source.Height);
    rotatedRatio = Math.Min(SystemParameters.WorkArea.Width / img.Source.Height, (SystemParameters.WorkArea.Height - interfaceHeight) / img.Source.Width);

    ScaleImage();
}

private void ScaleImage()
{
    double ratio = Degrees == 0 || Degrees == 180 ? normalRatio : rotatedRatio;
    img.Width = (img.Source.Width * ratio);
    img.Height = (img.Source.Height * ratio);
}

void Rotate(bool right)
{
    if (right)
    {
        Degrees -= 90;
        if (Degrees < 0) { Degrees += 360; }
    }
    else
    {
        Degrees += 90;
        if (Degrees >= 360) { Degrees -= 360; }
    }

    ScaleImage();
    Rotate(Degrees);
}

//I left the other methods, including Rotate(int degrees), the same as in your question
</code>```

Here's an explanation of what I changed:

interfaceHeight is calculated by subtracting the height of the image from the height of the window, the difference being the aggrigate size of everything else.

Instead of using MonitorInfo, I'm using SystemParameters.WorkArea, because it takes into account the size and placement of the Windows taskbar.

I calculate two scale ratios: normalRatio, for when the image is not rotated or is vertically flipped (180°), and rotatedRatio, for when the image is rotated 90° in either direction. I calculate the later by swapping img.Source.Height and img.Source.Width.

I added a ScaleImage() method to do the actual image scaling based on the intended rotation, so I can call it from two different places.

I simplified Rotate(bool right) to calculate the new angle using math, instead of listing out each possible rotation.

The above results in an image that is always as big as possible for the screen while maintaining the original aspect ratio. It will grow and shrink as it's rotated to fit the screen. If you want the image to stay a constant size instead, just use Math.Min(normalRatio, rotatedRatio).

Note that the above only works if you call Rotate(bool right), not if you call Rotate(int degrees) directly. This is because the logic of using two ratios only works because there are only two possible sizes for the image (portrait and landscape), which is only the case if you restrict the rotation to increments of 90°. If you want to set the angle to something else, like 20°, the math to calculate the image's effective size becomes a bit more complicated and you would need to start calculating it dynamically based on the angle.

Body:
I am currently having trouble when rotating an image in WPF, using RotateTransform and LayoutTransform. When an image, that has a pixel height size greater than the monitors height and is rotated at 90º or 270º, the window size will be higher than the monitors screen resolution size.

Example screenshots:
Application running with image at 90º
Application running with image at 0º

I am using the code below (simplified), with mainWindow.img being a System.Windows.Control.Image:

static void Rotate(int degrees)
{
    var rt = new RotateTransform { Angle = degrees };
    mainWindow.img.LayoutTransform = rt;
}

It is for a a picture viewer project, the full source code is available at https://github.com/Ruben2776/PicView

I have tried shifting the Width and Height values of the image, but it produces an undesired result (skewed proportion).

The sizing calculation, for the image size, is made based on the user's screen height, using the following trimmed code:

int interfaceHeight = 90;
double maxWidth = Math.Min(MonitorInfo.Width, width);
double maxHeight = Math.Min((MonitorInfo.Height - interfaceHeight), height);
double AspectRatio = Math.Min((maxWidth / width), (maxHeight / height));
mainWindow.img.Width = (width * AspectRatio);
mainWindow.img.Height = (height * AspectRatio);

with height and width being the image's dimensions and MonitorInfo being a class that retrieves the current monitors resolution.

Update

Below is the minimal code for a sample WPF app illustrating the issue:

MainWindow.xaml

<Window x:Class="RotateTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        SizeToContent="WidthAndHeight"
        Title="MainWindow" >
    <Grid>
        <Image x:Name="img" Stretch="Fill" Source="https://w.wallhaven.cc/full/nk/wallhaven-nkrwz1.jpg"/>
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace RotateTest
{
    public partial class MainWindow : Window
    {
        int Degrees;

        public MainWindow()
        {
            InitializeComponent();
            ContentRendered += MainWindow_ContentRendered;
            KeyDown += MainWindow_KeyDown;
        }

        private void MainWindow_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Up:
                    Rotate(true);
                    break;
                case Key.Down:
                    Rotate(false);
                    break;

            }
        }

        private void MainWindow_ContentRendered(object sender, EventArgs e)
        {
            int interfaceHeight = 90;
            double maxWidth = Math.Min(SystemParameters.PrimaryScreenWidth, img.Source.Width);
            double maxHeight = Math.Min(SystemParameters.PrimaryScreenHeight - interfaceHeight, img.Source.Height);
            double AspectRatio = Math.Min((maxWidth / img.Source.Width), (maxHeight / img.Source.Height));
            img.Width = (img.Source.Width * AspectRatio);
            img.Height = (img.Source.Height * AspectRatio);
        }

        void Rotate(int degrees)
        {
            var rt = new RotateTransform { Angle = Degrees = degrees };
            img.LayoutTransform = rt;
        }

        void Rotate(bool right)
        {
            switch (Degrees)
            {
                case 0:
                    if (right)
                    {
                        Rotate(270);
                    }
                    else
                    {
                        Rotate(90);
                    }

                    break;

                case 90:
                    if (right)
                    {
                        Rotate(0);
                    }
                    else
                    {
                        Rotate(180);
                    }

                    break;

                case 180:
                    if (right)
                    {
                        Rotate(90);
                    }
                    else
                    {
                        Rotate(270);
                    }

                    break;

                case 270:
                    if (right)
                    {
                        Rotate(180);
                    }
                    else
                    {
                        Rotate(0);
                    }

                    break;
            }
        }
    }
}

Body:
The root of the problem is that you are only calculating your scaling ratios based on the the image's size when it's not rotated. Once you rotate the image, img.ActualHeight effectively becomes its width and img.ActualWidth effectively becomes its height, and your calculation from when the image was un-rotated is no longer correct.

Here are the changes and additions I made to your code:

private double normalRatio;
private double rotatedRatio;

private void MainWindow_ContentRendered(object sender, EventArgs e)
{
    double interfaceHeight = this.ActualHeight - img.ActualHeight;

    normalRatio = Math.Min(SystemParameters.WorkArea.Width / img.Source.Width, (SystemParameters.WorkArea.Height - interfaceHeight) / img.Source.Height);
    rotatedRatio = Math.Min(SystemParameters.WorkArea.Width / img.Source.Height, (SystemParameters.WorkArea.Height - interfaceHeight) / img.Source.Width);

    ScaleImage();
}

private void ScaleImage()
{
    double ratio = Degrees == 0 || Degrees == 180 ? normalRatio : rotatedRatio;
    img.Width = (img.Source.Width * ratio);
    img.Height = (img.Source.Height * ratio);
}

void Rotate(bool right)
{
    if (right)
    {
        Degrees -= 90;
        if (Degrees < 0) { Degrees += 360; }
    }
    else
    {
        Degrees += 90;
        if (Degrees >= 360) { Degrees -= 360; }
    }

    ScaleImage();
    Rotate(Degrees);
}

//I left the other methods, including Rotate(int degrees), the same as in your question

Here's an explanation of what I changed:

interfaceHeight is calculated by subtracting the height of the image from the height of the window, the difference being the aggrigate size of everything else.

Instead of using MonitorInfo, I'm using SystemParameters.WorkArea, because it takes into account the size and placement of the Windows taskbar.

I calculate two scale ratios: normalRatio, for when the image is not rotated or is vertically flipped (180°), and rotatedRatio, for when the image is rotated 90° in either direction. I calculate the later by swapping img.Source.Height and img.Source.Width.

I added a ScaleImage() method to do the actual image scaling based on the intended rotation, so I can call it from two different places.

I simplified Rotate(bool right) to calculate the new angle using math, instead of listing out each possible rotation.

The above results in an image that is always as big as possible for the screen while maintaining the original aspect ratio. It will grow and shrink as it's rotated to fit the screen. If you want the image to stay a constant size instead, just use Math.Min(normalRatio, rotatedRatio).

Note that the above only works if you call Rotate(bool right), not if you call Rotate(int degrees) directly. This is because the logic of using two ratios only works because there are only two possible sizes for the image (portrait and landscape), which is only the case if you restrict the rotation to increments of 90°. If you want to set the angle to something else, like 20°, the math to calculate the image's effective size becomes a bit more complicated and you would need to start calculating it dynamically based on the angle.


问:
Can't create handler inside thread that has not called Looper.prepare()
I get this error "Can't create handler inside thread that has not called Looper.prepare()"

Can you tell me how to fix it?

```<code>public class PaymentActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.payment);

    final Button buttonBank = (Button) findViewById(R.id.buttonBank);

    buttonBank.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            progressDialog = ProgressDialog.show(PaymentActivity.this, "",
                    "Redirecting to payment gateway...", true, true);

            new Thread() {
                public void run() {
                    try {
                        startPayment("Bank");
                    } catch (Exception e) {
                        alertDialog.setMessage(e.getMessage());
                        handler.sendEmptyMessage(1);
                        progressDialog.cancel();
                    }
                }
            }.start();
        }

    });
</code>```

StartPayment Method:

```<code>    private void startPayment(String id) {
    Bundle b = getIntent().getExtras();
    final Sail sail = b.getParcelable(Constant.SAIL);

    final Intent bankIntent = new Intent(this, BankActivity.class);

    try {
        Reservation reservation = RestService.createReservation(
                sail.getId(),
                getSharedPreferences(Constant.PREF_NAME_CONTACT, 0));
        bankIntent.putExtra(Constant.RESERVATION, reservation);

        // <workingWithDB> Storing Reservation info in Database
        DBAdapter db = new DBAdapter(this);
        db.open();
        @SuppressWarnings("unused")
        long rowid;
        rowid = db.insertRow(sail.getId(), sail.getFrom(),
                sail.getTo(), sail.getShip(), sail.getDateFrom().getTime(),
                sail.getPrice().toString(), reservation.getId().floatValue());
        db.close();
        // </workingWithDB>

        String html = PaymentService.getRedirectHTML(id, reservation);

        bankIntent.putExtra(Constant.BANK, html);
    } catch (Exception e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder.create();
        alertDialog.setMessage(e.getMessage());
        alertDialog.show();
    }

    startActivity(bankIntent);
}
</code>```

答:
Instead of new Thread() line, try giving

```<code>this.runOnUiThread(new Runnable() {
</code>```

Body:
I get this error "Can't create handler inside thread that has not called Looper.prepare()"

Can you tell me how to fix it?

public class PaymentActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.payment);

    final Button buttonBank = (Button) findViewById(R.id.buttonBank);

    buttonBank.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            progressDialog = ProgressDialog.show(PaymentActivity.this, "",
                    "Redirecting to payment gateway...", true, true);

            new Thread() {
                public void run() {
                    try {
                        startPayment("Bank");
                    } catch (Exception e) {
                        alertDialog.setMessage(e.getMessage());
                        handler.sendEmptyMessage(1);
                        progressDialog.cancel();
                    }
                }
            }.start();
        }

    });

StartPayment Method:

    private void startPayment(String id) {
    Bundle b = getIntent().getExtras();
    final Sail sail = b.getParcelable(Constant.SAIL);

    final Intent bankIntent = new Intent(this, BankActivity.class);

    try {
        Reservation reservation = RestService.createReservation(
                sail.getId(),
                getSharedPreferences(Constant.PREF_NAME_CONTACT, 0));
        bankIntent.putExtra(Constant.RESERVATION, reservation);

        // <workingWithDB> Storing Reservation info in Database
        DBAdapter db = new DBAdapter(this);
        db.open();
        @SuppressWarnings("unused")
        long rowid;
        rowid = db.insertRow(sail.getId(), sail.getFrom(),
                sail.getTo(), sail.getShip(), sail.getDateFrom().getTime(),
                sail.getPrice().toString(), reservation.getId().floatValue());
        db.close();
        // </workingWithDB>

        String html = PaymentService.getRedirectHTML(id, reservation);

        bankIntent.putExtra(Constant.BANK, html);
    } catch (Exception e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder.create();
        alertDialog.setMessage(e.getMessage());
        alertDialog.show();
    }

    startActivity(bankIntent);
}

Body:
Instead of new Thread() line, try giving

this.runOnUiThread(new Runnable() {


问:
JMeter encode URL
I have to test the below URL that contains special char:

url\search.html?q=*&Filters=template_fac_s:3f87222389034212a868c5c0cd12cacc|market_l1_fac_sm:e73956c2506442399dd73ed1eb0ec165

I am getting this error:

Response message: Non HTTP response message: Illegal character in query at index 121: url/search.html?q=*&Filters=template_fac_s:3f87222389034212a868c5c0cd12cacc|market_l1_fac_sm:e73956c2506442399dd73ed1eb0ec165

I think I need to encode the URL but I do not know how to do it . Does anyone know how to do this , can someone help.

Thanks.

答:
JMeter provides __urlencode function which replaces characters which are not allowed in URL with url-encoded equivalents

References:

Understanding HTML Form Encoding: URL Encoded and Multipart Forms

Apache JMeter Functions - An Introduction

Title: JMeter encode URL


问:
UPDATE-FROM clause in jOOQ throws an expecption for CTE field
I am trying to convert following PostgreSQL query into jOOQ:

```<code>UPDATE book
SET amount = bat.amount
FROM (
    VALUES (2, 136),(5, 75)
) AS bat(book_id, amount)
WHERE book.book_id = bat.book_id;
</code>```

VALUES inside of FROM-clause are being created from Map<Long, Integer> bookIdsAmountMap parameter and I am trying to perform that this way:

```<code>class BookUtilHelper {

    @SuppressWarnings("unchecked")
    static Table<Record2<Long, Integer>> batTmp(DSLContext dsl, Map<Long, Integer> bookIdAmountMapUpdated) {
        Row2<Long,Integer> array[] = new Row2[bookIdAmountMapUpdated.size()];
        int i = 0;
        for (Map.Entry<Long, Integer> pair : bookIdAmountMapUpdated.entrySet()) {
            array[i]=DSL.row(pair.getKey(), pair.getValue());
            i++;
        }
        Table<Record2<Long, Integer>> batTmp = DSL.values(array);
        batTmp.fields("book_id", "amount");
        return batTmp;
    }
}
</code>```

Then, I try to also create fields which can be accessed like in this example

```<code>Field<Long> bookIdField = DSL.field(DSL.name("bat", "book_id"), Long.class);
Field<Integer> amountField = DSL.field(DSL.name("bat", "amount"), Integer.class);
Table<Record2<Long, Integer>> batTmp = BookUtilHelper.batTmp(dsl, bookIdAmountMapUpdated);
// ctx variable is of type DSLContext
ctx.update(BOOK).set(BOOK.AMOUNT, amountField).from(batTmp.as("bat"))
 .where(BOOK.BOOK_ID.eq(bookIdField));
</code>```

When I try to update book I get following exception:

column bat.book_id does not exist

Any advice on how to solve this issue would be greatly appreciated. :)

答:
This doesn't have any effect:

batTmp.fields("book_id", "amount");
```

<p>Whereas this only renames the table, not the columns:</p>

<pre class="lang-java prettyprint-override"><code>batTmp.as("bat")
</code>```

Write this instead:

batTmp.as("bat", "book_id", "amount")
```

Body:
I am trying to convert following PostgreSQL query into jOOQ:

UPDATE book
SET amount = bat.amount
FROM (
    VALUES (2, 136),(5, 75)
) AS bat(book_id, amount)
WHERE book.book_id = bat.book_id;

VALUES inside of FROM-clause are being created from Map<Long, Integer> bookIdsAmountMap parameter and I am trying to perform that this way:

class BookUtilHelper {

    @SuppressWarnings("unchecked")
    static Table<Record2<Long, Integer>> batTmp(DSLContext dsl, Map<Long, Integer> bookIdAmountMapUpdated) {
        Row2<Long,Integer> array[] = new Row2[bookIdAmountMapUpdated.size()];
        int i = 0;
        for (Map.Entry<Long, Integer> pair : bookIdAmountMapUpdated.entrySet()) {
            array[i]=DSL.row(pair.getKey(), pair.getValue());
            i++;
        }
        Table<Record2<Long, Integer>> batTmp = DSL.values(array);
        batTmp.fields("book_id", "amount");
        return batTmp;
    }
}

Then, I try to also create fields which can be accessed like in this example

Field<Long> bookIdField = DSL.field(DSL.name("bat", "book_id"), Long.class);
Field<Integer> amountField = DSL.field(DSL.name("bat", "amount"), Integer.class);
Table<Record2<Long, Integer>> batTmp = BookUtilHelper.batTmp(dsl, bookIdAmountMapUpdated);
// ctx variable is of type DSLContext
ctx.update(BOOK).set(BOOK.AMOUNT, amountField).from(batTmp.as("bat"))
 .where(BOOK.BOOK_ID.eq(bookIdField));

When I try to update book I get following exception:

column bat.book_id does not exist

Any advice on how to solve this issue would be greatly appreciated. :)

Body:
This doesn't have any effect:

batTmp.fields("book_id", "amount");

Whereas this only renames the table, not the columns:

batTmp.as("bat")

Write this instead:

batTmp.as("bat", "book_id", "amount")


问:
groovy list spreading
If you run the following Groovy code, the assertion passes

```<code>def foo(a, b) {
  a + b
}

assert 'aaabbb' == foo(['aaa', 'bbb'])
</code>```

This suggests that if a method is called with a List parameter that contains X elements, then the List will be spread and a method with X arguments will be invoked.

Of course, this will only happen if there isn't a method defined with a single parameter of type List (or ancestor thereof).

I only discovered this quite recently when reading another SO Groovy answer. I've never seen it mentioned in the Groovy docs, release notes, or books. Is it a hidden feature, a bug, or just something I've missed?

答:
Going to be removed in Groovy 2 apparently:
http://groovy.329449.n5.nabble.com/removing-features-in-Groovy-2-td4422494.html

JT's first on the to-remove list and it seems everyone (with clout) on Groovy User agrees.

Title: groovy list spreading

Body:
If you run the following Groovy code, the assertion passes

def foo(a, b) {
  a + b
}

assert 'aaabbb' == foo(['aaa', 'bbb'])

This suggests that if a method is called with a List parameter that contains X elements, then the List will be spread and a method with X arguments will be invoked.

Of course, this will only happen if there isn't a method defined with a single parameter of type List (or ancestor thereof).

I only discovered this quite recently when reading another SO Groovy answer. I've never seen it mentioned in the Groovy docs, release notes, or books. Is it a hidden feature, a bug, or just something I've missed?


问:
cause of ActionController::RoutingError (uninitialized constant Users::Confirmations) error
I can't figure out why I'm getting this error (ActionController::RoutingError (uninitialized constant Users::Confirmations)), because the structure connecting view, route, controller, and model is identical to similar method/route used on the same page.

view

```<code><%= link_to "Approve", approve_user_path(user), method: :patch %>
</code>```

route

```<code>as :user do
 patch 'users/:id/approve', to: 'users/confirmations/#approve', as: :approve_user
end
</code>```

controller

```<code>class Users::ConfirmationsController < Devise::ConfirmationsController
 def approve
  @user = User.find(params[:id])
  @user.approve
 end
end
</code>```

model

```<code>class User
 def approve
  self.approved = true
  save
 end
end
</code>```

In comparison, this one works just fine:

view

```<code><%= form_for user, url: add_name_path(user) do |f| %>
 <%= f.text_field :firstname %>
 <%= f.text_field :lastname %>
 <%= f.submit "Submit" %>
<% end %>
</code>```

route

```<code>patch 'users/:id/add_name', to: 'users/confirmations#add_name', via: :patch, as: :add_name
</code>```

controller

```<code>class Users::ConfirmationsController < Devise::ConfirmationsController
 def add_name
  @user = User.find(params[:id])
  @user.update(name_params)
 end

 private
 def name_params
  params.require(:user).permit(:firstname, :lastname)
 end
end
</code>```

Why does the latter go through, but the former causes an uninitialized constant error for the controller?

答:
The to: param in your first route has an extra / before the method name.

Try this:

as :user do
 patch 'users/:id/approve', to: 'users/confirmations#approve', as: :approve_user
end

Body:
I can't figure out why I'm getting this error (ActionController::RoutingError (uninitialized constant Users::Confirmations)), because the structure connecting view, route, controller, and model is identical to similar method/route used on the same page.

view

<%= link_to "Approve", approve_user_path(user), method: :patch %>

route

as :user do
 patch 'users/:id/approve', to: 'users/confirmations/#approve', as: :approve_user
end

controller

class Users::ConfirmationsController < Devise::ConfirmationsController
 def approve
  @user = User.find(params[:id])
  @user.approve
 end
end

model

class User
 def approve
  self.approved = true
  save
 end
end

In comparison, this one works just fine:

view

<%= form_for user, url: add_name_path(user) do |f| %>
 <%= f.text_field :firstname %>
 <%= f.text_field :lastname %>
 <%= f.submit "Submit" %>
<% end %>

route

patch 'users/:id/add_name', to: 'users/confirmations#add_name', via: :patch, as: :add_name

controller

class Users::ConfirmationsController < Devise::ConfirmationsController
 def add_name
  @user = User.find(params[:id])
  @user.update(name_params)
 end

 private
 def name_params
  params.require(:user).permit(:firstname, :lastname)
 end
end

Why does the latter go through, but the former causes an uninitialized constant error for the controller?


问:
Proportion request sql
There is a table of accidents and output the share of accidents number 2 to all accidents I wrote this code, but I can not make it work:

```<code>select ((select count("ID") from "DTP" where "REASON"=2)/count("REASON"))
from "DTP"
group by "ID"
</code>```

答:
You can use avg():

```<code>select id,
       avg(case when reason = 2 then 1.0 else 0 end)
from "DTP"
group by "ID"
</code>```

This produces the ratio for each id -- based on your sample query.  If you only want one row for all the data, then:

```<code>select avg(case when reason = 2 then 1.0 else 0 end)
from "DTP";
</code>```

Title: Proportion request sql

Body:
There is a table of accidents and output the share of accidents number 2 to all accidents I wrote this code, but I can not make it work:

select ((select count("ID") from "DTP" where "REASON"=2)/count("REASON"))
from "DTP"
group by "ID"

Body:
You can use avg():

select id,
       avg(case when reason = 2 then 1.0 else 0 end)
from "DTP"
group by "ID"

This produces the ratio for each id -- based on your sample query.  If you only want one row for all the data, then:

select avg(case when reason = 2 then 1.0 else 0 end)
from "DTP";


问:
Mapstruct choose between two Named Mapper methods
I'm trying to add a different mapper method with the same signature

```<code>@Mapper(componentModel = "spring", uses = TechnologyMapper.class)
public interface VersionMapper {

    VersionMapper INSTANCE = Mappers.getMapper(VersionMapper.class);

    @Named("Normal")
    VersionDTO versionToVersionDto(Version version, @Context CycleAvoidingMappingContext context);

    @Named("IgnoreTechnology")
    @Mapping(target = "technology", ignore = true)
    VersionDTO versionToVersionDtoIgnoreTechnology(Version version, @Context CycleAvoidingMappingContext context);
</code>```

In the official documentation it shows an example where a another mapper is used to choose between the two. However in my code I use this mapper directly:

```<code>versionMapper.versionToVersionDtoIgnoreTechnology(version, new CycleAvoidingMappingContext());
</code>```

So How Can I choose between the two?

答:
The @Named annotations is meant to signal to other usages of the methods within MapStruct.

When you use it directly it is entirely up to you to decide which method you need to invoke. Only you know the context if your direct invocation and whether you need the technology or not in your mapped VersionDTO

Body:
I'm trying to add a different mapper method with the same signature

@Mapper(componentModel = "spring", uses = TechnologyMapper.class)
public interface VersionMapper {

    VersionMapper INSTANCE = Mappers.getMapper(VersionMapper.class);

    @Named("Normal")
    VersionDTO versionToVersionDto(Version version, @Context CycleAvoidingMappingContext context);

    @Named("IgnoreTechnology")
    @Mapping(target = "technology", ignore = true)
    VersionDTO versionToVersionDtoIgnoreTechnology(Version version, @Context CycleAvoidingMappingContext context);

In the official documentation it shows an example where a another mapper is used to choose between the two. However in my code I use this mapper directly:

versionMapper.versionToVersionDtoIgnoreTechnology(version, new CycleAvoidingMappingContext());

So How Can I choose between the two?


问:
R: Subset rows from dataframe based on range of given time
Assume I have df1:

```<code>Start_Date    End_Date     Value
2001-01-01    2001-12-31   1
2002-01-01    2002-12-31   2
2003-01-01    2003-12-31   3
2004-01-01    2004-12-31   4
2005-01-01    2005-12-31   5
</code>```

& df2:

```<code>DateTime
2003-01-01
2003-05-09
2004-12-31
2005-01-31
2005-08-13
</code>```

What I would like to do is to import Value from df1 into df2 by checking which DateTime in df2 falls in between Start_Date & End_Date in df1. A view of desired outcome:

```<code>DateTime      Value
2003-01-01    3
2003-05-09    3
2004-12-31    4
2005-01-31    5
2005-08-13    5
</code>```

Please advise

答:
additional option. Using lubridate you can check in what interval the date is

```<code>library(tidyverse)
df2 %>%
  rowwise() %>%
  mutate(out = df1$Value[(DateTime %within% interval(df1$Start_Date, df1$End_Date))])
</code>```

Body:
Assume I have df1:

Start_Date    End_Date     Value
2001-01-01    2001-12-31   1
2002-01-01    2002-12-31   2
2003-01-01    2003-12-31   3
2004-01-01    2004-12-31   4
2005-01-01    2005-12-31   5

& df2:

DateTime
2003-01-01
2003-05-09
2004-12-31
2005-01-31
2005-08-13

What I would like to do is to import Value from df1 into df2 by checking which DateTime in df2 falls in between Start_Date & End_Date in df1. A view of desired outcome:

DateTime      Value
2003-01-01    3
2003-05-09    3
2004-12-31    4
2005-01-31    5
2005-08-13    5

Please advise

Body:
additional option. Using lubridate you can check in what interval the date is

library(tidyverse)
df2 %>%
  rowwise() %>%
  mutate(out = df1$Value[(DateTime %within% interval(df1$Start_Date, df1$End_Date))])


问:
BASH/SHELL - bad substitution
I have a set of variables (M1 to M20) with values 1 or 0 in them. And i want to loop through them and echo a message when one is 1.

```<code>#!/bin/sh
for r in {1..20}
do
    if [ ${"M$r"} -eq 1 ]
    then
        col=`expr 150 \+ $r`
        echo " M"$r" is here: "$col" "
    fi
done
</code>```

I can't figure out the substitution.

答:
You really should use an array for this sort of thing, but the syntax you're looking for is:

```<code>#!/bin/bash

for i in {1..20}; do
        v=M$i
        test "${!v}" = 1 && echo M$i = 1
done
</code>```

I would use = rather than -eq unless you know that all the values look like integers. Otherwise you'll probably want to suppress the error messages, but IMO it's easier just to do a string comparison.

Title: BASH/SHELL - bad substitution

Body:
I have a set of variables (M1 to M20) with values 1 or 0 in them. And i want to loop through them and echo a message when one is 1.

#!/bin/sh
for r in {1..20}
do
    if [ ${"M$r"} -eq 1 ]
    then
        col=`expr 150 \+ $r`
        echo " M"$r" is here: "$col" "
    fi
done

I can't figure out the substitution.

Body:
You really should use an array for this sort of thing, but the syntax you're looking for is:

#!/bin/bash

for i in {1..20}; do
        v=M$i
        test "${!v}" = 1 && echo M$i = 1
done

I would use = rather than -eq unless you know that all the values look like integers. Otherwise you'll probably want to suppress the error messages, but IMO it's easier just to do a string comparison.


问:
What makes some named Functions/Operators special?
Documenting on some C++20 features, i crossed some named Functions and Operators like the following under <compare> header :

```<code>  constexpr bool is_eq  (partial_ordering cmp) noexcept { return cmp == 0; }
  constexpr bool is_neq (partial_ordering cmp) noexcept { return cmp != 0; }
  constexpr bool is_lt  (partial_ordering cmp) noexcept { return cmp < 0; }
  constexpr bool is_lteq(partial_ordering cmp) noexcept { return cmp <= 0; }
  constexpr bool is_gt  (partial_ordering cmp) noexcept { return cmp > 0; }
  constexpr bool is_gteq(partial_ordering cmp) noexcept { return cmp >= 0; }
</code>```

Also under <utility>:

```<code>template< class T, class U >
constexpr bool cmp_greater_equal( T t, U u ) noexcept
{
    return !cmp_less(u, t);
}

template< class T, class U >
constexpr bool cmp_less_equal( T t, U u ) noexcept
{
    return !cmp_greater(t, u);
}
</code>```

What should we know about the difference between custom comparator (or simple comparators) and these functions ? and what's special about them ?

答:
The first set of functions is part of the library support for the spaceship operator <=>, added into C++20. Those utilities are there for the cases in which one finds themselves using <=> directly, instead of implicitly via the core language.

On one foot, the way spaceship works is by returning an object which can be compared to 0, thus signalling the order relation between two objects.

(a <=> b) == 0 iff a == b

(a <=> b)  < 0 iff a < b

etc.

Now, if you find yourself using a <=> b directly, or handling the result object from another source, you can compare with 0 to check the relation you want. However, the resulting code is arguably not the most obvious to read.

So those utilities are added to the library. They are there to make the code more expressive. They allow us to write is_eq(a <=> b) or is_lt(a <=> b) to query the meaning of the three way comparison. I would argue that it conveys the intent much clearer than a direct comparison with 0. Again, it's there only for the rare cases when we might need to work with the result of <=> directly.

The other set of functions serves another purpose. When comparing integers directly, the operands undergo certain integral promotions. So the result of -1 < 0u is a somewhat unintuitive false. That is because -1 is promoted to an unsigned integer prior to the comparison (because 0u is an unsigned integer literal). This wraps around into a very large unsigned number which is of course not less than 0.

To better support mixed comparisons, those functions were added. They examine the types involved, and give a result that is mathematically correct, given the values involved, without getting side-tracked due to value conversions that happen during integer promotion. To contrast with direct comparison via <, std::cmp_less(-1, 0u) returns true.

Body:
Documenting on some C++20 features, i crossed some named Functions and Operators like the following under <compare> header :

  constexpr bool is_eq  (partial_ordering cmp) noexcept { return cmp == 0; }
  constexpr bool is_neq (partial_ordering cmp) noexcept { return cmp != 0; }
  constexpr bool is_lt  (partial_ordering cmp) noexcept { return cmp < 0; }
  constexpr bool is_lteq(partial_ordering cmp) noexcept { return cmp <= 0; }
  constexpr bool is_gt  (partial_ordering cmp) noexcept { return cmp > 0; }
  constexpr bool is_gteq(partial_ordering cmp) noexcept { return cmp >= 0; }

Also under <utility>:

template< class T, class U >
constexpr bool cmp_greater_equal( T t, U u ) noexcept
{
    return !cmp_less(u, t);
}

template< class T, class U >
constexpr bool cmp_less_equal( T t, U u ) noexcept
{
    return !cmp_greater(t, u);
}

What should we know about the difference between custom comparator (or simple comparators) and these functions ? and what's special about them ?


问:
Create class column in data.table given a numeric vector
Currently I have a data.table like this:

```<code>item    dummyvar
4q7C0o     1
2BrKY63    1
3drUy6I    1
G5ALtO    1000
G5G859    1000
PAP589    2000
</code>```

And using a defined function I find out that the rows where there is a significant change in the dummyvar are in a numeric vector called imbalance = 4 6. What I would like to do is to create a new column in my data table such that all the rows below the given numbers given by imbalance are in a given class, for ex. something like this:

```<code>item    dummyvar   Class
4q7C0o     1         1
2BrKY63    1         1
3drUy6I    1         1
G5ALtO    1000       2
G5G859    1000       2
PAP589    2000       3
</code>```

答:
If I understand correctly, the vector imbalance contains the row indices into the data.table at which a new Class should start.

Here is one possible solution (among many other, I suppose) using cut() on the row index .I:

```<code>dt[, Class := cut(.I, c(0, imbalance, Inf), labels = FALSE, right = FALSE)][]
</code>```

```<code>      item dummyvar Class
1:  4q7C0o        1     1
2: 2BrKY63        1     1
3: 3drUy6I        1     1
4:  G5ALtO     1000     2
5:  G5G859     1000     2
6:  PAP589     2000     3
</code>```

Body:
Currently I have a data.table like this:

item    dummyvar
4q7C0o     1
2BrKY63    1
3drUy6I    1
G5ALtO    1000
G5G859    1000
PAP589    2000

And using a defined function I find out that the rows where there is a significant change in the dummyvar are in a numeric vector called imbalance = 4 6. What I would like to do is to create a new column in my data table such that all the rows below the given numbers given by imbalance are in a given class, for ex. something like this:

item    dummyvar   Class
4q7C0o     1         1
2BrKY63    1         1
3drUy6I    1         1
G5ALtO    1000       2
G5G859    1000       2
PAP589    2000       3

Body:
If I understand correctly, the vector imbalance contains the row indices into the data.table at which a new Class should start.

Here is one possible solution (among many other, I suppose) using cut() on the row index .I:

dt[, Class := cut(.I, c(0, imbalance, Inf), labels = FALSE, right = FALSE)][]

      item dummyvar Class
1:  4q7C0o        1     1
2: 2BrKY63        1     1
3: 3drUy6I        1     1
4:  G5ALtO     1000     2
5:  G5G859     1000     2
6:  PAP589     2000     3


答:
All you need to do is run a test on the first 3 elements of each array and then use the spread operator to join them:</p>

```<code>if A1[:3] == A2[:3]:
    result = [*A1, *A2]
</code>```

Title: Join two arrays of different size with condition

Body:
i have two arrays of different sizes and i want them to joint in one only if first three elements match.

for exapmle:

A1 = [
    [1,8,9,8,2],
    [2,9,9,8,2],
    [1,7,7,8,2],
    [8,6,2,6,7]
]

A2 = [[2,9,9,30,60],
      [8,6,2,70,20]]

Result = [[2,9,9,8,2,30,60]
         [8,6,2,6,7,70,20]]

I guess there is some numpy function for this but i couldn't find it.

Body:
All you need to do is run a test on the first 3 elements of each array and then use the spread operator to join them:

if A1[:3] == A2[:3]:
    result = [*A1, *A2]


问:
Reverse search an image in Yandex Images using Python
I'm interested in automatizing reverse image search. Yandex in particular is great for busting catfishes, even better than Google Images. So, consider this Python code:

```<code>import requests
import webbrowser

try:
    filePath = "C:\\path\\whateverThisIs.png"
    searchUrl = 'https://yandex.ru/images/'
    multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''}
    response = requests.post(searchUrl, files=multipart, allow_redirects=False)
    #fetchUrl = response.headers['Location']
    print(response)
    print(dir(response))
    print(response.content)
    input()
except Exception as e:
    print(e)
    print(e.with_traceback)
    input()```
```

The script fails with KeyError, 'location' is not found. I know the code works cause if you substitute searchUrl with http://www.google.hr/searchbyimage/upload then the script returns the correct url.
So, in short the expected outcome would be a url with an image search. In actuality we get a KeyError where that url was supposed to be stored.
Evidently, Yandex doesn't work in exactly the same way, maybe the url is off (although I tried a heap ton of variations) or the reason may be completely different.

Regardless of that, help in solving this problem is much appreciated!

答:
You can get url with an image search by using this code. Tested on ubuntu 18.04, with python 3.7 and requests 2.23.0

import json

import requests

file_path = "C:\\path\\whateverThisIs.png"
search_url = 'https://yandex.ru/images/search'
files = {'upfile': ('blob', open(file_path, 'rb'), 'image/jpeg')}
params = {'rpt': 'imageview', 'format': 'json', 'request': '{"blocks":[{"block":"b-page_type_search-by-image__link"}]}'}
response = requests.post(search_url, params=params, files=files)
query_string = json.loads(response.content)['blocks'][0]['params']['url']
img_search_url = search_url + '?' + query_string
print(img_search_url)
```

Body:
I'm interested in automatizing reverse image search. Yandex in particular is great for busting catfishes, even better than Google Images. So, consider this Python code:

import requests
import webbrowser

try:
    filePath = "C:\\path\\whateverThisIs.png"
    searchUrl = 'https://yandex.ru/images/'
    multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''}
    response = requests.post(searchUrl, files=multipart, allow_redirects=False)
    #fetchUrl = response.headers['Location']
    print(response)
    print(dir(response))
    print(response.content)
    input()
except Exception as e:
    print(e)
    print(e.with_traceback)
    input()```

The script fails with KeyError, 'location' is not found. I know the code works cause if you substitute searchUrl with http://www.google.hr/searchbyimage/upload then the script returns the correct url.
So, in short the expected outcome would be a url with an image search. In actuality we get a KeyError where that url was supposed to be stored.
Evidently, Yandex doesn't work in exactly the same way, maybe the url is off (although I tried a heap ton of variations) or the reason may be completely different.

Regardless of that, help in solving this problem is much appreciated!


问:
How can I hide Form2 using a button from Form1?
I have two windows forms, Form1 and Form2. In Form1 I have two buttons: "show form 2" and "hide form 2". When I press "show form 2", it shows the second form. But I don't know how to hide the second form when I press "hide form 2". Any ideas? </p>

答:
If Form2 is open you can access it by:

```<code>Form form2 = Application.OpenForms["Form2"];
</code>```

And then inside button click event, call:

```<code>form2.Hide();
</code>```

Body:
If Form2 is open you can access it by:

Form form2 = Application.OpenForms["Form2"];

And then inside button click event, call:

form2.Hide();