问:
Wordpress Insert post create tne meta key and meta value
I am creating wp_insert_post to create post from json, while creating post i need to create meta values i have tried both add_post_meta and update_post_meta no results Can anybody help

foreach ( $response->data as $single_data ) {

```<code>$post_title    = $single_data->name;
$video_id = $single_data->uri;
$thumnbnail_url = $single_data->pictures->sizes[4]->link;

if (!post_exists($post_title)) { // Determine if a post exists based on title, content, and date
    $post_id = wp_insert_post(array(
        'post_type'  => 'vimeo_videos',
        'post_title' => $post_title,
        'post_status' => 'publish',
     ));

}
$newPostID = wp_insert_post($post_id);

global $post;

add_post_meta( $post->ID, 'vimeo_video_thumnbnail_url_key', $thumnbnail_url, true );
update_post_meta( $newPostID, 'video_url_id', $video_id );
</code>```

答:
For insert new post used this syntax:

add_post_meta( int $post_id, string $meta_key, mixed $meta_value, bool $unique = false )

Body:
I am creating wp_insert_post to create post from json, while creating post i need to create meta values i have tried both add_post_meta and update_post_meta no results Can anybody help

foreach ( $response->data as $single_data ) {

$post_title    = $single_data->name;
$video_id = $single_data->uri;
$thumnbnail_url = $single_data->pictures->sizes[4]->link;

if (!post_exists($post_title)) { // Determine if a post exists based on title, content, and date
    $post_id = wp_insert_post(array(
        'post_type'  => 'vimeo_videos',
        'post_title' => $post_title,
        'post_status' => 'publish',
     ));

}
$newPostID = wp_insert_post($post_id);

global $post;

add_post_meta( $post->ID, 'vimeo_video_thumnbnail_url_key', $thumnbnail_url, true );
update_post_meta( $newPostID, 'video_url_id', $video_id );


来源: stackexchange

问:
Snippet to get prime numbers
I am trying to get prime numbers with the following script

I am getting errors while executing it

```<code>class PrimeClass(Object):
    def __init__(self, number):
        self.givenNumber= number
        self.outputPrimeNumbers=[]

    def getPrimeNumbers(self):
        primes =[]
        for possiblePrime in range(2,self.givenNumber + 1):
            isPrime =True
        for num in range(2, possiblePrime):
            if possiblePrime % num == 0:
                isPrime =False
            if isPrime:
                primes.append(possiblePrime)
        self.outputPrimeNumbers=primes
        return(primes)

@property
def getOutputPrimeNumbers(self):
    return self.getOutputPrimeNumbers

primeClass=PrimeClass(123)
print(primeClass.getOutputPrimeNumbers)
</code>```

答:
Python is very strict about indentation. And the way your example is formatted it won't ever work.

But with my Python 2.7, the following worked:

```<code>class PrimeClass:
    def __init__(self, number):
        self.givenNumber= number
        self.outputPrimeNumbers=[]

    def getPrimeNumbers(self):
        primes =[]
        for possiblePrime in range(2,self.givenNumber + 1):
            isPrime =True
            for num in range(2, possiblePrime):
                if possiblePrime % num == 0:
                    isPrime =False
            if isPrime:
                primes.append(possiblePrime)
        self.outputPrimeNumbers=primes
        return(primes)

    @property
    def getOutputPrimeNumbers(self):
        return self.getOutputPrimeNumbers

primeClass=PrimeClass(123)
print(primeClass.getPrimeNumbers())
</code>```

It outputs the following list:

```<code>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Snippet to get prime numbers

Body:
I am trying to get prime numbers with the following script

I am getting errors while executing it

class PrimeClass(Object):
    def __init__(self, number):
        self.givenNumber= number
        self.outputPrimeNumbers=[]

    def getPrimeNumbers(self):
        primes =[]
        for possiblePrime in range(2,self.givenNumber + 1):
            isPrime =True
        for num in range(2, possiblePrime):
            if possiblePrime % num == 0:
                isPrime =False
            if isPrime:
                primes.append(possiblePrime)
        self.outputPrimeNumbers=primes
        return(primes)

@property
def getOutputPrimeNumbers(self):
    return self.getOutputPrimeNumbers

primeClass=PrimeClass(123)
print(primeClass.getOutputPrimeNumbers)

Body:
Python is very strict about indentation. And the way your example is formatted it won't ever work.

But with my Python 2.7, the following worked:

class PrimeClass:
    def __init__(self, number):
        self.givenNumber= number
        self.outputPrimeNumbers=[]

    def getPrimeNumbers(self):
        primes =[]
        for possiblePrime in range(2,self.givenNumber + 1):
            isPrime =True
            for num in range(2, possiblePrime):
                if possiblePrime % num == 0:
                    isPrime =False
            if isPrime:
                primes.append(possiblePrime)
        self.outputPrimeNumbers=primes
        return(primes)

    @property
    def getOutputPrimeNumbers(self):
        return self.getOutputPrimeNumbers

primeClass=PrimeClass(123)
print(primeClass.getPrimeNumbers())

It outputs the following list:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113]


问:
How to delete a line from the file with php?
I have a file named $dir and  a string named $line, I know that this string is a complete line of that file but I don't know its line number and I want to remove it from file, what should I do?

Is it possible to use awk?

答:
Convert text to array, remove first line and reconvert to text</p>

```<code>$line=explode("\r\n",$text);
unset($line[0]);
$text=implode("\r\n",$line);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Convert text to array, remove first line and reconvert to text

$line=explode("\r\n",$text);
unset($line[0]);
$text=implode("\r\n",$line);


问:
How to give word wrap break word property to a datatable column
```<code><table id="user">
    <thead>
    <tr class="theader">
    <th>Order Id</th>
    <th>Message</th>
    <th>Date Created</th>

    </tr>
    </thead>
    <tbody>
    </tbody>
</table>

<script>
$("#user").dataTable({
    "bFilter": false,
    "bAutoWidth": false,
    "bProcessing" : false,
    "bServerSide" : true,
    "sAjaxSource" : "./getOrderDetails.cpm"
});
</script>
</code>```

Hi friends, here is my data-table. I want to implement word-wrap break word property to the message column so that long messages with out space will break. Can you please tell me how I should implement the word-wrap break word property to a column in the data-table.

答:
add inline css like this or internal css for it.

style="white-space: normal;word-wrap: break-word;word-break:
  normal;width:auto"

```<code><tr>
<td class="" style="white-space: normal;word-wrap: break-word;word-break: normal;width:auto"> {{$template->names}}
</td>
<tr>
</code>```

Body:
    Order Id
    Message
    Date Created

Hi friends, here is my data-table. I want to implement word-wrap break word property to the message column so that long messages with out space will break. Can you please tell me how I should implement the word-wrap break word property to a column in the data-table.

Body:
add inline css like this or internal css for it.

style="white-space: normal;word-wrap: break-word;word-break:
  normal;width:auto"

<tr>
<td class="" style="white-space: normal;word-wrap: break-word;word-break: normal;width:auto"> {{$template->names}}
</td>
<tr>


问:
Just installed Lazarus and my hello world doesn't show when I run project (ubuntu)
This is what I've done so far:
Clicked on File > New > Project > Program

And this is the program:

```<code>program project1;
begin
writeln('hello');
readln;
end.
</code>```

It compiles ok, I click on Run but it does nothing. It's like it's running but nothing shows up.

If I go to the folder where the program is saved there's an executable that works if I execute it from a terminal. Is that what im supposed to do everytime I want to run a program?

答:
It's easy to get tripped up by this, especially if you're used to running Windows.  The program below works fine for me on Ubuntu 14.04, but note the embedded comment.</p>

```<code>program consoleapp;

{$APPTYPE CONSOLE}

begin
  //  To see output use View > Debug Windows > Terminal Output
  writeln('hello world');
  readln;
end.
</code>```

Body:
This is what I've done so far:
Clicked on File > New > Project > Program

And this is the program:

program project1;
begin
writeln('hello');
readln;
end.

It compiles ok, I click on Run but it does nothing. It's like it's running but nothing shows up.

If I go to the folder where the program is saved there's an executable that works if I execute it from a terminal. Is that what im supposed to do everytime I want to run a program?

Body:
It's easy to get tripped up by this, especially if you're used to running Windows.  The program below works fine for me on Ubuntu 14.04, but note the embedded comment.

program consoleapp;

{$APPTYPE CONSOLE}

begin
  //  To see output use View > Debug Windows > Terminal Output
  writeln('hello world');
  readln;
end.


问:
python dataframe merge columns according to other column values
What I want to do is merge columns according to values in another column
It is better illustrated with a simple example:
I have a dataframe with 5 columns:

```<code>| player_num    | team_1.x  | team_1.y  | team_2.x  | team_2.y  |
|------------   |---------- |---------- |---------- |---------- |
| 1             | x_1       | y_1       | x_2       | y_2       |
| 4             | x_3       | y_3       | x_4       | y_4       |
| 8             | x_5       | y_5       | x_6       | y_6       |
</code>```

I want to get the following table:

```<code>| x     | y     |
|-----  |-----  |
| x_1   | y_1   |
| x_3   | y_3   |
| x_6   | y_6   |
</code>```

where the columns are filled with values from team_1.x and team_1.y for rows of players with number less than 5 and values from team_2.x and team_2.y for rows of players with number bigger than 5

答:
You can segregate the dataframe based on the conditions followed by concatenating the results</p>

```<code>l = df.loc[df["player_num"].lt(5), ["team_1.x", "team_1.y"]].rename(columns={"team_1.x": "x", "team_1.y": "y"})
g = df.loc[df["player_num"].gt(5), ["team_2.x", "team_2.y"]].rename(columns={"team_2.x": "x", "team_2.y": "y"})
df_res = pd.concat([l, g])
print(df_res)
</code>```

Body:
What I want to do is merge columns according to values in another column
It is better illustrated with a simple example:
I have a dataframe with 5 columns:

| player_num    | team_1.x  | team_1.y  | team_2.x  | team_2.y  |
|------------   |---------- |---------- |---------- |---------- |
| 1             | x_1       | y_1       | x_2       | y_2       |
| 4             | x_3       | y_3       | x_4       | y_4       |
| 8             | x_5       | y_5       | x_6       | y_6       |

I want to get the following table:

| x     | y     |
|-----  |-----  |
| x_1   | y_1   |
| x_3   | y_3   |
| x_6   | y_6   |

where the columns are filled with values from team_1.x and team_1.y for rows of players with number less than 5 and values from team_2.x and team_2.y for rows of players with number bigger than 5

Body:
You can segregate the dataframe based on the conditions followed by concatenating the results

l = df.loc[df["player_num"].lt(5), ["team_1.x", "team_1.y"]].rename(columns={"team_1.x": "x", "team_1.y": "y"})
g = df.loc[df["player_num"].gt(5), ["team_2.x", "team_2.y"]].rename(columns={"team_2.x": "x", "team_2.y": "y"})
df_res = pd.concat([l, g])
print(df_res)


问:
how to select distinct values from 2 tables in sql
table1

```<code>id
1
2
3
4
5
</code>```

table2

```<code>id
4
5
6
7
8
</code>```

I want to result in this way:

```<code>id
1
2
3
6
7
8
</code>```

答:
try the following

select distinct id from (
    select id from table 1
    union
    select id from table 2
)
```

Body:
table1

id
1
2
3
4
5

table2

id
4
5
6
7
8

I want to result in this way:

id
1
2
3
6
7
8


问:
How do approach one to many association in sequelize?
I have a forumposts table with the following columns:
id (primary key), categoryId, headline, content.

I have another table, forumcategories, with the following columns:
id (primary key), name

The categoryid column in forumposts corresponds to the id column in forumcategories.

How do I associate the two tables?

答:
You can do like this

```<code> let ForumPost = sequelize.define('ForumPost', {/* ... */})
 let ForumCategory = sequelize.define('ForumCategory', {/* ... */})

 ForumCategory.hasMany(ForumPost, {as: 'forumposts'})
</code>```

OR

```<code>ForumCategory.hasMany( ForumPost, { as: 'forumposts' } );
ForumPosts.hasOne( ForumCategory );
</code>```

You may refer Sequelize Associations for further details.

Body:
You can do like this

 let ForumPost = sequelize.define('ForumPost', {/* ... */})
 let ForumCategory = sequelize.define('ForumCategory', {/* ... */})

 ForumCategory.hasMany(ForumPost, {as: 'forumposts'})

OR

ForumCategory.hasMany( ForumPost, { as: 'forumposts' } );
ForumPosts.hasOne( ForumCategory );

You may refer Sequelize Associations for further details.


答:
Your logic is correct, but you have made some indentation errors moreover you have never called getPrimeNumbers() in your program.
I've made few changes and improvements to your code.
Here is the correct code:

```<code>class PrimeClass(object):
    def __init__(self, number):
        self.givenNumber = number
        self.outputPrimeNumbers = []

    def getPrimeNumbers(self):
        for possiblePrime in range(2, self.givenNumber + 1):
            isPrime = True
            for num in range(2, possiblePrime):
                if possiblePrime % num == 0:
                    isPrime = False

            if isPrime:
                self.outputPrimeNumbers.append(possiblePrime)

    @property
    def getOutputPrimeNumbers(self):
        return self.outputPrimeNumbers

primeClass = PrimeClass(123)
primeClass.getPrimeNumbers() # call the get primes
print(primeClass.getOutputPrimeNumbers) # display the result
</code>```

And the Output will be:

```<code>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113]
</code>```

Hope it helps you!

Title: Snippet to get prime numbers

Body:
Your logic is correct, but you have made some indentation errors moreover you have never called getPrimeNumbers() in your program.
I've made few changes and improvements to your code.
Here is the correct code:

class PrimeClass(object):
    def __init__(self, number):
        self.givenNumber = number
        self.outputPrimeNumbers = []

    def getPrimeNumbers(self):
        for possiblePrime in range(2, self.givenNumber + 1):
            isPrime = True
            for num in range(2, possiblePrime):
                if possiblePrime % num == 0:
                    isPrime = False

            if isPrime:
                self.outputPrimeNumbers.append(possiblePrime)

    @property
    def getOutputPrimeNumbers(self):
        return self.outputPrimeNumbers

primeClass = PrimeClass(123)
primeClass.getPrimeNumbers() # call the get primes
print(primeClass.getOutputPrimeNumbers) # display the result

And the Output will be:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113]

Hope it helps you!


问:
Get number of ISO weeks in given year in C#
I'm trying to get the number of ISO weeks in given year/leap year. I saw that .Net Core 3.0 have ISOWeek.GetWeeksInYear class, but we're running .Net Core 2.2.1... and it's not possible to update at the moment...

I've tried this:

```<code>var cultInfo = CultureInfo.CurrentCulture;
var lastDayOfYear = new DateTime(2019, 12, 31);
var numberOfWeeks = cultInfo.Calendar.GetWeekOfYear(
                                    lastDayOfYear,
                                    cultInfo.DateTimeFormat.CalendarWeekRule,
                                    DayOfWeek.Monday);
</code>```

With 2019 it returns 53, it's not correct by the result I wanted (52). And if I change the date to 2020 it is 53, which is correct, but yeah, not by ISO which is what I want.

Thanks in advance.

答:
You can have a look at ISOWeek sources and implement this method by yourself (since you can't target .NET Core 3.x)

private const int WeeksInLongYear = 53;
private const int WeeksInShortYear = 52;

public static int GetWeeksInYear(int year)
{
    if (year < 1 || year > 9999)
    {
        throw new ArgumentOutOfRangeException(nameof(year));
    }

    static int P(int y) => (y + (y / 4) - (y / 100) + (y / 400)) % 7;

    if (P(year) == 4 || P(year - 1) == 3)
    {
        return WeeksInLongYear;
    }

    return WeeksInShortYear;
}
```

<p>Then use it</p>

<pre class="lang-cs prettyprint-override"><code>var weeks = GetWeeksInYear(2019); //returns 52
weeks = GetWeeksInYear(2020); //returns 53
</code>```

Please, keep in mind, that static local functions are supported starting from C# 8, so you should switch to this version or rewrite a code a little bit

Body:
I'm trying to get the number of ISO weeks in given year/leap year. I saw that .Net Core 3.0 have ISOWeek.GetWeeksInYear class, but we're running .Net Core 2.2.1... and it's not possible to update at the moment...

I've tried this:

var cultInfo = CultureInfo.CurrentCulture;
var lastDayOfYear = new DateTime(2019, 12, 31);
var numberOfWeeks = cultInfo.Calendar.GetWeekOfYear(
                                    lastDayOfYear,
                                    cultInfo.DateTimeFormat.CalendarWeekRule,
                                    DayOfWeek.Monday);

With 2019 it returns 53, it's not correct by the result I wanted (52). And if I change the date to 2020 it is 53, which is correct, but yeah, not by ISO which is what I want.

Thanks in advance.

Body:
You can have a look at ISOWeek sources and implement this method by yourself (since you can't target .NET Core 3.x)

private const int WeeksInLongYear = 53;
private const int WeeksInShortYear = 52;

public static int GetWeeksInYear(int year)
{
    if (year < 1 || year > 9999)
    {
        throw new ArgumentOutOfRangeException(nameof(year));
    }

    static int P(int y) => (y + (y / 4) - (y / 100) + (y / 400)) % 7;

    if (P(year) == 4 || P(year - 1) == 3)
    {
        return WeeksInLongYear;
    }

    return WeeksInShortYear;
}

Then use it

var weeks = GetWeeksInYear(2019); //returns 52
weeks = GetWeeksInYear(2020); //returns 53

Please, keep in mind, that static local functions are supported starting from C# 8, so you should switch to this version or rewrite a code a little bit


问:
How to throw HTTP error code with AWS Lambda using Lambda Proxy?
I created an AWS Lambda function using Python 3.8 with a Lambda Proxy API Gateway trigger:

It is indeed possible to return custom HTTP error codes:

def lambda_handler(event, context):
    return {
        'statusCode': 400,
        'body': json.dumps('This is a bad request!')
    }
```

<p>However, some online examples (e.g. 1, 2) simply raise an Exception to return the error with a custom message. If an Exception is thrown on the handler as below, the server return a 502 as the response is not in the expected format for Proxy Integration:</p>

<pre class="lang-py prettyprint-override"><code>def lambda_handler(event, context):
    raise Exception('This is an exception!')
</code>```

I think the examples rely on some Integration Response templates and do not use the Proxy Integration. Is it possible to achieve the same thing with Lambda Proxy? I'd like to avoid to globally catch exceptions in the Lambda handler to build custom error responses.

答: As far as I know, using the language built in Exceptions won't work because the API Gateway expects a precise response format, which is a JSON. What you can do is still raise the exception so it can be logged in CloudWatch, but then wrap it inside a JSON object so you can also return it to the client if is needed. I really think this should be possible out of the box, since with ECS services you can do this (I use some services in .NET Core and when an Exception occurs I get the appropriate status code as a response, without doing extra work)

Body:
I created an AWS Lambda function using Python 3.8 with a Lambda Proxy API Gateway trigger:

It is indeed possible to return custom HTTP error codes:

def lambda_handler(event, context):
    return {
        'statusCode': 400,
        'body': json.dumps('This is a bad request!')
    }

However, some online examples (e.g. 1, 2) simply raise an Exception to return the error with a custom message. If an Exception is thrown on the handler as below, the server return a 502 as the response is not in the expected format for Proxy Integration:

def lambda_handler(event, context):
    raise Exception('This is an exception!')

I think the examples rely on some Integration Response templates and do not use the Proxy Integration. Is it possible to achieve the same thing with Lambda Proxy? I'd like to avoid to globally catch exceptions in the Lambda handler to build custom error responses.


问:
How to use a variable UIStackView in UITableView or UICollectionView?
I'm currently building a generic form builder using a UICollectionView.

Each form element is a cell, and for checkboxes, I'm using a UIStackView inside the cell to display all the available options.

The problem is that each time I reuse the cell, even if I remove all the arrangedSubviews, they stay in the view with the new one.

The following code is a simplified version of what I'm doing:

```<code>class cell: UICollectionViewCell {

    @IBOutlet weak var stackView: UIStackView!

    func setup(options: [String]) {

        for option in options {
            let label = UILabel()
            label.text = option
            stackView.addArrangedSubview(label)
        }

    }

    override func prepareForReuse() {
        super.prepareForReuse()
        optionsStackView.arrangedSubviews.forEach({ optionsStackView.removeArrangedSubview(view: $0) })
    }

}
</code>```

Instead of that, my current workaround is to hide() each arrangedSubview in prepareForReuse() instead of removing them, but I don't like that.

答:
In many cases, since removing from a superview in a reusable view could (and mostly, will) cause the view to be released, in a UIStackView simply putting

```<code>dynamicView.isHidden = false
</code>```

to remove and

```<code>dynamicView.isHidden = true
</code>```

to add again, will cause the stack view to rearrange the other arranged views.

Body:
I'm currently building a generic form builder using a UICollectionView.

Each form element is a cell, and for checkboxes, I'm using a UIStackView inside the cell to display all the available options.

The problem is that each time I reuse the cell, even if I remove all the arrangedSubviews, they stay in the view with the new one.

The following code is a simplified version of what I'm doing:

class cell: UICollectionViewCell {

    @IBOutlet weak var stackView: UIStackView!

    func setup(options: [String]) {

        for option in options {
            let label = UILabel()
            label.text = option
            stackView.addArrangedSubview(label)
        }

    }

    override func prepareForReuse() {
        super.prepareForReuse()
        optionsStackView.arrangedSubviews.forEach({ optionsStackView.removeArrangedSubview(view: $0) })
    }

}

Instead of that, my current workaround is to hide() each arrangedSubview in prepareForReuse() instead of removing them, but I don't like that.

Body:
In many cases, since removing from a superview in a reusable view could (and mostly, will) cause the view to be released, in a UIStackView simply putting

dynamicView.isHidden = false

to remove and

dynamicView.isHidden = true

to add again, will cause the stack view to rearrange the other arranged views.


问:
How to create a single request when submit multiple forms using a common single submit button
I have a form which include 2 dropzone secrtions and a textboxes from and a single submti button on button submbit form submit but create three requests 2 dor dropzoen files and one form textboxes form but i need all this data in a single request. So how can we submti multiple form in a single request of array

Below is my JS Code

```<code> <script>
    Dropzone.autoDiscover = false;
    var file_after;
    var fileList = new Array;
    var i = 0;

    // Dropzone class:
    var myDropzone = new Dropzone("div#mydropzone", {

        {{--url: "{{route('dropzone-files')}}",--}}
        url: "{{route('case-submit')}}",
        acceptedFiles: '.stl',
        addRemoveLinks: true,
        autoProcessQueue: false,
        uploadMultiple: true,
        paramName: "file_before",
        params: {
            _token: "{{csrf_token()}}"
        },
    });

    var fileafterdropzone = new Dropzone("div#fileafterdropzone", {
        {{--url: "{{route('dropzone-files')}}",--}}
        url: "{{route('case-submit')}}",
        acceptedFiles: '.stl',
        addRemoveLinks: true,
        parallelUploads: 10,
        uploadMultiple: true,
        paramName: "file_after",
        autoProcessQueue: false,
        params: {
            _token: "{{csrf_token()}}"
        },
    });

</script>

  <script>
     $(document).ready(function (e) {
        // Submit form data via Ajax
        $("#case-form").on('submit', function (e) {

            fileafterdropzone.processQueue();
            myDropzone.processQueue();

            e.preventDefault();
            var formData = new FormData(this);

            $.ajax({
                type: 'POST',
                url: '{{route('case-submit')}}',
                // data: new FormData(this),
                dataType: 'json',
                data: formData,
                contentType: false,
                cache: false,
                processData: false,
                success: function (response) {

                    var files_before = Dropzone.forElement("div#mydropzone");
                    files_before.removeAllFiles();
                    var fiels_after = Dropzone.forElement("div#fileafterdropzone");
                    fiels_after.removeAllFiles();

                    $.notify("Case Registered Successfully", "success");

                },
                error: function (xhr, json, errorThrown) {

                    var response = JSON.parse(xhr.responseText);

                    $.each(response.errors, function (key, value) {

                        $("#" + key + "_error").text(value[0]);
                        var element = document.getElementById(key + "_error");
                        element.classList.add('fa', 'fa-times-circle-o');
                        $("#" + key + "_error").css("color", "red");

                        $.notify(" There might be a problem case not registered", "error");
                    });
                }
            });
        });
    });
</script>
</code>```

答:
Each dropzone has its own post request, denoted by the url attribute on the dropzone creation and will want to send a request for each file.

What I would suggest doing is creating a new method to store your files (eg. to a File model). You could then return the $file->id back to the front-end using the dropzone success callback and append those file ids to the form.

Then on submit the form will have all the file ids of the files so you can associate them on the backend.


问:
How to Sync data from SQL database field type(nvarchar) to Dynamics CRM field type (Lookup)
I am trying to sync data from an SQL Server to Dynamics CRM.

I had created a solution/project in C#. Where syncing an account entity of CRM, all the details like name, account number, ship date, phone number all this kind of detail are successfully syncing because form SQL, the data type is nvarchar or int and in CRM it is a single line of text.

But while I am doing the same sync from nvarchar to a lookup field of CRM it is not working and the exception occurs.

Here, the account is the name of the entity in CRM and SalesContact is name of the field from SQL and data type is nvarchar and ppg_salescontact is the name of the field in CRM and data type is lookup.

```<code>  Entity enAccount = new Entity("account");

 if (!String.IsNullOrEmpty(drRowAccount["SalesContact"] + "")) { enAccount["ppg_salescontact"] =
 SecurityElement.Escape(drRowAccount["SalesContact"].ToString().Trim()); }
</code>```

Exception :" Message : Error converting attribute value to Property:
  Attribute [ppg_salescontact], Attribute type [lookup] of Entity
  [account] with value of type [System.String]:
  [System.InvalidCastException: Unable to cast object of type
  'System.String' to type 'Microsoft.Xrm.Sdk.EntityReference'. "

Please suggest me what can I do for this.

答:
The exception you get says it all: You can't assign a value whose type is string to a field whose type is EntityReference.

So, to get an EntityReference based on that string, what you must do is take your string value, and based on this value, query the CRM to get the appropriate CRM record. Specifically, you need to query the CRM entity whose ppg_salescontact is the lookup for.

The result of this query would be of a type that derives from Entity, which you can then turn into EntityReference (by calling ToEntityReference()).

For example, if ppg_salescontact is a lookup for the CRM Contact entity, and if drRowAccount["SalesContact"] gives you the full name of the contact, then you can query it as follows (that's LINQ syntax):

```<code>Contact contact = orgContext
   .ContactSet
   .Where(c => c.FullName == drRowAccount["SalesContact"])
   .FirstOrDefault();
EntityReference contactRef = contact?.ToEntityReference();
</code>```

Body:
I am trying to sync data from an SQL Server to Dynamics CRM.

I had created a solution/project in C#. Where syncing an account entity of CRM, all the details like name, account number, ship date, phone number all this kind of detail are successfully syncing because form SQL, the data type is nvarchar or int and in CRM it is a single line of text.

But while I am doing the same sync from nvarchar to a lookup field of CRM it is not working and the exception occurs.

Here, the account is the name of the entity in CRM and SalesContact is name of the field from SQL and data type is nvarchar and ppg_salescontact is the name of the field in CRM and data type is lookup.

  Entity enAccount = new Entity("account");

 if (!String.IsNullOrEmpty(drRowAccount["SalesContact"] + "")) { enAccount["ppg_salescontact"] =
 SecurityElement.Escape(drRowAccount["SalesContact"].ToString().Trim()); }

Exception :" Message : Error converting attribute value to Property:
  Attribute [ppg_salescontact], Attribute type [lookup] of Entity
  [account] with value of type [System.String]:
  [System.InvalidCastException: Unable to cast object of type
  'System.String' to type 'Microsoft.Xrm.Sdk.EntityReference'. "

Please suggest me what can I do for this.

Body:
The exception you get says it all: You can't assign a value whose type is string to a field whose type is EntityReference.

So, to get an EntityReference based on that string, what you must do is take your string value, and based on this value, query the CRM to get the appropriate CRM record. Specifically, you need to query the CRM entity whose ppg_salescontact is the lookup for.

The result of this query would be of a type that derives from Entity, which you can then turn into EntityReference (by calling ToEntityReference()).

For example, if ppg_salescontact is a lookup for the CRM Contact entity, and if drRowAccount["SalesContact"] gives you the full name of the contact, then you can query it as follows (that's LINQ syntax):

Contact contact = orgContext
   .ContactSet
   .Where(c => c.FullName == drRowAccount["SalesContact"])
   .FirstOrDefault();
EntityReference contactRef = contact?.ToEntityReference();


问:
VB Script to C# - Extract .arch file
I have to extract .arch type files. In an old VB script, it is done using wscript.shell commands.

```<code>Set shellobj = wscript.createobject ("wscript.shell")
cmdline = "wzunzip -d -n " & source & " " & destination & "\"
cmdexec = shellobj.run((cmdline), 1, true)
</code>```

I am converting this to c# so I used the following code to extract files:

```<code>ZipFile.ExtractToDirectory(source, destination);//Unzip file
</code>```

But this line is throwing an exception for .arch type files.

"An attempt was made to move the file pointer before the beginning of the file."

Is there a way I can extract .arch type files in C#. My file is of this specific type.

答:
Have you read the MS Docs?

https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.zipfile.extracttodirectory?view=netframework-4.8#System_IO_Compression_ZipFile_ExtractToDirectory_System_String_System_String_System_Text_Encoding_

Under IO Exception:

The directory specified by destinationDirectoryName
  already exists.

-or-

The name of an entry in the archive is Empty, contains only white
  space, or contains at least one invalid character.

-or-

Extracting an archive entry would create a file that is outside the
  directory specified by destinationDirectoryName. (For example, this
  might happen if the entry name contains parent directory accessors.)

-or-

An archive entry to extract has the same name as an entry that has
  already been extracted from the same archive.

So basically,

Does your directory already exist? If so it shouldn't.

Are any of the file name's empty? If so, they shouldn't be, they require names.

Does the destination file path have any file path characters (for
example, '..')? If so, they shouldn't.

Do any of the files have the same name? If so they shouldn't.

It doesn't actually look like any of those issues weirdly, and it's rare Microsoft miss something. The only other thing I see in the docs is that there is an overload for an encoding type, but this is for the encoding of the zip file rather than the files inside it...

It looks like the file is corrupt. This question seems to highlight your issue:
https://superuser.com/questions/457271/identifiying-a-zip-file-that-is-not-really-a-zip-file

Maybe when the .ARCH files are compressed, the file signature is lost? Or the file is corrupted somehow?

Title: VB Script to C# - Extract .arch file

Body:
I have to extract .arch type files. In an old VB script, it is done using wscript.shell commands.

Set shellobj = wscript.createobject ("wscript.shell")
cmdline = "wzunzip -d -n " & source & " " & destination & "\"
cmdexec = shellobj.run((cmdline), 1, true)

I am converting this to c# so I used the following code to extract files:

ZipFile.ExtractToDirectory(source, destination);//Unzip file

But this line is throwing an exception for .arch type files.

"An attempt was made to move the file pointer before the beginning of the file."

Is there a way I can extract .arch type files in C#. My file is of this specific type.


问:
Additional SQL Server db container in ddev setup beside web and db container
I am playing around to get a additional SQL Server container (as multi db playground setup for TYPO3) in ddev configuartion within docker-compose.override.yaml.

It works somehow and i can connect to the SQL Server from the host machine (to be honest with more luck than knowledge ;o).

What i absolutely don't know is how to connect the new mssql container to the web container that TYPO3 can access it. Absolutely no clue ;o( Any ideas?

UPDATE:
I had a little progress with my problem see below. It was simpler than expected. Ddev is building a additional MsSql Server container and TYPO3 can access it with an additional DB config.

Don't know if this is a good practical way. Will investigate more if MsSql support in TYPO3 is useable.

docker-compose.override.yaml:

```<code>version: '3.6'

services:
  web:
    environment:
      - TYPO3_CONTEXT=Development/Ddev
    links:
      - mssql:mssql

  mssql:
    # https://hub.docker.com/_/microsoft-mssql-server
    image: "mcr.microsoft.com/mssql/server"
    volumes:
      - mssql-db-data:/var/opt/mssql/
    environment:
      SA_PASSWORD: "MyPassword001"
      ACCEPT_EULA: "Y"
    ports:
      - "1433:1433"
volumes:
  mssql-db-data:
    driver: local
</code>```

DB Connections in LocalConfigurtion:

```<code>    'DB' => [
        'Connections' => [
            'Default' => [
                'charset'  => 'utf8',
                'dbname'   => 'db',
                'driver'   => 'mysqli',
                'host'     => 'db',
                'password' => 'db',
                'port'     => 3306,
                'user'     => 'db',
            ],
            'MsSql' => [
                'charset' => 'UTF-8',
                'dbname' => 'master',
                'driver' => 'sqlsrv',
                'host' => 'mssql',
                'password' => 'MyPassword001',
                'port' => '1433',
                'user' => 'SA',
            ],
        ],
        'TableMapping' => [
            'sys_log' => 'MsSql',
        ],
    ],
</code>```

Update 2:

Here is a little update see below.

docker-compose.mssql.yaml:

With this configuration i get in DDEV an mssql container.

```<code>version: '3.6'

services:
  web:
    links:
      - mssql:mssql

  mssql:
    # https://hub.docker.com/_/microsoft-mssql-server
    image: "mcr.microsoft.com/mssql/server"
    volumes:
      - mssql-db-data:/var/opt/mssql/
    environment:
      SA_PASSWORD: "MyPassword001"
      ACCEPT_EULA: "Y"
    ports:
      - "1433:1433"
volumes:
  mssql-db-data:
    driver: local
</code>```

web-build/Dockerfile:

The web container needs additional packages. This Dockerfile works for me quite well.
This link has a more advanced solution:
How to install the SQL Server PHP drivers in DDEV-Local?

```<code># https://ddev.readthedocs.io/en/stable/users/extend/customizing-images/#adding-extra-dockerfiles-for-webimage-and-dbimage
# https://stackoverflow.com/questions/58086933/how-to-install-the-sql-server-php-drivers-in-ddev-local#new-answer
ARG BASE_IMAGE
FROM $BASE_IMAGE

RUN curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
RUN curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list

RUN apt-get update
RUN apt-get --allow-downgrades -y install libssl1.1=1.1.1d-0+deb10u5
RUN apt-get -y update && yes | ACCEPT_EULA=Y apt-get -y install php7.4-dev php-pear unixodbc-dev htop
RUN ACCEPT_EULA=Y apt-get -y install msodbcsql17 mssql-tools
RUN sudo pecl channel-update pecl.php.net
RUN sudo pecl install sqlsrv
RUN sudo pecl install pdo_sqlsrv

RUN sudo printf "; priority=20\nextension=sqlsrv.so\n" > /etc/php/7.3/mods-available/sqlsrv.ini
RUN sudo printf "; priority=30\nextension=pdo_sqlsrv.so\n" > /etc/php/7.3/mods-available/pdo_sqlsrv.ini
RUN sudo phpenmod -v 7.3 -s cli sqlsrv pdo_sqlsrv
RUN sudo phpenmod -v 7.3 -s fpm sqlsrv pdo_sqlsrv
RUN sudo phpenmod -v 7.3 -s apache2 sqlsrv pdo_sqlsrv

RUN sudo printf "; priority=20\nextension=sqlsrv.so\n" > /etc/php/7.4/mods-available/sqlsrv.ini
RUN sudo printf "; priority=30\nextension=pdo_sqlsrv.so\n" > /etc/php/7.4/mods-available/pdo_sqlsrv.ini
RUN sudo phpenmod -v 7.4 -s cli sqlsrv pdo_sqlsrv
RUN sudo phpenmod -v 7.4 -s fpm sqlsrv pdo_sqlsrv
RUN sudo phpenmod -v 7.4 -s apache2 sqlsrv pdo_sqlsrv

RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile

</code>```

答:
Your configuration looks fine. This part links the mssql container to the web container:

```<code>services:
  web:
    links:
      - mssql:mssql
</code>```

It should be accessible using the host mssql, as you've rightly set in your LocalConfiguration.php.

I wouldn't call the file docker-compose.override.yaml though. I'd call it docker-compose.mssql.yaml. That way you can more easily add multiple 'override' docker-compose files and easily copy them to other projects if needed. All docker-compose.*.yaml files will be loaded.

Body:
I am playing around to get a additional SQL Server container (as multi db playground setup for TYPO3) in ddev configuartion within docker-compose.override.yaml.

It works somehow and i can connect to the SQL Server from the host machine (to be honest with more luck than knowledge ;o).

What i absolutely don't know is how to connect the new mssql container to the web container that TYPO3 can access it. Absolutely no clue ;o( Any ideas?

UPDATE:
I had a little progress with my problem see below. It was simpler than expected. Ddev is building a additional MsSql Server container and TYPO3 can access it with an additional DB config.

Don't know if this is a good practical way. Will investigate more if MsSql support in TYPO3 is useable.

docker-compose.override.yaml:

version: '3.6'

services:
  web:
    environment:
      - TYPO3_CONTEXT=Development/Ddev
    links:
      - mssql:mssql

  mssql:
    # https://hub.docker.com/_/microsoft-mssql-server
    image: "mcr.microsoft.com/mssql/server"
    volumes:
      - mssql-db-data:/var/opt/mssql/
    environment:
      SA_PASSWORD: "MyPassword001"
      ACCEPT_EULA: "Y"
    ports:
      - "1433:1433"
volumes:
  mssql-db-data:
    driver: local

DB Connections in LocalConfigurtion:

    'DB' => [
        'Connections' => [
            'Default' => [
                'charset'  => 'utf8',
                'dbname'   => 'db',
                'driver'   => 'mysqli',
                'host'     => 'db',
                'password' => 'db',
                'port'     => 3306,
                'user'     => 'db',
            ],
            'MsSql' => [
                'charset' => 'UTF-8',
                'dbname' => 'master',
                'driver' => 'sqlsrv',
                'host' => 'mssql',
                'password' => 'MyPassword001',
                'port' => '1433',
                'user' => 'SA',
            ],
        ],
        'TableMapping' => [
            'sys_log' => 'MsSql',
        ],
    ],

Update 2:

Here is a little update see below.

docker-compose.mssql.yaml:

With this configuration i get in DDEV an mssql container.

version: '3.6'

services:
  web:
    links:
      - mssql:mssql

  mssql:
    # https://hub.docker.com/_/microsoft-mssql-server
    image: "mcr.microsoft.com/mssql/server"
    volumes:
      - mssql-db-data:/var/opt/mssql/
    environment:
      SA_PASSWORD: "MyPassword001"
      ACCEPT_EULA: "Y"
    ports:
      - "1433:1433"
volumes:
  mssql-db-data:
    driver: local

web-build/Dockerfile:

The web container needs additional packages. This Dockerfile works for me quite well.
This link has a more advanced solution:
How to install the SQL Server PHP drivers in DDEV-Local?

# https://ddev.readthedocs.io/en/stable/users/extend/customizing-images/#adding-extra-dockerfiles-for-webimage-and-dbimage
# https://stackoverflow.com/questions/58086933/how-to-install-the-sql-server-php-drivers-in-ddev-local#new-answer
ARG BASE_IMAGE
FROM $BASE_IMAGE

RUN curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
RUN curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list

RUN apt-get update
RUN apt-get --allow-downgrades -y install libssl1.1=1.1.1d-0+deb10u5
RUN apt-get -y update && yes | ACCEPT_EULA=Y apt-get -y install php7.4-dev php-pear unixodbc-dev htop
RUN ACCEPT_EULA=Y apt-get -y install msodbcsql17 mssql-tools
RUN sudo pecl channel-update pecl.php.net
RUN sudo pecl install sqlsrv
RUN sudo pecl install pdo_sqlsrv

RUN sudo printf "; priority=20\nextension=sqlsrv.so\n" > /etc/php/7.3/mods-available/sqlsrv.ini
RUN sudo printf "; priority=30\nextension=pdo_sqlsrv.so\n" > /etc/php/7.3/mods-available/pdo_sqlsrv.ini
RUN sudo phpenmod -v 7.3 -s cli sqlsrv pdo_sqlsrv
RUN sudo phpenmod -v 7.3 -s fpm sqlsrv pdo_sqlsrv
RUN sudo phpenmod -v 7.3 -s apache2 sqlsrv pdo_sqlsrv

RUN sudo printf "; priority=20\nextension=sqlsrv.so\n" > /etc/php/7.4/mods-available/sqlsrv.ini
RUN sudo printf "; priority=30\nextension=pdo_sqlsrv.so\n" > /etc/php/7.4/mods-available/pdo_sqlsrv.ini
RUN sudo phpenmod -v 7.4 -s cli sqlsrv pdo_sqlsrv
RUN sudo phpenmod -v 7.4 -s fpm sqlsrv pdo_sqlsrv
RUN sudo phpenmod -v 7.4 -s apache2 sqlsrv pdo_sqlsrv

RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile

Body:
Your configuration looks fine. This part links the mssql container to the web container:

services:
  web:
    links:
      - mssql:mssql

It should be accessible using the host mssql, as you've rightly set in your LocalConfiguration.php.

I wouldn't call the file docker-compose.override.yaml though. I'd call it docker-compose.mssql.yaml. That way you can more easily add multiple 'override' docker-compose files and easily copy them to other projects if needed. All docker-compose.*.yaml files will be loaded.


问:
Restart the whole device from Android
Is there any way to restart a device per code from within android. I can highly customize all software on the device (tablet). As Backgroundinfo: I want a timer that restarts the device after a defined count if he did not get reseted.

Edit:

If there there is no Buildin-Way is it possible to do this anyway?

答:
This isn't possible from within an app, I believe.

The intent for rebooting the device (ACTION_REBOOT, if I recall, but I'm happy to be corrected!) can only be called from the system itself, not from any software residing on it.

(See the Android reference docs here.)

Title: Restart the whole device from Android


问:
program to print rectangle pattern in Javascript
Need help developing a JavaScript program that accepts number as an input and then displays a rectangle of 3 columns wide and 5 rows tall using that digit. </p>

```<code>Basically the output I want is as follows,
555
55
55
555
</code>```

<p>the below is the code I have but i am not happy with hardcoding - </p>

```<code>var input = document.getElementById("input");
function rectangle() {
    console.log(input.value, input.value, input.value);
    console.log(input.value, input.value);
    console.log(input.value, input.value);
    console.log(input.value, input.value);
    console.log(input.value, input.value, input.value);
}
</code>```

答:
I assumed 3 columns=30px
5 rows=50px

var inp=document.getElementById("length");
var div=document.getElementById("theDiv");
inp.onchange=(e)=>{
  div.style.width=inp.value*3*10+"px";
  div.style.height=inp.value*5*10+"px";

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="length" type="number"/>
<div id="theDiv" style="border:solid 1px black;width:0px;height:0px"></div></code>```

Body:
Need help developing a JavaScript program that accepts number as an input and then displays a rectangle of 3 columns wide and 5 rows tall using that digit.

Basically the output I want is as follows,
555
55
55
555

the below is the code I have but i am not happy with hardcoding -

var input = document.getElementById("input");
function rectangle() {
    console.log(input.value, input.value, input.value);
    console.log(input.value, input.value);
    console.log(input.value, input.value);
    console.log(input.value, input.value);
    console.log(input.value, input.value, input.value);
}

Body:
I assumed 3 columns=30px
5 rows=50px

var inp=document.getElementById("length");
var div=document.getElementById("theDiv");
inp.onchange=(e)=>{
  div.style.width=inp.value*3*10+"px";
  div.style.height=inp.value*5*10+"px";

}

<input id="length" type="number"/>
<div id="theDiv" style="border:solid 1px black;width:0px;height:0px"></div>


问:
Javascript is not doing sum of all records
I'm trying to do the sum of all cart items but it is not doing it.
It is showing only the sum of first or last item added in the cart.

What is the issue i cannot understand. I have tried by moving code in the java but no use.

Suppose i have 2 items.

Item1 total is = 100
Item2 total is = 200

Total should be 300 not only the 1 items total.

Below is my code.

Thanks in advance

```<code><script type="text/javascript" src="js/jquery-1.12.1.min.js"></script>

<table class="table mg-bottom-45 refresh" id="myTable">
    <thead>
    <tr>
    <th class="product-cart-price"><span>PRICE</span></th>
    <th class="product-cart-price"><span>TOTAL</span></th>
    </tr>
    </thead>

<tbody>
<?php
include ('inc/db.php');

$citem  = "select * from orders_temp
where user_id = 1 order by id
";
$ciquery    = $dba2->query($citem);
while ($cifetch = $ciquery->fetch_assoc()){
    $orderID    =   $cifetch['id'];
    $userID =   $cifetch['user_id'];
?>
    <td class="product-cart-thumbnail">
    <input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
    data-price="" value="<?php echo $cifetch['qty']; ?>"
    class="un quant" />
    </td>

    <td class="product-cart-thumbnail">
    <input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
    data-price="<?php echo $cifetch['price']; ?>"
    value="<?php echo $cifetch['price']; ?>" class="un pricex" />
    </td>

<?php } ?>
    <td class="totalAmount"></td>
</tbody>
</table>

<script type="text/javascript">
$(document).ready(function() {
  updatexx<?php echo $orderID; ?>();
  function updatexx<?php echo $orderID; ?>() {
    var sumx = '';
    $('#myTable > tbody  > tr').each(function() {
      var quantityx = $(this).find('.quant').val();
      var pricex = $(this).find('.pricex').attr('data-price').replace(',', '.');
      var amountx = (quantityx * pricex).toFixed(3);

      sumx += amountx;
    });
    $('.totalAmount').text(sumx);
  }
});
</script>
</code>```

答:
First, please make sure that your loop is running multiple times (same number of products in cart).

```<code>$('#myTable > tbody  > tr').each(function() {})
</code>```

so that the above loop iterate exact number times as per required.

You should make some changes in code as follows:

```<code>var sumx = 0.00;
</code>```

and in loop code should be

```<code> sumx += parsefloat(amountx);
</code>```

Body:
I'm trying to do the sum of all cart items but it is not doing it.
It is showing only the sum of first or last item added in the cart.

What is the issue i cannot understand. I have tried by moving code in the java but no use.

Suppose i have 2 items.

Item1 total is = 100
Item2 total is = 200

Total should be 300 not only the 1 items total.

Below is my code.

Thanks in advance

    PRICE
    TOTAL

<?php
include ('inc/db.php');

$citem  = "select * from orders_temp
where user_id = 1 order by id
";
$ciquery    = $dba2->query($citem);
while ($cifetch = $ciquery->fetch_assoc()){
    $orderID    =   $cifetch['id'];
    $userID =   $cifetch['user_id'];
?>

    <input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
    data-price="" value="<?php echo $cifetch['qty']; ?>"
    class="un quant" />

    <input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
    data-price="<?php echo $cifetch['price']; ?>"
    value="<?php echo $cifetch['price']; ?>" class="un pricex" />

<?php } ?>

Body:
First, please make sure that your loop is running multiple times (same number of products in cart).

$('#myTable > tbody  > tr').each(function() {})

so that the above loop iterate exact number times as per required.

You should make some changes in code as follows:

var sumx = 0.00;

and in loop code should be

 sumx += parsefloat(amountx);


问:
How do I make Except print out my error messages?
my name is Ana, and I'm a student taking a course in Python. I'm still a beginner and I'm recently learning how to use the try and except function. However, I'm trying to make the program print an error message when input is a string and not an integer. Instead, it prints out its own error message instead of mine. What am I doing wrong? I don't want to ask my teacher because I don't want to keep asking him to check my code. Here is a screenshot of my attempt.

Thanks for your help.

Sincerely

Ana Baird

答:
Anything that can throw an exception needs to be placed inside the try: block. In your code example, place the integer = int(userin) inside it, otherwise if a user enters a string Python will throw its own error.

And in the future, please don't post a picture of your code. Instead use the formatting provided on the site or a pastebin link  :)


问:
Move data from row to another row within a group of specified rows
I have this dataset that I want to transform, so I have just select a piece of how it looks like. So we have a column called Hospital which has those 4 rows which repeat until end of the dataframe. I want to transform so that all the data can only be saved on first row which is called prelim_arm_1 and delete the rest of the 3 rows arms.

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

# initialize data of lists.
data = {'Hospital':['prelim_arm_1' , '24_hour_review_arm_1','48_hour_review_arm_1',
                    '72_hour_review_arm_1','discharge_informat_arm_1','prelim_arm_1' ,
                    '24_hour_review_arm_1','48_hour_review_arm_1',
                    '72_hour_review_arm_1','discharge_informat_arm_1'],
        'Bug_Hosp':['133', 'NAN' , 'NAN', 'NAN', 'NAN','133', 'NAN' , 'NAN', 'NAN', 'NAN'],
        'code':['G45','NAN' ,'NAN','NAN', 'NAN', 'G45','NAN' ,'NAN','NAN', 'NAN'],
        'cont':['T256','NAN' ,'NAN','NAN', 'NAN','T256','NAN' ,'NAN','NAN', 'NAN'],
        'IPC':['NAN','NAN' ,'NAN','567TY', 'NAN','NAN','NAN' ,'NAN','567Tu', 'NAN'],
        'NO_CT':['NAN','NAN' ,'NAN','NAN', '5667','NAN','NAN' ,'NAN','3456', 'NAN'],
        }

# Create DataFrame
df_final = pd.DataFrame(data)

# Print the output.
print(df_final)

</code>```

Final dataset should look like this

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

# initialize data of lists.
data = {'Hospital':['prelim_arm_1'],
        'Bug_Hosp':['133'], 'code':['G45'],
        'cont':['T256'],
        'IPC':['567TY'],
        'NO_CT':['5667']}

# Create DataFrame
df_final = pd.DataFrame(data)

# Print the output.
print(df_final)

</code>```

The dataset is huge with repeated rows arms but I want for each group of 4 rows, it should only save data on prelim_arm_1 and delete the other 3 row arms. so final table will only have prelim_arm_1 with data per group of 4 arms.

答:
If want first non missing values per each 5 rows use first DataFrame.replace if NAN are strings, else omit this step and then use groupby with GroupBy.first by helper Series created compared Hospital column by first value prelim_arm_1 and Series.cumsum:

```<code>#if necessary
df_final = df_final.replace('NAN',np.nan)

df_final = df_final.groupby(df_final['Hospital'].eq('prelim_arm_1').cumsum()).first()
print(df_final)
              Hospital Bug_Hosp code  cont    IPC NO_CT
Hospital
1         prelim_arm_1      133  G45  T256  567TY  5667
2         prelim_arm_1      133  G45  T256  567Tu  3456
</code>```

Detail:

```<code>print(df_final['Hospital'].eq('prelim_arm_1').cumsum())
0    1
1    1
2    1
3    1
4    1
5    2
6    2
7    2
8    2
9    2
Name: Hospital, dtype: int32
</code>```

Body:
I have this dataset that I want to transform, so I have just select a piece of how it looks like. So we have a column called Hospital which has those 4 rows which repeat until end of the dataframe. I want to transform so that all the data can only be saved on first row which is called prelim_arm_1 and delete the rest of the 3 rows arms.

import pandas as pd
import numpy as np

# initialize data of lists.
data = {'Hospital':['prelim_arm_1' , '24_hour_review_arm_1','48_hour_review_arm_1',
                    '72_hour_review_arm_1','discharge_informat_arm_1','prelim_arm_1' ,
                    '24_hour_review_arm_1','48_hour_review_arm_1',
                    '72_hour_review_arm_1','discharge_informat_arm_1'],
        'Bug_Hosp':['133', 'NAN' , 'NAN', 'NAN', 'NAN','133', 'NAN' , 'NAN', 'NAN', 'NAN'],
        'code':['G45','NAN' ,'NAN','NAN', 'NAN', 'G45','NAN' ,'NAN','NAN', 'NAN'],
        'cont':['T256','NAN' ,'NAN','NAN', 'NAN','T256','NAN' ,'NAN','NAN', 'NAN'],
        'IPC':['NAN','NAN' ,'NAN','567TY', 'NAN','NAN','NAN' ,'NAN','567Tu', 'NAN'],
        'NO_CT':['NAN','NAN' ,'NAN','NAN', '5667','NAN','NAN' ,'NAN','3456', 'NAN'],
        }

# Create DataFrame
df_final = pd.DataFrame(data)

# Print the output.
print(df_final)

Final dataset should look like this

import pandas as pd
import numpy as np

# initialize data of lists.
data = {'Hospital':['prelim_arm_1'],
        'Bug_Hosp':['133'], 'code':['G45'],
        'cont':['T256'],
        'IPC':['567TY'],
        'NO_CT':['5667']}

# Create DataFrame
df_final = pd.DataFrame(data)

# Print the output.
print(df_final)

The dataset is huge with repeated rows arms but I want for each group of 4 rows, it should only save data on prelim_arm_1 and delete the other 3 row arms. so final table will only have prelim_arm_1 with data per group of 4 arms.

Body:
If want first non missing values per each 5 rows use first DataFrame.replace if NAN are strings, else omit this step and then use groupby with GroupBy.first by helper Series created compared Hospital column by first value prelim_arm_1 and Series.cumsum:

#if necessary
df_final = df_final.replace('NAN',np.nan)

df_final = df_final.groupby(df_final['Hospital'].eq('prelim_arm_1').cumsum()).first()
print(df_final)
              Hospital Bug_Hosp code  cont    IPC NO_CT
Hospital
1         prelim_arm_1      133  G45  T256  567TY  5667
2         prelim_arm_1      133  G45  T256  567Tu  3456

Detail:

print(df_final['Hospital'].eq('prelim_arm_1').cumsum())
0    1
1    1
2    1
3    1
4    1
5    2
6    2
7    2
8    2
9    2
Name: Hospital, dtype: int32


问:
Error with eXist-db while I am trying to insert data
I'm doing a school project which takes 7584 rows of a .csv and save it in a .xml file with eXist-db.
Here is my code to insert:

private static Collection collection = ExistConnection.getCollection();
private static XPathQueryService service;

static {
    try {
        service = (XPathQueryService) collection.getService("XPathQueryService", "1.0");
    } catch (XMLDBException e) {
        e.printStackTrace();
    }
}
```

<pre class="lang-java prettyprint-override"><code>public static void insert() {
    App.getCrimes().forEach(crime -> {
        try {
            String insert = "update insert" +
                    "<crime>" +
                    "<date>" + crime.getDate() + "</date>" +
                    "<address>" + crime.getAddress() + "</address>" +
                    "<district>" + crime.getDistrict() + "</district>" +
                    "<beat>" + crime.getBeat() + "</beat>" +
                    "<grid>" + crime.getGrid() + "</grid>" +
                    "<description>" + crime.getDescription() + "</description>" +
                    "<ncicCode>" + crime.getNcicCode() + "</ncicCode>" +
                    "<location>" +
                    "<latitude>" + crime.getLocation().getLatitude() + "</latitude>" +
                    "<longitude>" + crime.getLocation().getLongitude() + "</longitude>" +
                    "</location>" +
                    "</crime>" +
                    "into /crimes";
            service.query(insert);
        } catch (XMLDBException e) {
            System.out.println(e.getMessage());
        }
    });
}
</code>```

And now the code to count the number of crimes:

public static void countAll() {
    try {
        ResourceSet resourceSet = service.query("let $n := count(/crimes/crime) return $n");
        ResourceIterator i = resourceSet.getIterator();
        while (i.hasMoreResources()) {
            Resource r = i.nextResource();
            System.out.println((String) r.getContent());
        }
        ExistConnection.closeCollection();
    } catch (XMLDBException e) {
        e.printStackTrace();
    }
}
```

<p>When I run the application I got the next error and the result of count the numbers of crimes:</p>

```Failed to invoke method queryPT in class org.exist.xmlrpc.RpcConnection: org.exist.xquery.XPathException: err:XPST0003 unexpected token: $ (while expecting closing tag for element constructor: null) [at line 1, column 171]
Failed to invoke method queryPT in class org.exist.xmlrpc.RpcConnection: org.exist.xquery.XPathException: err:XPST0003 unexpected token: $ (while expecting closing tag for element constructor: null) [at line 1, column 177]
7582
```

I don't know the reason why I only can insert 7582 of 7584 rows.
I tried to delete the rows 7583 and 7584, in case that these rows were wrong for some reason, but the error persists and the count result is 7580.

答: There was an error in the .csv, 2 rows had the symbol < inside the data and these 2 rows couldn't be added.

Body:
I'm doing a school project which takes 7584 rows of a .csv and save it in a .xml file with eXist-db.
Here is my code to insert:

private static Collection collection = ExistConnection.getCollection();
private static XPathQueryService service;

static {
    try {
        service = (XPathQueryService) collection.getService("XPathQueryService", "1.0");
    } catch (XMLDBException e) {
        e.printStackTrace();
    }
}

public static void insert() {
    App.getCrimes().forEach(crime -> {
        try {
            String insert = "update insert" +
                    "<crime>" +
                    "<date>" + crime.getDate() + "</date>" +
                    "<address>" + crime.getAddress() + "</address>" +
                    "<district>" + crime.getDistrict() + "</district>" +
                    "<beat>" + crime.getBeat() + "</beat>" +
                    "<grid>" + crime.getGrid() + "</grid>" +
                    "<description>" + crime.getDescription() + "</description>" +
                    "<ncicCode>" + crime.getNcicCode() + "</ncicCode>" +
                    "<location>" +
                    "<latitude>" + crime.getLocation().getLatitude() + "</latitude>" +
                    "<longitude>" + crime.getLocation().getLongitude() + "</longitude>" +
                    "</location>" +
                    "</crime>" +
                    "into /crimes";
            service.query(insert);
        } catch (XMLDBException e) {
            System.out.println(e.getMessage());
        }
    });
}

And now the code to count the number of crimes:

public static void countAll() {
    try {
        ResourceSet resourceSet = service.query("let $n := count(/crimes/crime) return $n");
        ResourceIterator i = resourceSet.getIterator();
        while (i.hasMoreResources()) {
            Resource r = i.nextResource();
            System.out.println((String) r.getContent());
        }
        ExistConnection.closeCollection();
    } catch (XMLDBException e) {
        e.printStackTrace();
    }
}

When I run the application I got the next error and the result of count the numbers of crimes:

Failed to invoke method queryPT in class org.exist.xmlrpc.RpcConnection: org.exist.xquery.XPathException: err:XPST0003 unexpected token: $ (while expecting closing tag for element constructor: null) [at line 1, column 171]
Failed to invoke method queryPT in class org.exist.xmlrpc.RpcConnection: org.exist.xquery.XPathException: err:XPST0003 unexpected token: $ (while expecting closing tag for element constructor: null) [at line 1, column 177]
7582

I don't know the reason why I only can insert 7582 of 7584 rows.
I tried to delete the rows 7583 and 7584, in case that these rows were wrong for some reason, but the error persists and the count result is 7580.


问:
Compilation problem while running the sdm package in Rstudio
I am getting this error when compiling:

Error in FUN(X[[i]], ...): trying to get slot "presence" from an object of a basic class ("NULL") with no slots

How can I solve this?

答:
You should check the formula to see whether you are indicating the same name
ie

```<code>sdmdata<- sdmData(**species~.,** train, test, predictors, bg..)
</code>```

Writing this in the model will give you an error you described.

```<code>sdmmodel<- sdm(**specie~.,** data= methods=c("glm", "brt")).
</code>```

I solved a similar problem that way

Body:
You should check the formula to see whether you are indicating the same name
ie

sdmdata<- sdmData(**species~.,** train, test, predictors, bg..)

Writing this in the model will give you an error you described.

sdmmodel<- sdm(**specie~.,** data= methods=c("glm", "brt")).

I solved a similar problem that way


问:
How to remove lines from file1 that exist in file2 in C#
I would like to know how to remove lines from file1 that exist in file2 in C#.

I have written it in python, but how would I do it in C# (performance doesn't matter)?

The code in python looks like this:

```<code>file_1 = "file1.txt"
file_2 = "file2.txt"

data_1 = []
data_2 = []

with open(file_1,'r') as f:
    data_1 = f.readlines()

with open(file_2,'r') as f:
    data_2 = f.readlines()

for line in data_1:
    if line in data_2:
        print(f"Removing -> {line}")
        data_2.remove(line)

with open("output.txt",'w') as f:
    for line in data_2:
        f.write(line)
</code>```

This is my code in C#:

```<code>string fileName1 = @"c:\temp\file1.txt";
string fileName2 = @"c:\temp\file2.txt";

var allText1 = File.ReadAllLines(fileName1);
var allText2 = File.ReadAllLines(fileName2);

allText1 = allText1.Where(o => !allText2.Where(p => p == o).Any()).ToArray();
</code>```

How do I get the lines that are removed?
Thank you!

答:
Update:

```<code>var file1 = File.ReadLines(file1path);
var file2 = File.ReadAllLines(file2path);
File.WriteAllLines("removed.txt", file1.Except(file2));
</code>```

This gets the removed lines :)

Body:
I would like to know how to remove lines from file1 that exist in file2 in C#.

I have written it in python, but how would I do it in C# (performance doesn't matter)?

The code in python looks like this:

file_1 = "file1.txt"
file_2 = "file2.txt"

data_1 = []
data_2 = []

with open(file_1,'r') as f:
    data_1 = f.readlines()

with open(file_2,'r') as f:
    data_2 = f.readlines()

for line in data_1:
    if line in data_2:
        print(f"Removing -> {line}")
        data_2.remove(line)

with open("output.txt",'w') as f:
    for line in data_2:
        f.write(line)

This is my code in C#:

string fileName1 = @"c:\temp\file1.txt";
string fileName2 = @"c:\temp\file2.txt";

var allText1 = File.ReadAllLines(fileName1);
var allText2 = File.ReadAllLines(fileName2);

allText1 = allText1.Where(o => !allText2.Where(p => p == o).Any()).ToArray();

How do I get the lines that are removed?
Thank you!

Body:
Update:

var file1 = File.ReadLines(file1path);
var file2 = File.ReadAllLines(file2path);
File.WriteAllLines("removed.txt", file1.Except(file2));

This gets the removed lines :)


问:
How to create an SQL Server 2008 database from script
I'm trying to do an Entity Framework walkthrough so I:

downloaded SQL script here: http://www.learnentityframework.com

in SQL Server Management Studio, I right-clicked Database, Create Database, named it

right-clicked on the new database, New Query

clicked on "Open File" and opened the script file: Create_ProgrammingEFDB1_SQLServer2008.sql

clicked "! Execute"

But the script (756K) has been running for 10 minutes now and still says "executing..."

My questions are:

Is this the standard way to read in an SQL script into SQL Server?

Is it supposed to take this long? This is how I would do it in MySQL/PHPMyAdmin it it might take a couple seconds, so I assume I'm not doing something right.

Here is the beginning of the script, I changed the file paths so they point to the right .mdf and .ldf files:

```<code>****/

--PART ONE  CREATE THE DATABASE. Note the file paths in the first few commands.
--Change them for your own computer.--
USE [master]
GO

    /****** Object:  Database [ProgrammingEFDB1]    Script Date: 01/28/2009 10:17:44 ******/
    CREATE DATABASE [ProgrammingEFDB1] ON  PRIMARY
    ( NAME = N'ProgrammingEFDB1', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\ProgrammingEFDB1.mdf' , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
     LOG ON
    ( NAME = N'ProgrammingEFDB1_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\ProgrammingEFDB1_log.LDF' , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
    GO

    ALTER DATABASE [ProgrammingEFDB1] SET COMPATIBILITY_LEVEL = 90
    GO

    IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
    begin
    EXEC [ProgrammingEFDB1].[dbo].[sp_fulltext_database] @action = 'disable'
    end
    ...
</code>```

ANSWER:

I had already created a database with the same name so it was trying to create a database that was already there which made it hang for some reason. I deleted that database, reran the script and it completed successfully in 3 seconds.

答:
I don't know what does your script do exactly in the next 754K, but the lines you posted seem quite harmless.

Try adding the following to your script:

```<code>SET STATISTICS TIME ON
</code>```

This will show queries execution times as they run, and it will help you to locate the problem more exactly.

OwnerDisplayName: Edward Tanguay

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to do an Entity Framework walkthrough so I:

downloaded SQL script here: http://www.learnentityframework.com

in SQL Server Management Studio, I right-clicked Database, Create Database, named it

right-clicked on the new database, New Query

clicked on "Open File" and opened the script file: Create_ProgrammingEFDB1_SQLServer2008.sql

clicked "! Execute"

But the script (756K) has been running for 10 minutes now and still says "executing..."

My questions are:

Is this the standard way to read in an SQL script into SQL Server?

Is it supposed to take this long? This is how I would do it in MySQL/PHPMyAdmin it it might take a couple seconds, so I assume I'm not doing something right.

Here is the beginning of the script, I changed the file paths so they point to the right .mdf and .ldf files:

****/

--PART ONE  CREATE THE DATABASE. Note the file paths in the first few commands.
--Change them for your own computer.--
USE [master]
GO

    /****** Object:  Database [ProgrammingEFDB1]    Script Date: 01/28/2009 10:17:44 ******/
    CREATE DATABASE [ProgrammingEFDB1] ON  PRIMARY
    ( NAME = N'ProgrammingEFDB1', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\ProgrammingEFDB1.mdf' , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
     LOG ON
    ( NAME = N'ProgrammingEFDB1_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\ProgrammingEFDB1_log.LDF' , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
    GO

    ALTER DATABASE [ProgrammingEFDB1] SET COMPATIBILITY_LEVEL = 90
    GO

    IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
    begin
    EXEC [ProgrammingEFDB1].[dbo].[sp_fulltext_database] @action = 'disable'
    end
    ...

ANSWER:

I had already created a database with the same name so it was trying to create a database that was already there which made it hang for some reason. I deleted that database, reran the script and it completed successfully in 3 seconds.

LastEditorDisplayName: Edward Tanguay

Body:
I don't know what does your script do exactly in the next 754K, but the lines you posted seem quite harmless.

Try adding the following to your script:

SET STATISTICS TIME ON

This will show queries execution times as they run, and it will help you to locate the problem more exactly.

OwnerDisplayName: Quassnoi


问:
When to prefer `and` over `andalso` in guard tests
I am curious why the comma ‹,› is a shortcut for and and not andalso in guard tests.

Since I'd call myself a “C native” I fail to see any shortcomings of short-circuit boolean evaluation.

I compiled some test code using the to_core flag to see what code is actually generated. Using the comma, I see the left hand value and right and value get evaluated and both and'ed. With andalso you have a case block within the case block and no call to erlang:and/2.

I did no benchmark tests but I daresay the andalso variant is the faster one.

答: It's an historical reason. and was implemented before andalso, which was introduced in Erlang 5.1 (the only reference I can find right now is EEP-17). Guards have not been changed because of backwards compatibility.


问:
can I get 255 packets from VCP (virtual COM Port)?
I know the default setting value for 'VIRTUAL_COM_PORT_DATA_SIZE 64' at usb_desc.h for STM32 Library.
however, I want to get the 255 bytes at one time due to the long packets of our project.
So I have changed the following modify code point, I couldn't get the right value with problem for 'USB defect problem'.

```<code>/****** usb_prop.c **********/
DEVICE_PROP Device_Property =  {
Virtual_Com_Port_init,
Virtual_Com_Port_Reset,
Virtual_Com_Port_Status_In,
Virtual_Com_Port_Status_Out,
Virtual_Com_Port_Data_Setup,
Virtual_Com_Port_NoData_Setup,
Virtual_Com_Port_Get_Interface_Setting,
Virtual_Com_Port_GetDeviceDescriptor,
Virtual_Com_Port_GetConfigDescriptor,
Virtual_Com_Port_GetStringDescriptor,
0,
0xFF /*MAX PACKET SIZE*/ // default : 0x40
};

/****** usb_desc.c **********/
/* USB Standard Device Descriptor */
const uint8_t Virtual_Com_Port_DeviceDescriptor[] =  {
0x12,   /* bLength */
USB_DEVICE_DESCRIPTOR_TYPE,     /* bDescriptorType */
0x00,
0x02,   /* bcdUSB = 2.00 */
0x02,   /* bDeviceClass: CDC */
0x00,   /* bDeviceSubClass */
0x00,   /* bDeviceProtocol */
0xFF,   /* bMaxPacketSize0 */ // default : 0x40
0x83,
0x04,   /* idVendor = 0x0483 */
0x40,
0x57,   /* idProduct = 0x7540 */
0x00,
0x02,   /* bcdDevice = 2.00 */
1,              /* Index of string descriptor describing manufacturer */
2,              /* Index of string descriptor describing product */
3,              /* Index of string descriptor describing the device's serial number */
0x01    /* bNumConfigurations */  };

/****** usb_desc.h **********/
#define VIRTUAL_COM_PORT_DATA_SIZE              255 // 0xFF, default : 64
</code>```

please tell me how to modify in order to send as 255 bytes from USB packets.

答:
You can't do it this way. The size of the packet is USB endpoint related and for the FS USB it is always 64 bytes. My advice is: do not modify any descriptors unless you really know what are you doing (which is not the case here).

How to receive larger chunks of data:

create a buffer

when data arrives copy it (append) to that buffer

check if you have received all data needed

if not go to point (2) else goto point(5)

Do something with the data (your large packet)

Reset the buffer and goto point 2

Body:
I know the default setting value for 'VIRTUAL_COM_PORT_DATA_SIZE 64' at usb_desc.h for STM32 Library.
however, I want to get the 255 bytes at one time due to the long packets of our project.
So I have changed the following modify code point, I couldn't get the right value with problem for 'USB defect problem'.

/****** usb_prop.c **********/
DEVICE_PROP Device_Property =  {
Virtual_Com_Port_init,
Virtual_Com_Port_Reset,
Virtual_Com_Port_Status_In,
Virtual_Com_Port_Status_Out,
Virtual_Com_Port_Data_Setup,
Virtual_Com_Port_NoData_Setup,
Virtual_Com_Port_Get_Interface_Setting,
Virtual_Com_Port_GetDeviceDescriptor,
Virtual_Com_Port_GetConfigDescriptor,
Virtual_Com_Port_GetStringDescriptor,
0,
0xFF /*MAX PACKET SIZE*/ // default : 0x40
};

/****** usb_desc.c **********/
/* USB Standard Device Descriptor */
const uint8_t Virtual_Com_Port_DeviceDescriptor[] =  {
0x12,   /* bLength */
USB_DEVICE_DESCRIPTOR_TYPE,     /* bDescriptorType */
0x00,
0x02,   /* bcdUSB = 2.00 */
0x02,   /* bDeviceClass: CDC */
0x00,   /* bDeviceSubClass */
0x00,   /* bDeviceProtocol */
0xFF,   /* bMaxPacketSize0 */ // default : 0x40
0x83,
0x04,   /* idVendor = 0x0483 */
0x40,
0x57,   /* idProduct = 0x7540 */
0x00,
0x02,   /* bcdDevice = 2.00 */
1,              /* Index of string descriptor describing manufacturer */
2,              /* Index of string descriptor describing product */
3,              /* Index of string descriptor describing the device's serial number */
0x01    /* bNumConfigurations */  };

/****** usb_desc.h **********/
#define VIRTUAL_COM_PORT_DATA_SIZE              255 // 0xFF, default : 64

please tell me how to modify in order to send as 255 bytes from USB packets.


问:
How to delete duplicate rows using sequelize for Postgres?
I have a model like below: </p>

```<code>id, flatNo, buildingId
</code>```

<p>I want to delete the duplicate rows while retaining exactly one unique row. How can I do that in sequelize? </p>

答:
You can try to Join same table as below:</p>

```<code>DELETE
FROM
    Table1 a
        USING Table1 b
WHERE
    a.id < b.id
    AND a.flatNo = b.flatNo
    AND a.buildingId = b.buildingId;
</code>```

Body:
I have a model like below:

id, flatNo, buildingId

I want to delete the duplicate rows while retaining exactly one unique row. How can I do that in sequelize?

Body:
You can try to Join same table as below:

DELETE
FROM
    Table1 a
        USING Table1 b
WHERE
    a.id < b.id
    AND a.flatNo = b.flatNo
    AND a.buildingId = b.buildingId;


问:
Select multiple result by grouping same values from single column?
I am creating an email alert to send out three email separately from the below table:

```<code>|**ID** |**Name**      |**Company**    |**Count**|
|1      |John          |Apple          |2        |
|2      |Bill          |Microsoft      |2        |
|3      |Steve         |Apple          |2        |
|4      |Elon          |Tesla          |1        |
|5      |Satya         |Microsoft      |2        |
</code>```

I desire to get all three different result to send the email separately

```<code>|**ID** |**Name**      |**Company**    |
|1      |John          |Apple          |
|3      |Steve         |Apple          |

AND

|**ID** |**Name**      |**Company**    |
|2      |Bill          |Microsoft      |
|5      |Satya         |Microsoft      |

AND

|**ID** |**Name**      |**Company**    |
|4      |Elon          |Tesla          |
</code>```

How could I get the desired result as above in SQL?

答:
This query will help you:

```<code>SELECT * FROM table_name WHERE COMPANY="company_name"
</code>```

just replace company_name by Apple, Microsoft, or Tesla.

Body:
I am creating an email alert to send out three email separately from the below table:

|**ID** |**Name**      |**Company**    |**Count**|
|1      |John          |Apple          |2        |
|2      |Bill          |Microsoft      |2        |
|3      |Steve         |Apple          |2        |
|4      |Elon          |Tesla          |1        |
|5      |Satya         |Microsoft      |2        |

I desire to get all three different result to send the email separately

|**ID** |**Name**      |**Company**    |
|1      |John          |Apple          |
|3      |Steve         |Apple          |

AND

|**ID** |**Name**      |**Company**    |
|2      |Bill          |Microsoft      |
|5      |Satya         |Microsoft      |

AND

|**ID** |**Name**      |**Company**    |
|4      |Elon          |Tesla          |

How could I get the desired result as above in SQL?

Body:
This query will help you:

SELECT * FROM table_name WHERE COMPANY="company_name"

just replace company_name by Apple, Microsoft, or Tesla.


问:
Problem in GCC/C++17 with template template class
Consider the 2 following overloads

```<code>template<typename T>
bool test() {
    return true;
}

template<template<typename ...> class T>
bool test() {
    return false;
}
</code>```

The 1st one works for regular classes, while the 2nd one works for templates that are not instantiated.
For instance:

```<code>    std::cout<<test<int>()<<std::endl; <-- this yields 1
    std::cout<<test<std::list>()<<std::endl; <--this yields 0
</code>```

Now consider the following template function:

```<code>template<typename U>
bool templfun(){
    struct A{
        bool f(){
            return test<A>(); // <-- this gives an error
        }
    };
    return test<A>();  // <-- this is ok
}
</code>```

In GCC it gives an error for ambiguous overload resolution, while Clang compiles.
Interestingly, the second call to test() doesn't produce errors (even in GCC).
Moreover, if I remove the template<typename U> thing on top of templfun, gcc stops complaining.

Is this a bug with GCC or is it illegal code?

答:
GCC is wrong; struct A is a templated entity but clearly not a template (as it does not start with a template keyword), so there is no ambiguity.

To confirm, we can rename the type parameter to see that G++ is attempting to use the template-template overload.

```<code>template <typename X>
bool test() {
    return true;
}

template <template <typename...> class Y>
bool test() {
    return false;
}

template <typename U>
bool templfun() {
    struct A {
        bool f() {
            return test<A>(); // <-- this gives an error
        }
    };
    return test<A>(); // <-- this is ok
}

bool run() {
    return templfun<int>();
}
</code>```

G++ output: (link to godbolt)

```<code><source>:15:27: error: call of overloaded 'test<templfun() [with U = int]::A>()' is ambiguous
   15 |             return test<A>(); // <-- this gives an error
      |                    ~~~~~~~^~

<source>:2:6: note: candidate: 'bool test() [with X = templfun() [with U = int]::A]'
    2 | bool test() {
      |      ^~~~

<source>:7:6: note: candidate: 'bool test() [with Y = templfun()::A]'
    7 | bool test() {
      |      ^~~~
</code>```

Clearly "candidate: 'bool test() [with Y = templfun()::A]'" is bogus.

Note that local types were not allowed as template arguments prior to C++11 (see C++03 § 14.3.1.2), so that could explain the complexity of the G++ implementation.

Body:
Consider the 2 following overloads

template<typename T>
bool test() {
    return true;
}

template<template<typename ...> class T>
bool test() {
    return false;
}

The 1st one works for regular classes, while the 2nd one works for templates that are not instantiated.
For instance:

    std::cout<<test<int>()<<std::endl; <-- this yields 1
    std::cout<<test<std::list>()<<std::endl; <--this yields 0

Now consider the following template function:

template<typename U>
bool templfun(){
    struct A{
        bool f(){
            return test(); // <-- this gives an error
        }
    };
    return test();  // <-- this is ok
}

In GCC it gives an error for ambiguous overload resolution, while Clang compiles.
Interestingly, the second call to test() doesn't produce errors (even in GCC).
Moreover, if I remove the template<typename U> thing on top of templfun, gcc stops complaining.

Is this a bug with GCC or is it illegal code?

Body:
GCC is wrong; struct A is a templated entity but clearly not a template (as it does not start with a template keyword), so there is no ambiguity.

To confirm, we can rename the type parameter to see that G++ is attempting to use the template-template overload.

template <typename X>
bool test() {
    return true;
}

template <template <typename...> class Y>
bool test() {
    return false;
}

template <typename U>
bool templfun() {
    struct A {
        bool f() {
            return test<A>(); // <-- this gives an error
        }
    };
    return test<A>(); // <-- this is ok
}

bool run() {
    return templfun<int>();
}

G++ output: (link to godbolt)

<source>:15:27: error: call of overloaded 'test<templfun() [with U = int]::A>()' is ambiguous
   15 |             return test<A>(); // <-- this gives an error
      |                    ~~~~~~~^~

<source>:2:6: note: candidate: 'bool test() [with X = templfun() [with U = int]::A]'
    2 | bool test() {
      |      ^~~~

<source>:7:6: note: candidate: 'bool test() [with Y = templfun()::A]'
    7 | bool test() {
      |      ^~~~

Clearly "candidate: 'bool test() [with Y = templfun()::A]'" is bogus.

Note that local types were not allowed as template arguments prior to C++11 (see C++03 § 14.3.1.2), so that could explain the complexity of the G++ implementation.


问:
How to pass "everything possible" to by in a function?
I am trying to use data.table within a user facing function in a package I'm working on. I would like this function to behave as data.table-like as possible. This means for example that my function also features a by argument, which is passed to the underlying data.table call within the function. The user should be free to pass anything into "my" by which is possible directly in a data.table.

Citing from ?data.table this includes:

A single unquoted column name: e.g., DT[, .(sa=sum(a)), by=x]

a list() of expressions of column names: e.g., DT[, .(sa=sum(a)), by=.(x=x>0, y)]

a single character string containing comma separated column names (where spaces are significant since column names may contain spaces even at the start or end): e.g., DT[, sum(a), by="x,y,z"]

a character vector of column names: e.g., DT[, sum(a), by=c("x", "y")]

or of the form startcol:endcol: e.g., DT[, sum(a), by=x:z]

Here is a minimal (partially) working example to make my intent clear:

library(data.table)
#> Warning: package 'data.table' was built under R version 3.6.2
sample_dt <- data.table(a = 1:5, b = 5:1)

count_by <- function(dt, by = NULL) {
    by <- substitute(by)
    dt[, .N, by = eval(by, dt, parent.frame())]
}

count_by(sample_dt)
#>    N
#> 1: 5
count_by(sample_dt, by = a)       # refers to 1 from the list above
#>    by N
#> 1:  1 1
#> 2:  2 1
#> 3:  3 1
#> 4:  4 1
#> 5:  5 1
count_by(sample_dt, by = list(a)) # refers to 2 from the list above
#>    a N
#> 1: 1 1
#> 2: 2 1
#> 3: 3 1
#> 4: 4 1
#> 5: 5 1
count_by(sample_dt, by = "a")     # refers to 3 from the list above
#>    a N
#> 1: 1 1
#> 2: 2 1
#> 3: 3 1
#> 4: 4 1
#> 5: 5 1
count_by(sample_dt, by = c("a"))  # refers to 4 from the list above
#> Error in `[.data.table`(dt, , .N, by = eval(by, dt, parent.frame())): 'by' appears to evaluate to column names but isn't c() or key(). Use by=list(...) if you can. Otherwise, by=evalc("a") should work. This is for efficiency so data.table can detect which columns are needed.
count_by(sample_dt, by = a:b)     # refers to 5 from the list above
#>    a b N
#> 1: 1 5 1
#> 2: 2 4 1
#> 3: 3 3 1
#> 4: 4 2 1
#> 5: 5 1 1
```

<p><sup>Created on 2020-02-18 by the reprex package (v0.3.0)</sup></p>

<p>Apart from case 4, everything works as expected using simple substitution and evaluation in the proper context. So my question is:</p>

<p><strong>How can I create functions, which use <code>data.table</code> internally and mimic the original <code>by</code> user interface exactly?</strong></p>

<hr>

<p></p>

<p>Session info</p>

<pre class="lang-r prettyprint-override"><code>devtools::session_info()
#> - Session info ---------------------------------------------------------------
#>  setting  value
#>  version  R version 3.6.1 (2019-07-05)
#>  os       Windows 10 x64
#>  system   x86_64, mingw32
#>  ui       RTerm
#>  language (EN)
#>  collate  German_Germany.1252
#>  ctype    German_Germany.1252
#>  tz       Europe/Berlin
#>  date     2020-02-18
#>
#> - Packages -------------------------------------------------------------------
#>  package     * version date       lib source
#>  assertthat    0.2.1   2019-03-21 [1] CRAN (R 3.6.2)
#>  backports     1.1.5   2019-10-02 [1] CRAN (R 3.6.1)
#>  callr         3.4.1   2020-01-24 [1] CRAN (R 3.6.2)
#>  cli           2.0.1   2020-01-08 [1] CRAN (R 3.6.2)
#>  crayon        1.3.4   2017-09-16 [1] CRAN (R 3.6.2)
#>  data.table  * 1.12.8  2019-12-09 [1] CRAN (R 3.6.2)
#>  desc          1.2.0   2018-05-01 [1] CRAN (R 3.6.2)
#>  devtools      2.2.1   2019-09-24 [1] CRAN (R 3.6.2)
#>  digest        0.6.23  2019-11-23 [1] CRAN (R 3.6.2)
#>  ellipsis      0.3.0   2019-09-20 [1] CRAN (R 3.6.2)
#>  evaluate      0.14    2019-05-28 [1] CRAN (R 3.6.2)
#>  fansi         0.4.1   2020-01-08 [1] CRAN (R 3.6.2)
#>  fs            1.3.1   2019-05-06 [1] CRAN (R 3.6.2)
#>  glue          1.3.1   2019-03-12 [1] CRAN (R 3.6.2)
#>  highr         0.8     2019-03-20 [1] CRAN (R 3.6.2)
#>  htmltools     0.4.0   2019-10-04 [1] CRAN (R 3.6.2)
#>  knitr         1.27    2020-01-16 [1] CRAN (R 3.6.2)
#>  magrittr      1.5     2014-11-22 [1] CRAN (R 3.6.2)
#>  memoise       1.1.0   2017-04-21 [1] CRAN (R 3.6.2)
#>  pkgbuild      1.0.6   2019-10-09 [1] CRAN (R 3.6.2)
#>  pkgload       1.0.2   2018-10-29 [1] CRAN (R 3.6.2)
#>  prettyunits   1.1.1   2020-01-24 [1] CRAN (R 3.6.2)
#>  processx      3.4.1   2019-07-18 [1] CRAN (R 3.6.2)
#>  ps            1.3.0   2018-12-21 [1] CRAN (R 3.6.2)
#>  R6            2.4.1   2019-11-12 [1] CRAN (R 3.6.2)
#>  Rcpp          1.0.3   2019-11-08 [1] CRAN (R 3.6.2)
#>  remotes       2.1.0   2019-06-24 [1] CRAN (R 3.6.2)
#>  rlang         0.4.4   2020-01-28 [1] CRAN (R 3.6.2)
#>  rmarkdown     2.1     2020-01-20 [1] CRAN (R 3.6.2)
#>  rprojroot     1.3-2   2018-01-03 [1] CRAN (R 3.6.2)
#>  sessioninfo   1.1.1   2018-11-05 [1] CRAN (R 3.6.2)
#>  stringi       1.4.4   2020-01-09 [1] CRAN (R 3.6.2)
#>  stringr       1.4.0   2019-02-10 [1] CRAN (R 3.6.2)
#>  testthat      2.3.1   2019-12-01 [1] CRAN (R 3.6.2)
#>  usethis       1.5.1   2019-07-04 [1] CRAN (R 3.6.2)
#>  withr         2.1.2   2018-03-15 [1] CRAN (R 3.6.2)
#>  xfun          0.12    2020-01-13 [1] CRAN (R 3.6.2)
#>  yaml          2.2.1   2020-02-01 [1] CRAN (R 3.6.2)
#>
#> [1] C:/Program Files/R/library
</code>```

答:
Is there a particular reason for using eval inside the data.table? I think this would be better:

```<code>count_by <- function(dt, by = NULL) {
  eval(substitute(dt[, .N, by = by]))
}
</code>```

It passes all test cases (of course). Even the first one, where your function fails with column name by.

Body:
I am trying to use data.table within a user facing function in a package I'm working on. I would like this function to behave as data.table-like as possible. This means for example that my function also features a by argument, which is passed to the underlying data.table call within the function. The user should be free to pass anything into "my" by which is possible directly in a data.table.

Citing from ?data.table this includes:

A single unquoted column name: e.g., DT[, .(sa=sum(a)), by=x]

a list() of expressions of column names: e.g., DT[, .(sa=sum(a)), by=.(x=x>0, y)]

a single character string containing comma separated column names (where spaces are significant since column names may contain spaces even at the start or end): e.g., DT[, sum(a), by="x,y,z"]

a character vector of column names: e.g., DT[, sum(a), by=c("x", "y")]

or of the form startcol:endcol: e.g., DT[, sum(a), by=x:z]

Here is a minimal (partially) working example to make my intent clear:

library(data.table)
#> Warning: package 'data.table' was built under R version 3.6.2
sample_dt <- data.table(a = 1:5, b = 5:1)

count_by <- function(dt, by = NULL) {
    by <- substitute(by)
    dt[, .N, by = eval(by, dt, parent.frame())]
}

count_by(sample_dt)
#>    N
#> 1: 5
count_by(sample_dt, by = a)       # refers to 1 from the list above
#>    by N
#> 1:  1 1
#> 2:  2 1
#> 3:  3 1
#> 4:  4 1
#> 5:  5 1
count_by(sample_dt, by = list(a)) # refers to 2 from the list above
#>    a N
#> 1: 1 1
#> 2: 2 1
#> 3: 3 1
#> 4: 4 1
#> 5: 5 1
count_by(sample_dt, by = "a")     # refers to 3 from the list above
#>    a N
#> 1: 1 1
#> 2: 2 1
#> 3: 3 1
#> 4: 4 1
#> 5: 5 1
count_by(sample_dt, by = c("a"))  # refers to 4 from the list above
#> Error in `[.data.table`(dt, , .N, by = eval(by, dt, parent.frame())): 'by' appears to evaluate to column names but isn't c() or key(). Use by=list(...) if you can. Otherwise, by=evalc("a") should work. This is for efficiency so data.table can detect which columns are needed.
count_by(sample_dt, by = a:b)     # refers to 5 from the list above
#>    a b N
#> 1: 1 5 1
#> 2: 2 4 1
#> 3: 3 3 1
#> 4: 4 2 1
#> 5: 5 1 1

Created on 2020-02-18 by the reprex package (v0.3.0)

Apart from case 4, everything works as expected using simple substitution and evaluation in the proper context. So my question is:

How can I create functions, which use data.table internally and mimic the original by user interface exactly?

Session info

devtools::session_info()
#> - Session info ---------------------------------------------------------------
#>  setting  value
#>  version  R version 3.6.1 (2019-07-05)
#>  os       Windows 10 x64
#>  system   x86_64, mingw32
#>  ui       RTerm
#>  language (EN)
#>  collate  German_Germany.1252
#>  ctype    German_Germany.1252
#>  tz       Europe/Berlin
#>  date     2020-02-18
#>
#> - Packages -------------------------------------------------------------------
#>  package     * version date       lib source
#>  assertthat    0.2.1   2019-03-21 [1] CRAN (R 3.6.2)
#>  backports     1.1.5   2019-10-02 [1] CRAN (R 3.6.1)
#>  callr         3.4.1   2020-01-24 [1] CRAN (R 3.6.2)
#>  cli           2.0.1   2020-01-08 [1] CRAN (R 3.6.2)
#>  crayon        1.3.4   2017-09-16 [1] CRAN (R 3.6.2)
#>  data.table  * 1.12.8  2019-12-09 [1] CRAN (R 3.6.2)
#>  desc          1.2.0   2018-05-01 [1] CRAN (R 3.6.2)
#>  devtools      2.2.1   2019-09-24 [1] CRAN (R 3.6.2)
#>  digest        0.6.23  2019-11-23 [1] CRAN (R 3.6.2)
#>  ellipsis      0.3.0   2019-09-20 [1] CRAN (R 3.6.2)
#>  evaluate      0.14    2019-05-28 [1] CRAN (R 3.6.2)
#>  fansi         0.4.1   2020-01-08 [1] CRAN (R 3.6.2)
#>  fs            1.3.1   2019-05-06 [1] CRAN (R 3.6.2)
#>  glue          1.3.1   2019-03-12 [1] CRAN (R 3.6.2)
#>  highr         0.8     2019-03-20 [1] CRAN (R 3.6.2)
#>  htmltools     0.4.0   2019-10-04 [1] CRAN (R 3.6.2)
#>  knitr         1.27    2020-01-16 [1] CRAN (R 3.6.2)
#>  magrittr      1.5     2014-11-22 [1] CRAN (R 3.6.2)
#>  memoise       1.1.0   2017-04-21 [1] CRAN (R 3.6.2)
#>  pkgbuild      1.0.6   2019-10-09 [1] CRAN (R 3.6.2)
#>  pkgload       1.0.2   2018-10-29 [1] CRAN (R 3.6.2)
#>  prettyunits   1.1.1   2020-01-24 [1] CRAN (R 3.6.2)
#>  processx      3.4.1   2019-07-18 [1] CRAN (R 3.6.2)
#>  ps            1.3.0   2018-12-21 [1] CRAN (R 3.6.2)
#>  R6            2.4.1   2019-11-12 [1] CRAN (R 3.6.2)
#>  Rcpp          1.0.3   2019-11-08 [1] CRAN (R 3.6.2)
#>  remotes       2.1.0   2019-06-24 [1] CRAN (R 3.6.2)
#>  rlang         0.4.4   2020-01-28 [1] CRAN (R 3.6.2)
#>  rmarkdown     2.1     2020-01-20 [1] CRAN (R 3.6.2)
#>  rprojroot     1.3-2   2018-01-03 [1] CRAN (R 3.6.2)
#>  sessioninfo   1.1.1   2018-11-05 [1] CRAN (R 3.6.2)
#>  stringi       1.4.4   2020-01-09 [1] CRAN (R 3.6.2)
#>  stringr       1.4.0   2019-02-10 [1] CRAN (R 3.6.2)
#>  testthat      2.3.1   2019-12-01 [1] CRAN (R 3.6.2)
#>  usethis       1.5.1   2019-07-04 [1] CRAN (R 3.6.2)
#>  withr         2.1.2   2018-03-15 [1] CRAN (R 3.6.2)
#>  xfun          0.12    2020-01-13 [1] CRAN (R 3.6.2)
#>  yaml          2.2.1   2020-02-01 [1] CRAN (R 3.6.2)
#>
#> [1] C:/Program Files/R/library

Body:
Is there a particular reason for using eval inside the data.table? I think this would be better:

count_by <- function(dt, by = NULL) {
  eval(substitute(dt[, .N, by = by]))
}

It passes all test cases (of course). Even the first one, where your function fails with column name by.


问:
Android Studio: Can't start Git
When I start Android Studio there's a message

Can't start Git: C:\Program Files (x86)\Git\cmd\git.cmd Probably the
  path to Git executable is not valid. Fix it.

But I can see that the git.cmd IS there. How do I fix the issue then?

答:
I faced a similar issue, you can refer to my answer here.

But since links die too often, I'm going to leave a little part of the answer that might help:

For people still having this error even if their git is installed
  and android studio is pointing to its path, go to Settings ->
  Version Control -> Git and delete everything inside the text box
  with the label Path to Git executable, your android studio or what
  ever JetBrains product you're using, will auto-detect it.

Title: Android Studio: Can't start Git