问:
Spring Boot JPA does not prepend schema name to tables in query
From what I understand (for example, from here), if I specify the schema for my entity, then it should use that schema name when creating the query.

So, if I have an entity of:

```<code>@Entity
@Table(name="proposalstatuses",schema="sales")
public class ProposalStatus implements Serializable {
    private static final long serialVersionUID = 1L;
    private int proposalStatusID;
    private String proposalStatusName;

    public ProposalStatus() {}

    public ProposalStatus(String proposalStatusName) {
        this.proposalStatusName = proposalStatusName;
    }

    @Id
    @Column(name="pk_proposalstatusid")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getProposalStatusID() {
        return proposalStatusID;
    }

    public void setProposalStatusID(int proposalStatusID) {
        this.proposalStatusID = proposalStatusID;
    }

    @Column(name="proposalstatusname", unique=true, nullable=false)
    public String getProposalStatusName() {
        return proposalStatusName;
    }

    public void setProposalStatusName(String proposalStatusName) {
        this.proposalStatusName = proposalStatusName;
    }
}
</code>```

then I would expect Hibernate to generate its queries like select ... from sales.proposalstatuses.  However, instead I see:

```<code>select proposalst0_.pk_proposalstatusid as pk_propo1_8_, proposalst0_.proposalstatusname as proposal2_8_
from proposalstatuses proposalst0_
order by proposalst0_.proposalstatusname asc
</code>```

This is not a huge deal for this case, but now I want to be able to use joins with a table in a different schema, and that is failing because it thinks the tables don't exist (and they don't in the default schema).

So, I have one database (one connection) with multiple schema.  How do I get Hibernate to use the schema name when it references the tables?  It seems like it should be very straight-forward, but I must be missing something.

Thanks!

I am using Spring Boot 1.5.7 which uses Hibernate JPA 2.1 and Hibernate Core 5.0.12.  This does work if I use an H2 datasource.  I am only seeing a problem if MySQL is the datasource.

I have read about creating a view in the default schema for the table I want to reference. However, that is not a feasible option, as I would have to create a great many views; and it seems like Hibernate should be able to handle this without that much effort.

Here are the configuration settings from application.properties:

```<code>spring.datasource.url=jdbc:mysql://localhost/sales?verifyServerCertificate=false&useSSL=true
spring.datasource.username=user
spring.datasource.password=pass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1
spring.jpa.show-sql=true
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
</code>```

Changing the name of the schema in the url allows me to access the data in that schema, but I can't get to any other schema than the one listed in the url.

答:
The key that I was missing was in the configuration as well as the database type.  In MySQL, there is no real distinction between a database and a schema. With the schema property in the @Table annotation, it is referencing a "real" schema, but not as it is defined in MySQL.  This explains why the schema property works for an H2 database but not MySQL.

The @Table(name="SCHEMA_NAME.TABLE_NAME") annotation did not work initially because I had a default schema in my datasource url.  The url needed to be

```<code>spring.datasource.url=jdbc:mysql://localhost?verifyServerCertificate=false&useSSL=true
</code>```

With this change everything works with MySQL.

As one further note, in order for this to work with H2 as well, make sure you do not define the hibernate.default_schema property.

Body:
From what I understand (for example, from here), if I specify the schema for my entity, then it should use that schema name when creating the query.

So, if I have an entity of:

@Entity
@Table(name="proposalstatuses",schema="sales")
public class ProposalStatus implements Serializable {
    private static final long serialVersionUID = 1L;
    private int proposalStatusID;
    private String proposalStatusName;

    public ProposalStatus() {}

    public ProposalStatus(String proposalStatusName) {
        this.proposalStatusName = proposalStatusName;
    }

    @Id
    @Column(name="pk_proposalstatusid")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getProposalStatusID() {
        return proposalStatusID;
    }

    public void setProposalStatusID(int proposalStatusID) {
        this.proposalStatusID = proposalStatusID;
    }

    @Column(name="proposalstatusname", unique=true, nullable=false)
    public String getProposalStatusName() {
        return proposalStatusName;
    }

    public void setProposalStatusName(String proposalStatusName) {
        this.proposalStatusName = proposalStatusName;
    }
}

then I would expect Hibernate to generate its queries like select ... from sales.proposalstatuses.  However, instead I see:

select proposalst0_.pk_proposalstatusid as pk_propo1_8_, proposalst0_.proposalstatusname as proposal2_8_
from proposalstatuses proposalst0_
order by proposalst0_.proposalstatusname asc

This is not a huge deal for this case, but now I want to be able to use joins with a table in a different schema, and that is failing because it thinks the tables don't exist (and they don't in the default schema).

So, I have one database (one connection) with multiple schema.  How do I get Hibernate to use the schema name when it references the tables?  It seems like it should be very straight-forward, but I must be missing something.

Thanks!

I am using Spring Boot 1.5.7 which uses Hibernate JPA 2.1 and Hibernate Core 5.0.12.  This does work if I use an H2 datasource.  I am only seeing a problem if MySQL is the datasource.

I have read about creating a view in the default schema for the table I want to reference. However, that is not a feasible option, as I would have to create a great many views; and it seems like Hibernate should be able to handle this without that much effort.

Here are the configuration settings from application.properties:

spring.datasource.url=jdbc:mysql://localhost/sales?verifyServerCertificate=false&useSSL=true
spring.datasource.username=user
spring.datasource.password=pass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1
spring.jpa.show-sql=true
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

Changing the name of the schema in the url allows me to access the data in that schema, but I can't get to any other schema than the one listed in the url.

Body:
The key that I was missing was in the configuration as well as the database type.  In MySQL, there is no real distinction between a database and a schema. With the schema property in the @Table annotation, it is referencing a "real" schema, but not as it is defined in MySQL.  This explains why the schema property works for an H2 database but not MySQL.

The @Table(name="SCHEMA_NAME.TABLE_NAME") annotation did not work initially because I had a default schema in my datasource url.  The url needed to be

spring.datasource.url=jdbc:mysql://localhost?verifyServerCertificate=false&useSSL=true

With this change everything works with MySQL.

As one further note, in order for this to work with H2 as well, make sure you do not define the hibernate.default_schema property.


来源: stackexchange

问:
why Image numpy array transpose and its inverse change color channel?
When I just transpose the image and inverser the transpose Image color channel don't change as here

```<code>test = rgb.transpose(2,0,1)
test2 = test.transpose(1,2,0)
</code>```

But when I add them in slides array and do the same procedure the color change

```<code>Train_x = np.zeros((1,4,x,x))
Train_x[0,0:3,:,:] = rgb.transpose(2,0,1)
s = Train_x[0,0:3,:,:]
s = s.transpose(1,2,0)
</code>```

I tested their values they have exactly the same values. it is just when I plot them together using matplotlib they have different color

答:
The solution is just to cast the image into uint8 before giving it to matplotlib

```<code>astype(np.uint8)
</code>```

because of this function

```<code>if A.dtype != np.uint8:
    A = (255*A).astype(np.uint8)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I just transpose the image and inverser the transpose Image color channel don't change as here

test = rgb.transpose(2,0,1)
test2 = test.transpose(1,2,0)

But when I add them in slides array and do the same procedure the color change

Train_x = np.zeros((1,4,x,x))
Train_x[0,0:3,:,:] = rgb.transpose(2,0,1)
s = Train_x[0,0:3,:,:]
s = s.transpose(1,2,0)

I tested their values they have exactly the same values. it is just when I plot them together using matplotlib they have different color

Body:
The solution is just to cast the image into uint8 before giving it to matplotlib

astype(np.uint8)

because of this function

if A.dtype != np.uint8:
    A = (255*A).astype(np.uint8)


问:
how to unwind javascript object into Json object without duplicate entries
existingJsObj = {"a": [1,2,3,4], "b":[11,22,33,44]}

I want to convert this javascript into something that doesnt have array items in it, like below

desiredJsObj = [{"a":1, "b":11},{"a":2,"b":22},{"a":3, "b":33},{"a":4, "b":44}]

答:
You could iterate the keys and the values while using a new array and object for the result.

var object = { a: [1, 2, 3, 4], b: [11, 22, 33, 44] },
    array = Object.keys(object).reduce(function (r, k) {
        object[k].forEach(function (v, i) {
            (r[i] = r[i] || {})[k] = v;
        });
        return r;
    }, []);

console.log(array);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
You could iterate the keys and the values while using a new array and object for the result.

var object = { a: [1, 2, 3, 4], b: [11, 22, 33, 44] },
    array = Object.keys(object).reduce(function (r, k) {
        object[k].forEach(function (v, i) {
            (r[i] = r[i] || {})[k] = v;
        });
        return r;
    }, []);

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Doctrine entity manager find by empty array collection
I have an entity called Cycle, with a OneToMany association to CycleActeur (see code below).

I'd like to be able to fetch all Cycle objets in database with no CycleActeur objects associated, using a simple doctrine findBy* method from my controller.

That is to say something like this :

```<code>$manager = $this->getContainer()->get('doctrine.orm.entity_manager');
$cycleManager =  $manager->getRepository('ESI67Zen2Bundle:Cycle');
$cyclesWithNoCycleActeur = $cycleManager->findBy('acteurs', null);
</code>```

Is there a way to do this without having to write a specific method in the CycleRepository ?

Extract from the Cycle class code

```<code>class Cycle {
  /**
   * @ORM\OneToMany(
   *      targetEntity="CycleActeur",
   *      mappedBy="cycle",
   *      orphanRemoval=true)
   */
  private $acteurs;
}
</code>```

Extract from the Cycle class code

```<code>class CycleActeur {
 /**
  * @var Cycle Le cycle concerné
  *
  * @ORM\ManyToOne(targetEntity="Cycle", inversedBy="acteurs")
  * @ORM\JoinColumn(name="cycle_id", referencedColumnName="id")
  *
  */
  private $cycle;
}
</code>```

答:
Your Cycle entity is the inverse side of relationship and it's table in database has no 'acteurs' column, so you cannot use findBy(['acteurs'=>null]) or findByActeurs(null). But you can do something anyway:

```<code>$manager = $this->getContainer()->get('doctrine.orm.entity_manager');
$cycleManager =  $manager->getRepository('ESI67Zen2Bundle:Cycle');
$allCycles = $cycleManager->findAll();

$cyclesWithNoCycleActeur = [];
foreach($allCycles as $cycle)
{
    if($cycle->getActeurs()->isEmpty())
    {
        $cyclesWithNoCycleActeur[] = $cycle;
    }
}
</code>```

Body:
I have an entity called Cycle, with a OneToMany association to CycleActeur (see code below).

I'd like to be able to fetch all Cycle objets in database with no CycleActeur objects associated, using a simple doctrine findBy* method from my controller.

That is to say something like this :

$manager = $this->getContainer()->get('doctrine.orm.entity_manager');
$cycleManager =  $manager->getRepository('ESI67Zen2Bundle:Cycle');
$cyclesWithNoCycleActeur = $cycleManager->findBy('acteurs', null);

Is there a way to do this without having to write a specific method in the CycleRepository ?

Extract from the Cycle class code

class Cycle {
  /**
   * @ORM\OneToMany(
   *      targetEntity="CycleActeur",
   *      mappedBy="cycle",
   *      orphanRemoval=true)
   */
  private $acteurs;
}

Extract from the Cycle class code

class CycleActeur {
 /**
  * @var Cycle Le cycle concerné
  *
  * @ORM\ManyToOne(targetEntity="Cycle", inversedBy="acteurs")
  * @ORM\JoinColumn(name="cycle_id", referencedColumnName="id")
  *
  */
  private $cycle;
}

Body:
Your Cycle entity is the inverse side of relationship and it's table in database has no 'acteurs' column, so you cannot use findBy(['acteurs'=>null]) or findByActeurs(null). But you can do something anyway:

$manager = $this->getContainer()->get('doctrine.orm.entity_manager');
$cycleManager =  $manager->getRepository('ESI67Zen2Bundle:Cycle');
$allCycles = $cycleManager->findAll();

$cyclesWithNoCycleActeur = [];
foreach($allCycles as $cycle)
{
    if($cycle->getActeurs()->isEmpty())
    {
        $cyclesWithNoCycleActeur[] = $cycle;
    }
}


问:
Check if email attachment is password protected before sending
I'm trying to check all my attachments before sending an email to see if they are password protected. Typically these will be Word, Excel or PowerPoint files.

I've got as far as seeing if there are attachments.

I don't know how to loop through each attachment in the mail file to see if each one is password protected.

Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

Dim attachments2 As Outlook.attachments
Dim attachm As Outlook.Attachment

If Item.attachments.Count > 0 Then

    Set attachments2 = Item.attachments

    Set attachm = Item.Attachment

    For Each attachm In attachments2

    ' ***IM GUESSING CODE TO CHECK IF ATTACHMENTS ARE PROTECTED WOULD GO IN HERE?***

    Next

End If

End Sub
```

答:
The code below does not solve your issue, but does show how to check documents and databases to see if password protected. If you are able to obtain the file path, then this code could be modified to pass the path and filename, then return a flag to indicate PW status. Or just modify and embed this code in your module.

Revision 1:  Instead of trying to find the path of the file to check for a password, an alternate solution would be for your code to save the file to a temp folder, then delete when finished. The following line of code will give you a temp folder (i.e. C:\Users\MyName\AppData\Local\Temp)

```<code>strFolder = objFSO.GetSpecialFolder(2)
</code>```

This idea was obtained from a post that allows you to rename attachments: http://www.flobee.net/rename-outlook-attachments-before-you-send-them/

Also, the OP need to consider how to implement/perform the password check. If the code is called 'automatically', then unless you have some rule to only check certain files, then your code will always check ALL attachments for ALL emails! I doubt that's what you want to happen. Perhaps a user button on the tool bar?

Original Code:

```<code>Option Compare Database
Option Explicit

Public Function Check_For_Passwords()
Dim objWord     As Word.Application
Dim objWordDoc  As Word.Document
Dim sPath       As String
Dim sFileName   As String
Dim oAccess     As Access.Application

    On Error GoTo Error_Trap

    ' Set the following string to the path of your Word Document
    sPath = "C:\data\WP\"                   ' <<< CHANGE THIS!!
    sFileName = "Access.doc"                ' <<< CHANGE THIS!!
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = False
    ' Use a fake password - if no password on doc, OK; If password protected will fail
    Set objWordDoc = objWord.Documents.Open(sPath & sFileName, , True, , "*****")
    'Err: 5408    The password is incorrect. Word cannot open the document.

    Set oAccess = CreateObject("Access.Application")
    oAccess.Visible = False
    sPath = "C:\data\Access\"                   ' <<< CHANGE THIS!!
    sFileName = "PWD_DB.mdb"                    ' <<< CHANGE THIS!!

    'If error, then database has password
    oAccess.DBEngine.OpenDatabase sPath & sFileName, False
    'Err: 3031    Not a valid password.

    Exit Function

Error_Trap:
    If Err.Number = 5408 Then
        MsgBox "Document has a password! Do whatever...  " & sPath & sFileName
    ElseIf Err.Number = 3031 Then
        MsgBox "Access DB has a password! Do whatever...  " & sPath & sFileName
    Else
        MsgBox "Unexpected error: " * Err.Number & vbTab & Err.Description
    End If
End Function
</code>```

Body:
The code below does not solve your issue, but does show how to check documents and databases to see if password protected. If you are able to obtain the file path, then this code could be modified to pass the path and filename, then return a flag to indicate PW status. Or just modify and embed this code in your module.

Revision 1:  Instead of trying to find the path of the file to check for a password, an alternate solution would be for your code to save the file to a temp folder, then delete when finished. The following line of code will give you a temp folder (i.e. C:\Users\MyName\AppData\Local\Temp)

strFolder = objFSO.GetSpecialFolder(2)

This idea was obtained from a post that allows you to rename attachments: http://www.flobee.net/rename-outlook-attachments-before-you-send-them/

Also, the OP need to consider how to implement/perform the password check. If the code is called 'automatically', then unless you have some rule to only check certain files, then your code will always check ALL attachments for ALL emails! I doubt that's what you want to happen. Perhaps a user button on the tool bar?

Original Code:

Option Compare Database
Option Explicit

Public Function Check_For_Passwords()
Dim objWord     As Word.Application
Dim objWordDoc  As Word.Document
Dim sPath       As String
Dim sFileName   As String
Dim oAccess     As Access.Application

    On Error GoTo Error_Trap

    ' Set the following string to the path of your Word Document
    sPath = "C:\data\WP\"                   ' <<< CHANGE THIS!!
    sFileName = "Access.doc"                ' <<< CHANGE THIS!!
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = False
    ' Use a fake password - if no password on doc, OK; If password protected will fail
    Set objWordDoc = objWord.Documents.Open(sPath & sFileName, , True, , "*****")
    'Err: 5408    The password is incorrect. Word cannot open the document.

    Set oAccess = CreateObject("Access.Application")
    oAccess.Visible = False
    sPath = "C:\data\Access\"                   ' <<< CHANGE THIS!!
    sFileName = "PWD_DB.mdb"                    ' <<< CHANGE THIS!!

    'If error, then database has password
    oAccess.DBEngine.OpenDatabase sPath & sFileName, False
    'Err: 3031    Not a valid password.

    Exit Function

Error_Trap:
    If Err.Number = 5408 Then
        MsgBox "Document has a password! Do whatever...  " & sPath & sFileName
    ElseIf Err.Number = 3031 Then
        MsgBox "Access DB has a password! Do whatever...  " & sPath & sFileName
    Else
        MsgBox "Unexpected error: " * Err.Number & vbTab & Err.Description
    End If
End Function


问:
get the final result after looping through a list of data
I have a set of data in an array. Where the first value will denote the number of records and second number will denote the number of data in one record accordingly. Data will loop and calculate until the number of records equals to 0.

3 -> set 1 - no of records 3

  2 -> record 1 contain two data values

  10.00 -> data1

  20.00 -> data2

  4 -> record 2 contain four data values

  15.00

  15.01

  3.00

  3.01

  3

  5.00

  9.00

  4.00

  2 -> set 2 - no of records 2

  2

  8.00

  6.00

  2

  9.20

  6.75

  0

I need to calculate the sum of one set of records and need to divide it from the no of records and then need to minimise that value from each of the record to get the value (which gets after reduction of summation/no of records)

output

(1st set of records)

  1.99

  8.01

  10.01

  (2nd set of records)

  0.98 -> ((8.00+6.00) + (9.20+6.75))/2 - (8.00+6.00)

  0.98

This is the code I came up with but the results I am getting are different and could not find where it got wrong.

my output

171.38 <- 1st set of records

  135.36

  117.36

  118.57 <- 2nd set of records

  102.62

```<code>// (inputLines is the name of the array with data)

int data = 0;
float temp = 0;
List<string> tempOutputFileList = new List<string>();

while (inputLines[data] != "0")
{
    var listOfPeople = new List<float>();
    int people = int.Parse(inputLines[data]);

    for (int n = 0; n < people; n++)
    {
        data = data + 1;
        int receipts = int.Parse(inputLines[data]);

        for (int p = 0; p < receipts; p++)
        {
            data = data + 1;
            temp += float.Parse(inputLines[data]);
            listOfPeople.Add(temp);

            if (listOfPeople[n].ToString() != null)
            {
                listOfPeople[n] = temp;
            }
        }
    }

    float sum = 0;
    string tempValue = null;
    double receiptValue = 0;

    foreach (float item in listOfPeople)
    {
        sum += item;
    }

    for (int v = 0; v < people; v++)
    {
        receiptValue = (sum / people - listOfPeople[v]);
    }

    data++;
    tempOutputFileList.Add(" ");
    listOfPeople.Clear();
}

foreach (string val in tempOutputFileList)
{
    Console.WriteLine(val);
}
</code>```

答:
You need to compute average after summing a whole set of records. However, on the other hand you can also simplify the way to compute the average if you only store the sums per people. See the following code that produces the results you expected (however some with different sign):</p>

```<code>        int data = 0;
        List<string> tempOutputFileList = new List<string>();

        while (inputLines[data] != "0")
        {
            var listOfPeople = new List<float>();
            int people = int.Parse(inputLines[data++]);

            for (int n = 0; n < people; n++)
            {
                int receipts = int.Parse(inputLines[data++]);
                float tempPeople = 0;

                for (int p = 0; p < receipts; p++)
                {
                    tempPeople += float.Parse(inputLines[data++]);
                }

                listOfPeople.Add(tempPeople);
            }

            foreach (float item in listOfPeople)
            {
                Console.WriteLine(listOfPeople.Average() - item);
            }
        }

        Console.ReadLine();
</code>```

Body:
I have a set of data in an array. Where the first value will denote the number of records and second number will denote the number of data in one record accordingly. Data will loop and calculate until the number of records equals to 0.

3 -> set 1 - no of records 3

  2 -> record 1 contain two data values

  10.00 -> data1

  20.00 -> data2

  4 -> record 2 contain four data values

  15.00

  15.01

  3.00

  3.01

  3

  5.00

  9.00

  4.00

  2 -> set 2 - no of records 2

  2

  8.00

  6.00

  2

  9.20

  6.75

  0

I need to calculate the sum of one set of records and need to divide it from the no of records and then need to minimise that value from each of the record to get the value (which gets after reduction of summation/no of records)

output

(1st set of records)

  1.99

  8.01

  10.01

  (2nd set of records)

  0.98 -> ((8.00+6.00) + (9.20+6.75))/2 - (8.00+6.00)

  0.98

This is the code I came up with but the results I am getting are different and could not find where it got wrong.

my output

171.38 <- 1st set of records

  135.36

  117.36

  118.57 <- 2nd set of records

  102.62

// (inputLines is the name of the array with data)

int data = 0;
float temp = 0;
List<string> tempOutputFileList = new List<string>();

while (inputLines[data] != "0")
{
    var listOfPeople = new List<float>();
    int people = int.Parse(inputLines[data]);

    for (int n = 0; n < people; n++)
    {
        data = data + 1;
        int receipts = int.Parse(inputLines[data]);

        for (int p = 0; p < receipts; p++)
        {
            data = data + 1;
            temp += float.Parse(inputLines[data]);
            listOfPeople.Add(temp);

            if (listOfPeople[n].ToString() != null)
            {
                listOfPeople[n] = temp;
            }
        }
    }

    float sum = 0;
    string tempValue = null;
    double receiptValue = 0;

    foreach (float item in listOfPeople)
    {
        sum += item;
    }

    for (int v = 0; v < people; v++)
    {
        receiptValue = (sum / people - listOfPeople[v]);
    }

    data++;
    tempOutputFileList.Add(" ");
    listOfPeople.Clear();
}

foreach (string val in tempOutputFileList)
{
    Console.WriteLine(val);
}

Body:
You need to compute average after summing a whole set of records. However, on the other hand you can also simplify the way to compute the average if you only store the sums per people. See the following code that produces the results you expected (however some with different sign):

        int data = 0;
        List<string> tempOutputFileList = new List<string>();

        while (inputLines[data] != "0")
        {
            var listOfPeople = new List<float>();
            int people = int.Parse(inputLines[data++]);

            for (int n = 0; n < people; n++)
            {
                int receipts = int.Parse(inputLines[data++]);
                float tempPeople = 0;

                for (int p = 0; p < receipts; p++)
                {
                    tempPeople += float.Parse(inputLines[data++]);
                }

                listOfPeople.Add(tempPeople);
            }

            foreach (float item in listOfPeople)
            {
                Console.WriteLine(listOfPeople.Average() - item);
            }
        }

        Console.ReadLine();


问:
Select Customer ID who hasnt purchased product X
I have a table of customer IDs and Products Purchased.  A customer ID can purchase multiple products over time.

customerID, productID

In BigQuery I need to find the CustomerID for those who have not purchased product A.

I've been going around in circles trying to do self joins, inner joins, but I'm clueless.

Any help appreciated.

答:
Below is for BigQuery Standard SQL

```<code>#standardSQL
SELECT CustomerID
FROM `project.dataset.yourTable`
GROUP BY CustomerID
HAVING COUNTIF(Product = 'A') = 0
</code>```

You can test / play with it using dummy data as below

```<code>#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT 1234 CustomerID, 'A' Product UNION ALL
  SELECT 11234, 'A' UNION ALL
  SELECT 4567, 'A' UNION ALL
  SELECT 7896, 'C' UNION ALL
  SELECT 5432, 'B'
)
SELECT CustomerID
FROM `project.dataset.yourTable`
GROUP BY CustomerID
HAVING COUNTIF(Product = 'A') = 0
</code>```

how would I adjust this so it could be productID contains "xyz"

```<code>#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT 1234 CustomerID, 'Axyz' Product UNION ALL
  SELECT 11234, 'A' UNION ALL
  SELECT 4567, 'A' UNION ALL
  SELECT 7896, 'Cxyz' UNION ALL
  SELECT 5432, 'B'
)
SELECT CustomerID
FROM `project.dataset.yourTable`
GROUP BY CustomerID
HAVING COUNTIF(REGEXP_CONTAINS(Product, 'xyz')) = 0
</code>```

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT CustomerID
FROM `project.dataset.yourTable`
GROUP BY CustomerID
HAVING COUNTIF(Product = 'A') = 0

You can test / play with it using dummy data as below

#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT 1234 CustomerID, 'A' Product UNION ALL
  SELECT 11234, 'A' UNION ALL
  SELECT 4567, 'A' UNION ALL
  SELECT 7896, 'C' UNION ALL
  SELECT 5432, 'B'
)
SELECT CustomerID
FROM `project.dataset.yourTable`
GROUP BY CustomerID
HAVING COUNTIF(Product = 'A') = 0

how would I adjust this so it could be productID contains "xyz"

#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT 1234 CustomerID, 'Axyz' Product UNION ALL
  SELECT 11234, 'A' UNION ALL
  SELECT 4567, 'A' UNION ALL
  SELECT 7896, 'Cxyz' UNION ALL
  SELECT 5432, 'B'
)
SELECT CustomerID
FROM `project.dataset.yourTable`
GROUP BY CustomerID
HAVING COUNTIF(REGEXP_CONTAINS(Product, 'xyz')) = 0


问:
Why do byte arrays turn to gibberish when serialized?
What happens to the original structure of the data that was passed through a call like this:

```<code> MyImg bytes = new MyImg
            {
                Id = 1,
                Img = new byte[] { 1, 0, 5 },
                Text = "hiiiiiii"
            };

        IFormatter formatter2 = new BinaryFormatter();
        using (MemoryStream stream = new MemoryStream())
        {
            formatter2.Serialize(stream, bytes);
            bytes.Img = stream.ToArray();
        }
</code>```

There is a lot of abstraction to how this produces:

{"id":1,"img":"AAEAAAD/////AQAAAAAAAAAMAgAAAEpNZXNzYWdlQm9hcmRCYWNrZW5kLCBWZXJzaW9uPTEuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbAUBAAAAJU1lc3NhZ2VCb2FyZEJhY2tlbmQuQ29udHJvbGxlcnMuTXlJbWcDAAAAEzxJZD5rX19CYWNraW5nRmllbGQUPEltZz5rX19CYWNraW5nRmllbGQVPFRleHQ+a19fQmFja2luZ0ZpZWxkAAcBCAICAAAAAQAAAAkDAAAABgQAAAAIaGlpaWlpaWkPAwAAAAMAAAACAQAFCw==","text":"hiiiiiii"}

Im just trying to understand whats going on.

Is serial/deserialization a universal process or does .Net do something different then Java?

答: Your byte array is encoded as Base64 string in JSON, that's a common way to make sure your serialized bytes don't contain characters that aren't printable or used by the serializers themselves (for example < or > in XML, { or } in JSON etc.)

Body:
What happens to the original structure of the data that was passed through a call like this:

 MyImg bytes = new MyImg
            {
                Id = 1,
                Img = new byte[] { 1, 0, 5 },
                Text = "hiiiiiii"
            };

        IFormatter formatter2 = new BinaryFormatter();
        using (MemoryStream stream = new MemoryStream())
        {
            formatter2.Serialize(stream, bytes);
            bytes.Img = stream.ToArray();
        }

There is a lot of abstraction to how this produces:

{"id":1,"img":"AAEAAAD/////AQAAAAAAAAAMAgAAAEpNZXNzYWdlQm9hcmRCYWNrZW5kLCBWZXJzaW9uPTEuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbAUBAAAAJU1lc3NhZ2VCb2FyZEJhY2tlbmQuQ29udHJvbGxlcnMuTXlJbWcDAAAAEzxJZD5rX19CYWNraW5nRmllbGQUPEltZz5rX19CYWNraW5nRmllbGQVPFRleHQ+a19fQmFja2luZ0ZpZWxkAAcBCAICAAAAAQAAAAkDAAAABgQAAAAIaGlpaWlpaWkPAwAAAAMAAAACAQAFCw==","text":"hiiiiiii"}

Im just trying to understand whats going on.

Is serial/deserialization a universal process or does .Net do something different then Java?


问:
unsupported operand types in django
first date

```<code>    d = datetime.datetime.utcnow().replace(tzinfo=utc)
</code>```

second date

```<code>    checkin = models.DateTimeField(default = timezone.now)
    e = Checkin.objects.all().values()
    t = last value in 'e'
    co = d.time()
    ci = t.time()
</code>```

I want difference between 'co' and 'ci'

答:
It looks like you probably need to make both of your datetime objects time zone aware.

I have a local Page model that has a DateTimeField called first_published_at. Here's how I handle:

```<code>target_tz = datetime.tzinfo('utc')
now_dt = datetime.datetime.utcnow().replace(tzinfo=target_tz)
inst = m.Page.objects.get(pk=18)
model_dt = inst.first_published_at.replace(tzinfo=target_tz)

print(now_dt - model_dt) # 734 days, 12:46:53.059321
</code>```

Or you could make both of them timezone naive:

```<code>target_tz = None
now_dt = datetime.datetime.utcnow().replace(tzinfo=target_tz)
inst = m.Page.objects.get(pk=18)
model_dt = inst.first_published_at.replace(tzinfo=target_tz)

print(now_dt - model_dt) # Same as above
</code>```

Title: unsupported operand types in django

Body:
first date

    d = datetime.datetime.utcnow().replace(tzinfo=utc)

second date

    checkin = models.DateTimeField(default = timezone.now)
    e = Checkin.objects.all().values()
    t = last value in 'e'
    co = d.time()
    ci = t.time()

I want difference between 'co' and 'ci'

Body:
It looks like you probably need to make both of your datetime objects time zone aware.

I have a local Page model that has a DateTimeField called first_published_at. Here's how I handle:

target_tz = datetime.tzinfo('utc')
now_dt = datetime.datetime.utcnow().replace(tzinfo=target_tz)
inst = m.Page.objects.get(pk=18)
model_dt = inst.first_published_at.replace(tzinfo=target_tz)

print(now_dt - model_dt) # 734 days, 12:46:53.059321

Or you could make both of them timezone naive:

target_tz = None
now_dt = datetime.datetime.utcnow().replace(tzinfo=target_tz)
inst = m.Page.objects.get(pk=18)
model_dt = inst.first_published_at.replace(tzinfo=target_tz)

print(now_dt - model_dt) # Same as above


问:
Possible to open calendar widget after clicking anywhere in input?
I am working on a React component for a date picker. Specifically, I am trying to open the calendar widget in HTML5 date input whenever someone clicks anywhere inside the input, not just on the arrow icon. My current code is below, but for some reason the calendar won't open unless I click the arrow. I have also tried sending a F4 keyboard event to no avail.</p>

```<code>class DateInput extends React.Component {
  private input;

  onClick = e => {
    if (this.input) {
      this.input.focus();
    }
  }

  render() {
     const { value, onChange } = this.props;

     return (
      <input
        ref={input => (this.input = input)}
        type='date'
        value={value}
        onChange={onChange}
        onClick={this.onClick} />
    );
  }
}
</code>```

答:
i suggest you to put a <View> component over this input and put onClick event on it like code below :

```<code>class DateInput extends React.Component {
  private input;

  onClick = e => {
    if (this.input) {
      this.input.focus();
    }
  }

  render() {
     const { value, onChange } = this.props;

     return (
      <View onClick={this.onClick = this.onClick.bind(this)}>
      <input
        ref={input => (this.input = input)}
        type='date'
        value={value}
        onChange={onChange}
        onClick={this.onClick} />
      </View>
    );
  }
}
</code>```

Body:
I am working on a React component for a date picker. Specifically, I am trying to open the calendar widget in HTML5 date input whenever someone clicks anywhere inside the input, not just on the arrow icon. My current code is below, but for some reason the calendar won't open unless I click the arrow. I have also tried sending a F4 keyboard event to no avail.

class DateInput extends React.Component {
  private input;

  onClick = e => {
    if (this.input) {
      this.input.focus();
    }
  }

  render() {
     const { value, onChange } = this.props;

     return (
      <input
        ref={input => (this.input = input)}
        type='date'
        value={value}
        onChange={onChange}
        onClick={this.onClick} />
    );
  }
}

Body:
i suggest you to put a <View> component over this input and put onClick event on it like code below :

class DateInput extends React.Component {
  private input;

  onClick = e => {
    if (this.input) {
      this.input.focus();
    }
  }

  render() {
     const { value, onChange } = this.props;

     return (
      <View onClick={this.onClick = this.onClick.bind(this)}>
      <input
        ref={input => (this.input = input)}
        type='date'
        value={value}
        onChange={onChange}
        onClick={this.onClick} />
      </View>
    );
  }
}


问:
Spicing C with classes
Disclaimer: I am a complete newbie with C, but I've been playing with it trying to mimic some features of classes. Ok, I know that if I want to go that way I should learn C++, but consider the following a little experiment.

Schreiner, in the book Object-oriented programming with ANSI-C suggests a way to use pointers to get object orientation features in C. I must admit I have only skimmed through the book, but I don't like his approach too much. Basically, he uses pointers to functions in order to arrange that

```<code>func(foo);
</code>```

actually results in calling

```<code>foo.methods->func();
</code>```

where foo.methods is a struct containing pointers to functions. The thing I do not like in this approach is that one has to have the global function foo anyway; that is, methods are not namespaced by the class they live in. My feeling is that this will soon lead to clutter: think two objects foo and bar, both having a method func but with a different number of parameters.

So I have tried to get something more fit to my taste. A first attempt is the following (I omit the declarations for sake of brevity)

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

//Instances of this struct will be my objects
struct foo {
    //Properties
    int bar;

    //Methods
    void (* print)(struct foo self);
    void (* printSum)(struct foo self, int delta);
};

//Here is the actual implementation of the methods
static void printFoo(struct foo self) {
    printf("This is bar: %d\n", self.bar);
}

static void printSumFoo(struct foo self, int delta) {
    printf("This is bar plus delta: %d\n", self.bar + delta);
}

//This is a sort of constructor
struct foo Foo(int bar) {
    struct foo foo = {
        .bar = bar,
        .print = &printFoo,
        .printSum = &printSumFoo
    };
    return foo;
}

//Finally, this is how one calls the methods
void
main(void) {
    struct foo foo = Foo(14);
    foo.print(foo); // This is bar: 14
    foo.printSum(foo, 2); // This is bar plus delta: 16
}
</code>```

This is unconvenient but sort of works. What I do not like, though, is that you have to explicitly add the object itself as the first argument. With some preprocessor work I can do a little better:

```<code>#include <stdio.h>
#define __(stuff)     stuff.method(* stuff.object)

//Instances of this struct will be my objects
struct foo {
    //Properties
    int bar;

    //Methods
    //Note: these are now struct themselves
    //and they contain a pointer the object...
    struct {
        void (* method)(struct foo self);
        struct foo * object;
    } print;
};

//Here is the actual implementation of the methods
static void printFoo(struct foo self) {
    printf("This is bar: %d\n", self.bar);
}

//This is a sort of constructor
struct foo Foo(int bar) {
    struct foo foo = {
        .bar = bar,
        //...hence initialization is a little bit different
        .print = {
            .method = &printFoo,
            .object = &foo
        }
    };
    return foo;
}

//Finally, this is how one calls the methods
void
main(void) {
    struct foo foo = Foo(14);
    //This is long and unconvenient...
    foo.print.method(* foo.print.object); // This is bar: 14
    //...but it can be shortened by the preprocessor
    __(foo.print); // This is bar: 14
}
</code>```

This is as far as I can get. The problem here is that it will not work for methods with arguments, as preprocessor macros cannot take a variable number of arguments. Of course one can define macros _0, _1 and so on according to the number of arguments (until one gets tired), but this is hardly a good approach.

Is there any way to improve on this and let C use a more object-oriented syntax?

I should add that actually Schreiner does much more than what I said in his book, but I think the basic construction does not change.

答: Various frameworks already exists.  See for instance http://ldeniau.web.cern.ch/ldeniau/html/oopc.html</p>

ContentLicense: CC BY-SA 2.5

Title: Spicing C with classes

Body:
Disclaimer: I am a complete newbie with C, but I've been playing with it trying to mimic some features of classes. Ok, I know that if I want to go that way I should learn C++, but consider the following a little experiment.

Schreiner, in the book Object-oriented programming with ANSI-C suggests a way to use pointers to get object orientation features in C. I must admit I have only skimmed through the book, but I don't like his approach too much. Basically, he uses pointers to functions in order to arrange that

func(foo);

actually results in calling

foo.methods->func();

where foo.methods is a struct containing pointers to functions. The thing I do not like in this approach is that one has to have the global function foo anyway; that is, methods are not namespaced by the class they live in. My feeling is that this will soon lead to clutter: think two objects foo and bar, both having a method func but with a different number of parameters.

So I have tried to get something more fit to my taste. A first attempt is the following (I omit the declarations for sake of brevity)

#include <stdio.h>

//Instances of this struct will be my objects
struct foo {
    //Properties
    int bar;

    //Methods
    void (* print)(struct foo self);
    void (* printSum)(struct foo self, int delta);
};

//Here is the actual implementation of the methods
static void printFoo(struct foo self) {
    printf("This is bar: %d\n", self.bar);
}

static void printSumFoo(struct foo self, int delta) {
    printf("This is bar plus delta: %d\n", self.bar + delta);
}

//This is a sort of constructor
struct foo Foo(int bar) {
    struct foo foo = {
        .bar = bar,
        .print = &printFoo,
        .printSum = &printSumFoo
    };
    return foo;
}

//Finally, this is how one calls the methods
void
main(void) {
    struct foo foo = Foo(14);
    foo.print(foo); // This is bar: 14
    foo.printSum(foo, 2); // This is bar plus delta: 16
}

This is unconvenient but sort of works. What I do not like, though, is that you have to explicitly add the object itself as the first argument. With some preprocessor work I can do a little better:

#include <stdio.h>
#define __(stuff)     stuff.method(* stuff.object)

//Instances of this struct will be my objects
struct foo {
    //Properties
    int bar;

    //Methods
    //Note: these are now struct themselves
    //and they contain a pointer the object...
    struct {
        void (* method)(struct foo self);
        struct foo * object;
    } print;
};

//Here is the actual implementation of the methods
static void printFoo(struct foo self) {
    printf("This is bar: %d\n", self.bar);
}

//This is a sort of constructor
struct foo Foo(int bar) {
    struct foo foo = {
        .bar = bar,
        //...hence initialization is a little bit different
        .print = {
            .method = &printFoo,
            .object = &foo
        }
    };
    return foo;
}

//Finally, this is how one calls the methods
void
main(void) {
    struct foo foo = Foo(14);
    //This is long and unconvenient...
    foo.print.method(* foo.print.object); // This is bar: 14
    //...but it can be shortened by the preprocessor
    __(foo.print); // This is bar: 14
}

This is as far as I can get. The problem here is that it will not work for methods with arguments, as preprocessor macros cannot take a variable number of arguments. Of course one can define macros _0, _1 and so on according to the number of arguments (until one gets tired), but this is hardly a good approach.

Is there any way to improve on this and let C use a more object-oriented syntax?

I should add that actually Schreiner does much more than what I said in his book, but I think the basic construction does not change.


问:
Add protobuf file as dependency to py_proto_library in Bazel
I would like to import a.proto into b.proto and compile with Bazel.

BUILD:

```<code>py_proto_library(
    name = "b_py_proto",
    protos = ["b.proto"],
    deps = [
        ":a_proto"
    ]
)

py_proto_library(
  name = "a_proto",
  protos = ["a.proto"]
)
</code>```

b.proto

```<code>import public "a.proto";
</code>```

When I run it with Bazel I get does not have mandatory providers: 'py'. error, even though according to the example here that's how it should work.

I tried using filegroup to add a.proto as a dependency, and same error, because apparently deps expects python files.
Is py_proto_library operating differently than java_proto_library? If so, how can I add a.proto as dependency so that it gets imported correctly?

EDIT:
I am loading protobuf from https://github.com/pubref/rules_protobuf/archive/v0.8.1.tar.gz

This rule accepts .proto files if you pass them as proto_deps, but then I get an error Import "a.proto" was not found or had errors.

Maybe I should specify imports somehow?

答:
Finally figured this out. My confusion came from the fact that there are different protobuf libraries with different definitions:

https://github.com/pubref/rules_protobuf/blob/master/python/rules.bzl

https://github.com/google/protobuf/blob/master/protobuf.bzl

I was using the first one, and that one takes the .proto dependencies as proto_deps. Another thing I missed is that the import statemnt path has to be relative to the WORKSPACE file.

b.proto:

```<code>import public "path/relative/to/WORKSPACE/a.proto";
</code>```

BUILD:

```<code>py_proto_library(
    name = "b_py_proto",
    protos = ["b.proto"],
    proto_deps = [
        ":a_proto"
    ]
)

py_proto_library(
  name = "a_proto",
  protos = ["a.proto"]
)
</code>```

WORKSPACE:

```<code>http_archive(
    name = "org_pubref_rules_protobuf",
    strip_prefix = "rules_protobuf-0.8.1",
    urls = ["https://github.com/pubref/rules_protobuf/archive/v0.8.1.tar.gz"],
    sha256 = "fb9852446b5ba688cd7178a60ff451623e4112d015c6adfe0e9a06c5d2dedc08"
)

load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_repositories")
py_proto_repositories()
</code>```

Body:
I would like to import a.proto into b.proto and compile with Bazel.

BUILD:

py_proto_library(
    name = "b_py_proto",
    protos = ["b.proto"],
    deps = [
        ":a_proto"
    ]
)

py_proto_library(
  name = "a_proto",
  protos = ["a.proto"]
)

b.proto

import public "a.proto";

When I run it with Bazel I get does not have mandatory providers: 'py'. error, even though according to the example here that's how it should work.

I tried using filegroup to add a.proto as a dependency, and same error, because apparently deps expects python files.
Is py_proto_library operating differently than java_proto_library? If so, how can I add a.proto as dependency so that it gets imported correctly?

EDIT:
I am loading protobuf from https://github.com/pubref/rules_protobuf/archive/v0.8.1.tar.gz

This rule accepts .proto files if you pass them as proto_deps, but then I get an error Import "a.proto" was not found or had errors.

Maybe I should specify imports somehow?

Body:
Finally figured this out. My confusion came from the fact that there are different protobuf libraries with different definitions:

https://github.com/pubref/rules_protobuf/blob/master/python/rules.bzl

https://github.com/google/protobuf/blob/master/protobuf.bzl

I was using the first one, and that one takes the .proto dependencies as proto_deps. Another thing I missed is that the import statemnt path has to be relative to the WORKSPACE file.

b.proto:

import public "path/relative/to/WORKSPACE/a.proto";

BUILD:

py_proto_library(
    name = "b_py_proto",
    protos = ["b.proto"],
    proto_deps = [
        ":a_proto"
    ]
)

py_proto_library(
  name = "a_proto",
  protos = ["a.proto"]
)

WORKSPACE:

http_archive(
    name = "org_pubref_rules_protobuf",
    strip_prefix = "rules_protobuf-0.8.1",
    urls = ["https://github.com/pubref/rules_protobuf/archive/v0.8.1.tar.gz"],
    sha256 = "fb9852446b5ba688cd7178a60ff451623e4112d015c6adfe0e9a06c5d2dedc08"
)

load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_repositories")
py_proto_repositories()


问:
Better method for acting upon state change in JavaScript classes
I'm trying to move from procedural to object-oriented JavaScript and I'm coming up against an issue I'm sure there's an answer to, but I can't work it out.

Currently, each of my methods checks the state of a property, and then performs an action based on that state. What I'd rather do is update the state and those methods execute as a result of the state change. Is that possible, or am I missing the point?

Here's what I have currently:

```<code>class ClassExample {
    constructor({state = false} = {}) {
        this.state = state;
        ...
    }

    aMethod() {
        if(this.state) {
            //Do something
            this.state = false;
        } else {
            //Do something else
            this.state = true;
        }
    }

    bMethod() {
        if(this.state) {
            //Do something
            this.state = false;
        } else {
            //Do something else
            this.state = true;
        }
    }
}
</code>```

And:

```<code>const myObject = new ClassExample();
myObject.aMethod();
myObject.bMethod();
</code>```

Given both methods are checking the same property, it's resulting in a lot of redundant if statements. Is there a better way to organise this class to achieve the same result?

答:
I'd suggest you use an event driven system based on the EventEmitter() object built into node.js.

To keep track of state changes, you can define a setter for your state variables so that any time someone sets a new state, then your setter function will get called and it can then trigger an event that indicates the state changed.  Meanwhile, anyone in your object out outside your object can register an event listener for state changes.

Here's a short example:

```<code>const EventEmitter = require('events');

class ClassExample extends EventEmitter {
    constructor(state = 0) {
        super();
        // declare private state variable
        let internalState = state;
        // define setter and getter for private state variable
        Object.defineProperty(this, "state", {
            get: function() {
                return internalState;
            },
            set: function(val) {
                if (internalState !== val) {
                    internalState = val;
                    // send out notification
                    this.emit("stateChanged", val);
                }
            }
        });
    }
}

let e = new ClassExample(1);
console.log(e.state);

e.on("stateChanged", function(newVal) {
    console.log("state has changed to ", newVal);
});

e.state = 3;
console.log(e.state);
</code>```

Body:
I'm trying to move from procedural to object-oriented JavaScript and I'm coming up against an issue I'm sure there's an answer to, but I can't work it out.

Currently, each of my methods checks the state of a property, and then performs an action based on that state. What I'd rather do is update the state and those methods execute as a result of the state change. Is that possible, or am I missing the point?

Here's what I have currently:

class ClassExample {
    constructor({state = false} = {}) {
        this.state = state;
        ...
    }

    aMethod() {
        if(this.state) {
            //Do something
            this.state = false;
        } else {
            //Do something else
            this.state = true;
        }
    }

    bMethod() {
        if(this.state) {
            //Do something
            this.state = false;
        } else {
            //Do something else
            this.state = true;
        }
    }
}

And:

const myObject = new ClassExample();
myObject.aMethod();
myObject.bMethod();

Given both methods are checking the same property, it's resulting in a lot of redundant if statements. Is there a better way to organise this class to achieve the same result?

Body:
I'd suggest you use an event driven system based on the EventEmitter() object built into node.js.

To keep track of state changes, you can define a setter for your state variables so that any time someone sets a new state, then your setter function will get called and it can then trigger an event that indicates the state changed.  Meanwhile, anyone in your object out outside your object can register an event listener for state changes.

Here's a short example:

const EventEmitter = require('events');

class ClassExample extends EventEmitter {
    constructor(state = 0) {
        super();
        // declare private state variable
        let internalState = state;
        // define setter and getter for private state variable
        Object.defineProperty(this, "state", {
            get: function() {
                return internalState;
            },
            set: function(val) {
                if (internalState !== val) {
                    internalState = val;
                    // send out notification
                    this.emit("stateChanged", val);
                }
            }
        });
    }
}

let e = new ClassExample(1);
console.log(e.state);

e.on("stateChanged", function(newVal) {
    console.log("state has changed to ", newVal);
});

e.state = 3;
console.log(e.state);


问:
How to rasterize a specific angle of circle, MIDPOINT
I'm facing a problem. I'm trying to rasterize just part of circle using midpoint algorithm. The part is entered by startAngle, endAngle.

With help of google I did this:

```<code>public RasterImage<PixelType> rasterizeCircleSector(RasterImage<PixelType> img,
                                                    double centerX, double centerY,
                                                    double x, double y,
                                                    int startAngle, int endAngle,
                                                    PixelType value){

    RasterImage<PixelType> result = img;

    int angle = (int)toDegrees(atan2(y, x));

    if(x<y) {
        if (90 - angle >= startAngle && 90 - angle <= endAngle) {
            result.withPixel((int) (centerX - y), (int) (centerY - x), value);
        }
        if (angle >= startAngle && angle <= endAngle) {
            result.withPixel((int) (centerX - x), (int) (centerY - y), value);
        }
        if (180 - angle >= startAngle && 180 - angle <= endAngle) {
            result.withPixel((int) (centerX + x), (int) (centerY - y), value);
        }
        if (angle + 90 >= startAngle && angle + 90 <= endAngle) {
            result.withPixel((int) (centerX + y), (int) (centerY - x), value);
        }
        if (270 - angle >= startAngle && 270 - angle <= endAngle) {
            result.withPixel((int) (centerX + y), (int) (centerY + x), value);
        }
        if (angle + 180 >= startAngle && angle + 180 <= endAngle) {
            result.withPixel((int) (centerX + x), (int) (centerY + y), value);
        }
        if (360 - angle >= startAngle && 360 - angle <= endAngle) {
            result.withPixel((int) (centerX - x), (int) (centerY + y), value);
        }
        if (angle + 270 >= startAngle && angle + 270 <= endAngle) {
            result.withPixel((int) (centerX - y), (int) (centerY + x), value);
        }
    }
    return result;
}
</code>```

Angles work fine, but the problem is that, I do not know how to rasterize every point on circle (this code rasterize just 8 points)

Calling function:

```<code>    rasterImage = linerCircle.rasterizeCircleSector(rasterImage,200,200,
            15, 30,
            1, 200,
            0xf0f0f0);
</code>```

and the result is:

Can anybody help me? or is this method completely wrong?

Thank you.

答:
Midpoint (and Bresenham) algorithm usually fill one octant (sometimes one quadrant) of  circle, mirroring points to fill other octants.

At first you need to determine - what octant start and end angles belong to, and what octants are filled completely (if exist).

Then get x/y limits for starting and ending angles.

Then apply midpoint algorithm, omitting points that lie out of calculated x/y limits and filling needed parts of the circle.

Body:
I'm facing a problem. I'm trying to rasterize just part of circle using midpoint algorithm. The part is entered by startAngle, endAngle.

With help of google I did this:

public RasterImage<PixelType> rasterizeCircleSector(RasterImage<PixelType> img,
                                                    double centerX, double centerY,
                                                    double x, double y,
                                                    int startAngle, int endAngle,
                                                    PixelType value){

    RasterImage<PixelType> result = img;

    int angle = (int)toDegrees(atan2(y, x));

    if(x<y) {
        if (90 - angle >= startAngle && 90 - angle <= endAngle) {
            result.withPixel((int) (centerX - y), (int) (centerY - x), value);
        }
        if (angle >= startAngle && angle <= endAngle) {
            result.withPixel((int) (centerX - x), (int) (centerY - y), value);
        }
        if (180 - angle >= startAngle && 180 - angle <= endAngle) {
            result.withPixel((int) (centerX + x), (int) (centerY - y), value);
        }
        if (angle + 90 >= startAngle && angle + 90 <= endAngle) {
            result.withPixel((int) (centerX + y), (int) (centerY - x), value);
        }
        if (270 - angle >= startAngle && 270 - angle <= endAngle) {
            result.withPixel((int) (centerX + y), (int) (centerY + x), value);
        }
        if (angle + 180 >= startAngle && angle + 180 <= endAngle) {
            result.withPixel((int) (centerX + x), (int) (centerY + y), value);
        }
        if (360 - angle >= startAngle && 360 - angle <= endAngle) {
            result.withPixel((int) (centerX - x), (int) (centerY + y), value);
        }
        if (angle + 270 >= startAngle && angle + 270 <= endAngle) {
            result.withPixel((int) (centerX - y), (int) (centerY + x), value);
        }
    }
    return result;
}

Angles work fine, but the problem is that, I do not know how to rasterize every point on circle (this code rasterize just 8 points)

Calling function:

    rasterImage = linerCircle.rasterizeCircleSector(rasterImage,200,200,
            15, 30,
            1, 200,
            0xf0f0f0);

and the result is:

Can anybody help me? or is this method completely wrong?

Thank you.


问:
Treating class as a constant
```<code>abstract class Coin{
    String name;
    String currency;

    class EUR extends Coin{
        EUR() {
        super("EUR", "€");
        }

    }
    class USD extends Coin{
        USD() {
        super("USD", "$");
        }

    }

    private Coin (String name, String currency){
    this.name = name
    this.currency = currency}
    }

class Person{
    ///variables
    Coin coin;

    Person(//Variables, Coin coin){
        //Other assignments
        this.coin = coin
    }

}
</code>```

Basically i would like to initialize a Person passing EUR as Coin, without creating a new EUR.
Something like

```<code>static final EUR euro = EUR
</code>```

and then:

```<code>Person person = new Person(... , euro);
</code>```

I do not need millions of instances of EUR so i don't want to create each time a new EUR

I know i can make something like this using constant Strings, but i actually want to pass a Coin object

I also tried initializing EUR inside Coin class like this

```<code>static EUR euro = new EUR();
</code>```

But IDE is warning me this could cause thread deadlock

答:
This is a perfect job for an enum:

```<code>public enum Coin {
    EUR("EUR", "€"),
    USD("USD", "$");

    private String name;
    private String currency;

    private Coin(String name, String currency) {
        this.name = name;
        this.currency = currency;
    }
}
</code>```

Once you've defined it, you can use the enum constants:

```<code>Person person = new Person(... , Coin.EUR);
</code>```

Title: Treating class as a constant

Body:
abstract class Coin{
    String name;
    String currency;

    class EUR extends Coin{
        EUR() {
        super("EUR", "€");
        }

    }
    class USD extends Coin{
        USD() {
        super("USD", "$");
        }

    }

    private Coin (String name, String currency){
    this.name = name
    this.currency = currency}
    }

class Person{
    ///variables
    Coin coin;

    Person(//Variables, Coin coin){
        //Other assignments
        this.coin = coin
    }

}

Basically i would like to initialize a Person passing EUR as Coin, without creating a new EUR.
Something like

static final EUR euro = EUR

and then:

Person person = new Person(... , euro);

I do not need millions of instances of EUR so i don't want to create each time a new EUR

I know i can make something like this using constant Strings, but i actually want to pass a Coin object

I also tried initializing EUR inside Coin class like this

static EUR euro = new EUR();

But IDE is warning me this could cause thread deadlock

Body:
This is a perfect job for an enum:

public enum Coin {
    EUR("EUR", "€"),
    USD("USD", "$");

    private String name;
    private String currency;

    private Coin(String name, String currency) {
        this.name = name;
        this.currency = currency;
    }
}

Once you've defined it, you can use the enum constants:

Person person = new Person(... , Coin.EUR);


问:
Allow "semi anonymous" authentication
I have a case where I need some controller methods to be accessible either by an authenticated user, or if the request contains a sort of "acccess token" in the url.

For example:

Either an authenticated user could make a call to:
https://example.com/some/resource

Or a non authenticated user could make the same call, but add some kind of token to the url (or as a header):
https://example.com/some/resource?token=123abc

The token does not have to be super secret, only something hard to guess.

```<code>[AllowSpecialToken]
[HttpGet]
[Route("some/resource")]
public async Task<string> GetSomeResource()
{
    return "some resource";
}
</code>```

What I'm struggling with is how to write the AllowSpecialTokenAttribute. And how to get that to run before the authentication (using OpenIddict) we have in place now.

Is this a stupid use case? Should I find another solution?

To give some context: We have a SPA that calls our API. Some pages of the SPA can be shared with others (non user) just by sending a link. That link will contain the token. The content of those pages are not critical security wise, but they shouldn't be completely open.

答:
You could try the below and see if it works for you.
Caveat: I have absolutely no idea if this is the "correct" way to do this. I just know it is a way that appears to work. Please test and downvote if you find problems. I still have an open question on another authentication handler I have written, but with no replies, so use with caution. It may be worth contacting blowdart (search users) at MS if you are going to pursue this use case.

Middleware Class

```<code>public class TokenCodeAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public const string DefaultSchemeName = "TokenAuthScheme";

    public TokenCodeAuthHandler(
        IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        AuthenticateResult result = await this.Context.AuthenticateAsync();
        if (result.Succeeded)
        {
            //User has supplied details
            return AuthenticateResult.Success(result.Ticket);
        }
        else if (Context.Request.Query["token"] == "123abc")   //TODO: Change hard-coded token
        {
            //User has supplied token
            string username = "Test";    //Get/set username here
            var claims = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, username, ClaimValueTypes.String, Options.ClaimsIssuer),
                    new Claim(ClaimTypes.Name, username, ClaimValueTypes.String, Options.ClaimsIssuer)
                };

            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme.Name));
            AuthenticationTicket ticket = new AuthenticationTicket(principal, Scheme.Name);
            return AuthenticateResult.Success(ticket);
        }
        return AuthenticateResult.Fail("Unauthorized");
    }
}
</code>```

Configure Services in Startup

```<code>services.AddAuthentication()
    .AddScheme<AuthenticationSchemeOptions, TokenCodeAuthHandler>(
        TokenCodeAuthHandler.DefaultSchemeName,
        (o) => { });
</code>```

Attribute Usage

Use on controller actions as follows:
Note - I couldn't seem to override controller level authorize attributes).

```<code>[Authorize(AuthenticationSchemes = TokenCodeAuthHandler.DefaultSchemeName)]
[HttpGet]
[Route("some/resource")]
public async Task<string> GetSomeResource()
{
    return "some resource";
}
</code>```

Title: Allow "semi anonymous" authentication

Body:
I have a case where I need some controller methods to be accessible either by an authenticated user, or if the request contains a sort of "acccess token" in the url.

For example:

Either an authenticated user could make a call to:
https://example.com/some/resource

Or a non authenticated user could make the same call, but add some kind of token to the url (or as a header):
https://example.com/some/resource?token=123abc

The token does not have to be super secret, only something hard to guess.

[AllowSpecialToken]
[HttpGet]
[Route("some/resource")]
public async Task<string> GetSomeResource()
{
    return "some resource";
}

What I'm struggling with is how to write the AllowSpecialTokenAttribute. And how to get that to run before the authentication (using OpenIddict) we have in place now.

Is this a stupid use case? Should I find another solution?

To give some context: We have a SPA that calls our API. Some pages of the SPA can be shared with others (non user) just by sending a link. That link will contain the token. The content of those pages are not critical security wise, but they shouldn't be completely open.

Body:
You could try the below and see if it works for you.
Caveat: I have absolutely no idea if this is the "correct" way to do this. I just know it is a way that appears to work. Please test and downvote if you find problems. I still have an open question on another authentication handler I have written, but with no replies, so use with caution. It may be worth contacting blowdart (search users) at MS if you are going to pursue this use case.

Middleware Class

public class TokenCodeAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public const string DefaultSchemeName = "TokenAuthScheme";

    public TokenCodeAuthHandler(
        IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        AuthenticateResult result = await this.Context.AuthenticateAsync();
        if (result.Succeeded)
        {
            //User has supplied details
            return AuthenticateResult.Success(result.Ticket);
        }
        else if (Context.Request.Query["token"] == "123abc")   //TODO: Change hard-coded token
        {
            //User has supplied token
            string username = "Test";    //Get/set username here
            var claims = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, username, ClaimValueTypes.String, Options.ClaimsIssuer),
                    new Claim(ClaimTypes.Name, username, ClaimValueTypes.String, Options.ClaimsIssuer)
                };

            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme.Name));
            AuthenticationTicket ticket = new AuthenticationTicket(principal, Scheme.Name);
            return AuthenticateResult.Success(ticket);
        }
        return AuthenticateResult.Fail("Unauthorized");
    }
}

Configure Services in Startup

services.AddAuthentication()
    .AddScheme<AuthenticationSchemeOptions, TokenCodeAuthHandler>(
        TokenCodeAuthHandler.DefaultSchemeName,
        (o) => { });

Attribute Usage

Use on controller actions as follows:
Note - I couldn't seem to override controller level authorize attributes).

[Authorize(AuthenticationSchemes = TokenCodeAuthHandler.DefaultSchemeName)]
[HttpGet]
[Route("some/resource")]
public async Task<string> GetSomeResource()
{
    return "some resource";
}


问:
Excel Fill blank rows with values from above
Looking to fill blank values in a row with the 'top' value, similar to the functionality provided by Editing>Fill>Top. The difference being that the Fill function requires you to go row-by-row rather than applying itself to a larger dataset. Example below:

```<code>Apple   1   foo
Banana  1   foo
        2   foo
            bar
Cherry  2   bar
        3   foo
        6   bar
Grape   1   foo
</code>```

Would end up as the following:

```<code>Apple   1   foo
Banana  1   foo
Banana* 2   foo
Banana* 2*  bar
Cherry  2   bar
Cherry* 3   foo
Cherry* 6   bar
Grape   1   foo       //new values represented with *
</code>```

Note that the third entry in the second column (2) was also brought down implying this could be applied to multiple columns.

The value in this would be converting a table that has the relationships Cherry>2, Cherry>3, Cherry>6 represented in the first table into a format that could be used as an associative table.

答:
Try this short macro:</p>

```<code>Sub FillInTheBlanks()
    Dim i As Long, N As Long, j As Long

    N = Cells(Rows.Count, "C").End(xlUp).Row

    For i = 2 To N
        For j = 1 To 2
            If Cells(i, j).Value = "" Then Cells(i, j).Value = Cells(i, j).Offset(-1, 0).Value
        Next j
    Next i
End Sub
</code>```

Body:
Looking to fill blank values in a row with the 'top' value, similar to the functionality provided by Editing>Fill>Top. The difference being that the Fill function requires you to go row-by-row rather than applying itself to a larger dataset. Example below:

Apple   1   foo
Banana  1   foo
        2   foo
            bar
Cherry  2   bar
        3   foo
        6   bar
Grape   1   foo

Would end up as the following:

Apple   1   foo
Banana  1   foo
Banana* 2   foo
Banana* 2*  bar
Cherry  2   bar
Cherry* 3   foo
Cherry* 6   bar
Grape   1   foo       //new values represented with *

Note that the third entry in the second column (2) was also brought down implying this could be applied to multiple columns.

The value in this would be converting a table that has the relationships Cherry>2, Cherry>3, Cherry>6 represented in the first table into a format that could be used as an associative table.

Body:
Try this short macro:

Sub FillInTheBlanks()
    Dim i As Long, N As Long, j As Long

    N = Cells(Rows.Count, "C").End(xlUp).Row

    For i = 2 To N
        For j = 1 To 2
            If Cells(i, j).Value = "" Then Cells(i, j).Value = Cells(i, j).Offset(-1, 0).Value
        Next j
    Next i
End Sub


问:
building glib gives error: gfileutils.c:57:25: error: linux/magic.h: No such file or directory
I am on CentOS 5.5 and I am getting the error above when running make in the glib 2.27 directory. What is magic.h and what should I do to correct this?

Also - is there an easier way to get gtk installed on centos?

答:
CentOS package repositories already contain GTK+ 2.10 and GLib 2.12 packages. Unless you specifically need a newer version, just install the distro packages:

```<code>yum install gtk2-devel
</code>```

If these versions are too old for your development work, consider upgrading to a distro which ships with newer GTK+ stack like Fedora 14.

Body:
CentOS package repositories already contain GTK+ 2.10 and GLib 2.12 packages. Unless you specifically need a newer version, just install the distro packages:

yum install gtk2-devel

If these versions are too old for your development work, consider upgrading to a distro which ships with newer GTK+ stack like Fedora 14.


问:
Reshape array using numpy - ValueError: cannot reshape array
I have an array of floats vec which I want to reshape

```<code>vec.shape
>>> (3,)
len(vec[0]) # all 3 rows of vec have 150 columns
>>> 150
np.reshape(vec, (3,150))
>>> ValueError: cannot reshape array of size 3 into shape (3,150)
</code>```

but I get the error above.

What's going wrong? How can I fix this? Thanks!

Body:
I have an array of floats vec which I want to reshape

vec.shape
>>> (3,)
len(vec[0]) # all 3 rows of vec have 150 columns
>>> 150
np.reshape(vec, (3,150))
>>> ValueError: cannot reshape array of size 3 into shape (3,150)

but I get the error above.

What's going wrong? How can I fix this? Thanks!

Body:
The vec.shape means that the array has 3 items.  But they are dtype object, that is, pointers to items else where in memory.

Apparently the items are arrays themselves.  One of the concatenate or stack functions can join them into one array, provided the dimensions match.

I'd suggest printing

[x.shape for x in vec]

to verify the shape.  And of course make sure that those sub arrays are not, themselves object dtypes.

In [261]: vec = np.empty(3, object)
In [262]: vec[:] = [np.arange(10), np.ones(10), np.zeros(10)]
In [263]: vec
Out[263]:
array([array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
       array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.]),
       array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])], dtype=object)
In [264]: vec.reshape(3,10)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-264-cd555975140c> in <module>()
----> 1 vec.reshape(3,10)

ValueError: cannot reshape array of size 3 into shape (3,10)
In [265]: [x.shape for x in vec]
Out[265]: [(10,), (10,), (10,)]
In [266]: np.stack(vec)
Out[266]:
array([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
In [267]: np.concatenate(vec)
Out[267]:
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.,  1.,  1.,  1.,
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.])
In [268]: np.concatenate(vec).reshape(3,10)
Out[268]:
array([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

len is not a good test; use shape.  For example if I change one array to be 2d

In [269]: vec[1]=np.ones((10,1))
In [270]: vec
Out[270]:
array([array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
       array([[ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.],
       [ 1.]]),
       array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])], dtype=object)
In [271]: [len(x) for x in vec]
Out[271]: [10, 10, 10]
In [272]: [x.shape for x in vec]
Out[272]: [(10,), (10, 1), (10,)]
In [273]: np.concatenate(vec)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-273-a253d8b9b25d> in <module>()
----> 1 np.concatenate(vec)

ValueError: all the input arrays must have same number of dimensions


问:
Is Login-AzureRmAccount an object or do I need to store it in one?
I have a question about the Login-AzureRmAccount cmdlet and I'm trying to wrap my head around it.  When I run Login-AzureRmAccount and authenticate with my credentials, does a credential object get stored anywhere?  If I'm writing a script with lots of Azure cmdlets, do I need to keep those credentials around or store those somehow to pass into other cmdlets, or do I get some sort of authentication token which stays with me for a while?  I've done a little bit of research on this and I apologize if my google-fu was weak on this subject.  Thanks!</p>

答: Actually, now that you can use context persistence, this is less useful.  If you run  Enable-AzureRmContextAutosave then PowerShell will store this context container in '%AppData%\Roaming\Windows Azure PowerShell', so that you won't need to log in again the next time you open a powershell window.


问:
How to specify Docker private registry credentials in Docker configuration File?
I am creating Docker container of nodejs application. Below is the sample of my Docker configuration file

```<code>FROM node:6.11
WORKDIR /usr/src/app
COPY package.json .
npm install
copy . /usr/src/app
EXPOSE 80
CMD [ "npm", "start" ]
</code>```

This will download the node image from Docker hub and then it will create Docker image as per the configuration.

For security reasons I don't want to download nodejs image from Docker hub, Instead I want to use my private repository to download nodejs image.

As I have setup private repository I am not sure how to specify registry credentials in DockerFile.

Can anyone help me with this?

答: Before you build the Docker image you'll have to do docker login to your private repo. Then pulls - explicit or implicit through FROM will use that registry (and while I can't find any documentation to back that up, I suspect it also fallback to Docker Hub if it can't find the image there, but that may be dependent on the registry settings????)

Body:
I am creating Docker container of nodejs application. Below is the sample of my Docker configuration file

FROM node:6.11
WORKDIR /usr/src/app
COPY package.json .
npm install
copy . /usr/src/app
EXPOSE 80
CMD [ "npm", "start" ]

This will download the node image from Docker hub and then it will create Docker image as per the configuration.

For security reasons I don't want to download nodejs image from Docker hub, Instead I want to use my private repository to download nodejs image.

As I have setup private repository I am not sure how to specify registry credentials in DockerFile.

Can anyone help me with this?


问:
Name of a property that is `undefined`
If I have a defined property or function on a class, I can get the name of it. e.g. I can get a class name with this...

```<code>console.log(`${this.constructor.name} is my name.);
</code>```

or a function name with

```<code>fnA() {
  console.log(`There is a function called ${this.fnA.name});
}
</code>```

But I want to know the name of a property/function that has not been declared i.e. the typeof is undefined. Which means .name fails.

Is there a way to get the name in code of an undefined field?

Or as @skyboyer put it: "(I'm) getting some function as a parameter and if it's undefined (I) would like to know what was original variable name"

Something like this...

```<code>if (typeof this.missing == 'undefined') {
  console.log(`${getTheName(this.missing)} needs to be created.`);
}
</code>```

答:
Use a Proxy get handler trap:

let ns = new Proxy({}, {
  get (target, name) {
    if (name in target) {
      return target[name]
    }

    // handle missing values
    console.log(name)
  }
})

ns.contains = true

// does nothing
ns.contains

// logs 'missing'
ns.missing```

Title: Name of a property that is `undefined`

Body:
If I have a defined property or function on a class, I can get the name of it. e.g. I can get a class name with this...

console.log(`${this.constructor.name} is my name.);

or a function name with

fnA() {
  console.log(`There is a function called ${this.fnA.name});
}

But I want to know the name of a property/function that has not been declared i.e. the typeof is undefined. Which means .name fails.

Is there a way to get the name in code of an undefined field?

Or as @skyboyer put it: "(I'm) getting some function as a parameter and if it's undefined (I) would like to know what was original variable name"

Something like this...

if (typeof this.missing == 'undefined') {
  console.log(`${getTheName(this.missing)} needs to be created.`);
}


问:
How to change Hive Database to Oracle Database as Primary Database in Kylo?
I'm kylo platform for my tool. I need the Oracle database instead of the hive database on the kylo platform.</p>

答:
The Kylo dependencies page currently only lists MySQL, PostgreSQL, and MS SQL as supported databases: http://kylo.readthedocs.io/en/latest/installation/Dependencies.html#kylo-stack-dependencies

You can try using Oracle by setting the following properties appropriately:

```<code>spring.datasource.url=jdbc:oracle:thin:@myhost:1521:orcl
spring.datasource.username=
spring.datasource.password=
spring.datasource.maxActive=30
spring.datasource.validationQuery=SELECT 1
spring.datasource.testOnBorrow=true
spring.datasource.driverClassName=oracle.jdbc.OracleDriver
spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect
</code>```

You will also need to download the Oracle JDBC driver and install it to /opt/kylo/kylo-services/plugin/. There's more information in the Kylo docs:
http://kylo.readthedocs.io/en/latest/installation/KyloApplicationProperties.html#kylo

ContentLicense: CC BY-SA 4.0

Body:
The Kylo dependencies page currently only lists MySQL, PostgreSQL, and MS SQL as supported databases: http://kylo.readthedocs.io/en/latest/installation/Dependencies.html#kylo-stack-dependencies

You can try using Oracle by setting the following properties appropriately:

spring.datasource.url=jdbc:oracle:thin:@myhost:1521:orcl
spring.datasource.username=
spring.datasource.password=
spring.datasource.maxActive=30
spring.datasource.validationQuery=SELECT 1
spring.datasource.testOnBorrow=true
spring.datasource.driverClassName=oracle.jdbc.OracleDriver
spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect

You will also need to download the Oracle JDBC driver and install it to /opt/kylo/kylo-services/plugin/. There's more information in the Kylo docs:
http://kylo.readthedocs.io/en/latest/installation/KyloApplicationProperties.html#kylo


问:
Unsupported symbols appearing in lieu of white space

This bug was captured on a Windows machine with Chrome (on my Windows instead of a box it's an "L". I don't understand why these symbols are appearing.

This is my html code:

```<code><p> ... are linked  to specific <strong>disease</strong> or physical <strong>traits</strong>.  Other sections of DNA ... </p>
</code>```

Is this a browser specific issue/user specific issue? Or is this a issue with my code (like adding another fallback font)?

Any ideas, suggestions, direction would be greatly appreciated.

Thank you!

答: From looking at it it seems like you might be using non-breaking spaces. It is unusual that that is a problem for a font, but you might want to just not use them. Most Editors can highlight such "invisible characters" in one way or another. It is worth searching for that for your editor.</p>

Body:
This bug was captured on a Windows machine with Chrome (on my Windows instead of a box it's an "L". I don't understand why these symbols are appearing.

This is my html code:

 ... are linked  to specific disease or physical traits.  Other sections of DNA ...

Is this a browser specific issue/user specific issue? Or is this a issue with my code (like adding another fallback font)?

Any ideas, suggestions, direction would be greatly appreciated.

Thank you!


问:
Visual Studio C# Project-to-project Reference
I have two .NET Framework libraries in the same solution. If I set project A as a dependency of project B is there a way to get it to copy over the dll when I build the solution?

Thanks,

答: Dude, build a project as a library, then take the dll and import it into the project you want to use</p>


问:
How to avoid writing ugly code while dealing with object properties in javascript
I find that when I write javascript I encounter a situation where I am forced to write ugly code. This is due to my inability to reconcile the following two criteria:

1) Define data using shorthand, e.g. var data = { a: 1, b: { c: 2, d: 3 ... } }

2) Use a primitive operator to check for property existence

For example consider a function which returns the intersection of two Object instances' keys as an Array of the intersecting keys:

```<code>var intersection = function(obj1, obj2) {
    var result = [];
    for (var k in obj1) if (k in obj2) result.push(k);
    return result;
};
</code>```

That code looks quite nice. But unfortunately, it doesn't always work as expected! This is due to the inconsistency between for (x in y), and if (x in y): Using for (x in y) will only iterate over "own" properties (properties which return true for hasOwnProperty), while if (x in y) while apply for "own" and "non-own" properties!

If I call intersection like so:

```<code>var obj1 = { toString: 'hahaha' };
var obj2 = {};
var intersectingKeys = intersection(obj1, obj2);
</code>```

I will wind up with intersectingKeys === [ 'toString' ]; Obviously this is not correct: an intersection operation involving an empty set (as obj2 appears to be) must return an empty set. While {} is clearly intended to be "empty", our problem is that ('toString' in {}) === true. This also applies to terms such as 'constructor', 'valueOf', as well as any new properties that are introduced to Object.prototype in the future.

In my opinion, if a native operator can provide iteration over keys, a native operator should be able to verify whether a key will appear in an iteration. It feels inconsistent and ugly, to me, to use a native operator for one, but a function call for the other. For that reason I dislike this fix:

```<code>var safeIntersection = function(obj1, obj2) {
    var result = [];
    for (var k in obj1) if (obj2.hasOwnProperty(k)) result.push(k);
    return result;
};
</code>```

If if (x in y) must be used, I only see one other possible solution: Ensure that the parameters passed to intersection have no properties at all, apart from properties explicitly defined by our code. In other words, ensure that we only work with prototype-less objects:

```<code>var obj1 = Object.create(null, {
    toString: {
        configurable: true,
        enumerable: true,
        writable: true,
        value: 'hahaha'
    }
});
var obj2 = Object.create(null, {});
var intersectingKeys = intersection(obj1, obj2);
</code>```

Note that this code uses intersection, not safeIntersection, and still works because obj1 and obj2 are prototype-less. But the problem is, now data definition is really, really clunky! Look at how much code it takes to define an object with a single "toString" property. This approach prevents us from using javascript's beautiful object-shorthand. Even if we write a utility function to encompass prototype-less object creation, the definition of nested objects is still incredibly clunky:

```<code>// Utility function for prototype-less object definition
var obj = function(props) {
    return Object.create(null, props.map(function(v) {
        return {
            writable: true,
            configurable: true,
            enumerable: true,
            value: v
        };
    }));
};

// Now defining `obj1` looks ok...
var obj1 = obj({ toString: 'hahaha' });

// But for large, nested object definitions it's sooper ugly:
var big = obj({
    a: 'a value',
    b: 'b value',
    moreProps: obj({
        wheee: 'yay',
        evenMoreProps: obj({
            prop: 'propMeUp'
            /* ... */
        })
        /* ... */
    })
});
</code>```

Javascript's object-definition shorthand is a huge perk of the language, and throwing it away by being forced to wrap all { ... } instances in a function call seems like a tremendous pity.

My ideal solution to this problem would involve converting the shorthand object constructor to produce prototype-less objects. Perhaps a global setting:

```<code>// Perhaps along with other global settings such as:
'use strict';
Error.stackTraceLimit = Infinity;

// We could also have:
Object.shorthandIncludesPrototype = false;
</code>```

Although even if this solutions were available it would break tons and tons of pre-existing libraries. :(

How do I reconcile the following criteria???:

1) Write code that works

2) Use the primitive in operator to check for property existence

3) Define objects using typical shorthand

Perhaps it's impossible to meet all these criteria simultaneously. In that case, what are some of the next-best approaches for keeping code clean in these cases?

答:
As jfriend00 already wrote, the question proposes constraints that are fundamentally impossible in the current versions of JavaScript. The best we can do is write some abstractions within the limitations of the language.

We've already looked at some possibilities, such as using a wrapper function (like obj() in the question). Because "universal support" is not a criterion in the question, I'll propose one solution using ES6 Proxies. We can use the has() handler method of a Proxy to alter the behavior of the in operator so that it only considers own properties:

Object.prototype.own = function () {
    return new Proxy(this, {
        has: function (target, propertyName) {
            return target.hasOwnProperty(propertyName);
        }
    });
};

document.writeln('toString' in {});
document.writeln('toString' in {}.own());
document.writeln('foo' in { foo: 1 });
document.writeln('foo' in { foo: 1 }.own());```
</div>
</div>
</p>

<p>This requires a modern browser (no IE; Edge OK) or Node 6.4.0+. Of course, adding members to the prototype of <code>Object</code> is a risky move. We can add additional handlers to the <code>Proxy</code> as needed, or rewrite the implementation for ES5 and below (but this requires significantly more code).</p>

<p>Compatibility concerns aside, this approach satisfies the requirements of the question: we can use object literals and the <code>in</code> operator, and the code is concise and readable. We just need to remember to call <code>own()</code> when we need it.</p>

<p>We can rewrite the <code>intersection()</code> method from the question using this convention: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Object.prototype.own = function () {
    return new Proxy(this, {
        has: function (target, propertyName) {
            return target.hasOwnProperty(propertyName);
        }
    });
};

var intersection = function(obj1, obj2) {
    var result = [];
    for (var k in obj1.own()) if (k in obj2.own()) result.push(k);
    return result;
};

document.writeln(intersection({ a: 1, b: 2, c: 3 }, { b: 2, c: 3, d: 4}));</code>```

Body:
I find that when I write javascript I encounter a situation where I am forced to write ugly code. This is due to my inability to reconcile the following two criteria:

1) Define data using shorthand, e.g. var data = { a: 1, b: { c: 2, d: 3 ... } }

2) Use a primitive operator to check for property existence

For example consider a function which returns the intersection of two Object instances' keys as an Array of the intersecting keys:

var intersection = function(obj1, obj2) {
    var result = [];
    for (var k in obj1) if (k in obj2) result.push(k);
    return result;
};

That code looks quite nice. But unfortunately, it doesn't always work as expected! This is due to the inconsistency between for (x in y), and if (x in y): Using for (x in y) will only iterate over "own" properties (properties which return true for hasOwnProperty), while if (x in y) while apply for "own" and "non-own" properties!

If I call intersection like so:

var obj1 = { toString: 'hahaha' };
var obj2 = {};
var intersectingKeys = intersection(obj1, obj2);

I will wind up with intersectingKeys === [ 'toString' ]; Obviously this is not correct: an intersection operation involving an empty set (as obj2 appears to be) must return an empty set. While {} is clearly intended to be "empty", our problem is that ('toString' in {}) === true. This also applies to terms such as 'constructor', 'valueOf', as well as any new properties that are introduced to Object.prototype in the future.

In my opinion, if a native operator can provide iteration over keys, a native operator should be able to verify whether a key will appear in an iteration. It feels inconsistent and ugly, to me, to use a native operator for one, but a function call for the other. For that reason I dislike this fix:

var safeIntersection = function(obj1, obj2) {
    var result = [];
    for (var k in obj1) if (obj2.hasOwnProperty(k)) result.push(k);
    return result;
};

If if (x in y) must be used, I only see one other possible solution: Ensure that the parameters passed to intersection have no properties at all, apart from properties explicitly defined by our code. In other words, ensure that we only work with prototype-less objects:

var obj1 = Object.create(null, {
    toString: {
        configurable: true,
        enumerable: true,
        writable: true,
        value: 'hahaha'
    }
});
var obj2 = Object.create(null, {});
var intersectingKeys = intersection(obj1, obj2);

Note that this code uses intersection, not safeIntersection, and still works because obj1 and obj2 are prototype-less. But the problem is, now data definition is really, really clunky! Look at how much code it takes to define an object with a single "toString" property. This approach prevents us from using javascript's beautiful object-shorthand. Even if we write a utility function to encompass prototype-less object creation, the definition of nested objects is still incredibly clunky:

// Utility function for prototype-less object definition
var obj = function(props) {
    return Object.create(null, props.map(function(v) {
        return {
            writable: true,
            configurable: true,
            enumerable: true,
            value: v
        };
    }));
};

// Now defining `obj1` looks ok...
var obj1 = obj({ toString: 'hahaha' });

// But for large, nested object definitions it's sooper ugly:
var big = obj({
    a: 'a value',
    b: 'b value',
    moreProps: obj({
        wheee: 'yay',
        evenMoreProps: obj({
            prop: 'propMeUp'
            /* ... */
        })
        /* ... */
    })
});

Javascript's object-definition shorthand is a huge perk of the language, and throwing it away by being forced to wrap all { ... } instances in a function call seems like a tremendous pity.

My ideal solution to this problem would involve converting the shorthand object constructor to produce prototype-less objects. Perhaps a global setting:

// Perhaps along with other global settings such as:
'use strict';
Error.stackTraceLimit = Infinity;

// We could also have:
Object.shorthandIncludesPrototype = false;

Although even if this solutions were available it would break tons and tons of pre-existing libraries. :(

How do I reconcile the following criteria???:

1) Write code that works

2) Use the primitive in operator to check for property existence

3) Define objects using typical shorthand

Perhaps it's impossible to meet all these criteria simultaneously. In that case, what are some of the next-best approaches for keeping code clean in these cases?

Body:
As jfriend00 already wrote, the question proposes constraints that are fundamentally impossible in the current versions of JavaScript. The best we can do is write some abstractions within the limitations of the language.

We've already looked at some possibilities, such as using a wrapper function (like obj() in the question). Because "universal support" is not a criterion in the question, I'll propose one solution using ES6 Proxies. We can use the has() handler method of a Proxy to alter the behavior of the in operator so that it only considers own properties:

Object.prototype.own = function () {
    return new Proxy(this, {
        has: function (target, propertyName) {
            return target.hasOwnProperty(propertyName);
        }
    });
};

document.writeln('toString' in {});
document.writeln('toString' in {}.own());
document.writeln('foo' in { foo: 1 });
document.writeln('foo' in { foo: 1 }.own());

This requires a modern browser (no IE; Edge OK) or Node 6.4.0+. Of course, adding members to the prototype of Object is a risky move. We can add additional handlers to the Proxy as needed, or rewrite the implementation for ES5 and below (but this requires significantly more code).

Compatibility concerns aside, this approach satisfies the requirements of the question: we can use object literals and the in operator, and the code is concise and readable. We just need to remember to call own() when we need it.

We can rewrite the intersection() method from the question using this convention:

Object.prototype.own = function () {
    return new Proxy(this, {
        has: function (target, propertyName) {
            return target.hasOwnProperty(propertyName);
        }
    });
};

var intersection = function(obj1, obj2) {
    var result = [];
    for (var k in obj1.own()) if (k in obj2.own()) result.push(k);
    return result;
};

document.writeln(intersection({ a: 1, b: 2, c: 3 }, { b: 2, c: 3, d: 4}));


问:
Is sizeof in C++ evaluated at compilation time or run time?
For example result of this code snippet depends on which machine: the compiler machine or the machine executable file works?</p>

```<code>sizeof(short int)
</code>```

答:
As of C99, sizeof is evaluated at runtime if and only if the operand is a variable-length array, e.g. int a[b], where b is not known at compile time. In this case, sizeof(a) is evaluated at runtime and its result is the size (in bytes) of the entire array, i.e. the size of all elements in the array, combined. To get the number of elements in the array, use sizeof(a) / sizeof(b). From the C99 standard:

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an
  integer constant.

Note that all of this is different from what you'd get if you allocated an array on the heap, e.g. int* a = new int[b]. In that case, sizeof(a) would just give you the size of a pointer to int, i.e. 4 or 8 bytes, regardless of how many elements are in the array.

Body:
For example result of this code snippet depends on which machine: the compiler machine or the machine executable file works?

sizeof(short int)