问:
Remove duplicates from list of lists by column value
I have a list of list that look like this, they have been sorted so that duplicate IDs are arranged with the one I want to keep at the top..

```<code>[
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '23', 'type': 'car', 'price': '78'},
    {'id': '23', 'type': 'car', 'price': '34'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '125', 'type': 'truck', 'price': '722'},
    {'id': '125', 'type': 'truck', 'price': '100'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]
</code>```

What is the simplest way to remove rows that have duplicate IDs but always keep the first one? In this instance the end result would look like this...

```<code>[
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]
</code>```

I know I can remove duplicates from lists by converting to set like set(my_list) but in this instance it is duplicates by ID that I want to remove by

答:
Here's an answer that involves no external modules or unnecessary manipulation of the data:

```<code>data = [
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '23', 'type': 'car', 'price': '78'},
    {'id': '23', 'type': 'car', 'price': '34'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '125', 'type': 'truck', 'price': '722'},
    {'id': '125', 'type': 'truck', 'price': '100'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]
seen = set()
result = [row for row in data if row['id'] not in seen and not seen.add(row['id'])]
print(result)
</code>```

Result:

```<code>[{'id': '23', 'type': 'car', 'price': '445'},
 {'id': '125', 'type': 'truck', 'price': '998'},
 {'id': '87', 'type': 'bike', 'price': '50'}]
</code>```

Note that the not seen.add(row['id'])] part of the list comprehension will always be True.  It's just a way of noting that a unique entry has been seen by adding it to the seen set.

Body:
I have a list of list that look like this, they have been sorted so that duplicate IDs are arranged with the one I want to keep at the top..

[
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '23', 'type': 'car', 'price': '78'},
    {'id': '23', 'type': 'car', 'price': '34'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '125', 'type': 'truck', 'price': '722'},
    {'id': '125', 'type': 'truck', 'price': '100'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]

What is the simplest way to remove rows that have duplicate IDs but always keep the first one? In this instance the end result would look like this...

[
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]

I know I can remove duplicates from lists by converting to set like set(my_list) but in this instance it is duplicates by ID that I want to remove by

Body:
Here's an answer that involves no external modules or unnecessary manipulation of the data:

data = [
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '23', 'type': 'car', 'price': '78'},
    {'id': '23', 'type': 'car', 'price': '34'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '125', 'type': 'truck', 'price': '722'},
    {'id': '125', 'type': 'truck', 'price': '100'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]
seen = set()
result = [row for row in data if row['id'] not in seen and not seen.add(row['id'])]
print(result)

Result:

[{'id': '23', 'type': 'car', 'price': '445'},
 {'id': '125', 'type': 'truck', 'price': '998'},
 {'id': '87', 'type': 'bike', 'price': '50'}]

Note that the not seen.add(row['id'])] part of the list comprehension will always be True.  It's just a way of noting that a unique entry has been seen by adding it to the seen set.


来源: stackexchange

问:
Xml database in PHP
I need to use xml as database in php. Till now i used mssql,mysql as database in php. Is it possible to do so? </p>

答:
XML is not a database. It's simply a standardized method of marking up data. You can treat it as a database, but you don't want to. The overhead of maintaining an XML tree is massive, especially if you have a lot of data. XML is NOT efficient for fast/random/abitrary access, especially since you'd have to load/parse the whole XML tree for every "database query" you perform.

About the only thing you'd gain from this is portability, but whatever site you're building would run slower than Windows 7 on an abacus.

ContentLicense: CC BY-SA 3.0

Title: Xml database in PHP


问:
What is object serialization?
What is meant by "object serialization"? Can you please explain it with some examples? </p>

答:
Serialization is a process of saving the specific state of an object by converting it into byte code. This converted byte code is used to transfer object states between 2 JVM where the receiving JVM deserialises the bytecode to retrieve the state of the object that was shared.
The serialization and de-serialization is done using serialVersionUID as reference in JVMS involved.

In Java the same is achieved using Serialization and Externalisation interfaces

OwnerDisplayName: Warrior

ContentLicense: CC BY-SA 2.5

Title: What is object serialization?

LastEditorDisplayName: mmyers

ContentLicense: CC BY-SA 4.0


问:
How to clean Premake generated files using 'premake5 clean' command
To create a Visual Studio solution file and its respective project files using premake, I can type premake5.exe vs2019 in cmd and it works perfectly fine.

However, when I command premake5.exe clean to remove all binaries and generated files created by premake it shows

Running action 'clean'...

** The clean action has not yet been ported

What do I have to do to make the clean action work? I'm really appreciate for your help.

答:
You can roll your own in your project script.

if _ACTION == 'clean' then
   os.rmdir('bin')
   os.rmdir('obj')
   os.remove('*.sln')
   os.remove('*.vcxproj')
   -- etc
end
```


问:
How to specify the path of `package.json` to npm?
I use npm scripts to build my project.  I'd like to be able to run the scripts from a different directory.  That is, instead of doing the following:

```<code>cd project;
npm run build;
cd ..
</code>```

...I'd like to simply do something like:

```<code>npm run build -config project/package.json;
</code>```

or

```<code>npm run build -wd project;
</code>```

Is this possible?

答:
to change the path of package.json that npm gets
this didnt work for me

```<code>npm --prefix /path/to/project run build
</code>```

but this did

```<code>npm --prefix /path/to/project run
</code>```

but this does not permanently change it
for example you can say

```<code>npm --prefix /path/to/project run test
</code>```

Body:
I use npm scripts to build my project.  I'd like to be able to run the scripts from a different directory.  That is, instead of doing the following:

cd project;
npm run build;
cd ..

...I'd like to simply do something like:

npm run build -config project/package.json;

or

npm run build -wd project;

Is this possible?

Body:
to change the path of package.json that npm gets
this didnt work for me

npm --prefix /path/to/project run build

but this did

npm --prefix /path/to/project run

but this does not permanently change it
for example you can say

npm --prefix /path/to/project run test


问:
Calling function from typescript in html not working
Hey im using a django and wanted to use typescript for a specific function I need for my application.

Here is my typescript file:

testselector.ts:

```<code>getSelectionText() {
    var text = "";
    if (window.getSelection) {
      text = window.getSelection().toString();
      console.log('a');
    } else if (document.selection && document.selection.type != "Control") {
      console.log('b');
      text = document.selection.createRange().text;
  }
  return text;
}
</code>```

And here is my html where I want to call the function:

```<code>{% extends "base_generic2.html" %}

{% block content %}

  <script src="textselector.js"></script>

  <div id="app" onmouseup="getSelectionText()">
  </div>

{% endblock %}
</code>```

For some reason it doesnt find getSelectionText() and I dont really know why?

EDIT:

Here are the errors popping up for  my typescript:

Error:(2, 3) TS2304: Cannot find name 'getSelectionText'.

Error:(7, 27) TS2339: Property 'selection' does not exist on type 'Document'.

Error:(7, 49) TS2339: Property 'selection' does not exist on type 'Document'.

Error:(9, 27) TS2339: Property 'selection' does not exist on type 'Document'.

Error:(2, 22) TS1005: ';' expected.

答:
Try this for your Typescript:

```<code>    window.getSelectionText = function(){
        var text = "";
        if (window.getSelection()) {
          text = window.getSelection().toString();
          console.log('a');
        } else if (window.getSelection() && window.getSelection().type != "Control") {
          console.log('b');
          text = document.getSelection().createRange().text;
      }
      return text;
    }
</code>```

Body:
Hey im using a django and wanted to use typescript for a specific function I need for my application.

Here is my typescript file:

testselector.ts:

getSelectionText() {
    var text = "";
    if (window.getSelection) {
      text = window.getSelection().toString();
      console.log('a');
    } else if (document.selection && document.selection.type != "Control") {
      console.log('b');
      text = document.selection.createRange().text;
  }
  return text;
}

And here is my html where I want to call the function:

{% extends "base_generic2.html" %}

{% block content %}

{% endblock %}

For some reason it doesnt find getSelectionText() and I dont really know why?

EDIT:

Here are the errors popping up for  my typescript:

Error:(2, 3) TS2304: Cannot find name 'getSelectionText'.

Error:(7, 27) TS2339: Property 'selection' does not exist on type 'Document'.

Error:(7, 49) TS2339: Property 'selection' does not exist on type 'Document'.

Error:(9, 27) TS2339: Property 'selection' does not exist on type 'Document'.

Error:(2, 22) TS1005: ';' expected.

Body:
Try this for your Typescript:

    window.getSelectionText = function(){
        var text = "";
        if (window.getSelection()) {
          text = window.getSelection().toString();
          console.log('a');
        } else if (window.getSelection() && window.getSelection().type != "Control") {
          console.log('b');
          text = document.getSelection().createRange().text;
      }
      return text;
    }


问:
How to display even Fibonacci numbers by specifying their number?
I have a function that checks Fibonacci numbers for even.

```<code>def fibonacci(num=4):
    fib1 = fib2 = 1
    print(0, end=' ')
    for i in range(1, num):
        fib1, fib2 = fib2, fib1 + fib2
        if (fib2 % 2) == 0:
            print(fib2, end=' ')

fibonacci()
</code>```

I need it to output a specified number of even numbers

Example input: 4

Example output: 0 2 8 34

答:
You could make your fibonacci function a generator that only yields even Fibonacci numbers, and then just pull the desired number of values from it:

```<code>def even_fibonacci():
    fib1, fib2 = 0, 1
    while True:
        if fib1 % 2 == 0:
            yield fib1
        fib1, fib2 = fib2, fib1 + fib2

it = even_fibonacci()
for _ in range(4):
    print(next(it))
</code>```

prints:

```<code>0
2
8
34
</code>```

Body:
I have a function that checks Fibonacci numbers for even.

def fibonacci(num=4):
    fib1 = fib2 = 1
    print(0, end=' ')
    for i in range(1, num):
        fib1, fib2 = fib2, fib1 + fib2
        if (fib2 % 2) == 0:
            print(fib2, end=' ')

fibonacci()

I need it to output a specified number of even numbers

Example input: 4

Example output: 0 2 8 34

Body:
You could make your fibonacci function a generator that only yields even Fibonacci numbers, and then just pull the desired number of values from it:

def even_fibonacci():
    fib1, fib2 = 0, 1
    while True:
        if fib1 % 2 == 0:
            yield fib1
        fib1, fib2 = fib2, fib1 + fib2

it = even_fibonacci()
for _ in range(4):
    print(next(it))

prints:

0
2
8
34


问:
Trying to remove checkboxes from specific table rows
I'm trying to add checkboxes to a table using Javascript and then remove them from totals columns (that have class "kn-table-totals"). However, my code removes all of the checkboxes. I have a table that displays some data and totals the values at the bottom. I'd like the checkboxes at the start of each data set but not the in the totals columns. See the fiddle below. Heres my code:

```<code>$('#' + view.key + '.kn-table tbody tr').each(function() {
    $(this).prepend('<td><input type="checkbox"></td>');
});
   $('#' + view.key + '.kn-table tbody tr.kn-table-totals td input').each(function() {
    $(this).remove()
}
</code>```

Here's one of the checkboxes I'm trying to target:

```<code><tr class="kn-table-totals">
<td style="background-color: rgb(238, 238, 238); border-top: 1px solid rgb(218, 218, 218); text-align: right;">
<strong>Totals -
<input type="checkbox">
</strong>
</td>
</code>```

The full code is here: https://jsfiddle.net/rainybird/50wya2k7/1/

Any help would be appreciated!

答:
You will have to check for unique identifier eg. checkbox value or id.

Example:

Using value <input type="checkbox" value="value1">

```<code>$(`#${view.key}.kn-table tbody tr.kn-table-totals td input[value='value1']`).remove();
</code>```

Using id <input type="checkbox" id="uniqueId">

```<code>$(`#${view.key}.kn-table tbody tr.kn-table-totals td input#uniqueId`).remove();
</code>```

Body:
I'm trying to add checkboxes to a table using Javascript and then remove them from totals columns (that have class "kn-table-totals"). However, my code removes all of the checkboxes. I have a table that displays some data and totals the values at the bottom. I'd like the checkboxes at the start of each data set but not the in the totals columns. See the fiddle below. Heres my code:

$('#' + view.key + '.kn-table tbody tr').each(function() {
    $(this).prepend('<input type="checkbox">	');
});
   $('#' + view.key + '.kn-table tbody tr.kn-table-totals td input').each(function() {
    $(this).remove()
}

Here's one of the checkboxes I'm trying to target:

Totals -
<input type="checkbox">

The full code is here: https://jsfiddle.net/rainybird/50wya2k7/1/

Any help would be appreciated!

Body:
You will have to check for unique identifier eg. checkbox value or id.

Example:

Using value <input type="checkbox" value="value1">

$(`#${view.key}.kn-table tbody tr.kn-table-totals td input[value='value1']`).remove();

Using id <input type="checkbox" id="uniqueId">

$(`#${view.key}.kn-table tbody tr.kn-table-totals td input#uniqueId`).remove();


问:
Rust http crate create a request with post parameters
I have this;

```<code>Request::builder()
 .method(http::Method::POST)
 .uri("/create_mapping")
 .body()
</code>```

And I want to add POST parameters into the body(). Say something like a=1&b=2.

答:
The easiest way seems to be to use from_urlencoded and do something like:

```<code>let encoded = form_urlencoded::Serializer::new(String::new())
            .append_pair("a", "1")
            .append_pair("b", "2")
            .finish();
</code>```

and then create the body like this: Body::from(encoded)

Body:
I have this;

Request::builder()
 .method(http::Method::POST)
 .uri("/create_mapping")
 .body()

And I want to add POST parameters into the body(). Say something like a=1&b=2.

Body:
The easiest way seems to be to use from_urlencoded and do something like:

let encoded = form_urlencoded::Serializer::new(String::new())
            .append_pair("a", "1")
            .append_pair("b", "2")
            .finish();

and then create the body like this: Body::from(encoded)


问:
Saving JSON into MySQL using PHP overwrites rather than adds a new sub array
I'm trying to save a json array into a MySQL field using PHP. The idea is that when someone submits a new comment, the comment is added into a json array of all comments and saved into the database as a multidimensional array. I've searched StackOverflow - but when any new comment submitted it just overwrites the existing array - rather than adding to it. And I can't see what I'm doing wrong. Here is my code:

The form has a hidden field, where I echo the json from the database:

```<code><input type="hidden" name="json" value=" <?php echo json_encode($item->issue_comments);?> "/>
</code>```

Then, when the form submits using POST, I have the following code to decode and add the new sub array (date/name/comment) into the main array and reencode.

```<code>$comments = json_decode($_POST['json'], true);
$comments['comment'][] = array('date'=>$comment_date, 'name'=>$issue_commenter, 'comment'=>$_POST['issue_comment']);
$json = json_encode($comments);
</code>```

This is what is saved in the database:

```<code>{"comment": [{"date": "2022-02-12 18:02:02", "name": 1, "comment": "comment text"}]}
</code>```

Thanks for any help

Body:
I'm trying to save a json array into a MySQL field using PHP. The idea is that when someone submits a new comment, the comment is added into a json array of all comments and saved into the database as a multidimensional array. I've searched StackOverflow - but when any new comment submitted it just overwrites the existing array - rather than adding to it. And I can't see what I'm doing wrong. Here is my code:

The form has a hidden field, where I echo the json from the database:

<input type="hidden" name="json" value=" <?php echo json_encode($item->issue_comments);?> "/>

Then, when the form submits using POST, I have the following code to decode and add the new sub array (date/name/comment) into the main array and reencode.

$comments = json_decode($_POST['json'], true);
$comments['comment'][] = array('date'=>$comment_date, 'name'=>$issue_commenter, 'comment'=>$_POST['issue_comment']);
$json = json_encode($comments);

This is what is saved in the database:

{"comment": [{"date": "2022-02-12 18:02:02", "name": 1, "comment": "comment text"}]}

Thanks for any help

Body:
If you want to store data as JSON in MySQL, you should read about MySQL's JSON data type and builtin JSON functions that you can use to manipulate JSON documents.

Here's a demo of appending an object to an array:

I create a test table to use:

mysql> create table mytable (id serial primary key, comment_thread json);
Query OK, 0 rows affected (0.01 sec)

mysql> insert into mytable set comment_thread = '{"comment": [{"date": "2022-02-12 18:02:02", "name": 1, "comment": "comment text"}]}';
Query OK, 1 row affected (0.01 sec)

Now I can show that the JSON is in the table:

mysql> select json_pretty(comment_thread) from mytable;
+--------------------------------------------------------------------------------------------------------------------------+
| json_pretty(comment_thread)                                                                                |
+--------------------------------------------------------------------------------------------------------------------------+
| {
  "comment": [
    {
      "date": "2022-02-12 18:02:02",
      "name": 1,
      "comment": "comment text"
    }
  ]
} |
+--------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

One can use the builtin JSON_ARRAY_APPEND() function to add a new element to an array. The element I append is itself a JSON object, which I create with the JSON_OBJECT() function from name/value pairs.

mysql> select json_pretty(json_array_append(comment_thread, '$.comment',
 json_object('date', now(), 'name', 2, 'comment', 'new comment'))) as newdoc from mytable;
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| newdoc                                                                                |
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| {
  "comment": [
    {
      "date": "2022-02-12 18:02:02",
      "name": 1,
      "comment": "comment text"
    },
    {
      "date": "2022-02-12 11:19:20.000000",
      "name": 2,
      "comment": "new comment"
    }
  ]
} |
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

That demonstrates using SELECT so we can see the result. When you're satisfied that you have the expression coded to produce the result you want, use that expression in an UPDATE statement:

mysql> update mytable set comment_thread = json_array_append(
    comment_thread,
    '$.comment',
    json_object('date', now(), 'name', 2, 'comment', 'new comment'))
  where id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

If that seems like a lot of complexity, then I'd suggest using normal rows and columns instead of JSON. That is, store comments one per row, and use a separate column for the date, name and comment text. Then adding a new comment is a lot more conventional and straightforward:

INSERT INTO comments (date, name, comment) VALUES (NOW(), 2, 'new comment');


答:
You can modify the timestamp of your image files to the desired in-video timestamp and use the ts_from_file option of the image2 demuxer. You need to do this before running ffmpeg.

Here is a question on superuser which relates to your question.

Also, if you haven't read up on it, here is the image2 documentation

Title: Dynamically Add TimeStamps to each jpeg images that is used to create a video

Body:
using ffmpeg and C# I create video files from jpeg images stored on my harddrive.

So, these jpeg images can be in many different locations so I create a fiel called:

Test.txt

and inside that file I write the jpegs I want to use in the new video file I am creating:

file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110405363.0.1.1.10.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.5
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110405491.0.1.1.12.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.128
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110405619.0.1.1.12.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.128
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110406594.0.1.1.16.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.975
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110406708.0.1.1.24.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.114
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110406787.0.1.1.05.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.079
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110406923.0.1.1.05.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.136
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110407434.0.1.1.05.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.511
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110407446.0.1.1.05.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.012
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110407575.0.1.1.05.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.129
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110407699.0.1.1.05.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.124
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110407827.0.1.1.36.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.128
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110407963.0.1.1.35.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.136
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110408091.0.1.1.24.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.128
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110408223.0.1.1.00.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.132
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110408347.0.1.1.00.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'
duration 0.124
file 'D:\TestPi\Library\DESKTOP-L3DDUI8\2022\02\12\11\04\20220212110408574.0.1.1.00.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg'

Then I execute this command line action:

ffmpeg -y -f concat  -safe 0 -i Test.txt -pix_fmt yuv420p Test.mp4

This all works very well.  But not I am looking at wring a timestamp onto each jpeg iamge.

The TimeStamp is part of the file name of each jpeg:

20220212110405363.0.1.1.10.efab8311-b8d9-4abf-a9d4-c67a65a9b827.jpg

So this bit:

20220212110405363

is the timestamp for that image.

2022     Year
02       Month
12       Day
11       Hour
04       Minute
05       Second
363      Millisecond

Is there a way I can modify my script etc to do this?

Thanks


问:
drawCircle vs drawBitmap
I'm planning on implementing a new set of figures in my game: plain circles. The number of drawn sprites (in this case circles) starts with 2-3, and can go up endlessly (potentially). The maximum will probably be around 60 though. In total there will have to be 5 types of circles, each with a different color and probably size too. Now seeing as I won't implement it until monday I thought I'd ask it at stackoverflow.

Does anybody already know which method is faster?

答:
Bitmaps are almost always faster than any kind of draw. With the right preparation drawing a bitmap is simply dumping memory to the screen. Drawing a circle involves a significant number of calculations, including anti-aliasing. I presented a paper which covered this at JavaOne 2009, but papers that old seem to have been removed from the site.

It does depend on how big your bitmap would need to be, but for sizes under 10 pixels bitmap sprites are much faster than even simple graphic operations like drawing crosses and lines. You also need to make sure that your sprite won't require any kind of transform when it is drawn, and that it is a form compatible with the screen memory.

If every circle is to be a different color or thickness, or worse a different size, then that's another matter. The cost of creating each bitmap would outweigh the savings.

You should also remember the first rule of optimization: don't do it unless you have to.

Title: drawCircle vs drawBitmap


问:
Is there any function to split data in R, depending on a certain value?
I want to create a new table with these conditions:  all the data that in transition=13-14 was size_age=j.

答:
You can use dplyr::filter, with conditions to get your desired subset</p>
```<code>dplyr::filter(df, transition =="13-14", size_age=="j")
</code>```

Body:
You can use dplyr::filter, with conditions to get your desired subset

dplyr::filter(df, transition =="13-14", size_age=="j")


问:
Flutter project can't be build because of plugin Geolocator
Since I have included the geolocator plugin in my flutter project, the build fails with the message

```<code>A problem occurred evaluating root project 'android'.
Basedir C:\Users\<user>\flutter\.pub-cache\hosted\pub.dartlang.org\geolocator-8.1.1\android does not exist
</code>```

It's true that this directory does not exist but that's the way is done in github project.

答:
do you have implement geolocator for a platform like android or ios?

after you have implemented you can try:

run: flutter clean and try again

Make sure your Android project uses gradle version 3.5.0 and gradle-wrapper 5.6.2.

Body:
Since I have included the geolocator plugin in my flutter project, the build fails with the message

A problem occurred evaluating root project 'android'.
Basedir C:\Users\<user>\flutter\.pub-cache\hosted\pub.dartlang.org\geolocator-8.1.1\android does not exist

It's true that this directory does not exist but that's the way is done in github project.


问:
How to set menuIndex properly in EasyAdmin AdminUrlGenerator?
Within EasyAdmin for Symfony you can use the AdminUrlGenerator for easily generating URLs to for example EasyAdmin CRUD Controllers.

Documentation here: https://symfony.com/doc/current/EasyAdminBundle/crud.html#generating-admin-urls

In my case i want to generate an URL to CRUD controller which is also linked within the Dashboard. If i create a link to a CRUD controller, the link works, but the corresponding MenuItem is not highlighted.
I found out, that EasyAdmin highlights the MenuItem with an URL parameter calling menuIndex. I can unset the menuIndex during Link Generation, but then no menuItem is highlightd in the menu.

I havn't found any information on how to get the correct menuIndex for a generated CRUD URL.

So how can i generate Admin URLs with correct menuIndex?

答:
I want to give one possible answer. But to be honest, i don't really like my solution. Maybe someone has a better solution.

So, i am iterating over the configured menuItems within the DashboardController and trying to determine the menuIndex for a given Entity.

The code lookes like this:

```<code>private function getIndexLinkForCrudController(string $controller): string
{
    return $this->adminUrlGenerator
        ->unsetAll()
        ->setController($controller)
        ->setAction(Action::INDEX)
        ->set('menuIndex', $this->determineMenuIndexForEntity($controller::getEntityFqcn()))
        ->generateUrl();
}

private function determineMenuIndexForEntity(string $entity): ?int
{
    $menuItems = $this->configureMenuItems();

    foreach ($menuItems as $id => $menuItem) {
        /* @var MenuItemInterface $menuItem */
        $routeParameter = $menuItem->getAsDto()->getRouteParameters();
        if (
            is_array($routeParameter) &&
            array_key_exists(EA::ENTITY_FQCN, $routeParameter) &&
            $routeParameter[EA::ENTITY_FQCN] == $entity
        ) {
            return $id;
        }
    }

    return null;
}
</code>```

This code works for me. But this code only works within the DashboardController. If i want to create Admin URLs within a CRUD controller i need to move the menu config to a static method and accessing it there.
Also i am not fetching the error case when i cannot determine the menuIndex and returning null. For my case it's fine.

Maybe this is helpfull for someone.
If somebody has better solution, i would be happy to here about it.

Body:
I want to give one possible answer. But to be honest, i don't really like my solution. Maybe someone has a better solution.

So, i am iterating over the configured menuItems within the DashboardController and trying to determine the menuIndex for a given Entity.

The code lookes like this:

private function getIndexLinkForCrudController(string $controller): string
{
    return $this->adminUrlGenerator
        ->unsetAll()
        ->setController($controller)
        ->setAction(Action::INDEX)
        ->set('menuIndex', $this->determineMenuIndexForEntity($controller::getEntityFqcn()))
        ->generateUrl();
}

private function determineMenuIndexForEntity(string $entity): ?int
{
    $menuItems = $this->configureMenuItems();

    foreach ($menuItems as $id => $menuItem) {
        /* @var MenuItemInterface $menuItem */
        $routeParameter = $menuItem->getAsDto()->getRouteParameters();
        if (
            is_array($routeParameter) &&
            array_key_exists(EA::ENTITY_FQCN, $routeParameter) &&
            $routeParameter[EA::ENTITY_FQCN] == $entity
        ) {
            return $id;
        }
    }

    return null;
}

This code works for me. But this code only works within the DashboardController. If i want to create Admin URLs within a CRUD controller i need to move the menu config to a static method and accessing it there.
Also i am not fetching the error case when i cannot determine the menuIndex and returning null. For my case it's fine.

Maybe this is helpfull for someone.
If somebody has better solution, i would be happy to here about it.


问:
Adding an object to NSMutableArray from UITextField
With this code, I get this error:

'* -[NSMutableArray insertObject:atIndex:]: attempt to insert nil
  object at 0'

```<code>categories=[[NSMutableArray alloc] init ];
UIAlertView* dialog = [[UIAlertView alloc] init];
    [dialog setDelegate:self];
    [dialog setTitle:@"Category name"];
    [dialog setMessage:@" "];
    [dialog addButtonWithTitle:@"Cancel"];
    [dialog addButtonWithTitle:@"OK"];

    nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
    [nameField setBackgroundColor:[UIColor whiteColor]];
    [dialog addSubview:nameField];

    [dialog show];
    [dialog release];

    [categories addObject:[nameField text]];

    [nameField release];
    [categoryTable reloadData];
</code>```

When I run this in simulator, I get a crash before the alert view even pops up. Any ideas?

答:
An exception will be raised in an NSArray if you try to add a nil object. Check for the condition first:

```<code>if ([nameField text]) [categories addObject:[nameField text]];
</code>```

EDIT:

Also from your code, you need to implement the UIAlertViewDelegate protocol and attempt to add your object to your array there.  For example:

```<code>- (void) showDialog {
    UIAlertView* dialog = [[UIAlertView alloc] init];
    [dialog setDelegate:self];
    [dialog setTitle:@"Category name"];
    [dialog setMessage:@" "];
    [dialog addButtonWithTitle:@"Cancel"];
    [dialog addButtonWithTitle:@"OK"];

    nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
    [nameField setBackgroundColor:[UIColor whiteColor]];
    [dialog addSubview:nameField];

    [dialog show];
    [dialog release];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {

    if ([nameField text]) [categories addObject:[nameField text]];
    [categoryTable reloadData];

}
</code>```

Assumes nameField and categories are iVars and you will need to release them when they are no longer needed.  You should also check which button was pressed in the delegate method.  HTH Dave

Body:
With this code, I get this error:

'* -[NSMutableArray insertObject:atIndex:]: attempt to insert nil
  object at 0'

categories=[[NSMutableArray alloc] init ];
UIAlertView* dialog = [[UIAlertView alloc] init];
    [dialog setDelegate:self];
    [dialog setTitle:@"Category name"];
    [dialog setMessage:@" "];
    [dialog addButtonWithTitle:@"Cancel"];
    [dialog addButtonWithTitle:@"OK"];

    nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
    [nameField setBackgroundColor:[UIColor whiteColor]];
    [dialog addSubview:nameField];

    [dialog show];
    [dialog release];

    [categories addObject:[nameField text]];

    [nameField release];
    [categoryTable reloadData];

When I run this in simulator, I get a crash before the alert view even pops up. Any ideas?

Body:
An exception will be raised in an NSArray if you try to add a nil object. Check for the condition first:

if ([nameField text]) [categories addObject:[nameField text]];

EDIT:

Also from your code, you need to implement the UIAlertViewDelegate protocol and attempt to add your object to your array there.  For example:

- (void) showDialog {
    UIAlertView* dialog = [[UIAlertView alloc] init];
    [dialog setDelegate:self];
    [dialog setTitle:@"Category name"];
    [dialog setMessage:@" "];
    [dialog addButtonWithTitle:@"Cancel"];
    [dialog addButtonWithTitle:@"OK"];

    nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
    [nameField setBackgroundColor:[UIColor whiteColor]];
    [dialog addSubview:nameField];

    [dialog show];
    [dialog release];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {

    if ([nameField text]) [categories addObject:[nameField text]];
    [categoryTable reloadData];

}

Assumes nameField and categories are iVars and you will need to release them when they are no longer needed.  You should also check which button was pressed in the delegate method.  HTH Dave


问:
Xcode Storyboard constraint changing image size
I have an image on my storyboard. When I select it and try to add the top constraint it will resize the image and make it bigger. I cannot figure out what it is doing that. Any help would be greatly appreciated!</p>

答:
A UIImageView has no intrinsic size, until you've assigned its image property.

At that point, if you have not given it any other constraints to control its width and height, it will use the image size as its intrinsic size.


问:
how to fix setting subsystem to console in visual studio?
I want to pause console from exiting. so I'have set subsystem to console every time I make new project. I sick of this process. is there any way to fix subsystem to console when I make new project?</p>

答: When you make projects, make an empty project. It is set to console by default.</p>


问:
List of branches a commit appears on
Using the GitHub API (v3) I'd like to figure out which branches a commit appears on. I didn't find a way to directly query this, either through repo commits or the commit data objects. An alternate solution would be to list all the branches, and compare with their HEAD; I guess the comparison would fail if the commit is not on the given branch.

Is this supported via the current API, and I just missed it? If not, do you have a (better) workaround?

答:
There is no direct endpoint to list the branches by a commit ID. But you can use a combination of other endpoints to solve this.

Condition 1
Use branches-where-head endpoint to get the name of the branches where the given commit ID is the head.

Condition 2
If condition 1 returns empty, get pull info object using the commit ID and extract the branch information using pulls info endpoint.
Tip: The return object contains properties - base.ref and head.ref which has the branch name. If base.ref is the name of the master branch, use head.ref which should give you the name of the branches that contains the commit ID.

Title: List of branches a commit appears on


问:
How to access 2 dimensional Array Pointer in a typedef-struct over a function in c
I have Problems with accessing the 2D Array in a typedef from a other function over a pointer, even if i allocate the array in heap!

```<code>#include <stdlib.h>
#include <stdio.h>
typedef struct {
    int a;
    int b;
    int **data;
} Image;
Image *createImage(int a, int b) {
    Image createImage;
    createImage.data = malloc(a * sizeof(int *));
    for (int i = 0; i < a; i++) {
         createImage.data[i] = malloc(b * sizeof(int));
    }
    Image *imagePointer = malloc(sizeof(Image));
    imagePointer = &createImage;
    return imagePointer;
}
int main () {
     int a = 70;
     int b = 90;
     Image *imagePointer = createImage(a, b);
     for (int i = 0; i < a; i++) {
          for (int j = 0; j < b; j++) {
               imagePointer->data[i][j] = i + j;
          }
     }
}
</code>```

I get an error at load Image because i have done something wrong with accessing the allocated storage. What should i change?

Jonathan

答:
Instead of returning a pointer to Image return the local variable itself and it works. Also variable name and function name should not be same createImage it creates confusion sometimes.

```<code>#include <stdlib.h>

typedef struct {
    int a;
    int b;
    int **data;
} Image;
Image createImage(int a, int b) {
    Image ci;
    ci.data = malloc(a * sizeof(int *));
    for (int i = 0; i < a; i++) {
         ci.data[i] = malloc(b * sizeof(int));
    }
    return ci;
}
int loadImage () {
     int a = 70;
     int b = 90;
     Image imagePointer = createImage(a, b);
     for (int i = 0; i < a; i++) {
          for (int j = 0; j < b; j++) {
               imagePointer.data[i][j] = i + j;
          }
     }
}

int main(int argc, char const *argv[])
{
    loadImage();
    return 0;
}
</code>```

Body:
I have Problems with accessing the 2D Array in a typedef from a other function over a pointer, even if i allocate the array in heap!

#include <stdlib.h>
#include <stdio.h>
typedef struct {
    int a;
    int b;
    int **data;
} Image;
Image *createImage(int a, int b) {
    Image createImage;
    createImage.data = malloc(a * sizeof(int *));
    for (int i = 0; i < a; i++) {
         createImage.data[i] = malloc(b * sizeof(int));
    }
    Image *imagePointer = malloc(sizeof(Image));
    imagePointer = &createImage;
    return imagePointer;
}
int main () {
     int a = 70;
     int b = 90;
     Image *imagePointer = createImage(a, b);
     for (int i = 0; i < a; i++) {
          for (int j = 0; j data[i][j] = i + j;
          }
     }
}

I get an error at load Image because i have done something wrong with accessing the allocated storage. What should i change?

Jonathan

Body:
Instead of returning a pointer to Image return the local variable itself and it works. Also variable name and function name should not be same createImage it creates confusion sometimes.

#include <stdlib.h>

typedef struct {
    int a;
    int b;
    int **data;
} Image;
Image createImage(int a, int b) {
    Image ci;
    ci.data = malloc(a * sizeof(int *));
    for (int i = 0; i < a; i++) {
         ci.data[i] = malloc(b * sizeof(int));
    }
    return ci;
}
int loadImage () {
     int a = 70;
     int b = 90;
     Image imagePointer = createImage(a, b);
     for (int i = 0; i < a; i++) {
          for (int j = 0; j < b; j++) {
               imagePointer.data[i][j] = i + j;
          }
     }
}

int main(int argc, char const *argv[])
{
    loadImage();
    return 0;
}


问:
ROOM database entity modeling
There must be a better way of doing this. I want to create a database table with all my clothing and have subcategories of clothing, like outerwear, dresses, shoes, etc. They all will have the same attributes (Id, name, image, about, price). Couldn't I create one table? I believe this is a One-to-Many relationship.</p>
```<code>@Serializable
@Entity(tableName = CLOTHING_DATABASE_TABLE)
data class Clothing(
    @PrimaryKey(autoGenerate = false)
    val id: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = POPULAR_DATABASE_TABLE)
data class Popular(
    @PrimaryKey(autoGenerate = false)
    val popularId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = OUTERWEAR_DATABASE_TABLE)
data class Outerwear(
    @PrimaryKey(autoGenerate = false)
    val outerwearId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = TOPS_DATABASE_TABLE)
data class Tops(
    @PrimaryKey(autoGenerate = false)
    val topsId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = SWIMWEAR_DATABASE_TABLE)
data class Swimwear(
    @PrimaryKey(autoGenerate = false)
    val swimwearId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = SHOES_DATABASE_TABLE)
data class Shoes(
    @PrimaryKey(autoGenerate = false)
    val shoesId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = BUNDLES_DATABASE_TABLE)
data class Bundles(
    @PrimaryKey(autoGenerate = false)
    val bundlesId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = DRESSES_DATABASE_TABLE)
data class Dresses(
    @PrimaryKey(autoGenerate = false)
    val dressesId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = PAJAMAS_DATABASE_TABLE)
data class Pajamas(
    @PrimaryKey(autoGenerate = false)
    val pajamasId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = ACCESSORIES_DATABASE_TABLE)
data class Accessories(
    @PrimaryKey(autoGenerate = false)
    val accessoriesId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)
</code>```

答:
You would typically have either 2 or 3 tables (3 for a many-many i.e. an item of clothing could have multiple sub-categories).

For one-many have a clothing table which has a column for the sub-category that references(relates) to the single sub-category and a sub-category table that is referenced according to a unique column (the primary key).

For the many-many you have the clothing table (without the column to reference the single sub-category), the sub-category table and then a third table that has two columns, one for the reference to the clothing and the other for the reference to the sub-category with the primary key being a composite of both.

So you could have:-

```<code>@Entity(tableName = CLOTHING_DATABASE_TABLE)
data class Clothing(
    @PrimaryKey(autoGenerate = false)
    val id: Long, /* should really be Long as */
    val subCategoryReference: Long, /*<<<<< ADDED for the 1 subcategory */
    val name: String,
    val image: String,
    val about: String,
    val price: String
)
</code>```

and :-

```<code>@Entity(tableName = SUBCATEGORY_DATABASE_TABLE)
data class SubCategory(
    @PrimaryKey
    val id: Long?,
    val subCategoryName: String
)
</code>```

to enforce referential integrity you could add a foreign key constraint to the subCategoryReference column of the clothing table.

If you wanted a many-many, allowing a clothing to have multiple sub-categories then you could have the third table as :-

```<code>@Entity(
    tableName = CLOTHING_SUBCATEGORY_MAP_DATABASE_TABLE,
    primaryKeys = ["clothingMap","subcategoryMap"],
)
data class ClothingSubCategoryMap(
    val clothingMap: Long,
    @ColumnInfo(index = true)
    val subcategoryMap: Long
)
</code>```

Of course you could have a single clothing table and just have a column for the sub-category. However this would be considered as not being normalised as you would be duplicating the sub-category throughout.

Example 1-many (i.e. using the 2 tables Clothing and SubCategory)

As you would very likely want to retrieve clothing along with it's sub-category then you would have a POJO that uses the @Embedded and @Relation annotations e.g.

```<code>data class ClothingWithSingleSubCategory (
    @Embedded
    val clothing: Clothing,
    @Relation(
        entity = SubCategory::class,
        parentColumn = "subCategoryReference",
        entityColumn = "id"
    )
    val subCategory: SubCategory
)
</code>```

You could then have the following as an @Dao annotated class :-

```<code>@Dao
interface AllDao {
    @Insert(onConflict = IGNORE)
    fun insert(clothing: Clothing): Long
    @Insert(onConflict = IGNORE)
    fun insert(subCategory: SubCategory): Long
    @Transaction
    @Query("SELECT * FROM clothing")
    fun getAllClothingWithSubCategory(): List<ClothingWithSingleSubCategory>
}
</code>```

With a suitable @Database annotated class you could then have something like the following in an activity:-

```<code>class MainActivity : AppCompatActivity() {

    lateinit var db: TheDatabase
    lateinit var dao: AllDao
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        db = TheDatabase.getInstance(this)
        dao = db.getAllDao()

        val sc_popular = dao.insert(SubCategory(null,"Popular"))
        val sc_outerwear = dao.insert(SubCategory(null,"OuterWear"))
        val sc_tops = dao.insert(SubCategory(null,"Tops"))
        val sc_swimwear = dao.insert(SubCategory(100,"Swimwear"))
        val sc_shoes = dao.insert(SubCategory(null,"Shoes"))
        val sc_dresses = dao.insert(SubCategory(null,"Dresses"))
        val sc_pyjamas = dao.insert(SubCategory(null,"Pyjamas"))

        dao.insert(Clothing(100200300400,sc_popular,"Jeans","jeans_image","blah","100.55"))
        dao.insert(Clothing(100200300500,sc_outerwear,"Anorak","anorak_image","blah","214.55"))

        for (cwsc: ClothingWithSingleSubCategory in dao.getAllClothingWithSubCategory()) {
            Log.d("DBINFO","Name = ${cwsc.clothing.name} Price is ${cwsc.clothing.price} Sub-Category is ${cwsc.subCategory.subCategoryName}")
        }

    }
}
</code>```

When run the log would then include:-

```<code>D/DBINFO: Name = Jeans Price is 100.55 Sub-Category is Popular
D/DBINFO: Name = Anorak Price is 214.55 Sub-Category is OuterWear
</code>```

Example many-many

Like the 1-many you will want a POJO BUT one that has a List of sub-categories obtained via the mapping table. This uses the @Embeded annotation and the @Relation annotation but extended to include the associateBy to inform Room about the intermediate table. So you could have:-

```<code>data class ClothingWithListOfSubCategories(
    @Embedded
    val clothing: Clothing,
    @Relation(
        entity = SubCategory::class,
        parentColumn = "id",
        entityColumn = "id",
        associateBy = Junction(
            value = ClothingSubCategoryMap::class,
            parentColumn = "clothingMap",
            entityColumn = "subcategoryMap"
        )
    )
    val subCategories: List<SubCategory>
)
</code>```

The you could have the following in an @Dao annotated class:-

```<code>/* ADDED for many-many */
@Insert(onConflict = IGNORE)
fun insert(clothingSubCategoryMap: ClothingSubCategoryMap): Long
@Transaction
@Query("SELECT * FROM clothing")
fun getAllClothingWithSubCategories(): List<ClothingWithListOfSubCategories>
</code>```

and if the activity were extended to include :-

```<code>    /* Added for many-many */
    /* Note utilises clothing and sub-categories above */
    dao.insert(ClothingSubCategoryMap(jeans,sc_popular))
    dao.insert(ClothingSubCategoryMap(jeans,sc_swimwear))
    dao.insert(ClothingSubCategoryMap(jeans,sc_shoes))
    dao.insert(ClothingSubCategoryMap(anorak,sc_popular))
    dao.insert(ClothingSubCategoryMap(anorak,sc_outerwear))

    for(cwlsc: ClothingWithListOfSubCategories in dao.getAllClothingWithSubCategories()) {
        Log.d("DBINFO","Name = ${cwlsc.clothing.name} Price is ${cwlsc.clothing.price} it is in ${cwlsc.subCategories.size} sub-categories. They are:-")
        for(sc: SubCategory in cwlsc.subCategories) {
            Log.d("DBINFO","\t${sc.subCategoryName}")
        }
    }
</code>```

The the log would also include :-

```<code>D/DBINFO: Name = Jeans Price is 100.55 it is in 3 sub-categories. They are:-
D/DBINFO:   Popular
D/DBINFO:   Swimwear
D/DBINFO:   Shoes
D/DBINFO: Name = Anorak Price is 214.55 it is in 2 sub-categories. They are:-
D/DBINFO:   Popular
D/DBINFO:   OuterWear
</code>```

Title: ROOM database entity modeling

Body:
There must be a better way of doing this. I want to create a database table with all my clothing and have subcategories of clothing, like outerwear, dresses, shoes, etc. They all will have the same attributes (Id, name, image, about, price). Couldn't I create one table? I believe this is a One-to-Many relationship.

@Serializable
@Entity(tableName = CLOTHING_DATABASE_TABLE)
data class Clothing(
    @PrimaryKey(autoGenerate = false)
    val id: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = POPULAR_DATABASE_TABLE)
data class Popular(
    @PrimaryKey(autoGenerate = false)
    val popularId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = OUTERWEAR_DATABASE_TABLE)
data class Outerwear(
    @PrimaryKey(autoGenerate = false)
    val outerwearId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = TOPS_DATABASE_TABLE)
data class Tops(
    @PrimaryKey(autoGenerate = false)
    val topsId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = SWIMWEAR_DATABASE_TABLE)
data class Swimwear(
    @PrimaryKey(autoGenerate = false)
    val swimwearId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = SHOES_DATABASE_TABLE)
data class Shoes(
    @PrimaryKey(autoGenerate = false)
    val shoesId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = BUNDLES_DATABASE_TABLE)
data class Bundles(
    @PrimaryKey(autoGenerate = false)
    val bundlesId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = DRESSES_DATABASE_TABLE)
data class Dresses(
    @PrimaryKey(autoGenerate = false)
    val dressesId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = PAJAMAS_DATABASE_TABLE)
data class Pajamas(
    @PrimaryKey(autoGenerate = false)
    val pajamasId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

@Serializable
@Entity(tableName = ACCESSORIES_DATABASE_TABLE)
data class Accessories(
    @PrimaryKey(autoGenerate = false)
    val accessoriesId: Int,
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

Body:
You would typically have either 2 or 3 tables (3 for a many-many i.e. an item of clothing could have multiple sub-categories).

For one-many have a clothing table which has a column for the sub-category that references(relates) to the single sub-category and a sub-category table that is referenced according to a unique column (the primary key).

For the many-many you have the clothing table (without the column to reference the single sub-category), the sub-category table and then a third table that has two columns, one for the reference to the clothing and the other for the reference to the sub-category with the primary key being a composite of both.

So you could have:-

@Entity(tableName = CLOTHING_DATABASE_TABLE)
data class Clothing(
    @PrimaryKey(autoGenerate = false)
    val id: Long, /* should really be Long as */
    val subCategoryReference: Long, /*<<<<< ADDED for the 1 subcategory */
    val name: String,
    val image: String,
    val about: String,
    val price: String
)

and :-

@Entity(tableName = SUBCATEGORY_DATABASE_TABLE)
data class SubCategory(
    @PrimaryKey
    val id: Long?,
    val subCategoryName: String
)

to enforce referential integrity you could add a foreign key constraint to the subCategoryReference column of the clothing table.

If you wanted a many-many, allowing a clothing to have multiple sub-categories then you could have the third table as :-

@Entity(
    tableName = CLOTHING_SUBCATEGORY_MAP_DATABASE_TABLE,
    primaryKeys = ["clothingMap","subcategoryMap"],
)
data class ClothingSubCategoryMap(
    val clothingMap: Long,
    @ColumnInfo(index = true)
    val subcategoryMap: Long
)

Of course you could have a single clothing table and just have a column for the sub-category. However this would be considered as not being normalised as you would be duplicating the sub-category throughout.

Example 1-many (i.e. using the 2 tables Clothing and SubCategory)

As you would very likely want to retrieve clothing along with it's sub-category then you would have a POJO that uses the @Embedded and @Relation annotations e.g.

data class ClothingWithSingleSubCategory (
    @Embedded
    val clothing: Clothing,
    @Relation(
        entity = SubCategory::class,
        parentColumn = "subCategoryReference",
        entityColumn = "id"
    )
    val subCategory: SubCategory
)

You could then have the following as an @Dao annotated class :-

@Dao
interface AllDao {
    @Insert(onConflict = IGNORE)
    fun insert(clothing: Clothing): Long
    @Insert(onConflict = IGNORE)
    fun insert(subCategory: SubCategory): Long
    @Transaction
    @Query("SELECT * FROM clothing")
    fun getAllClothingWithSubCategory(): List<ClothingWithSingleSubCategory>
}

With a suitable @Database annotated class you could then have something like the following in an activity:-

class MainActivity : AppCompatActivity() {

    lateinit var db: TheDatabase
    lateinit var dao: AllDao
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        db = TheDatabase.getInstance(this)
        dao = db.getAllDao()

        val sc_popular = dao.insert(SubCategory(null,"Popular"))
        val sc_outerwear = dao.insert(SubCategory(null,"OuterWear"))
        val sc_tops = dao.insert(SubCategory(null,"Tops"))
        val sc_swimwear = dao.insert(SubCategory(100,"Swimwear"))
        val sc_shoes = dao.insert(SubCategory(null,"Shoes"))
        val sc_dresses = dao.insert(SubCategory(null,"Dresses"))
        val sc_pyjamas = dao.insert(SubCategory(null,"Pyjamas"))

        dao.insert(Clothing(100200300400,sc_popular,"Jeans","jeans_image","blah","100.55"))
        dao.insert(Clothing(100200300500,sc_outerwear,"Anorak","anorak_image","blah","214.55"))

        for (cwsc: ClothingWithSingleSubCategory in dao.getAllClothingWithSubCategory()) {
            Log.d("DBINFO","Name = ${cwsc.clothing.name} Price is ${cwsc.clothing.price} Sub-Category is ${cwsc.subCategory.subCategoryName}")
        }

    }
}

When run the log would then include:-

D/DBINFO: Name = Jeans Price is 100.55 Sub-Category is Popular
D/DBINFO: Name = Anorak Price is 214.55 Sub-Category is OuterWear

Example many-many

Like the 1-many you will want a POJO BUT one that has a List of sub-categories obtained via the mapping table. This uses the @Embeded annotation and the @Relation annotation but extended to include the associateBy to inform Room about the intermediate table. So you could have:-

data class ClothingWithListOfSubCategories(
    @Embedded
    val clothing: Clothing,
    @Relation(
        entity = SubCategory::class,
        parentColumn = "id",
        entityColumn = "id",
        associateBy = Junction(
            value = ClothingSubCategoryMap::class,
            parentColumn = "clothingMap",
            entityColumn = "subcategoryMap"
        )
    )
    val subCategories: List<SubCategory>
)

The you could have the following in an @Dao annotated class:-

/* ADDED for many-many */
@Insert(onConflict = IGNORE)
fun insert(clothingSubCategoryMap: ClothingSubCategoryMap): Long
@Transaction
@Query("SELECT * FROM clothing")
fun getAllClothingWithSubCategories(): List<ClothingWithListOfSubCategories>

and if the activity were extended to include :-

    /* Added for many-many */
    /* Note utilises clothing and sub-categories above */
    dao.insert(ClothingSubCategoryMap(jeans,sc_popular))
    dao.insert(ClothingSubCategoryMap(jeans,sc_swimwear))
    dao.insert(ClothingSubCategoryMap(jeans,sc_shoes))
    dao.insert(ClothingSubCategoryMap(anorak,sc_popular))
    dao.insert(ClothingSubCategoryMap(anorak,sc_outerwear))

    for(cwlsc: ClothingWithListOfSubCategories in dao.getAllClothingWithSubCategories()) {
        Log.d("DBINFO","Name = ${cwlsc.clothing.name} Price is ${cwlsc.clothing.price} it is in ${cwlsc.subCategories.size} sub-categories. They are:-")
        for(sc: SubCategory in cwlsc.subCategories) {
            Log.d("DBINFO","\t${sc.subCategoryName}")
        }
    }

The the log would also include :-

D/DBINFO: Name = Jeans Price is 100.55 it is in 3 sub-categories. They are:-
D/DBINFO:   Popular
D/DBINFO:   Swimwear
D/DBINFO:   Shoes
D/DBINFO: Name = Anorak Price is 214.55 it is in 2 sub-categories. They are:-
D/DBINFO:   Popular
D/DBINFO:   OuterWear


问:
python doesn't get page content
I've got the Python Beautifulsoup script below (adapted to python 3 from that script ).
It executes fine but nothing is returned in cmd.

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

Newlines = re.compile(r'[\r\n]\s+')

def getPageText(url):
    # given a url, get page content
    data = urlopen(url).read()
    # parse as html structured document
    soup = BeautifulSoup(data, 'html.parser')
    # kill javascript content
    for s in soup.findAll('script'):
        s.replaceWith('')
    # find body and extract text
    txt = soup.find('body').getText('\n')
    # remove multiple linebreaks and whitespace
    return Newlines.sub('\n', txt)

def main():
    urls = [
        'http://www.stackoverflow.com/questions/5331266/python-easiest-way-to-scrape-text-from-list-of-urls-using-beautifulsoup',
        'http://stackoverflow.com/questions/5330248/how-to-rewrite-a-recursive-function-to-use-a-loop-instead'
    ]
    txt = [getPageText(url) for url in urls]

if __name__=="__main__":
    main()
</code>```

Here's my cmd output

```<code>Microsoft Windows [Version 10.0..]
(c) Microsoft Corporation. All rights reserved.

C:\Users\user\Desktop\urls>python urls.py

C:\Users\user\Desktop\urls>
</code>```

Why doesn't it return the pages contents?

答:
Nothing is returned in cmd because there is no print statement in the code.
if you want to print out all the texts parsed from the given URL just use print function in main() function

def main():
    urls = [
        'http://www.stackoverflow.com/questions/5331266/python-easiest-way-to-scrape-text-from-list-of-urls-using-beautifulsoup',
        'http://stackoverflow.com/questions/5330248/how-to-rewrite-a-recursive-function-to-use-a-loop-instead'
    ]
    txt = [getPageText(url) for url in URLs]
    for t in txt:
        print(t)

```

Title: python doesn't get page content

Body:
I've got the Python Beautifulsoup script below (adapted to python 3 from that script ).
It executes fine but nothing is returned in cmd.

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

Newlines = re.compile(r'[\r\n]\s+')

def getPageText(url):
    # given a url, get page content
    data = urlopen(url).read()
    # parse as html structured document
    soup = BeautifulSoup(data, 'html.parser')
    # kill javascript content
    for s in soup.findAll('script'):
        s.replaceWith('')
    # find body and extract text
    txt = soup.find('body').getText('\n')
    # remove multiple linebreaks and whitespace
    return Newlines.sub('\n', txt)

def main():
    urls = [
        'http://www.stackoverflow.com/questions/5331266/python-easiest-way-to-scrape-text-from-list-of-urls-using-beautifulsoup',
        'http://stackoverflow.com/questions/5330248/how-to-rewrite-a-recursive-function-to-use-a-loop-instead'
    ]
    txt = [getPageText(url) for url in urls]

if __name__=="__main__":
    main()

Here's my cmd output

Microsoft Windows [Version 10.0..]
(c) Microsoft Corporation. All rights reserved.

C:\Users\user\Desktop\urls>python urls.py

C:\Users\user\Desktop\urls>

Why doesn't it return the pages contents?


问:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0 when deploying to Heroku
I tried to deploy my simple django project on heroku, but i couldn't understand how to solve this problem

This is the git push heroku master

```<code>remote: Traceback (most recent call last):
remote:   File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module>
remote:     r = f.read().strip()
remote:   File "/usr/lib/python3.8/codecs.py", line 322, in decode
remote:     (result, consumed) = self._buffer_decode(data, self.errors, final)
remote: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
remote: /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input
remote: ) is not available for this stack (heroku-20).
remote:  !     Aborting.  More info: https://devcenter.heroku.com/articles/python-support
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote:  !
remote:  ! ## Warning - The same version of this code has already been built: 898dd95ff261fc77ac4dcd00edd162d7b7c054f2
remote:  !
remote:  ! We have detected that you have triggered a build from source code with version 898dd95ff261fc77ac4dcd00edd162d7b7c054f2
remote:  ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch.
remote:  !
remote:  ! If you are developing on a branch and deploying via git you must run:
remote:  !
remote:  !     git push heroku <branchname>:main
remote:  !
remote:  ! This article goes into details on the behavior:
remote:  !   https://devcenter.heroku.com/articles/duplicate-build-version
remote:
remote: Verifying deploy...
remote:
remote: !       Push rejected to portfolio-project10.
remote:
To https://git.heroku.com/portfolio-project10.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/portfolio-project10.git'

C:...\portfolio-project>
</code>```

It would be very nice if anyone could help me with this, or even recommending an other way to deploy django projects for free

答:
That entire traceback is inside these parentheses: () is not available for this stack. That is the message shown when you request a Python runtime that isn't available. In this case, it looks like your runtime.txt can't even be read due to an unexpected encoding.

Delete it, then create a new file containing something like

python-3.10.2
```

only. Make sure it is UTF-8 encoded, commit, and redeploy.

At the moment, these are the currently supported Python versions, but the list changes as new versions are released:

python-3.10.2

python-3.9.10

python-3.8.12

python-3.7.12

Body:
I tried to deploy my simple django project on heroku, but i couldn't understand how to solve this problem

This is the git push heroku master

remote: Traceback (most recent call last):
remote:   File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module>
remote:     r = f.read().strip()
remote:   File "/usr/lib/python3.8/codecs.py", line 322, in decode
remote:     (result, consumed) = self._buffer_decode(data, self.errors, final)
remote: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
remote: /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input
remote: ) is not available for this stack (heroku-20).
remote:  !     Aborting.  More info: https://devcenter.heroku.com/articles/python-support
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote:  !
remote:  ! ## Warning - The same version of this code has already been built: 898dd95ff261fc77ac4dcd00edd162d7b7c054f2
remote:  !
remote:  ! We have detected that you have triggered a build from source code with version 898dd95ff261fc77ac4dcd00edd162d7b7c054f2
remote:  ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch.
remote:  !
remote:  ! If you are developing on a branch and deploying via git you must run:
remote:  !
remote:  !     git push heroku <branchname>:main
remote:  !
remote:  ! This article goes into details on the behavior:
remote:  !   https://devcenter.heroku.com/articles/duplicate-build-version
remote:
remote: Verifying deploy...
remote:
remote: !       Push rejected to portfolio-project10.
remote:
To https://git.heroku.com/portfolio-project10.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/portfolio-project10.git'

C:...\portfolio-project>

It would be very nice if anyone could help me with this, or even recommending an other way to deploy django projects for free

Body:
That entire traceback is inside these parentheses: () is not available for this stack. That is the message shown when you request a Python runtime that isn't available. In this case, it looks like your runtime.txt can't even be read due to an unexpected encoding.

Delete it, then create a new file containing something like

python-3.10.2

only. Make sure it is UTF-8 encoded, commit, and redeploy.

At the moment, these are the currently supported Python versions, but the list changes as new versions are released:

python-3.10.2

python-3.9.10

python-3.8.12

python-3.7.12


问:
MySQL matching 2 out of 5 fields
In MySQL I'm trying to select any row that matches at least 2 fields of the provided data

Eg. I have been given firstName, lastName, dob, website, email and I want any rows that match firstName and lastName, or firstName and email, or website and email etc.

I know I could write a very long winded statement along the lines of
(this=this AND this=this) OR (this=this etc
but this query could potentially get really large, especially if we decide we want to match on more than 5 fields.

We will also need to rank the matching rows, so if some rows match 3 instead of only the minimum 2 fields then they should show up higher in the returned results.

I could process this afterwards with PHP, or do multiple SQL queries, I'm just wondering if anyone knows an easier/cleaner way to match this data?

I appreciate any help!
Jo

答:
As a'r's answer recommended, you can add together values. If you want to use this for ranking, you might not include it in the where clause as he did.

```<code>SELECT *, ((firstName = @inputFirst) + (lastName = @inputLast) + (dob = @inputDob) + (website = @inputWebsite) + (email = @inputEmail)) as Matches
FROM mytable
HAVING Matches > 1
ORDER BY Matches DESC
</code>```

I don't have access to a mysql db to test this syntax at the moment, but I believe it should work properly.

Title: MySQL matching 2 out of 5 fields

Body:
As a'r's answer recommended, you can add together values. If you want to use this for ranking, you might not include it in the where clause as he did.

SELECT *, ((firstName = @inputFirst) + (lastName = @inputLast) + (dob = @inputDob) + (website = @inputWebsite) + (email = @inputEmail)) as Matches
FROM mytable
HAVING Matches > 1
ORDER BY Matches DESC

I don't have access to a mysql db to test this syntax at the moment, but I believe it should work properly.


问:
How do i make my button link to the next page without changing the styling?
How do i make my button link to the next page without changing the styling?</p>

```<code>  <div class="image-round-fit">

    <img src="images/pic.jpg" alt="photo" width="300px" height="300px" />

    <span class="caption">Hello World</span></br>

      <a href="#" class="btn btn-info role=button">Click Next</a>

  </div>
</code>```

答:
Firstly, you have role=button inside your class. It should be outside your class as an attribute :

```<code><a href="#" class="btn btn-info" role="button">Click Next</a>
</code>```

This is for assistive technologies and button element should be used instead when possible.

Body:
How do i make my button link to the next page without changing the styling?

    Hello World

      Click Next

Body:
Firstly, you have role=button inside your class. It should be outside your class as an attribute :

<a href="#" class="btn btn-info" role="button">Click Next</a>

This is for assistive technologies and button element should be used instead when possible.


问:
Databricks throwing error: truncating data
Whenever I try to save a specific DataFrame on the DW I get the message:

ERROR:  An error occurred while calling o692.save.
      : com.databricks.spark.sqldw.SqlDWSideException: SQL DW failed to execute the JDBC query produced by the connector.
      Underlying SQLException(s):
        - com.microsoft.sqlserver.jdbc.SQLServerException: HdfsBridge::recordReaderFillBuffer - Unexpected error encountered
  filling record reader buffer: HadoopSqlException: String or binary
  data would be truncated. [ErrorCode = 107090] [SQLState = S0001]

I've checked the size of the strings in my csv file. The bigger one has 38 chars.

This is my save/write method (worked for other DataFrames):

```<code>df.write\
 .format('com.databricks.spark.sqldw') \
 .option('url', conn_string_dw) \
 .option('maxStrLength', '4000') \
 .option('forwardSparkAzureStorageCredentials', 'true') \
 .option('dbTable', db_table_name) \
 .option('tempDir', dw_temporary_path_url) \
 .option('truncate', 'False')\
 .mode('append')\
 .save()
</code>```

What could be happening here?

答:
Same error using Databricks to send tables to Synapse. Suspected that one or more of my string cols in my spark Df had exceeded the 256 NVARCHAR default length.

Ran this on my databricks df to get the max length for every string column.

```<code>import pandas as pd
df = df.toPandas()
dict([(v, df[v].apply(lambda r: len(str(r)) if r!=None else 0).max())for v in df.columns.values])
</code>```

Found my culprit. Had a col with a max len of 416.

Changed my df.write procedure for Synapse to include maxStrLength as you have shown

Body:
Whenever I try to save a specific DataFrame on the DW I get the message:

ERROR:  An error occurred while calling o692.save.
      : com.databricks.spark.sqldw.SqlDWSideException: SQL DW failed to execute the JDBC query produced by the connector.
      Underlying SQLException(s):
        - com.microsoft.sqlserver.jdbc.SQLServerException: HdfsBridge::recordReaderFillBuffer - Unexpected error encountered
  filling record reader buffer: HadoopSqlException: String or binary
  data would be truncated. [ErrorCode = 107090] [SQLState = S0001]

I've checked the size of the strings in my csv file. The bigger one has 38 chars.

This is my save/write method (worked for other DataFrames):

df.write\
 .format('com.databricks.spark.sqldw') \
 .option('url', conn_string_dw) \
 .option('maxStrLength', '4000') \
 .option('forwardSparkAzureStorageCredentials', 'true') \
 .option('dbTable', db_table_name) \
 .option('tempDir', dw_temporary_path_url) \
 .option('truncate', 'False')\
 .mode('append')\
 .save()

What could be happening here?

Body:
Same error using Databricks to send tables to Synapse. Suspected that one or more of my string cols in my spark Df had exceeded the 256 NVARCHAR default length.

Ran this on my databricks df to get the max length for every string column.

import pandas as pd
df = df.toPandas()
dict([(v, df[v].apply(lambda r: len(str(r)) if r!=None else 0).max())for v in df.columns.values])

Found my culprit. Had a col with a max len of 416.

Changed my df.write procedure for Synapse to include maxStrLength as you have shown


问:
how to restore a collection or collections in mongodb from an archive file?
I have created a dump in an archive file by the following command :

```<code>mongodump --archive=newcollection.1.archive --db neel --collection newcollection
</code>```

While restoring with the mongorestore i am getting an error :the --db and --collection args should only be used when restoring from a BSON file.

I got the syntax from [https://docs.mongodb.com/manual/reference/program/mongorestore/#examples][1] .

I fired the following command :

```<code>mongorestore --archive=newcollection.1.archive  --db backup2.
</code>```

答:
```<code>mongorestore  --archive=<filename>.archive
</code>```

Body:
I have created a dump in an archive file by the following command :

mongodump --archive=newcollection.1.archive --db neel --collection newcollection

While restoring with the mongorestore i am getting an error :the --db and --collection args should only be used when restoring from a BSON file.

I got the syntax from [https://docs.mongodb.com/manual/reference/program/mongorestore/#examples][1] .

I fired the following command :

mongorestore --archive=newcollection.1.archive  --db backup2.


问:
How to use custom data base dialect in spring data?
I need to avoid some bug in db2 dialect in hibernate.
I use spring data + gradle (several modules) + kotlin
I  created my custom dialect

```<code>DB2zOSDialect : DB2Dialect()
</code>```

And try to add it to application.properties

```<code>spring:
  jpa:
    properties:
      hibernate:
        dialect: com.my.config.DB2zOSDialect
</code>```

But spring data continuous using DB2Dialect

I tried the same code but using java + maven + the same spring data and it's works.

So, i have no ideas why my custom dialect isn't being use by spring data.

Are there ways how to add dialect to spring data?

答:
public class CustomDialectResolver implements DialectResolver {
    private static final Map<String, Class<? extends Dialect>> DIALECT_BY_NAME = new HashMap<>();

    static {
        DIALECT_BY_NAME.put("Oracle", Oracle10gDialect.class);
        DIALECT_BY_NAME.put("PostgreSQL", PostgreSQL10Dialect.class);
        DIALECT_BY_NAME.put("HSQL Database Engine", HSQLDialect.class);
        DIALECT_BY_NAME.put("H2", H2Dialect.class);
    }

    @Override
    public Dialect resolveDialect(DialectResolutionInfo dialectResolutionInfo) {
        final String name = dialectResolutionInfo.getDatabaseName();
        return lookupDialect(name);
    }

    private Dialect lookupDialect(String databaseName) {
        Class<? extends Dialect> dialectClass = DIALECT_BY_NAME.get(databaseName);
        if (dialectClass == null) {
            log.warn("Could not find dialect for database name {}", databaseName);
            return null;
        }
        try {
            return dialectClass.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            log.error("Error while init dialect for database name {} - {}", databaseName, e.getLocalizedMessage());
            return null;
        }
    }
}
```
<p>and next</p>
```spring.jpa.properties.hibernate.dialect_resolvers=CustomDialectResolver
```

Body:
I need to avoid some bug in db2 dialect in hibernate.
I use spring data + gradle (several modules) + kotlin
I  created my custom dialect

DB2zOSDialect : DB2Dialect()

And try to add it to application.properties

spring:
  jpa:
    properties:
      hibernate:
        dialect: com.my.config.DB2zOSDialect

But spring data continuous using DB2Dialect

I tried the same code but using java + maven + the same spring data and it's works.

So, i have no ideas why my custom dialect isn't being use by spring data.

Are there ways how to add dialect to spring data?

Body:
public class CustomDialectResolver implements DialectResolver {
    private static final Map<String, Class<? extends Dialect>> DIALECT_BY_NAME = new HashMap<>();

    static {
        DIALECT_BY_NAME.put("Oracle", Oracle10gDialect.class);
        DIALECT_BY_NAME.put("PostgreSQL", PostgreSQL10Dialect.class);
        DIALECT_BY_NAME.put("HSQL Database Engine", HSQLDialect.class);
        DIALECT_BY_NAME.put("H2", H2Dialect.class);
    }

    @Override
    public Dialect resolveDialect(DialectResolutionInfo dialectResolutionInfo) {
        final String name = dialectResolutionInfo.getDatabaseName();
        return lookupDialect(name);
    }

    private Dialect lookupDialect(String databaseName) {
        Class<? extends Dialect> dialectClass = DIALECT_BY_NAME.get(databaseName);
        if (dialectClass == null) {
            log.warn("Could not find dialect for database name {}", databaseName);
            return null;
        }
        try {
            return dialectClass.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            log.error("Error while init dialect for database name {} - {}", databaseName, e.getLocalizedMessage());
            return null;
        }
    }
}

and next

spring.jpa.properties.hibernate.dialect_resolvers=CustomDialectResolver


问:
Generate Random numbers in array, add them together and store the answers in array
I am new to Java and trying to solve the problem below

So this is my story:
Program generates 20 numbers up to 100 and stores every number in array. Once generated the program has to add two numbers and stores the answer in array.. Example

```<code>randomNumber[0]+randomNumber[1]=answer[0]
randomNumber[2]+randomNumber[3]=answer[1]
randomNumber[4]+randomNumber[5]=answer[2]
</code>```

etc..

Once done I check user input with answers and count the correct answers.

The problem is: I can't figure out how to add two numbers together and store it in Array. It seems easy but I am not experienced enough :)

Currently I am stuck here, I would really appreciate if someone could explain or help me how to solve this problem.

```<code>public class gNumber {
    private final int[] num = new int[20]; // array of randomly generated numbers
    private int[] answers; // array of correct answers and UserAnswers
    private final int[] userAnswers = new int[10];
    private int numOfCorrect = 0;

    // Accessor to get the randomly generated number
    int getNumbers(final int n) {
        return num[n];
    }

    int numOfCorrectAnswers() {
        return numOfCorrect;
    }

    // Mutator to store store user input
    void setUsrAnswers(final int _index, final int answer) {
        userAnswers[_index] = answer;
    }

    // Method to generate random 20 numbers
    public void RandomN() {

        for (int i = 0; i < num.length; i++) {
            final int randomNum = (int) (Math.random() * 100);
            num[i] = randomNum;
            final int a = num[i];
            // int b =num[i];
            answers[i] = a + a;
            System.out.println(i + ")" + num[i] + answers[i]);
        }

    }

    // method to add two numbers and store in in answers array
    public void add(int arg1, int arg2) {
        int b = 0;
        while (b < 10) {
            arg1 = num[b];
            arg2 = num[b + 1];
            answers[b] = arg1 + arg2;

            System.out.println(answers[b]);
            b = b + 1;
        }
    }

    // method to check user answers
    public void usrInput(final int usrAnwer) {
        for (final int num : answers) {
            if (num == usrAnwer) {
                numOfCorrect++;
            }
        }

    }
}
</code>```

答:
A solution quite simply:

```<code>int N = 20; //20 Random numbers
int[] randomNumber = new int[N];
int[] answer = new int[N/2];

//Generate random numbers of size N
for (int i = 0; i < N; i++) {
    randomNumber = generateRandom(0, 100);
}

//populate answers
for (int i = 0; i < answer.length; i++) {
    answer[i] = randomNumber[i*2] + randomNumber[i*2 + 1];
}

//Generate a random number from [min, max]
private int generateRandom(int min, int max) {
    return min + (int)(Math.random() * ((max - min) + 1));
}
</code>```

The explanations are on the comments. :-)

Body:
I am new to Java and trying to solve the problem below

So this is my story:
Program generates 20 numbers up to 100 and stores every number in array. Once generated the program has to add two numbers and stores the answer in array.. Example

randomNumber[0]+randomNumber[1]=answer[0]
randomNumber[2]+randomNumber[3]=answer[1]
randomNumber[4]+randomNumber[5]=answer[2]

etc..

Once done I check user input with answers and count the correct answers.

The problem is: I can't figure out how to add two numbers together and store it in Array. It seems easy but I am not experienced enough :)

Currently I am stuck here, I would really appreciate if someone could explain or help me how to solve this problem.

public class gNumber {
    private final int[] num = new int[20]; // array of randomly generated numbers
    private int[] answers; // array of correct answers and UserAnswers
    private final int[] userAnswers = new int[10];
    private int numOfCorrect = 0;

    // Accessor to get the randomly generated number
    int getNumbers(final int n) {
        return num[n];
    }

    int numOfCorrectAnswers() {
        return numOfCorrect;
    }

    // Mutator to store store user input
    void setUsrAnswers(final int _index, final int answer) {
        userAnswers[_index] = answer;
    }

    // Method to generate random 20 numbers
    public void RandomN() {

        for (int i = 0; i < num.length; i++) {
            final int randomNum = (int) (Math.random() * 100);
            num[i] = randomNum;
            final int a = num[i];
            // int b =num[i];
            answers[i] = a + a;
            System.out.println(i + ")" + num[i] + answers[i]);
        }

    }

    // method to add two numbers and store in in answers array
    public void add(int arg1, int arg2) {
        int b = 0;
        while (b < 10) {
            arg1 = num[b];
            arg2 = num[b + 1];
            answers[b] = arg1 + arg2;

            System.out.println(answers[b]);
            b = b + 1;
        }
    }

    // method to check user answers
    public void usrInput(final int usrAnwer) {
        for (final int num : answers) {
            if (num == usrAnwer) {
                numOfCorrect++;
            }
        }

    }
}

Body:
A solution quite simply:

int N = 20; //20 Random numbers
int[] randomNumber = new int[N];
int[] answer = new int[N/2];

//Generate random numbers of size N
for (int i = 0; i < N; i++) {
    randomNumber = generateRandom(0, 100);
}

//populate answers
for (int i = 0; i < answer.length; i++) {
    answer[i] = randomNumber[i*2] + randomNumber[i*2 + 1];
}

//Generate a random number from [min, max]
private int generateRandom(int min, int max) {
    return min + (int)(Math.random() * ((max - min) + 1));
}

The explanations are on the comments. :-)


问:
How to use NavigationLink for List view swipe action
I'm wondering how to place NavigationLink into swipeActions section in code below. Code itself is compiled without any issue but when I tap "Edit" link nothing happens. My intention is to show another view by tapping "Edit".
Thanks</p>
```<code>var body: some View {
    List {
        ForEach(processes, id: \.id) { process in
            NavigationLink(process.name!, destination: MeasurementsView(procID: process.id!, procName: process.name!))
                .swipeActions() {
                    Button("Delete") {
                        deleteProcess = true
                    }.tint(.red)
                    NavigationLink("Edit", destination: ProcessView(procID: process.id!, procName: process.name!)).tint(.blue)
                }
        }
    }
}
</code>```

答:
It does not work because swipeActions context is out of NavigationView. Instead we can use same NavigationLink for conditional navigation, depending on action.

Here is a simplified demo of possible approach - make destination conditional and use programmatic activation of link.

Tested with Xcode 13.2 / iOS 15.2

```<code>struct ContentView: View {
    var body: some View {
        NavigationView {
            List {
                ForEach(0..<2, id: \.id) {
                    // separate into standalone view for better
                    // state management
                    ProcessRowView(process: $0)
                }
            }
        }
    }
}

struct ProcessRowView: View {
    enum Action {
        case view
        case edit
    }
    @State private var isActive = false
    @State private var action: Action?
    let process: Int

    var body: some View {
        // by default navigate as-is
        NavigationLink("Item: \(process)", destination: destination, isActive: $isActive)
            .swipeActions() {
                Button("Delete") {

                }.tint(.red)
                Button("Edit") {
                    action = .edit    // specific action
                    isActive = true   // activate link programmatically
                }.tint(.blue)
            }
            .onChange(of: isActive) {
                if !$0 {
                    action = nil  // reset back
                }
            }
    }

    @ViewBuilder
    private var destination: some View {
        // construct destination depending on action
        if case .edit = action {
            Text("ProcessView")
        } else {
            // just to demo different type destinations
            Color.yellow.overlay(Text("MeasurementsView"))
        }
    }
}
</code>```

Body:
I'm wondering how to place NavigationLink into swipeActions section in code below. Code itself is compiled without any issue but when I tap "Edit" link nothing happens. My intention is to show another view by tapping "Edit".
Thanks

var body: some View {
    List {
        ForEach(processes, id: \.id) { process in
            NavigationLink(process.name!, destination: MeasurementsView(procID: process.id!, procName: process.name!))
                .swipeActions() {
                    Button("Delete") {
                        deleteProcess = true
                    }.tint(.red)
                    NavigationLink("Edit", destination: ProcessView(procID: process.id!, procName: process.name!)).tint(.blue)
                }
        }
    }
}

Body:
It does not work because swipeActions context is out of NavigationView. Instead we can use same NavigationLink for conditional navigation, depending on action.

Here is a simplified demo of possible approach - make destination conditional and use programmatic activation of link.

Tested with Xcode 13.2 / iOS 15.2

struct ContentView: View {
    var body: some View {
        NavigationView {
            List {
                ForEach(0..<2, id: \.id) {
                    // separate into standalone view for better
                    // state management
                    ProcessRowView(process: $0)
                }
            }
        }
    }
}

struct ProcessRowView: View {
    enum Action {
        case view
        case edit
    }
    @State private var isActive = false
    @State private var action: Action?
    let process: Int

    var body: some View {
        // by default navigate as-is
        NavigationLink("Item: \(process)", destination: destination, isActive: $isActive)
            .swipeActions() {
                Button("Delete") {

                }.tint(.red)
                Button("Edit") {
                    action = .edit    // specific action
                    isActive = true   // activate link programmatically
                }.tint(.blue)
            }
            .onChange(of: isActive) {
                if !$0 {
                    action = nil  // reset back
                }
            }
    }

    @ViewBuilder
    private var destination: some View {
        // construct destination depending on action
        if case .edit = action {
            Text("ProcessView")
        } else {
            // just to demo different type destinations
            Color.yellow.overlay(Text("MeasurementsView"))
        }
    }
}


问:
How to display even Fibonacci numbers by specifying their number?
I have a function that checks Fibonacci numbers for even.

```<code>def fibonacci(num=4):
    fib1 = fib2 = 1
    print(0, end=' ')
    for i in range(1, num):
        fib1, fib2 = fib2, fib1 + fib2
        if (fib2 % 2) == 0:
            print(fib2, end=' ')

fibonacci()
</code>```

I need it to output a specified number of even numbers

Example input: 4

Example output: 0 2 8 34

答:
Use while loop instead.

```<code>def fibonacci(count=4):
    fib1 = fib2 = 1
    i = 1
    print(0, end=' ')
    while i < count:
        fib1, fib2 = fib2, fib1 + fib2
        if (fib2 % 2) == 0:
            print(fib2, end=' ')
            i +=1

fibonacci()
</code>```

Output:
0 2 8 34

Body:
I have a function that checks Fibonacci numbers for even.

def fibonacci(num=4):
    fib1 = fib2 = 1
    print(0, end=' ')
    for i in range(1, num):
        fib1, fib2 = fib2, fib1 + fib2
        if (fib2 % 2) == 0:
            print(fib2, end=' ')

fibonacci()

I need it to output a specified number of even numbers

Example input: 4

Example output: 0 2 8 34

Body:
Use while loop instead.

def fibonacci(count=4):
    fib1 = fib2 = 1
    i = 1
    print(0, end=' ')
    while i < count:
        fib1, fib2 = fib2, fib1 + fib2
        if (fib2 % 2) == 0:
            print(fib2, end=' ')
            i +=1

fibonacci()

Output:
0 2 8 34


问:
Prevalence meta-analysis with metafor - percentages instead of proportions
I'm running a meta-analysis of prevalence rates using the metafor package.
The dataset is named 'metaAAS' and it has the study's author/year, the number of participants exposed to the condition (ni) and the number of those presenting the symptom (nphy).

I'm using the following code to call the dataset from a csv file:

metaAAS <- read.csv("metaAAS.csv")
dat <- get(metaAAS)

Then I'm using the function 'escalc' to calculate effect sizes and outcome measures. I am using the argument 'PR' because the studies measure a dichotomous variable (either participants present the symptom or not):

metaAAS <- escalc(measure="PR", xi=nphy, ni=ni, data=metaAAS, slab=paste (authors, year))

And this code to run the meta-analysis and show the results:

res <- rma(yi, vi, data=metaAAS)
res
confint(res)

My model results show this:

estimate: 0.3497

se: 0.0352

zval:9.9428

pval:<.0001

ci.lb: 0.2807

ci.ub:0.4186

How can I change the results to percentages (e.g. 34.97) instead of proportions (0.3497)?
It would be easy just to change this in the description of the results, but the whole Forest Plot shows the estimated prevalence as proportions, and I need them as percentages.

Any thoughts? Thanks!

答:
I didn't manage to change the 'model results' output, but I changed the Forest Plot, which was the main goal.

First, create a function to multiply numbers *100:

mytransf<-function(x)

(x)*100

Then add this function to the forest plot arguments:

forest (res, ylim=c(-1,28),transf=mytransf)


问:
How to generate gdb symbol file with nasm?
I'm working on a toy bootloader/kernel written in assembly and run on the qemu emulator. I can run qemu with -s -S option and debug with gdb using remote target, but I don't have any debug symbols loaded with gdb. How can I generate a symbol file from my assembly?

I'm using nasm to generate a binary image for qemu to run from my assembly file, but I haven't found anyway to include debug information in the image itself (I'm not sure if that even makes sense). I also found that gdb allows you to load an separate symbol file for debugging, so now my issue is how to generate a symbol file from my assembly code.

I've seen suggestions to use objcopy, but I believe that only works on elf files, not binary. I've tried getting nasm to generate an elf, but it keeps barfing because of my (necessary) org directive in the assembly file.

答:
```<code>$  nasm -g -f elf64 -l 2.lst  2.asm
$  gcc -m64 -o 2.exe  2.o
</code>```


问:
repeater-type control for asp.net mvc 3
is there any sort of control for .net mvc 3 (some html helper method perhaps) that works like an asp:repeater?

I've done some googling and only found some home grown solutions.

Here's what I need:
My users will have a drop down list of numbers, depending what they select (1-8), I need to repeat a set of code below to offer them the same list of input fields (between 1 and 8 times).

what would be the best way to accomplish this with mvc 3 and jquery?

答: Put all 8 input fields on the page, and use jQuery to show/hide the fields based on the selected number in the select box.</p>

Title: repeater-type control for asp.net mvc 3


问:
Consistent display of UTF8 emojis across browsers
I have a text-only comment textbox (users can submit comments), and UTF8 emojis are accepted, such as "Hello ".

This is finally displayed in a
, that already uses a Google Font (Barlow Semi Condensed).

How to make that the rendering of this emoji is consistent across the different browsers?

For example,  (codepoint U+1F602) does not appear in color in Chrome for Windows (at least on certain versions), but only in black and white, whereas, it appears in yellow and blue colors in Firefox.

I thought that using font-awesome would allow this, but instead font-awesome requires that we use  instead which is not possible since users will submit ordinary text, containg UTF8 emojis.

答:
This is impossible for various reasons:

Windows officially supports multi colored fonts since 8.1. If a browser uses the font rendering of the system then results will differ by the operating system and its version already.

Gecko engines (e.g. Firefox) and Goanna engines (e.g. Pale Moon) come with their own font(s) (which you can delete) and on top render that font themselves, instead of relying to the system. As a result even under Windows 7 the browsers render colored Emojis although the operating system itself is unable to do that.

The default font and/or the default font for Emojis may differ as per personal settings, either in the scope of the operating system (user settings) and/or in the scope of an installation (program settings). Settings can be modified - not everybody uses the factory setting of Times New Roman as default font for websites in an internet browser. Likewise the default for displaying Emojis can be different if you leave it undefined (as per CSS).

It's as impossible as expecting a user to have installed the fonts of interest and also in the minimal version of interest: having Tahoma is one question, but having version 5.22 or 7.00 of it is yet another.