问:
Model design django
The model looks as follows. Where apps is a field which can have only app1 and app2 as choices which can be incremented in the future. Also, each app choice (app1, app2) should be a model with fields representing features. How to implement this in Django models.

```<code>apps:
      app1:
        feature_app1_1: "Data"
        feature_app1_2: "Data"
      app2:
        feature_app2_1: "Data"
        feature_app2_2: "Data"
</code>```

答:
This sounds like you need many-to-many relationships. The Many to Many field will limit choices to the models you have created, so if you only have 2 apps, then those will be your only choices. As you add more, they will appear.

So, I imagine you want something like this:

You say "apps" is a field, so if that is a field on a parent model.

```<code>Class Foo(models.Model):
    apps = models.ManyToManyField(App)

Class App(models.Model):
    name = models.Charfield(max_legnth=100) #App name
    features = models.ManytoManyField(Feature)

Class Feature(models.Model):
    name = models.Charfield(max_legnth=100) #Feature name
    ...... # Your data fields here.
</code>```

Your parent class will have a many to many field ("apps") linking to all the apps you want on it, and then each app will link to every feature ("features") you need. Then each feature contains the data.

Title: Model design django

Body:
The model looks as follows. Where apps is a field which can have only app1 and app2 as choices which can be incremented in the future. Also, each app choice (app1, app2) should be a model with fields representing features. How to implement this in Django models.

apps:
      app1:
        feature_app1_1: "Data"
        feature_app1_2: "Data"
      app2:
        feature_app2_1: "Data"
        feature_app2_2: "Data"

Body:
This sounds like you need many-to-many relationships. The Many to Many field will limit choices to the models you have created, so if you only have 2 apps, then those will be your only choices. As you add more, they will appear.

So, I imagine you want something like this:

You say "apps" is a field, so if that is a field on a parent model.

Class Foo(models.Model):
    apps = models.ManyToManyField(App)

Class App(models.Model):
    name = models.Charfield(max_legnth=100) #App name
    features = models.ManytoManyField(Feature)

Class Feature(models.Model):
    name = models.Charfield(max_legnth=100) #Feature name
    ...... # Your data fields here.

Your parent class will have a many to many field ("apps") linking to all the apps you want on it, and then each app will link to every feature ("features") you need. Then each feature contains the data.


来源: stackexchange

问:
How to specify the schemalocation in a generated wsdl
When I generate a wsdl with

```<code>myservice?wsdl
</code>```

Imports have no schemaLocation

```<code><xs:import namespace="http://mynamespace" />
</code>```

How do I get scemaLocation included?

```<code><xs:import namespace="http://mynamespace" schemaLocation="myxsd.xsd"/>
</code>```

I can't find any information on this, can someone put me on to something? Do I have to go through a binding file?

答: You could try to use @XmlSchema annotation, which is set in package-info.java file. Responsible for schemaLocation attribute is field location, which was introduced in JAXB2.1.</p>

ContentLicense: CC BY-SA 4.0

Body:
When I generate a wsdl with

myservice?wsdl

Imports have no schemaLocation

<xs:import namespace="http://mynamespace" />

How do I get scemaLocation included?

<xs:import namespace="http://mynamespace" schemaLocation="myxsd.xsd"/>

I can't find any information on this, can someone put me on to something? Do I have to go through a binding file?


问:
Is there a way to intercept setters and getters in C#?
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

```<code>public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</code>```

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.

答: You will have to write the properties in full to achieve this.</p>

ContentLicense: CC BY-SA 3.0

Body:
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.


问:
Assign an incremental number to a field in a MongoDB aggregation
I have a MongoDB aggregation and each document has a field (groupNumber) like this:

I need that each groupNumber has a different number for each document (could be incremental 1,2,3..)

Most of the solutions that I had found are using "find" like this one , but I think that cannot be used in an aggregation.

Thanks in advance.

答:
You can do this with a lookup, but I don't think it will scale well.  I would think this should be persisted in some way, perhaps $out to another collection, so that the numbers are stable and deleting or inserting a document won't change the numbers for any other group.

```<code>db.target.aggregate([
    {"$lookup":{
        "from":"target",
        "as":"looked",
        "let":{"srcId":"$_id"},
        "pipeline":[
          {"$match":{"$expr":{"$lte":["$_id","$$srcId"]}}},
          {"$group":{"_id":"null", "cnt":{"$sum":1}}}
        ]
    }},
    {"$addFields":{"groupNumber":{"$arrayElemAt":["$looked.cnt",0]}}},
    {"$project":{"looked":0}}
])
</code>```

Body:
You can do this with a lookup, but I don't think it will scale well.  I would think this should be persisted in some way, perhaps $out to another collection, so that the numbers are stable and deleting or inserting a document won't change the numbers for any other group.

db.target.aggregate([
    {"$lookup":{
        "from":"target",
        "as":"looked",
        "let":{"srcId":"$_id"},
        "pipeline":[
          {"$match":{"$expr":{"$lte":["$_id","$$srcId"]}}},
          {"$group":{"_id":"null", "cnt":{"$sum":1}}}
        ]
    }},
    {"$addFields":{"groupNumber":{"$arrayElemAt":["$looked.cnt",0]}}},
    {"$project":{"looked":0}}
])


问:
Using 'exec' in bash_profile stops login shell
I'm creating the following .bash_profile (from linuxfromscratch guide) for lfs user:

```<code>exec env -i HOME=$HOME TERM=$TERM PS1='\u:\w\$ ' /bin/bash
</code>```

When executing su - lfs I get:

```<code>[1]+  Stopped                 su - lfs
</code>```

Executing fg resumes lfs' user shell. Why is this happening?

答:
That's because exec executes the code in the current process. Normally a command is executed in a child shell/environment. Try the following:

$ bash        # open second shell
$ exec false  # close second shell
$ echo $?     # get exit code
$ exit        # close terminal
```

The man page isn't really helpful here. I often use exec if I run a script through a Qt process and it should end after some period of time, regardless whether the command if finished or not.

Body:
I'm creating the following .bash_profile (from linuxfromscratch guide) for lfs user:

exec env -i HOME=$HOME TERM=$TERM PS1='\u:\w\$ ' /bin/bash

When executing su - lfs I get:

[1]+  Stopped                 su - lfs

Executing fg resumes lfs' user shell. Why is this happening?

Body:
That's because exec executes the code in the current process. Normally a command is executed in a child shell/environment. Try the following:

$ bash        # open second shell
$ exec false  # close second shell
$ echo $?     # get exit code
$ exit        # close terminal

The man page isn't really helpful here. I often use exec if I run a script through a Qt process and it should end after some period of time, regardless whether the command if finished or not.


问:
Get the sign of a number in C# without conditional statement
Just out of curiosity, is there a way to get the sign of a number, any kind (but obviously a signed type), not just integer using some bitwise/masking, or other kind of, operation?
That is without using any conditional statement or calling the Math.Sign() function.

Thanks in advance!

EDIT: I recognize it was a misleading question. What I had in mind more likely something like: "get the same output of the Math.Sign() or, simplifying get 0 if x <= 0, 1 otherwise".

EDIT #2: to all those asking for code, I didn't have any in mind when I posted the question, but here's an example I came up with, just to give a context of a possible application:

```<code>x = (x < 0) ? 0 : x;
</code>```

Having the sign into a variable could lead to:

```<code>x = sign * x; //where sign = 0 for x <= 0, otherwise sign = 1;
</code>```

The aim would be to achieve the same result as the above :)

EDIT #3: FOUND IT! :D

```<code>// THIS IS NOT MEANT TO BE PLAIN C#!
// Returns 0 if x <= 0, 1 otherwise.
int SignOf(x)
{
    return (1+x-(x+1)%x)/x;
}
</code>```

Thanks to everyone!

答:
if x==0 you will have a divby0 exception with this code you posted:

```<code>int SignOf(x) {
    return (1+x-(x+1)%x)/x; }
</code>```

Body:
Just out of curiosity, is there a way to get the sign of a number, any kind (but obviously a signed type), not just integer using some bitwise/masking, or other kind of, operation?
That is without using any conditional statement or calling the Math.Sign() function.

Thanks in advance!

EDIT: I recognize it was a misleading question. What I had in mind more likely something like: "get the same output of the Math.Sign() or, simplifying get 0 if x <= 0, 1 otherwise".

EDIT #2: to all those asking for code, I didn't have any in mind when I posted the question, but here's an example I came up with, just to give a context of a possible application:

x = (x < 0) ? 0 : x;

Having the sign into a variable could lead to:

x = sign * x; //where sign = 0 for x <= 0, otherwise sign = 1;

The aim would be to achieve the same result as the above :)

EDIT #3: FOUND IT! :D

// THIS IS NOT MEANT TO BE PLAIN C#!
// Returns 0 if x <= 0, 1 otherwise.
int SignOf(x)
{
    return (1+x-(x+1)%x)/x;
}

Thanks to everyone!

Body:
if x==0 you will have a divby0 exception with this code you posted:

int SignOf(x) {
    return (1+x-(x+1)%x)/x; }


问:
Batch script Is there a way to loop through a log of directories and look for a folder with a specific name in each directory
Sorry if the question is confusing. Basically, I have a log.txt with a list of directories. Is there a way to loop through the list, and see if any of the directories contain a folder with a specific name.
So if the log has :

C:\test1

C:\test2

and we are looking for a folder called "test3" inside any of the directories in the log, then output that it was found.

edit:
I am new to batch and kinda mashed other code i found on here to make this, apologies if its a mess.

```<code>for /F "tokens=*" %%Z in (%dir1%\log.txt) do (

    cd %%Z

    for /d /r "%%Z" %%a in (*) do if /i "%%~nxa"=="test3" set "foldername=%%a"

    echo "%foldername%"
)
</code>```

where dir1 is the directory I'm using elsewhere in the code, and test3 is the string I'm looking for in the subfolder name.

I think I need to use SetLocal EnableDelayedExpansion? but I don't really understand it.

答:
The following syntax will return all lines within your text file that contain a folder name you specify:

```<code>type log.txt | findstr foldername
</code>```

I tested this by creating a text file that contained the following:

test1 line 1

    test2 line 2

    test3 line 3

    test2 line 4

And then I ran:

```<code>type mytextfile.txt | findstr test2
</code>```

And it returned:

test2 line 2

    test2 line 4

Is this basically what you were looking for?

Body:
Sorry if the question is confusing. Basically, I have a log.txt with a list of directories. Is there a way to loop through the list, and see if any of the directories contain a folder with a specific name.
So if the log has :

C:\test1

C:\test2

and we are looking for a folder called "test3" inside any of the directories in the log, then output that it was found.

edit:
I am new to batch and kinda mashed other code i found on here to make this, apologies if its a mess.

for /F "tokens=*" %%Z in (%dir1%\log.txt) do (

    cd %%Z

    for /d /r "%%Z" %%a in (*) do if /i "%%~nxa"=="test3" set "foldername=%%a"

    echo "%foldername%"
)

where dir1 is the directory I'm using elsewhere in the code, and test3 is the string I'm looking for in the subfolder name.

I think I need to use SetLocal EnableDelayedExpansion? but I don't really understand it.

Body:
The following syntax will return all lines within your text file that contain a folder name you specify:

type log.txt | findstr foldername

I tested this by creating a text file that contained the following:

test1 line 1

    test2 line 2

    test3 line 3

    test2 line 4

And then I ran:

type mytextfile.txt | findstr test2

And it returned:

test2 line 2

    test2 line 4

Is this basically what you were looking for?


问:
Python, Regular Expression, string to string with dots
Could someone help me with this:

Version 1:

```<code>import re
text = "12032020"
Version **ONE**
r = re.compile(r'\d{8}')
r1 = re.compile(r'\d{2}\.\d{2}\.\d{4}')
output = re.sub(r, r1, text)
</code>```

Version 2:

```<code>output1 = re.sub(r'\d{8}', r'\d{2}\.\d{2}\.\d{4})', text)
print(output)
</code>```

I expect outcome:

```<code>12.03.2020
</code>```

Not working

答:
How about doing string substitution with:

```<code>(\d{2})(\d{2})(\d{4})
</code>```

Here would be an example from regex101:

Here you would capture each of the three groups (2-digit, 2-digit, 4-digit) and then re-insert those three captured strings with a dot between them. In python:

```<code>>>> re.sub(r'(\d{2})(\d{2})(\d{4})', r'\1.\2.\3', '12032020')
'12.03.2020'
</code>```

Though it looks like you're trying to parse a date so why not do:

```<code>>>> datetime.datetime.strptime(text, '%m%d%Y')
datetime.datetime(2020, 3, 12, 0, 0)
</code>```

Body:
Could someone help me with this:

Version 1:

import re
text = "12032020"
Version **ONE**
r = re.compile(r'\d{8}')
r1 = re.compile(r'\d{2}\.\d{2}\.\d{4}')
output = re.sub(r, r1, text)

Version 2:

output1 = re.sub(r'\d{8}', r'\d{2}\.\d{2}\.\d{4})', text)
print(output)

I expect outcome:

12.03.2020

Not working

Body:
How about doing string substitution with:

(\d{2})(\d{2})(\d{4})

Here would be an example from regex101:

Here you would capture each of the three groups (2-digit, 2-digit, 4-digit) and then re-insert those three captured strings with a dot between them. In python:

>>> re.sub(r'(\d{2})(\d{2})(\d{4})', r'\1.\2.\3', '12032020')
'12.03.2020'

Though it looks like you're trying to parse a date so why not do:

>>> datetime.datetime.strptime(text, '%m%d%Y')
datetime.datetime(2020, 3, 12, 0, 0)


问:
How to highlight a cell using the hex color value within the cell?
I have a spreadsheet of symbols and matching hex colors. I want to fill the cell itself (or the one next to it) with the hex color within the cell. I've read a bit about "conditional formatting", and I think that's the way to do it.

How might I achieve the result I would like?

答:
This is another option - it updates the cell color when you select the cell assuming the value in the cell starts with "#" and is 7 characters.</p>

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  If (Left(ActiveCell.Text, 1) = "#" And Len(ActiveCell.Text) = 7) Then
    ActiveCell.Interior.Color = WorksheetFunction.Hex2Dec(Mid$(ActiveCell.Text, 2))
End If

End Sub
</code>```

Body:
This is another option - it updates the cell color when you select the cell assuming the value in the cell starts with "#" and is 7 characters.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  If (Left(ActiveCell.Text, 1) = "#" And Len(ActiveCell.Text) = 7) Then
    ActiveCell.Interior.Color = WorksheetFunction.Hex2Dec(Mid$(ActiveCell.Text, 2))
End If

End Sub


问:
Create an Ad Creatives over LinkedIn API V2 not working
I use the api version 2.0 and want to create an ad creatives https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads/account-structure/create-and-manage-creatives#create-a-sponsored-content-share

PHP Code

```<code>    POST https://api.linkedin.com/v2/adCreativesV2

    {
      "campaign": "urn:li:sponsoredCampaign:XXXXXXXX",
      "reference": "urn:li:share:XXXXXXXXXXXXX",
      "status": "ACTIVE",
      "type": "SPONSORED_STATUS_UPDATE",
      "variables": {
          "data": {
              "com.linkedin.ads.SponsoredUpdateCreativeVariables": {
                  "directSponsoredContent": true,
                  "share": "urn:li:share:XXXXXXXXXX",
                  "activity": "urn:li:activity:XXXXXXXXXXX"
              }
          }
      }
   }
</code>```

API response

```<code>{"message":"Your application is not configured to access the related advertiser account(s), please ensure you have added the account ID(s) in your Account Management list.","status":403}
</code>```

Any idea, How to fix this error?

答:
Try with an empty object for the SponsoredUpdateCreativeVariables variable as in the example in the doc:

```<code>{
  "campaign": "urn:li:sponsoredCampaign:XXXXXXXX",
  "reference": "urn:li:share:XXXXXXXXXXXXX",
  "status": "ACTIVE",
  "type": "SPONSORED_STATUS_UPDATE",
  "variables": {
      "data": {
          "com.linkedin.ads.SponsoredUpdateCreativeVariables": {}
      }
  }
</code>```

}

Body:
I use the api version 2.0 and want to create an ad creatives https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads/account-structure/create-and-manage-creatives#create-a-sponsored-content-share

PHP Code

    POST https://api.linkedin.com/v2/adCreativesV2

    {
      "campaign": "urn:li:sponsoredCampaign:XXXXXXXX",
      "reference": "urn:li:share:XXXXXXXXXXXXX",
      "status": "ACTIVE",
      "type": "SPONSORED_STATUS_UPDATE",
      "variables": {
          "data": {
              "com.linkedin.ads.SponsoredUpdateCreativeVariables": {
                  "directSponsoredContent": true,
                  "share": "urn:li:share:XXXXXXXXXX",
                  "activity": "urn:li:activity:XXXXXXXXXXX"
              }
          }
      }
   }

API response

{"message":"Your application is not configured to access the related advertiser account(s), please ensure you have added the account ID(s) in your Account Management list.","status":403}

Any idea, How to fix this error?

Body:
Try with an empty object for the SponsoredUpdateCreativeVariables variable as in the example in the doc:

{
  "campaign": "urn:li:sponsoredCampaign:XXXXXXXX",
  "reference": "urn:li:share:XXXXXXXXXXXXX",
  "status": "ACTIVE",
  "type": "SPONSORED_STATUS_UPDATE",
  "variables": {
      "data": {
          "com.linkedin.ads.SponsoredUpdateCreativeVariables": {}
      }
  }

}


答:
Not out of the box. You would need to insert code into each properties setter and getter, either manually or automatically using IL rewriting.

When you want to do it manually, you can't use automatic properties any more.

When you want to do it automatically, have a look at AOP.

Title: Is there a way to intercept setters and getters in C#?


问:
Convert int array to std::vector<int*>
I'm trying to "convert" an integer C style array to std::vector<int*> without using a for loop, or rather insert pointers of all array items in a vector.

I'm currently implementing this by doing the follow:

```<code>for (size_t i = 0; i < 5; i++)
{
    vector.push_back(&values[i]);
}
</code>```

Is it possible to implement this by using std::vector::insert() and std::being/end?

答:
Note: as pointed out in comments my below answer is wrongly related to vector<int> not vector<int*> which was asked for in question.

Solution with std::copy and C-style array:

```<code>int ar[] = {1,2,3,4,3,2,1};
std::vector<int> vec;
std::copy(ar, ar+sizeof(ar)/sizeof(ar[0]), back_inserter(vec));
</code>```

Title: Convert int array to std::vector<int*>

Body:
I'm trying to "convert" an integer C style array to std::vector<int*> without using a for loop, or rather insert pointers of all array items in a vector.

I'm currently implementing this by doing the follow:

for (size_t i = 0; i < 5; i++)
{
    vector.push_back(&values[i]);
}

Is it possible to implement this by using std::vector::insert() and std::being/end?

Body:
Note: as pointed out in comments my below answer is wrongly related to vector<int> not vector<int*> which was asked for in question.

Solution with std::copy and C-style array:

int ar[] = {1,2,3,4,3,2,1};
std::vector<int> vec;
std::copy(ar, ar+sizeof(ar)/sizeof(ar[0]), back_inserter(vec));


问:
Find and print outliers of data using Numpy
I want to find any outliers in a csv data table column using Pandas and Numpy. Currently I can get the the outliers on the higher end side but I'm not sure how to get the minimum outliers or the "lower" outliers if that makes sense.

Here is the function that I am using:

```<code>def detect_outlier(data_1):
    outliers = []
    threshold = 3
    mean_1 = np.mean(data_1)
    std_1 = np.std(data_1)

    for y in data_1:
        z_score = (y - mean_1) / std_1
        if np.abs(z_score) > threshold:
            outliers.append(y)
    return outliers
</code>```

This returns the outliers with a z-score greater than 3(threshold) and it works. I tried changing the threshold to -3 to get the outliers on the lower spectrum but it just returns all the values of the specific column. Does that just signify that there are no lower outliers or am I doing something wrong? All the questions that I find deal with removing the outliers but I just want to display any outliers.

Also some of the outliers using the function provided for the columns return an empty array, does this signify that there are no outliers for that specific column?

The dataset is too large to post here but here is the link if it can help answer this question:
https://archive.ics.uci.edu/ml/datasets/Absenteeism+at+work

答:
I changed your outlier logic and it works on an artificial example.

Rather than checking if the absolute value of your z_score is greater than the threshold, you should check if the raw z_score is less than your threshold in this case.

See below.

```<code>import random
import numpy as np

    def detect_outlier(data_1):
        outliers = []
        threshold = -3
        mean_1 = np.mean(data_1)
        std_1 = np.std(data_1)
        for y in data_1:
            z_score = (y - mean_1) / std_1
            if z_score < threshold:
                outliers.append(y)
        return outliers

data = [random.randrange(200,300,1) for i in range(1000)]
data.append(0.01)

result = detect_outlier(data)
print(f'Outlier: {result}')
</code>```

Output:

```<code>Outlier: [0.01]
</code>```

It's also possible that your dataset doesn't have extreme outliers on the negative side of the distribution, but the logic would have missed them regardless.

Body:
I want to find any outliers in a csv data table column using Pandas and Numpy. Currently I can get the the outliers on the higher end side but I'm not sure how to get the minimum outliers or the "lower" outliers if that makes sense.

Here is the function that I am using:

def detect_outlier(data_1):
    outliers = []
    threshold = 3
    mean_1 = np.mean(data_1)
    std_1 = np.std(data_1)

    for y in data_1:
        z_score = (y - mean_1) / std_1
        if np.abs(z_score) > threshold:
            outliers.append(y)
    return outliers

This returns the outliers with a z-score greater than 3(threshold) and it works. I tried changing the threshold to -3 to get the outliers on the lower spectrum but it just returns all the values of the specific column. Does that just signify that there are no lower outliers or am I doing something wrong? All the questions that I find deal with removing the outliers but I just want to display any outliers.

Also some of the outliers using the function provided for the columns return an empty array, does this signify that there are no outliers for that specific column?

The dataset is too large to post here but here is the link if it can help answer this question:
https://archive.ics.uci.edu/ml/datasets/Absenteeism+at+work

Body:
I changed your outlier logic and it works on an artificial example.

Rather than checking if the absolute value of your z_score is greater than the threshold, you should check if the raw z_score is less than your threshold in this case.

See below.

import random
import numpy as np

    def detect_outlier(data_1):
        outliers = []
        threshold = -3
        mean_1 = np.mean(data_1)
        std_1 = np.std(data_1)
        for y in data_1:
            z_score = (y - mean_1) / std_1
            if z_score < threshold:
                outliers.append(y)
        return outliers

data = [random.randrange(200,300,1) for i in range(1000)]
data.append(0.01)

result = detect_outlier(data)
print(f'Outlier: {result}')

Output:

Outlier: [0.01]

It's also possible that your dataset doesn't have extreme outliers on the negative side of the distribution, but the logic would have missed them regardless.


问:
Return all objects in array
I'm missing something super obvious here so please excuse my ignorance :(

I have a set of 5 checkboxes and would like to print out steps based on what checkbox was chosen. I'll need this for a bigger output so I'm storing the selection in it's own variable like so:

```<code>        $checkBox.find('input:checked').each(function() {
        $rec = $(this).val() + "\n";
        console.log($rec);

    });
</code>```

Everything returns fine when I select all 5 checkboxes and check in console:

console.log

However, I want to use the output stored in $rec to use later so I did this to see what it will look like:

```<code>        $checkBox.find('input:checked').each(function() {

        $rec = $(this).val() + "\n";
        console.log($rec);

    });

// call rec into text input
        $textOutput.val($textOutput.val() + $rec + "\n");
        console.log($rec);
</code>```

But for some reason, only the "Do Step 5" is returned when calling $rec again

second console.log

Since I'm already storing output of the 5 checkboxes in $rec why can't I access all again rather than just the last object?

答:
Try to make $rec an array[]

and push your values into it. Something like

```<code>$rec.push($(this).val() + "\n");
</code>```

Title: Return all objects in array

Body:
I'm missing something super obvious here so please excuse my ignorance :(

I have a set of 5 checkboxes and would like to print out steps based on what checkbox was chosen. I'll need this for a bigger output so I'm storing the selection in it's own variable like so:

        $checkBox.find('input:checked').each(function() {
        $rec = $(this).val() + "\n";
        console.log($rec);

    });

Everything returns fine when I select all 5 checkboxes and check in console:

console.log

However, I want to use the output stored in $rec to use later so I did this to see what it will look like:

        $checkBox.find('input:checked').each(function() {

        $rec = $(this).val() + "\n";
        console.log($rec);

    });

// call rec into text input
        $textOutput.val($textOutput.val() + $rec + "\n");
        console.log($rec);

But for some reason, only the "Do Step 5" is returned when calling $rec again

second console.log

Since I'm already storing output of the 5 checkboxes in $rec why can't I access all again rather than just the last object?

Body:
Try to make $rec an array[]

and push your values into it. Something like

$rec.push($(this).val() + "\n");


问:
xml to make rounded corners on button is not working
I have many rounded buttons in my app, but some of my buttons dont work with any kind of background, doesnt matter if its rounded corners or changed color. Here is the XML file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/colorAppBackground"
    tools:context=".activities.GameActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:orientation="horizontal"
        android:weightSum="10">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2" />

        <TextView
            android:id="@+id/textViewGameCategory"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="6"
            android:gravity="center"
            android:textSize="28sp"
            android:textColor="@color/colorBlack"
            tools:text="Gemälde"/>

        <TextView
            android:id="@+id/textViewGameCounter"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:gravity="center"
            android:textSize="20sp"
            tools:text="9/107"/>
    </LinearLayout>

    <View style="@style/Divider" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="10">

        <TextView
            android:id="@+id/textViewGameQuestion"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginStart="15dp"
            android:layout_marginLeft="15dp"
            android:layout_marginEnd="15dp"
            android:layout_marginRight="15dp"
            android:layout_weight="1.5"
            android:gravity="center"
            android:textSize="20sp"
            android:textColor="@color/colorBlack"
            tools:text="Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam"/>

        <ImageView
            android:id="@+id/imageViewCardFlip"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:paddingStart="15dp"
            android:paddingLeft="15dp"
            android:paddingEnd="15dp"
            android:paddingRight="15dp"
            android:paddingBottom="15dp"
            android:layout_weight="3.5"
            android:src="@drawable/cover_quizgame" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:orientation="vertical"
            android:layout_weight="5"
            android:weightSum="2">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:orientation="horizontal"
                android:weightSum="2">

                <Button
                    android:id="@+id/buttonGameOptionOne"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginEnd="5dp"
                    android:layout_marginRight="5dp"
                    android:layout_marginTop="5dp"
                    android:layout_marginBottom="5dp"
                    android:layout_weight="1"
                    android:textSize="12sp"
                    android:gravity="center"
                    android:textAllCaps="false"
                    android:padding="3dp"
                    android:background="@drawable/btn_answer_rounded_corners" />

                <Button
                    android:id="@+id/buttonGameOptionTwo"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_marginStart="5dp"
                    android:layout_marginLeft="5dp"
                    android:layout_marginEnd="15dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="5dp"
                    android:layout_marginBottom="5dp"
                    android:layout_weight="1"
                    android:textSize="12sp"
                    android:gravity="center"
                    android:textAllCaps="false"
                    android:padding="3dp"
                    android:background="@drawable/btn_answer_rounded_corners" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:orientation="horizontal"
                android:weightSum="2">

                <Button
                    android:id="@+id/buttonGameOptionThree"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginEnd="5dp"
                    android:layout_marginRight="5dp"
                    android:layout_marginTop="5dp"
                    android:layout_marginBottom="5dp"
                    android:layout_weight="1"
                    android:textSize="12sp"
                    android:gravity="center"
                    android:textAllCaps="false"
                    android:padding="3dp"
                    android:background="@drawable/btn_answer_rounded_corners" />

                <Button
                    android:id="@+id/buttonGameOptionFour"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_marginStart="5dp"
                    android:layout_marginLeft="5dp"
                    android:layout_marginEnd="15dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="5dp"
                    android:layout_marginBottom="5dp"
                    android:layout_weight="1"
                    android:textSize="12sp"
                    android:gravity="center"
                    android:textAllCaps="false"
                    android:padding="3dp"
                    android:background="@drawable/btn_answer_rounded_corners" />
            </LinearLayout>

            <Button
                android:id="@+id/buttonContinue"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginStart="70dp"
                android:layout_marginLeft="70dp"
                android:layout_marginEnd="70dp"
                android:layout_marginRight="70dp"
                android:layout_marginBottom="15dp"
                android:layout_marginTop="15dp"
                android:background="@drawable/btn_continue_rounded_corners"
                android:text="@string/singlegame_continue" />

            <ProgressBar
                android:id="@+id/progressBarSingleGame"
                style="?android:attr/progressBarStyleHorizontal"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginStart="15dp"
                android:layout_marginLeft="15dp"
                android:layout_marginEnd="15dp"
                android:layout_marginRight="15dp"
                android:layout_marginBottom="15dp"
                android:layout_marginTop="15dp"
                android:progressDrawable="@drawable/progressbar_greenprogress"
                android:visibility="gone"
                />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
</code>```

The buttons with ID "buttonGameOption*" have set a background "btn_answer_rounded_corners". In Preview the corners are rounded but when I start the app the buttons still dont have rounded corners. Here the XML file

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <layer-list>
                <item android:right="1dp" android:top="1dp" android:bottom="1dp"      android:left="1dp">
                    <shape>
                        <corners android:radius="10dp"></corners>
                        <solid android:color="@color/colorNotAnswered"></solid>
                    </shape>
                </item>
            </layer-list>
        </item>
    </selector>
</code>```

Can someone tell me how I can fix this?

答:
I've checked your code and works without any problems.
Check your activity theming or maybe you do something to your buttons programmatically

Body:
I have many rounded buttons in my app, but some of my buttons dont work with any kind of background, doesnt matter if its rounded corners or changed color. Here is the XML file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/colorAppBackground"
    tools:context=".activities.GameActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:orientation="horizontal"
        android:weightSum="10">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2" />

        <TextView
            android:id="@+id/textViewGameCategory"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="6"
            android:gravity="center"
            android:textSize="28sp"
            android:textColor="@color/colorBlack"
            tools:text="Gemälde"/>

        <TextView
            android:id="@+id/textViewGameCounter"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:gravity="center"
            android:textSize="20sp"
            tools:text="9/107"/>
    </LinearLayout>

    <View style="@style/Divider" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="10">

        <TextView
            android:id="@+id/textViewGameQuestion"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginStart="15dp"
            android:layout_marginLeft="15dp"
            android:layout_marginEnd="15dp"
            android:layout_marginRight="15dp"
            android:layout_weight="1.5"
            android:gravity="center"
            android:textSize="20sp"
            android:textColor="@color/colorBlack"
            tools:text="Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam"/>

        <ImageView
            android:id="@+id/imageViewCardFlip"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:paddingStart="15dp"
            android:paddingLeft="15dp"
            android:paddingEnd="15dp"
            android:paddingRight="15dp"
            android:paddingBottom="15dp"
            android:layout_weight="3.5"
            android:src="@drawable/cover_quizgame" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:orientation="vertical"
            android:layout_weight="5"
            android:weightSum="2">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:orientation="horizontal"
                android:weightSum="2">

                <Button
                    android:id="@+id/buttonGameOptionOne"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginEnd="5dp"
                    android:layout_marginRight="5dp"
                    android:layout_marginTop="5dp"
                    android:layout_marginBottom="5dp"
                    android:layout_weight="1"
                    android:textSize="12sp"
                    android:gravity="center"
                    android:textAllCaps="false"
                    android:padding="3dp"
                    android:background="@drawable/btn_answer_rounded_corners" />

                <Button
                    android:id="@+id/buttonGameOptionTwo"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_marginStart="5dp"
                    android:layout_marginLeft="5dp"
                    android:layout_marginEnd="15dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="5dp"
                    android:layout_marginBottom="5dp"
                    android:layout_weight="1"
                    android:textSize="12sp"
                    android:gravity="center"
                    android:textAllCaps="false"
                    android:padding="3dp"
                    android:background="@drawable/btn_answer_rounded_corners" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:orientation="horizontal"
                android:weightSum="2">

                <Button
                    android:id="@+id/buttonGameOptionThree"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginEnd="5dp"
                    android:layout_marginRight="5dp"
                    android:layout_marginTop="5dp"
                    android:layout_marginBottom="5dp"
                    android:layout_weight="1"
                    android:textSize="12sp"
                    android:gravity="center"
                    android:textAllCaps="false"
                    android:padding="3dp"
                    android:background="@drawable/btn_answer_rounded_corners" />

                <Button
                    android:id="@+id/buttonGameOptionFour"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_marginStart="5dp"
                    android:layout_marginLeft="5dp"
                    android:layout_marginEnd="15dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="5dp"
                    android:layout_marginBottom="5dp"
                    android:layout_weight="1"
                    android:textSize="12sp"
                    android:gravity="center"
                    android:textAllCaps="false"
                    android:padding="3dp"
                    android:background="@drawable/btn_answer_rounded_corners" />
            </LinearLayout>

            <Button
                android:id="@+id/buttonContinue"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginStart="70dp"
                android:layout_marginLeft="70dp"
                android:layout_marginEnd="70dp"
                android:layout_marginRight="70dp"
                android:layout_marginBottom="15dp"
                android:layout_marginTop="15dp"
                android:background="@drawable/btn_continue_rounded_corners"
                android:text="@string/singlegame_continue" />

            <ProgressBar
                android:id="@+id/progressBarSingleGame"
                style="?android:attr/progressBarStyleHorizontal"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginStart="15dp"
                android:layout_marginLeft="15dp"
                android:layout_marginEnd="15dp"
                android:layout_marginRight="15dp"
                android:layout_marginBottom="15dp"
                android:layout_marginTop="15dp"
                android:progressDrawable="@drawable/progressbar_greenprogress"
                android:visibility="gone"
                />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

The buttons with ID "buttonGameOption*" have set a background "btn_answer_rounded_corners". In Preview the corners are rounded but when I start the app the buttons still dont have rounded corners. Here the XML file

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <layer-list>
                <item android:right="1dp" android:top="1dp" android:bottom="1dp"      android:left="1dp">
                    <shape>
                        <corners android:radius="10dp"></corners>
                        <solid android:color="@color/colorNotAnswered"></solid>
                    </shape>
                </item>
            </layer-list>
        </item>
    </selector>

Can someone tell me how I can fix this?


问:
How do I check if a double is a multiple of another double in c#?
I am currently attempting:

```<code>if (4.750 % 0.125 == 0 )
</code>```

but it looks like c# doesn't want decimal for mod operation. How do I check if a number is a multiple of 0.125 then?

thanks!

答:
What you could do is create a custom function to find the mod of any decimals for you:

static double DecimalMod(double a, double b) {
        if (a < b) {
            return a;
        }

        return DecimalMod(a - b, b);
}
```

<p>And since comparing doubles will be annoying with floating-point precision, you'll want to use the bounds checking of:</p>

<pre class="lang-cs prettyprint-override"><code>if (Mathf.Abs(DecimalMod(4.750, 0.125)) < 0.01) {
     // Do Stuff
}```
```

Body:
I am currently attempting:

if (4.750 % 0.125 == 0 )

but it looks like c# doesn't want decimal for mod operation. How do I check if a number is a multiple of 0.125 then?

thanks!

Body:
What you could do is create a custom function to find the mod of any decimals for you:

static double DecimalMod(double a, double b) {
        if (a < b) {
            return a;
        }

        return DecimalMod(a - b, b);
}

And since comparing doubles will be annoying with floating-point precision, you'll want to use the bounds checking of:

if (Mathf.Abs(DecimalMod(4.750, 0.125)) < 0.01) {
     // Do Stuff
}```


问:
Word2Vec compare vectors from different models with different sizes
I have trained several word2vec models using gensim for different languages, but the size is different for each of them.

vectors are obtained like this:

```<code>vec_sp = word_vectors_sp.get_vector("uno")
</code>```

How to use vec_sp as input for different model with different vector size:

```<code>word_vectors_en.most_similar(positive=[vec_sp], topn=1)
</code>```

to obtain the corresponding word in the second model

答:
If the models were trained separately, even if they had the same number of dimensions, the vectors wouldn't be meaningfully comparable.

It is only the interleaved training tug-of-war, between words that are being learned for the same model from mixes of varied contexts, that causes their end-positions to have meaningful distances.

For example, even if both models are for the same language, and include many similar text examples, the word 'apple' in one, and the word 'apple' in another, could wind up in arbitrarily different final positions – thanks to both random initialization & lots of randomization use during the algorithm's operation. The distance/direction between these positions is essentially meaningless. The only consistency that should be expected is that from training material of roughly similar quality/sufficiency, the word's neighbors should be very similar.

If two models do contain many of the same words, there is a possibility to separately learn a "translation" between the two spaces, in a separate optimization process. It takes a large number of shared anchor words, learns a mathematical transformation that does a fair job of moving words from one coordinate space to another, and then that same transformation can be applied to words that aren't in both models.

This technique has had some success in suggesting similar words in a another language in machine translation, and there's some example implementing code in the gensim library's TranslationMatrix class:

https://radimrehurek.com/gensim/models/translation_matrix.html

(It's usually used between models of the same dimensionality but it might work more generally.)

Body:
I have trained several word2vec models using gensim for different languages, but the size is different for each of them.

vectors are obtained like this:

vec_sp = word_vectors_sp.get_vector("uno")

How to use vec_sp as input for different model with different vector size:

word_vectors_en.most_similar(positive=[vec_sp], topn=1)

to obtain the corresponding word in the second model


问:
EnityManagerFactory Singleton. Please just check out?
I am just cruious if this looks solid. It gives no errors but I just want to double check as I am having a pooling issue with c3p0. Just checking to see if anything here is the cause. Thank you in advance!

```<code>import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerFactorySingleton {
    private static EntityManagerFactorySingleton singleton;
    private EntityManagerFactory emf;

public EntityManagerFactorySingleton(){
    emf = Persistence.createEntityManagerFactory(ConfigList.getProperty(Config.PERSISTENCE_UNIT), System.getProperties());
}

public synchronized static EntityManagerFactorySingleton getInstance() {
   if(singleton == null) {
    singleton = new EntityManagerFactorySingleton();
   }
   return singleton;
}

public EntityManagerFactory getEntityManagerFactory(){
    return emf;
}
</code>```

}

答: To answer your question - I think you should make the constructor private, to ensure other Classes cannot instantiate another EntityManagerFactorySingleton.  However, if that is not happening, then I can see no reason why this class would be causing a pooling issue.

Body:
I am just cruious if this looks solid. It gives no errors but I just want to double check as I am having a pooling issue with c3p0. Just checking to see if anything here is the cause. Thank you in advance!

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerFactorySingleton {
    private static EntityManagerFactorySingleton singleton;
    private EntityManagerFactory emf;

public EntityManagerFactorySingleton(){
    emf = Persistence.createEntityManagerFactory(ConfigList.getProperty(Config.PERSISTENCE_UNIT), System.getProperties());
}

public synchronized static EntityManagerFactorySingleton getInstance() {
   if(singleton == null) {
    singleton = new EntityManagerFactorySingleton();
   }
   return singleton;
}

public EntityManagerFactory getEntityManagerFactory(){
    return emf;
}

}


问:
How to parse XML and get instances of a particular node attribute?
I have many rows in XML and I'm trying to get instances of a particular node attribute.

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>
```

How do I access the values of the attribute foobar? In this example, I want "1" and "2".

答:
If the source is an xml file, say like this sample

```<code><pa:Process xmlns:pa="http://sssss">
        <pa:firsttag>SAMPLE</pa:firsttag>
    </pa:Process>
</code>```

you may try the following code

```<code>from lxml import etree, objectify
metadata = 'C:\\Users\\PROCS.xml' # this is sample xml file the contents are shown above
parser = etree.XMLParser(remove_blank_text=True) # this line removes the  name space from the xml in this sample the name space is --> http://sssss
tree = etree.parse(metadata, parser) # this line parses the xml file which is PROCS.xml
root = tree.getroot() # we get the root of xml which is process and iterate using a for loop
for elem in root.getiterator():
    if not hasattr(elem.tag, 'find'): continue  # (1)
    i = elem.tag.find('}')
    if i >= 0:
        elem.tag = elem.tag[i+1:]

dict={}  # a python dictionary is declared
for elem in tree.iter(): #iterating through the xml tree using a for loop
    if elem.tag =="firsttag": # if the tag name matches the name that is equated then the text in the tag is stored into the dictionary
        dict["FIRST_TAG"]=str(elem.text)
        print(dict)
</code>```

Output would be

```<code>{'FIRST_TAG': 'SAMPLE'}
</code>```

Body:
I have many rows in XML and I'm trying to get instances of a particular node attribute.

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>

How do I access the values of the attribute foobar? In this example, I want "1" and "2".

Body:
If the source is an xml file, say like this sample

<pa:Process xmlns:pa="http://sssss">
        <pa:firsttag>SAMPLE</pa:firsttag>
    </pa:Process>

you may try the following code

from lxml import etree, objectify
metadata = 'C:\\Users\\PROCS.xml' # this is sample xml file the contents are shown above
parser = etree.XMLParser(remove_blank_text=True) # this line removes the  name space from the xml in this sample the name space is --> http://sssss
tree = etree.parse(metadata, parser) # this line parses the xml file which is PROCS.xml
root = tree.getroot() # we get the root of xml which is process and iterate using a for loop
for elem in root.getiterator():
    if not hasattr(elem.tag, 'find'): continue  # (1)
    i = elem.tag.find('}')
    if i >= 0:
        elem.tag = elem.tag[i+1:]

dict={}  # a python dictionary is declared
for elem in tree.iter(): #iterating through the xml tree using a for loop
    if elem.tag =="firsttag": # if the tag name matches the name that is equated then the text in the tag is stored into the dictionary
        dict["FIRST_TAG"]=str(elem.text)
        print(dict)

Output would be

{'FIRST_TAG': 'SAMPLE'}


问:
SQL - Multiplied Column Not summing correctly
I have a query where I have to take two columns ( one quantity and one price) multiply the two together to get the issued cost ( per component) and then SUM them in the second . These parts are calculating correctly. The area I am having issues with is SUMMING these totals. When I summarize this area, I get an incorrect result.

Here is the full query ( Including a union all)
The column I am having an issue summarizing is the 'Total Issued Cost' in the second query.
It should be taking the 'Issued Cost' column from the first query (T1.IssuedQty * T2.Price) and summing them.

The value I am receiving is not correct ( much higher)

Here is my query

```<code>SELECT DISTINCT CONVERT(NVARCHAR(100), T0.DOCNUM) AS 'Production Order'
    ,CONVERT(NVARCHAR(100), ((T1.IssuedQty) * T2.Price)) AS 'Issued Cost'
    ,'' 'Total Issued Cost'
FROM OWOR T0
INNER JOIN WOR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
LEFT JOIN IGE1 T2 ON T2.BaseEntry = T1.DocEntry
    AND T2.BaseType = '202'
    AND T1.ItemCode = T2.ItemCode
LEFT JOIN IGN1 T3 ON T3.BaseEntry = T0.DocEntry
    AND T3.BaseType = '202'
LEFT JOIN IGN1 T8 ON T8.BaseEntry = T0.DocEntry
    AND T3.BaseType = '202'
    AND T8.ItemCode = T0.ItemCode
LEFT JOIN ORSC T4 ON T1.Itemcode = T4.ResCode
FULL OUTER JOIN (
    SELECT ITT1.Code 'BOMCODE'
        ,ITT1.Father 'BomFather'
        ,ITT1.VisOrder
        ,ITT1.Quantity
    FROM ITT1
    ) ITT1 ON T0.Itemcode = ITT1.BomFather
    AND T1.Linenum = ITT1.VisOrder

UNION ALL

SELECT T0.DocNum 'Production Order'
    ,'' 'Issued Cost'
    ,Convert(NVARCHAR(100), (T1.IssuedQty * T2.Price)) AS 'Total Issued Cost'
FROM OWOR T0
LEFT JOIN WOR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
INNER JOIN IGE1 T2 ON T2.BaseEntry = T1.DocEntry
    AND T2.BaseType = '202'
    AND T1.ItemCode = T2.ItemCode
</code>```

答:
You have changed the inner join to OWOR to a left join in the second query which may be increasing the numbers. Also, I did not find the sum function in the query, so I have added that:

```<code>SELECT DISTINCT
      CONVERT(nVARCHAR(100),T0.DOCNUM ) AS 'Production Order'
     ,CONVERT(nvarchar(100), ((T1.IssuedQty)*T2.Price)) as 'Issued Cost'
     , '' 'Total Issued Cost'
FROM OWOR T0
INNER JOIN WOR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
LEFT JOIN IGE1 T2 ON T2.BaseEntry = T1.DocEntry and T2.BaseType = '202' and T1.ItemCode = T2.ItemCode
LEFT JOIN IGN1 T3 on T3.BaseEntry = T0.DocEntry and T3.BaseType = '202'
LEFT JOIN IGN1 T8 on T8.BaseEntry = T0.DocEntry and T3.BaseType = '202' and T8.ItemCode = T0.ItemCode
LEFT JOIN ORSC T4 on T1.Itemcode = T4.ResCode
FULL OUTER Join
    (Select ITT1.Code 'BOMCODE', ITT1.Father 'BomFather', ITT1.VisOrder,ITT1.Quantity
     from ITT1  ) ITT1 on T0.Itemcode = ITT1.BomFather and T1.Linenum = ITT1.VisOrder

Union All

SELECT
    T0.DocNum 'Production Order'
    ,'' 'Issued Cost'
    , Convert(Nvarchar(100), SUM(T1.IssuedQty*T2.Price))) as 'Total Issued Cost'
FROM OWOR T0
inner JOIN WOR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
inner JOIN IGE1 T2 ON T2.BaseEntry = T1.DocEntry and T2.BaseType = '202' and T1.ItemCode = T2.ItemCode
Group by T0.DocNum
</code>```

Hope this helps.

Body:
I have a query where I have to take two columns ( one quantity and one price) multiply the two together to get the issued cost ( per component) and then SUM them in the second . These parts are calculating correctly. The area I am having issues with is SUMMING these totals. When I summarize this area, I get an incorrect result.

Here is the full query ( Including a union all)
The column I am having an issue summarizing is the 'Total Issued Cost' in the second query.
It should be taking the 'Issued Cost' column from the first query (T1.IssuedQty * T2.Price) and summing them.

The value I am receiving is not correct ( much higher)

Here is my query

SELECT DISTINCT CONVERT(NVARCHAR(100), T0.DOCNUM) AS 'Production Order'
    ,CONVERT(NVARCHAR(100), ((T1.IssuedQty) * T2.Price)) AS 'Issued Cost'
    ,'' 'Total Issued Cost'
FROM OWOR T0
INNER JOIN WOR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
LEFT JOIN IGE1 T2 ON T2.BaseEntry = T1.DocEntry
    AND T2.BaseType = '202'
    AND T1.ItemCode = T2.ItemCode
LEFT JOIN IGN1 T3 ON T3.BaseEntry = T0.DocEntry
    AND T3.BaseType = '202'
LEFT JOIN IGN1 T8 ON T8.BaseEntry = T0.DocEntry
    AND T3.BaseType = '202'
    AND T8.ItemCode = T0.ItemCode
LEFT JOIN ORSC T4 ON T1.Itemcode = T4.ResCode
FULL OUTER JOIN (
    SELECT ITT1.Code 'BOMCODE'
        ,ITT1.Father 'BomFather'
        ,ITT1.VisOrder
        ,ITT1.Quantity
    FROM ITT1
    ) ITT1 ON T0.Itemcode = ITT1.BomFather
    AND T1.Linenum = ITT1.VisOrder

UNION ALL

SELECT T0.DocNum 'Production Order'
    ,'' 'Issued Cost'
    ,Convert(NVARCHAR(100), (T1.IssuedQty * T2.Price)) AS 'Total Issued Cost'
FROM OWOR T0
LEFT JOIN WOR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
INNER JOIN IGE1 T2 ON T2.BaseEntry = T1.DocEntry
    AND T2.BaseType = '202'
    AND T1.ItemCode = T2.ItemCode

Body:
You have changed the inner join to OWOR to a left join in the second query which may be increasing the numbers. Also, I did not find the sum function in the query, so I have added that:

SELECT DISTINCT
      CONVERT(nVARCHAR(100),T0.DOCNUM ) AS 'Production Order'
     ,CONVERT(nvarchar(100), ((T1.IssuedQty)*T2.Price)) as 'Issued Cost'
     , '' 'Total Issued Cost'
FROM OWOR T0
INNER JOIN WOR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
LEFT JOIN IGE1 T2 ON T2.BaseEntry = T1.DocEntry and T2.BaseType = '202' and T1.ItemCode = T2.ItemCode
LEFT JOIN IGN1 T3 on T3.BaseEntry = T0.DocEntry and T3.BaseType = '202'
LEFT JOIN IGN1 T8 on T8.BaseEntry = T0.DocEntry and T3.BaseType = '202' and T8.ItemCode = T0.ItemCode
LEFT JOIN ORSC T4 on T1.Itemcode = T4.ResCode
FULL OUTER Join
    (Select ITT1.Code 'BOMCODE', ITT1.Father 'BomFather', ITT1.VisOrder,ITT1.Quantity
     from ITT1  ) ITT1 on T0.Itemcode = ITT1.BomFather and T1.Linenum = ITT1.VisOrder

Union All

SELECT
    T0.DocNum 'Production Order'
    ,'' 'Issued Cost'
    , Convert(Nvarchar(100), SUM(T1.IssuedQty*T2.Price))) as 'Total Issued Cost'
FROM OWOR T0
inner JOIN WOR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
inner JOIN IGE1 T2 ON T2.BaseEntry = T1.DocEntry and T2.BaseType = '202' and T1.ItemCode = T2.ItemCode
Group by T0.DocNum

Hope this helps.


问:
How do you add a favicon to HTML page?
I know this is a duplicate question, but I was trying to add a favicon.ico file to my site on localhost:8000 made with Django. The favicon exists on templates\articles (in an app called articles), and I've tried everything on stackoverflow, youtube, and used realfavicongenerator.net, but nothing works. Do I have to define the Django URL/view for the ICO file, as localhost:8000/favicon.ico brings up error? Here's my (simplified) code by the way:

```<code><title>Newsreed | Articles</title>
<link rel="shortcut icon" type = 'image/x-icon' href="favicon.ico">
</code>```

What should I do, because I've been struggling with it for several days now and tere has been no solution on anything.

答: Best way to have a favicon on every page on your site is to link it to the base.html with href="{% static 'articles/favicon.ico' %}. Mind that you need to put {% load static %} in the template too.

Title: How do you add a favicon to HTML page?

Body:
I know this is a duplicate question, but I was trying to add a favicon.ico file to my site on localhost:8000 made with Django. The favicon exists on templates\articles (in an app called articles), and I've tried everything on stackoverflow, youtube, and used realfavicongenerator.net, but nothing works. Do I have to define the Django URL/view for the ICO file, as localhost:8000/favicon.ico brings up error? Here's my (simplified) code by the way:

<title>Newsreed | Articles</title>
<link rel="shortcut icon" type = 'image/x-icon' href="favicon.ico">

What should I do, because I've been struggling with it for several days now and tere has been no solution on anything.


问:
Is there a way to intercept setters and getters in C#?
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

```<code>public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</code>```

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.

答:
It is possible to do directly in the property body itself, but then you need to use a proper backing field instead of auto-implemented properties.

```<code>private string firstName;

public string FirstName
{
  get { return firstName;}
  set
  {
    if(check(value))
    {
       firstName = value;
    }
  }
}
</code>```

Even with auto-implemented properties you get a backing field - this is generated by the compiler and you don't have direct access to it.

Edit:

Seeing as you don't want a backing field, you have other options - using an AOP tool such as PostSharp could help with that.

Body:
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.

Body:
It is possible to do directly in the property body itself, but then you need to use a proper backing field instead of auto-implemented properties.

private string firstName;

public string FirstName
{
  get { return firstName;}
  set
  {
    if(check(value))
    {
       firstName = value;
    }
  }
}

Even with auto-implemented properties you get a backing field - this is generated by the compiler and you don't have direct access to it.

Edit:

Seeing as you don't want a backing field, you have other options - using an AOP tool such as PostSharp could help with that.


问:
Is it possible to avoid nested RetryLoop.callWithRetry calls so I get a consistent timeout?
I've configured a reasonable timeout using BoundedExponentialBackoffRetry, and generally it works as I'd expect if ZK is down when I make a call like "create.forPath". But if ZK is unavailable when I call acquire on an InterProcessReadWriteLock, it takes far longer before it finally times out.

I call acquire which is wrapped in "RetryLoop.callWithRetry" and it goes onto call findProtectedNodeInForeground which is also wrapped in "RetryLoop.callWithRetry". If I've configured the BoundedExponentialBackoffRetry to retry 20 times, the inner retry tries 20 times for every one of the 20 outer retry loops, so it retries 400 times.

We really need a consistent timeout after which we fail. Have I done anything wrong / anyway around this? If not, I guess I'll call the troublesome methods in a new thread that I can kill after my own timeout.

Here is the sample code to recreate it. I stick break points at the lines following the comments, bring ZK down and then let it continue and take the stacktrace whilst it's re-trying.

```<code>public class GoCurator {
public static void main(String[] args) throws Exception {

    CuratorFramework cf = CuratorFrameworkFactory.newClient(
            "localhost:2181",
            new BoundedExponentialBackoffRetry(200, 10000, 20)
    );
    cf.start();

    String root = "/myRoot";
    if(cf.checkExists().forPath(root) == null) {
        // Stacktrace A showing what happens if ZK is down for this call
        cf.create().forPath(root);
    }

    InterProcessReadWriteLock lcok = new InterProcessReadWriteLock(cf, "/grant/myLock");

    // See stacktrace B showing the nested re-try if ZK is down for this call
    lcok.readLock().acquire();

    lcok.readLock().release();

    System.out.println("done");
}
</code>```

}

Stacktrace A (if ZK is down when I'm calling create().forPath). This shows the single retry loop so it exist after the correct number of attempts:

```<code>  java.lang.Thread.State: WAITING
  at java.lang.Object.wait(Object.java:-1)
  at java.lang.Object.wait(Object.java:502)
  at org.apache.zookeeper.ClientCnxn.submitRequest(ClientCnxn.java:1499)
  at org.apache.zookeeper.ClientCnxn.submitRequest(ClientCnxn.java:1487)
  at org.apache.zookeeper.ZooKeeper.getChildren(ZooKeeper.java:2617)
  at org.apache.curator.framework.imps.GetChildrenBuilderImpl$3.call(GetChildrenBuilderImpl.java:242)
  at org.apache.curator.framework.imps.GetChildrenBuilderImpl$3.call(GetChildrenBuilderImpl.java:231)
  at org.apache.curator.connection.StandardConnectionHandlingPolicy.callWithRetry(StandardConnectionHandlingPolicy.java:64)
  at org.apache.curator.RetryLoop.callWithRetry(RetryLoop.java:100)
  at org.apache.curator.framework.imps.GetChildrenBuilderImpl.pathInForeground(GetChildrenBuilderImpl.java:228)
  at org.apache.curator.framework.imps.GetChildrenBuilderImpl.forPath(GetChildrenBuilderImpl.java:219)
  at org.apache.curator.framework.imps.GetChildrenBuilderImpl.forPath(GetChildrenBuilderImpl.java:41)
  at com.gebatech.curator.GoCurator.main(GoCurator.java:25)
</code>```

Stacktrace B (if ZK is down when I call InterProcessReadWriteLock#readLock#acquire). This shows the nested re-try loop so it doesn't exit until 20*20 attempts.

```<code>  java.lang.Thread.State: WAITING
  at sun.misc.Unsafe.park(Unsafe.java:-1)
  at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
  at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedNanos(AbstractQueuedSynchronizer.java:1037)
  at java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireSharedNanos(AbstractQueuedSynchronizer.java:1328)
  at java.util.concurrent.CountDownLatch.await(CountDownLatch.java:277)
  at org.apache.curator.CuratorZookeeperClient.internalBlockUntilConnectedOrTimedOut(CuratorZookeeperClient.java:434)
  at org.apache.curator.connection.StandardConnectionHandlingPolicy.callWithRetry(StandardConnectionHandlingPolicy.java:56)
  at org.apache.curator.RetryLoop.callWithRetry(RetryLoop.java:100)
  at org.apache.curator.framework.imps.CreateBuilderImpl.findProtectedNodeInForeground(CreateBuilderImpl.java:1239)
  at org.apache.curator.framework.imps.CreateBuilderImpl.access$1700(CreateBuilderImpl.java:51)
  at org.apache.curator.framework.imps.CreateBuilderImpl$17.call(CreateBuilderImpl.java:1167)
  at org.apache.curator.framework.imps.CreateBuilderImpl$17.call(CreateBuilderImpl.java:1156)
  at org.apache.curator.connection.StandardConnectionHandlingPolicy.callWithRetry(StandardConnectionHandlingPolicy.java:64)
  at org.apache.curator.RetryLoop.callWithRetry(RetryLoop.java:100)
  at org.apache.curator.framework.imps.CreateBuilderImpl.pathInForeground(CreateBuilderImpl.java:1153)
  at org.apache.curator.framework.imps.CreateBuilderImpl.protectedPathInForeground(CreateBuilderImpl.java:607)
  at org.apache.curator.framework.imps.CreateBuilderImpl.forPath(CreateBuilderImpl.java:597)
  at org.apache.curator.framework.imps.CreateBuilderImpl.forPath(CreateBuilderImpl.java:575)
  at org.apache.curator.framework.imps.CreateBuilderImpl.forPath(CreateBuilderImpl.java:51)
  at org.apache.curator.framework.recipes.locks.StandardLockInternalsDriver.createsTheLock(StandardLockInternalsDriver.java:54)
  at org.apache.curator.framework.recipes.locks.LockInternals.attemptLock(LockInternals.java:225)
  at org.apache.curator.framework.recipes.locks.InterProcessMutex.internalLock(InterProcessMutex.java:237)
  at org.apache.curator.framework.recipes.locks.InterProcessMutex.acquire(InterProcessMutex.java:89)
  at com.gebatech.curator.GoCurator.main(GoCurator.java:29)
</code>```

答: This turns out to be a real, longstanding, problem with how Curator uses retries. I have a fix and PR ready here: https://github.com/apache/curator/pull/346 - I'd appreciate more eyes on it.</p>

Body:
I've configured a reasonable timeout using BoundedExponentialBackoffRetry, and generally it works as I'd expect if ZK is down when I make a call like "create.forPath". But if ZK is unavailable when I call acquire on an InterProcessReadWriteLock, it takes far longer before it finally times out.

I call acquire which is wrapped in "RetryLoop.callWithRetry" and it goes onto call findProtectedNodeInForeground which is also wrapped in "RetryLoop.callWithRetry". If I've configured the BoundedExponentialBackoffRetry to retry 20 times, the inner retry tries 20 times for every one of the 20 outer retry loops, so it retries 400 times.

We really need a consistent timeout after which we fail. Have I done anything wrong / anyway around this? If not, I guess I'll call the troublesome methods in a new thread that I can kill after my own timeout.

Here is the sample code to recreate it. I stick break points at the lines following the comments, bring ZK down and then let it continue and take the stacktrace whilst it's re-trying.

public class GoCurator {
public static void main(String[] args) throws Exception {

    CuratorFramework cf = CuratorFrameworkFactory.newClient(
            "localhost:2181",
            new BoundedExponentialBackoffRetry(200, 10000, 20)
    );
    cf.start();

    String root = "/myRoot";
    if(cf.checkExists().forPath(root) == null) {
        // Stacktrace A showing what happens if ZK is down for this call
        cf.create().forPath(root);
    }

    InterProcessReadWriteLock lcok = new InterProcessReadWriteLock(cf, "/grant/myLock");

    // See stacktrace B showing the nested re-try if ZK is down for this call
    lcok.readLock().acquire();

    lcok.readLock().release();

    System.out.println("done");
}

}

Stacktrace A (if ZK is down when I'm calling create().forPath). This shows the single retry loop so it exist after the correct number of attempts:

  java.lang.Thread.State: WAITING
  at java.lang.Object.wait(Object.java:-1)
  at java.lang.Object.wait(Object.java:502)
  at org.apache.zookeeper.ClientCnxn.submitRequest(ClientCnxn.java:1499)
  at org.apache.zookeeper.ClientCnxn.submitRequest(ClientCnxn.java:1487)
  at org.apache.zookeeper.ZooKeeper.getChildren(ZooKeeper.java:2617)
  at org.apache.curator.framework.imps.GetChildrenBuilderImpl$3.call(GetChildrenBuilderImpl.java:242)
  at org.apache.curator.framework.imps.GetChildrenBuilderImpl$3.call(GetChildrenBuilderImpl.java:231)
  at org.apache.curator.connection.StandardConnectionHandlingPolicy.callWithRetry(StandardConnectionHandlingPolicy.java:64)
  at org.apache.curator.RetryLoop.callWithRetry(RetryLoop.java:100)
  at org.apache.curator.framework.imps.GetChildrenBuilderImpl.pathInForeground(GetChildrenBuilderImpl.java:228)
  at org.apache.curator.framework.imps.GetChildrenBuilderImpl.forPath(GetChildrenBuilderImpl.java:219)
  at org.apache.curator.framework.imps.GetChildrenBuilderImpl.forPath(GetChildrenBuilderImpl.java:41)
  at com.gebatech.curator.GoCurator.main(GoCurator.java:25)

Stacktrace B (if ZK is down when I call InterProcessReadWriteLock#readLock#acquire). This shows the nested re-try loop so it doesn't exit until 20*20 attempts.

  java.lang.Thread.State: WAITING
  at sun.misc.Unsafe.park(Unsafe.java:-1)
  at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
  at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedNanos(AbstractQueuedSynchronizer.java:1037)
  at java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireSharedNanos(AbstractQueuedSynchronizer.java:1328)
  at java.util.concurrent.CountDownLatch.await(CountDownLatch.java:277)
  at org.apache.curator.CuratorZookeeperClient.internalBlockUntilConnectedOrTimedOut(CuratorZookeeperClient.java:434)
  at org.apache.curator.connection.StandardConnectionHandlingPolicy.callWithRetry(StandardConnectionHandlingPolicy.java:56)
  at org.apache.curator.RetryLoop.callWithRetry(RetryLoop.java:100)
  at org.apache.curator.framework.imps.CreateBuilderImpl.findProtectedNodeInForeground(CreateBuilderImpl.java:1239)
  at org.apache.curator.framework.imps.CreateBuilderImpl.access$1700(CreateBuilderImpl.java:51)
  at org.apache.curator.framework.imps.CreateBuilderImpl$17.call(CreateBuilderImpl.java:1167)
  at org.apache.curator.framework.imps.CreateBuilderImpl$17.call(CreateBuilderImpl.java:1156)
  at org.apache.curator.connection.StandardConnectionHandlingPolicy.callWithRetry(StandardConnectionHandlingPolicy.java:64)
  at org.apache.curator.RetryLoop.callWithRetry(RetryLoop.java:100)
  at org.apache.curator.framework.imps.CreateBuilderImpl.pathInForeground(CreateBuilderImpl.java:1153)
  at org.apache.curator.framework.imps.CreateBuilderImpl.protectedPathInForeground(CreateBuilderImpl.java:607)
  at org.apache.curator.framework.imps.CreateBuilderImpl.forPath(CreateBuilderImpl.java:597)
  at org.apache.curator.framework.imps.CreateBuilderImpl.forPath(CreateBuilderImpl.java:575)
  at org.apache.curator.framework.imps.CreateBuilderImpl.forPath(CreateBuilderImpl.java:51)
  at org.apache.curator.framework.recipes.locks.StandardLockInternalsDriver.createsTheLock(StandardLockInternalsDriver.java:54)
  at org.apache.curator.framework.recipes.locks.LockInternals.attemptLock(LockInternals.java:225)
  at org.apache.curator.framework.recipes.locks.InterProcessMutex.internalLock(InterProcessMutex.java:237)
  at org.apache.curator.framework.recipes.locks.InterProcessMutex.acquire(InterProcessMutex.java:89)
  at com.gebatech.curator.GoCurator.main(GoCurator.java:29)


问:
Is it possible to capture all current Uncaught Exceptions handlers in Node.js?
I am making a Node.js exception reporter (NPM package) and I need it to work with other exception reporters (such as Raven). The problem with Raven and a few other Exceptions handlers is that it exits the process after receiving an Uncaught Exception. This makes it impossible for my exception reporter to send the exception report via http.

I want to know if it is possible to:

get all current running Uncaught Exceptions handlers.

get all upcoming Uncaught Exceptions handlers.

So basically what I want to do is to wrap around these bad boys and make sure my exception reporter runs first. Such as:

Uncaught Exception => my exception reporter => Raven => process.exit(1);

OR

Uncaught Exception => my exception reporter => the project's own exception reporter => whatever it sees fit;

AND I also need to make sure if there is no other exception reporters, we should exit the process:

Uncaught Exception => my exception reporter => nothing => process.exit(1);

答:
process is an EventEmitter. That's how

```<code>process.on('uncaughtException, ...)
</code>```

works.

You can reach inside the EventEmitter part of the process object and find all the handlers registered for uncaughtExceptions and manipulate things to put yours first in line. It's kind of a hack, but it could be done. You could even monkey patch .on() on the process object so you can capture any subsequent listeners for that event.

Here's a function that would remove any existing listenders for unhandledRejection insert yours, then add back the others so yours was guaranteed to be the first one to be called.

```<code>function addListenerFirstInLine(emitter, eventName, listener) {
    // get existing listeners for the target event
    const listeners = emitter.listeners(eventName);

    // remove then all
    emitter.removeAllListeners(eventName);

    // add new listener first in line
    emitter.on(eventName, listener);

    // put back prior listeners after ours
    for (const fn of listeners) {
        emitter.on(eventName, fn);
    }
}
</code>```

And, you could then use it for your application like this:

```<code>addListenerFirstInLine(process, "uncaughtException", myListener)
</code>```

Body:
process is an EventEmitter. That's how

process.on('uncaughtException, ...)

works.

You can reach inside the EventEmitter part of the process object and find all the handlers registered for uncaughtExceptions and manipulate things to put yours first in line. It's kind of a hack, but it could be done. You could even monkey patch .on() on the process object so you can capture any subsequent listeners for that event.

Here's a function that would remove any existing listenders for unhandledRejection insert yours, then add back the others so yours was guaranteed to be the first one to be called.

function addListenerFirstInLine(emitter, eventName, listener) {
    // get existing listeners for the target event
    const listeners = emitter.listeners(eventName);

    // remove then all
    emitter.removeAllListeners(eventName);

    // add new listener first in line
    emitter.on(eventName, listener);

    // put back prior listeners after ours
    for (const fn of listeners) {
        emitter.on(eventName, fn);
    }
}

And, you could then use it for your application like this:

addListenerFirstInLine(process, "uncaughtException", myListener)


问:
How to keep an image open in OpenCV even if u press a key
How I do it? In matplotlib we have Show with False argument you can keep the image without closing. In my script, I pop out two images with cv2.imshow and I read that I can keep them up with waitKey(0), but when I press a key, they dissapear as the waitKey stablishs.

I want to know if there is a equivalent method for OpenCV as Show(False) from matplotlib.pyplot.

答:
You can use a while loop:

```<code>while cv2.waitKey(0) != 27:
    pass
</code>```

The loop waits until Escape key is pressed.

Put it at the end of the script, because it's blocking the execution.

Body:
You can use a while loop:

while cv2.waitKey(0) != 27:
    pass

The loop waits until Escape key is pressed.

Put it at the end of the script, because it's blocking the execution.


问:
Save button in table
I have an array of data that is taken from the site and output to the table, I want to add a button that will store a certain row from the table in the database how can I implement it?</p>

```<code>   let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
   cell.textLabel?.text = news[indexPath.row].tittle

   let tipDouble = NumberFormatter().number(from: news[indexPath.row].time!)!.doubleValue
   let date = Date(timeIntervalSince1970: tipDouble)

   let dateFormatter = DateFormatter()
   dateFormatter.timeZone = TimeZone(abbreviation: "GMT+2") //Set timezone that you want
   dateFormatter.locale = NSLocale.current
   dateFormatter.dateFormat = "MM-dd HH:mm" //Specify your format that you want

   let strDate = dateFormatter.string(from: date)

   cell.detailTextLabel?.text = strDate

   return cell
</code>```

答:
Yes Exactly If going through delete and insert. But there is a solution for this.</p>

```<code>var arrData: dataTag = [dataTag]()

class dataTag {
    var name:String?
    .......

    var tag: Int? =  Date().IntegerValue. Here "anyUniqueEntry value".
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.button.tag = IndexPath.row
..

}
func buttonAction(sender:UIButton){

let data = arrData[sender.tag]

...

}
</code>```

Title: Save button in table

Body:
I have an array of data that is taken from the site and output to the table, I want to add a button that will store a certain row from the table in the database how can I implement it?

   let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
   cell.textLabel?.text = news[indexPath.row].tittle

   let tipDouble = NumberFormatter().number(from: news[indexPath.row].time!)!.doubleValue
   let date = Date(timeIntervalSince1970: tipDouble)

   let dateFormatter = DateFormatter()
   dateFormatter.timeZone = TimeZone(abbreviation: "GMT+2") //Set timezone that you want
   dateFormatter.locale = NSLocale.current
   dateFormatter.dateFormat = "MM-dd HH:mm" //Specify your format that you want

   let strDate = dateFormatter.string(from: date)

   cell.detailTextLabel?.text = strDate

   return cell

Body:
Yes Exactly If going through delete and insert. But there is a solution for this.

var arrData: dataTag = [dataTag]()

class dataTag {
    var name:String?
    .......

    var tag: Int? =  Date().IntegerValue. Here "anyUniqueEntry value".
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.button.tag = IndexPath.row
..

}
func buttonAction(sender:UIButton){

let data = arrData[sender.tag]

...

}


问:
Custom TensorFlow Keras optimizer
Suppose I want to write a custom optimizer class that conforms to the tf.keras API (using TensorFlow version>=2.0). I am confused about the documented way to do this versus what's done in implementations.

The documentation for tf.keras.optimizers.Optimizer states,

  ### Write a customized optimizer.
  If you intend to create your own optimization algorithm, simply inherit from
  this class and override the following methods:

    - resource_apply_dense (update variable given gradient tensor is dense)
    - resource_apply_sparse (update variable given gradient tensor is sparse)
    - create_slots (if your optimizer algorithm requires additional variables)
```

However, the current tf.keras.optimizers.Optimizer implementation does not define a resource_apply_dense method, but it does define a private-looking _resource_apply_dense method stub. Similarly, there are no resource_apply_sparse or create_slots methods, but there are a _resource_apply_sparse method stub and a _create_slots method call.

In official tf.keras.optimizers.Optimizer subclasses (using tf.keras.optimizers.Adam as an example), there are _resource_apply_dense, _resource_apply_sparse, and _create_slots methods, and there are no such methods without the leading underscore.

There are similar leading-underscore methods in slightly-less-official tf.keras.optimizers.Optimizer subclasses (e.g., tfa.optimizers.MovingAverage from TensorFlow Addons: _resource_apply_dense, _resource_apply_sparse, _create_slots).

Another confounding point for me is that some of the TensorFlow Addons optimizers also override the apply_gradients method (e.g., tfa.optimizers.MovingAverage), whereas the tf.keras.optimizers optimizers do not.

Moreover, I noticed that the apply_gradients method of tf.keras.optimizers.Optimizer method calls _create_slots, but the base tf.keras.optimizers.Optimizer class does not have a _create_slots method.
So, it seems that a _create_slots method must be defined in an optimizer subclass if that subclass does not override apply_gradients.

Questions

What is the correct way to subclass a tf.keras.optimizers.Optimizer? Specifically,

Does the tf.keras.optimizers.Optimizer documentation listed at the top simply mean to override the leading-underscore versions of the methods they mention (e.g., _resource_apply_dense instead of resource_apply_dense)? If so, are there any API guarantees about these private-looking methods not changing their behavior in future versions of TensorFlow? What are the signatures of these methods?

When would one override apply_gradients in addition to the _apply_resource_[dense|sparse] methods?

Edit. Opened issue on GitHub: #36449

答:
Yes, this looks to be a documentation error. The preceding underscore names are the correct methods to override. Related is the non-Keras Optimizer which has these all defined, but not implemented in the base class https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/optimizer.py

```<code>  def _create_slots(self, var_list):
    """Create all slots needed by the variables.
    Args:
      var_list: A list of `Variable` objects.
    """
    # No slots needed by default
    pass

  def _resource_apply_dense(self, grad, handle):
    """Add ops to apply dense gradients to the variable `handle`.
    Args:
      grad: a `Tensor` representing the gradient.
      handle: a `Tensor` of dtype `resource` which points to the variable
       to be updated.
    Returns:
      An `Operation` which updates the value of the variable.
    """
    raise NotImplementedError()

  def _resource_apply_sparse(self, grad, handle, indices):
    """Add ops to apply sparse gradients to the variable `handle`.
    Similar to `_apply_sparse`, the `indices` argument to this method has been
    de-duplicated. Optimizers which deal correctly with non-unique indices may
    instead override `_resource_apply_sparse_duplicate_indices` to avoid this
    overhead.
    Args:
      grad: a `Tensor` representing the gradient for the affected indices.
      handle: a `Tensor` of dtype `resource` which points to the variable
       to be updated.
      indices: a `Tensor` of integral type representing the indices for
       which the gradient is nonzero. Indices are unique.
    Returns:
      An `Operation` which updates the value of the variable.
    """
    raise NotImplementedError()
</code>```

I don't know about apply_dense. For one thing, if you do override it, the code mentions that a per-replica DistributionStrategy could be "dangerous"

```<code>    # TODO(isaprykin): When using a DistributionStrategy, and when an
    # optimizer is created in each replica, it might be dangerous to
    # rely on some Optimizer methods.  When such methods are called on a
    # per-replica optimizer, an exception needs to be thrown.  We do
    # allow creation per-replica optimizers however, because the
    # compute_gradients()->apply_gradients() sequence is safe.
</code>```

Title: Custom TensorFlow Keras optimizer

Body:
Suppose I want to write a custom optimizer class that conforms to the tf.keras API (using TensorFlow version>=2.0). I am confused about the documented way to do this versus what's done in implementations.

The documentation for tf.keras.optimizers.Optimizer states,

  ### Write a customized optimizer.
  If you intend to create your own optimization algorithm, simply inherit from
  this class and override the following methods:

    - resource_apply_dense (update variable given gradient tensor is dense)
    - resource_apply_sparse (update variable given gradient tensor is sparse)
    - create_slots (if your optimizer algorithm requires additional variables)

However, the current tf.keras.optimizers.Optimizer implementation does not define a resource_apply_dense method, but it does define a private-looking _resource_apply_dense method stub. Similarly, there are no resource_apply_sparse or create_slots methods, but there are a _resource_apply_sparse method stub and a _create_slots method call.

In official tf.keras.optimizers.Optimizer subclasses (using tf.keras.optimizers.Adam as an example), there are _resource_apply_dense, _resource_apply_sparse, and _create_slots methods, and there are no such methods without the leading underscore.

There are similar leading-underscore methods in slightly-less-official tf.keras.optimizers.Optimizer subclasses (e.g., tfa.optimizers.MovingAverage from TensorFlow Addons: _resource_apply_dense, _resource_apply_sparse, _create_slots).

Another confounding point for me is that some of the TensorFlow Addons optimizers also override the apply_gradients method (e.g., tfa.optimizers.MovingAverage), whereas the tf.keras.optimizers optimizers do not.

Moreover, I noticed that the apply_gradients method of tf.keras.optimizers.Optimizer method calls _create_slots, but the base tf.keras.optimizers.Optimizer class does not have a _create_slots method.
So, it seems that a _create_slots method must be defined in an optimizer subclass if that subclass does not override apply_gradients.

Questions

What is the correct way to subclass a tf.keras.optimizers.Optimizer? Specifically,

Does the tf.keras.optimizers.Optimizer documentation listed at the top simply mean to override the leading-underscore versions of the methods they mention (e.g., _resource_apply_dense instead of resource_apply_dense)? If so, are there any API guarantees about these private-looking methods not changing their behavior in future versions of TensorFlow? What are the signatures of these methods?

When would one override apply_gradients in addition to the _apply_resource_[dense|sparse] methods?

Edit. Opened issue on GitHub: #36449

Body:
Yes, this looks to be a documentation error. The preceding underscore names are the correct methods to override. Related is the non-Keras Optimizer which has these all defined, but not implemented in the base class https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/optimizer.py

  def _create_slots(self, var_list):
    """Create all slots needed by the variables.
    Args:
      var_list: A list of `Variable` objects.
    """
    # No slots needed by default
    pass

  def _resource_apply_dense(self, grad, handle):
    """Add ops to apply dense gradients to the variable `handle`.
    Args:
      grad: a `Tensor` representing the gradient.
      handle: a `Tensor` of dtype `resource` which points to the variable
       to be updated.
    Returns:
      An `Operation` which updates the value of the variable.
    """
    raise NotImplementedError()

  def _resource_apply_sparse(self, grad, handle, indices):
    """Add ops to apply sparse gradients to the variable `handle`.
    Similar to `_apply_sparse`, the `indices` argument to this method has been
    de-duplicated. Optimizers which deal correctly with non-unique indices may
    instead override `_resource_apply_sparse_duplicate_indices` to avoid this
    overhead.
    Args:
      grad: a `Tensor` representing the gradient for the affected indices.
      handle: a `Tensor` of dtype `resource` which points to the variable
       to be updated.
      indices: a `Tensor` of integral type representing the indices for
       which the gradient is nonzero. Indices are unique.
    Returns:
      An `Operation` which updates the value of the variable.
    """
    raise NotImplementedError()

I don't know about apply_dense. For one thing, if you do override it, the code mentions that a per-replica DistributionStrategy could be "dangerous"

    # TODO(isaprykin): When using a DistributionStrategy, and when an
    # optimizer is created in each replica, it might be dangerous to
    # rely on some Optimizer methods.  When such methods are called on a
    # per-replica optimizer, an exception needs to be thrown.  We do
    # allow creation per-replica optimizers however, because the
    # compute_gradients()->apply_gradients() sequence is safe.


问:
Reference tunnel variable within a "%>%" chain
Following up from my prior question - how can you reference the newly created column later in the analysis? How can you reference .data[["cyl"]] and rename the title as cyl?

Tunnel data-variables through env-variable with "{{" operator

library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.6.2
#> Warning: package 'tidyr' was built under R version 3.6.2
# Variables to pass into function
params <-  setdiff(colnames(mtcars) ,"mpg") %>% head(3)

graph_by <- function(data, by, var, prefix = "avg") {
  data %>%
    group_by({{ by }}) %>%
    summarise(mean_value := mean({{ var }}, na.rm = TRUE)) %>%
    ggplot(aes(mean_value, {{ by }})) +
    geom_line() +
    geom_point()
}

graph_by(mtcars, by = cyl, var = mpg)
```

<p><img src="https://i.imgur.com/BdHBBMK.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>
purrr::map(params, ~ graph_by(mtcars, by = .data[[.x]], var = mpg))
#> [[1]]
</code>```

```<code>#>
#> [[2]]
</code>```

```<code>#>
#> [[3]]
</code>```

## Goal would be to refer to the created variable later in the analysis

# graph_by <- function(data, by, var, prefix = "avg") {
#   data %>%
#     group_by({{ by }}) %>%
#     summarise("{prefix}_{{ var }}" := mean({{ var }}, na.rm = TRUE)) %>%
#     ggplot(aes(.data[[.x]], {{ by }})) +
#     geom_line() +
#     geom_point() +
#     labs(x = "{{ by }}")
# }
```

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

答:
This version will work

```<code>graph_by <- function(data, by, var, prefix = "avg") {
  by <- rlang::ensym(by)
  data %>%
    group_by({{ by }}) %>%
    summarise(mean_value := mean({{ var }}, na.rm = TRUE)) %>%
    ggplot(aes(mean_value, {{by}})) +
    geom_line() +
    geom_point()
}

purrr::map(params, ~ graph_by(mtcars, by = !!.x, var = mpg))
</code>```

Note that we do the expansion in the map call with !! and then use ensym explicitly so it will accept both literal character values and unquoted symbols.

Body:
Following up from my prior question - how can you reference the newly created column later in the analysis? How can you reference .data[["cyl"]] and rename the title as cyl?

Tunnel data-variables through env-variable with "{{" operator

library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.6.2
#> Warning: package 'tidyr' was built under R version 3.6.2
# Variables to pass into function
params <-  setdiff(colnames(mtcars) ,"mpg") %>% head(3)

graph_by <- function(data, by, var, prefix = "avg") {
  data %>%
    group_by({{ by }}) %>%
    summarise(mean_value := mean({{ var }}, na.rm = TRUE)) %>%
    ggplot(aes(mean_value, {{ by }})) +
    geom_line() +
    geom_point()
}

graph_by(mtcars, by = cyl, var = mpg)

purrr::map(params, ~ graph_by(mtcars, by = .data[[.x]], var = mpg))
#> [[1]]

#>
#> [[2]]

#>
#> [[3]]

## Goal would be to refer to the created variable later in the analysis

# graph_by <- function(data, by, var, prefix = "avg") {
#   data %>%
#     group_by({{ by }}) %>%
#     summarise("{prefix}_{{ var }}" := mean({{ var }}, na.rm = TRUE)) %>%
#     ggplot(aes(.data[[.x]], {{ by }})) +
#     geom_line() +
#     geom_point() +
#     labs(x = "{{ by }}")
# }

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

Body:
This version will work

graph_by <- function(data, by, var, prefix = "avg") {
  by <- rlang::ensym(by)
  data %>%
    group_by({{ by }}) %>%
    summarise(mean_value := mean({{ var }}, na.rm = TRUE)) %>%
    ggplot(aes(mean_value, {{by}})) +
    geom_line() +
    geom_point()
}

purrr::map(params, ~ graph_by(mtcars, by = !!.x, var = mpg))

Note that we do the expansion in the map call with !! and then use ensym explicitly so it will accept both literal character values and unquoted symbols.