问:
Understanding mutable Seq
I'm pretty new to Scala and try to understand mutable Seq. Since it's in package mutable I expected there is a method that allows us to append element without copying the whole collection.

But there is no += method in the mutable.Seq, but in Buffer is. :+ and +: both copy the collection.

So why is it mutable?

答:
Because mutable and growable isn't the same thing.
(the latter is one specific type of the former: everything, that's growable is mutable, but not everything that's mutable is growable).

mutable.Seq has update, that allows you to change the element at a given index, but it does not grow or shrink.
Buffer is s specialization of Seq, that is both mutable and growable.

Title: Understanding mutable Seq


来源: stackexchange

问:
Error after parallel_for lambda function filling a 2D-vector
Long story short: I am stuck with some code that throws an error I can't really understand (please have mercy, I am a c++ newbie).

My code (dumbed down) does the following:

```<code>vector<vector<double>> AmplCo;
AmplCo.resize(1025, vector<double>(65, 0));

Concurrency::parallel_for((long)0, (long)65, [&](long i) {

    for (j = 0; j <= 64; j++)
    {
        PhiRad = double(j) / 128 * PI;
        CosPhi = cos(PhiRad); SinPhi = sin(PhiRad);
        RealCoij = static_cast<double>(RealCo[j * 1025 + i]);
        A = RealCoij * CosPhi;
        B = RealCoij * SinPhi;
        AmplCo.at(i).at(j) =log10(A * A + B * B);
    }

});                  // <- A breakpoint here is reached
RealCo = nullptr;    // <- A breakpoint here is never reached
</code>```

Where RealCo is, of course, a pointer.

The execution doesn't reach RealCo = nullptr; because between the end of the lambda function and that line, I get an unhandled exception.

Any idea of what I am doing wrong?

EDIT: once again, if you want to downvote, at least have some decency to explain why.

答:
Ok I found out the mistake: multithreading doesn't like much the variables already initialized before the parallel_for, so I had to set (basically all of) them to private:

```<code>for (long j = 0; j <= 64; j++)
    {
        double PhiRad = double(j) / 128 * PI;
        double CosPhi = cos(PhiRad); double SinPhi = sin(PhiRad);
        double RealCoij = static_cast<double>(RealCo[j * 1025 + i]);
        double A = RealCoij * CosPhi;
        double B = RealCoij * SinPhi;
        AmplCo.at(i).at(j) =log10(A * A + B * B);
    }
</code>```

The problem was most probably 2 threads accessing j at the same time.

ContentLicense: CC BY-SA 3.0

Body:
Long story short: I am stuck with some code that throws an error I can't really understand (please have mercy, I am a c++ newbie).

My code (dumbed down) does the following:

vector<vector<double>> AmplCo;
AmplCo.resize(1025, vector<double>(65, 0));

Concurrency::parallel_for((long)0, (long)65, [&](long i) {

    for (j = 0; j <= 64; j++)
    {
        PhiRad = double(j) / 128 * PI;
        CosPhi = cos(PhiRad); SinPhi = sin(PhiRad);
        RealCoij = static_cast<double>(RealCo[j * 1025 + i]);
        A = RealCoij * CosPhi;
        B = RealCoij * SinPhi;
        AmplCo.at(i).at(j) =log10(A * A + B * B);
    }

});                  // <- A breakpoint here is reached
RealCo = nullptr;    // <- A breakpoint here is never reached

Where RealCo is, of course, a pointer.

The execution doesn't reach RealCo = nullptr; because between the end of the lambda function and that line, I get an unhandled exception.

Any idea of what I am doing wrong?

EDIT: once again, if you want to downvote, at least have some decency to explain why.

Body:
Ok I found out the mistake: multithreading doesn't like much the variables already initialized before the parallel_for, so I had to set (basically all of) them to private:

for (long j = 0; j <= 64; j++)
    {
        double PhiRad = double(j) / 128 * PI;
        double CosPhi = cos(PhiRad); double SinPhi = sin(PhiRad);
        double RealCoij = static_cast<double>(RealCo[j * 1025 + i]);
        double A = RealCoij * CosPhi;
        double B = RealCoij * SinPhi;
        AmplCo.at(i).at(j) =log10(A * A + B * B);
    }

The problem was most probably 2 threads accessing j at the same time.


问:
How to get all security groups through AWS CLI of an EC2 to show in a table
I am trying to show all instances along with attached security groups, block device name and their deleteontermination status. I need to show this data in table format but I am continuously getting the below error.

Kindly help me to understand what I am missing here.

```<code>PR-MacBook-Pro:~ pr$ aws ec2 describe-instances --output table --query 'Reservations[*].Instances[*].[InstanceId,SecurityGroups[].GroupName,Placement.AvailabilityZone,BlockDeviceMappings[].DeviceName, BlockDeviceMappings[].Ebs.DeleteOnTermination]'

Row should have 1 elements, instead it has 2
PR-MacBook-Pro:~ pr$
</code>```

答:
modify your command as below to make it work

```<code>aws ec2 describe-instances  --output table  --region "us-east-1"  --query 'Reservations[*].Instances[*].[InstanceId,SecurityGroups[].GroupName |[0],Placement.AvailabilityZone,BlockDeviceMappings[].DeviceName |[0], BlockDeviceMappings[].Ebs.DeleteOnTermination|[0] ]'
</code>```

the response was in the format of

```<code>[
    [
        "i-xxxxxxxx",
        [
            "xxxxxx"
        ],
        "us-east-1a",
        [
            "/dev/xvda"
        ],
        [
            true
        ]
    ]
]
</code>```

so you need parse the array element using | [0]

Body:
I am trying to show all instances along with attached security groups, block device name and their deleteontermination status. I need to show this data in table format but I am continuously getting the below error.

Kindly help me to understand what I am missing here.

PR-MacBook-Pro:~ pr$ aws ec2 describe-instances --output table --query 'Reservations[*].Instances[*].[InstanceId,SecurityGroups[].GroupName,Placement.AvailabilityZone,BlockDeviceMappings[].DeviceName, BlockDeviceMappings[].Ebs.DeleteOnTermination]'

Row should have 1 elements, instead it has 2
PR-MacBook-Pro:~ pr$

Body:
modify your command as below to make it work

aws ec2 describe-instances  --output table  --region "us-east-1"  --query 'Reservations[*].Instances[*].[InstanceId,SecurityGroups[].GroupName |[0],Placement.AvailabilityZone,BlockDeviceMappings[].DeviceName |[0], BlockDeviceMappings[].Ebs.DeleteOnTermination|[0] ]'

the response was in the format of

[
    [
        "i-xxxxxxxx",
        [
            "xxxxxx"
        ],
        "us-east-1a",
        [
            "/dev/xvda"
        ],
        [
            true
        ]
    ]
]

so you need parse the array element using | [0]


问:
Outlook 2007 - Business Contact Manager Without Cached Mode
Is it possible to employ Business Contact Manager 2007 without running Outlook in Cached mode?

According to all the reasearch I have done this is a prerequisite, and certainly upon installing and testing it seems to be the case, but keeping local copies of inboxes is simply too large a security hole for us, I find it difficult to believe that this is a requirement!

Thanks in advance for your responses!

答:
The answer on the most basic level here is No.

But the security hole created by storing copies of Mailboxes on workstations can be worked around, it is as simple as moving the local mailbox storage file (.ost file) to a secure server then re wiring outlook to find it in its new location.

Hope this helps someone!

ContentLicense: CC BY-SA 2.5


问:
Go lang is it possible to create a struct that can also be used as a slice?
Is it possible to have a struct in go that can also be accessed as a slice?
So, for example, I'd want something like this:

```<code>type Item struct {
    Name string
}

type ItemList struct {
    PackDate time.Time
    []Item
}
</code>```

And then I could access an Item in the ItemList as a slice.

```<code>myItemList[0].Name
</code>```

Or access the members of ItemList in the normal struct way.

```<code>myItemList.PackDate
</code>```

If this is not possible, are there any recommended patterns for handling a sort of slice with metadata like this in go?

答:
For example,

```<code>package main

import (
    "fmt"
    "time"
)

type Item struct {
    Name string
}

type ItemList struct {
    PackDate time.Time
    Items    []Item
}

func main() {
    list := ItemList{
        PackDate: time.Now(),
        Items:    []Item{{Name: "John"}, {Name: "Jane"}},
    }
    fmt.Println(list)
    fmt.Println(list.PackDate)
    fmt.Println(list.Items[1].Name)
}
</code>```

Output:

```<code>{2009-11-10 23:00:00 +0000 UTC [{John} {Jane}]}
2009-11-10 23:00:00 +0000 UTC
Jane
</code>```

Body:
Is it possible to have a struct in go that can also be accessed as a slice?
So, for example, I'd want something like this:

type Item struct {
    Name string
}

type ItemList struct {
    PackDate time.Time
    []Item
}

And then I could access an Item in the ItemList as a slice.

myItemList[0].Name

Or access the members of ItemList in the normal struct way.

myItemList.PackDate

If this is not possible, are there any recommended patterns for handling a sort of slice with metadata like this in go?

Body:
For example,

package main

import (
    "fmt"
    "time"
)

type Item struct {
    Name string
}

type ItemList struct {
    PackDate time.Time
    Items    []Item
}

func main() {
    list := ItemList{
        PackDate: time.Now(),
        Items:    []Item{{Name: "John"}, {Name: "Jane"}},
    }
    fmt.Println(list)
    fmt.Println(list.PackDate)
    fmt.Println(list.Items[1].Name)
}

Output:

{2009-11-10 23:00:00 +0000 UTC [{John} {Jane}]}
2009-11-10 23:00:00 +0000 UTC
Jane


问:
Create dynamic overlapping divs which will change height based on inner content
I want to create a structure in which there is a background container which will contain some image and will have some min-height. On top of that container there will be another container which will have some text content in it. Now if the text content increases, my parent container's height need to get increased.

I've implemented this using position:relative and absolute properties of css. The content div being absolute doesn't allow the parent div's height to get increased once the content increases.

Can I get some solutions for this. I don't want the change the existing implementation and need some fix in this one only.

I've created a dummy fiddle for this:

Thanks for helping..!!

.parent{
          position:relative;
          min-height:300px;
          border:1px solid;
}
.child{
          position:absolute;
          width:200px;
          height:auto;
          border:1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
    <div class="child">
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </div>
</div></code>```

https://jsfiddle.net/arpagrawal/kd144czz/1/

答:
Is there a specific reason why the child must be absolute?
I don't see why it's necessary since the child is nested. If you add padding to the parent div that allows you to add as much content as you want to the child div without an overlap.

```<code>.parent {
  min-height: 300px;
  width: 100%;
  border: 1px solid;
  padding: 1em;
  background-image: url('https://via.placeholder.com/350x150');
  background-repeat: no-repeat;
  background-size: cover;
}
</code>```

Here's an example: JSFiddle

Body:
I want to create a structure in which there is a background container which will contain some image and will have some min-height. On top of that container there will be another container which will have some text content in it. Now if the text content increases, my parent container's height need to get increased.

I've implemented this using position:relative and absolute properties of css. The content div being absolute doesn't allow the parent div's height to get increased once the content increases.

Can I get some solutions for this. I don't want the change the existing implementation and need some fix in this one only.

I've created a dummy fiddle for this:

Thanks for helping..!!

.parent{
          position:relative;
          min-height:300px;
          border:1px solid;
}
.child{
          position:absolute;
          width:200px;
          height:auto;
          border:1px solid;
}

        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

https://jsfiddle.net/arpagrawal/kd144czz/1/

Body:
Is there a specific reason why the child must be absolute?
I don't see why it's necessary since the child is nested. If you add padding to the parent div that allows you to add as much content as you want to the child div without an overlap.

.parent {
  min-height: 300px;
  width: 100%;
  border: 1px solid;
  padding: 1em;
  background-image: url('https://via.placeholder.com/350x150');
  background-repeat: no-repeat;
  background-size: cover;
}

Here's an example: JSFiddle


问:
How to resolve class conflict in import statements
Im trying to write a program that will read an xml file and print to itext.

However, I getting a class conflict in import statements. I dont know how to resolve this issue.

```<code>import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import org.w3c.dom.NodeList;
import org.w3c.dom.*;

import com.itextpdf.text.Annotation;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
</code>```

The "Document" and "Element" classes between dom4j and itext are conflicting.

Does anyone know a workaround? Is there any eclipse magic I can do?

答:
The workaround here is to only import one of the two (or many) conflicting classes.  Then use the fully qualified class name for the class not imported.  For example:

```<code>import org.dom4j.Document;
// import com.itextpdf.text.Document;     <-- don't import this
</code>```

Then when using the itext class, refer to it as:

```<code>com.itextpdf.text.Document doc;
</code>```

I would recommed importing the class/package of classes which you use the most in your Java file.  This would let you avoid having to type a fully qualified class name as much as possible.

Body:
Im trying to write a program that will read an xml file and print to itext.

However, I getting a class conflict in import statements. I dont know how to resolve this issue.

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import org.w3c.dom.NodeList;
import org.w3c.dom.*;

import com.itextpdf.text.Annotation;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

The "Document" and "Element" classes between dom4j and itext are conflicting.

Does anyone know a workaround? Is there any eclipse magic I can do?

Body:
The workaround here is to only import one of the two (or many) conflicting classes.  Then use the fully qualified class name for the class not imported.  For example:

import org.dom4j.Document;
// import com.itextpdf.text.Document;     <-- don't import this

Then when using the itext class, refer to it as:

com.itextpdf.text.Document doc;

I would recommed importing the class/package of classes which you use the most in your Java file.  This would let you avoid having to type a fully qualified class name as much as possible.


问:
Stored few arrays in one array
I'm trying to store all this data into one array cust_data and after that, add new records with a while loop. But I'm using different types of data and don't have any idea on how to make this. Could somebody explain or give link to website with explanation how to make this.

```<code>int add_new_customer() {
    char name[50];
    char last_name[50];
    int phone_number;
    char address[50];
    printf("Enter name: ");
    scanf("%s", name);
    printf("Enter last name: ");
    scanf("%s", last_name);
    printf("Enter number: ");
    scanf("%d", phone_number);
    printf("Enter address: ");
    scanf("%s", address);
    char cust_data[100][256];
    return 0;
}
</code>```

答:
I'd define a struct customer_struct that represents a customer, and an array of type customer_struct[] that represents a list of customers as follows.

```<code>typedef struct customer_struct {
    char name[50];
    char last_name[50];
    char phone_number[15];
    char address[50];
} Customer;

void add_new_customer(Customer *c) {
    printf("Enter name: ");
    scanf("%s", c->name);
    printf("Enter last name: ");
    scanf("%s", c->last_name);
    printf("Enter number: ");
    scanf("%s", c->phone_number);
    printf("Enter address: ");
    scanf("%s", c->address);
}

int main(){

    Customer customers[3];
    for (int i=0; i<3; i++) {
        add_new_customer(&customers[i]);
    }
    return 0;
}
</code>```

Hope it helps :-)

Title: Stored few arrays in one array

Body:
I'm trying to store all this data into one array cust_data and after that, add new records with a while loop. But I'm using different types of data and don't have any idea on how to make this. Could somebody explain or give link to website with explanation how to make this.

int add_new_customer() {
    char name[50];
    char last_name[50];
    int phone_number;
    char address[50];
    printf("Enter name: ");
    scanf("%s", name);
    printf("Enter last name: ");
    scanf("%s", last_name);
    printf("Enter number: ");
    scanf("%d", phone_number);
    printf("Enter address: ");
    scanf("%s", address);
    char cust_data[100][256];
    return 0;
}

Body:
I'd define a struct customer_struct that represents a customer, and an array of type customer_struct[] that represents a list of customers as follows.

typedef struct customer_struct {
    char name[50];
    char last_name[50];
    char phone_number[15];
    char address[50];
} Customer;

void add_new_customer(Customer *c) {
    printf("Enter name: ");
    scanf("%s", c->name);
    printf("Enter last name: ");
    scanf("%s", c->last_name);
    printf("Enter number: ");
    scanf("%s", c->phone_number);
    printf("Enter address: ");
    scanf("%s", c->address);
}

int main(){

    Customer customers[3];
    for (int i=0; i<3; i++) {
        add_new_customer(&customers[i]);
    }
    return 0;
}

Hope it helps :-)


问:
Calculating the cumulative ttl (Time to live) for a series of requests
I have a series of requests and asked to calculate a the cumulative ttl of the series and given these requests .

```<code>let requests = [
{requestId: 't2',  startedAt: 1489744808, ttl: 8},
{requestId: 't3',  startedAt: 1489744803, ttl: 3},
{requestId: 't1', startedAt: 1489744806, ttl: 12},
{requestId: 't4',  startedAt: 1489744810, ttl: 1}
]
</code>```

What is the algorithm to solve this as I know that the answer should be 15 in the end.

I would assume that the earliest request 1489744803 should have the largest ttl but thats not the case, instead the 1489744806 request has the largest here so why is it like that?

Thanks :D

Body:
I have a series of requests and asked to calculate a the cumulative ttl of the series and given these requests .

let requests = [
{requestId: 't2',  startedAt: 1489744808, ttl: 8},
{requestId: 't3',  startedAt: 1489744803, ttl: 3},
{requestId: 't1', startedAt: 1489744806, ttl: 12},
{requestId: 't4',  startedAt: 1489744810, ttl: 1}
]

What is the algorithm to solve this as I know that the answer should be 15 in the end.

I would assume that the earliest request 1489744803 should have the largest ttl but thats not the case, instead the 1489744806 request has the largest here so why is it like that?

Thanks :D

Body:
first we need to find min and max every request using startedAt and ttl, once you get end min, max then we need to subtract max - min, finally we get the solution.

function cumulativeTtl(requests){
    var min = requests[0].startedAt, max = 0;
    for(var i in requests){
        min = (requests[i].startedAt < min)?requests[i].startedAt:min;
        max = ((requests[i].startedAt + requests[i].ttl) > max)?(requests[i].startedAt + requests[i].ttl):max;
    }
    return max - min;
};

explanation:

when i = 0;

min = 1489744808 // (1489744808 < 1489744808)?1489744808:1489744808;
max = 1489744816 // ((1489744808 + 8) > 0)?(1489744808 + 8):0;

when i = 1;

min = 1489744803 // (1489744803 < 1489744808)?1489744803:1489744808;
max = 1489744816 // ((1489744803 + 3) > 1489744816)?(1489744803 + 3):1489744816;

when i = 2;

min = 1489744803 // (1489744806 < 1489744803)?1489744806:1489744803;
max = 1489744818 // ((1489744806 + 12) > 1489744816)?(1489744806 + 12):1489744816;

when i = 3;

min = 1489744803 // (1489744810 < 1489744803)?1489744810:1489744803;
max = 1489744818 // ((1489744810 + 1) > 1489744818)?(1489744810 + 1):1489744818;

finally max-min then we get solution, that's it.

max-min = 15 // 1489744818 - 1489744803


问:
programing practices : how to choose a packet size for UDP datagrams?
Disclaimer : this is not a "how to" question. I would more like to know, as a background information what are the different actual practices actually used.

We know that UDP does not have a PMTU discovery like TCP. So I see several approaches to avoid IP fragmentation with UDP :

Sending 512 bytes packets max (the UDP approach)

re-implementing some PMTU  (using ICMP "needs fragmentation" message).

Relying on local MTU (but how far is it reliable, as UDP isn't a connected protocol, how can it knows which interface its packets are going to go through ?)

others... ?

So what I would like is to have a "background" idea of which approaches are being used by current UDP programs/protocols, especially regarding streaming/VoIP common applications ?

Thanks by advance,

Jocelyn

答:
Limiting to 576 bytes is very common. Most of the Internet protocols such as DNS do this. Most real-time streaming protocols also use smaller packets since it has the added benefit of providing lower serialization delay and less impact if a single packet is lost.

Some protocols have ways of negotiating a larger packet size, though often not in a way that's as robust as PMTU discovery (DHCP, for example allows a maximum message size negotiation).

There's also stuff that defaults to 1500 or so and lets the user lower it if necessary. Most implementations of SNMP seem to do something like this.

In any event, the DF bit isn't generally set, so the consequence of being overly optimistic is fragmentation, not brokenness.


问:
putting breakpoint in a file using "rbreak filename.c:." doesn't work
I want to put breakpoint on all functions of a file. I came across this link : http://sourceware.org/gdb/download/onlinedocs/gdb/Set-Breaks.html#Set-Breaks

It suggest the use of rbreak command for this purpose. When i use "rbreak ." , it works fine as expected and puts breakpoint in all functions of a prog. But when is use

rbreak filename.c:.

This doesn't work at all and no breakpoint is put anywhere. I even tried a variation of this putting spaces around :, but even that doesn't work.

Any idea on how this can be done ? Is it possible at all ?
Any help will be greatly appreciated.

thanks,
vikas

答:
rbreak filename.cpp:.* works fine for me.

Note that in order to put breakpoint in a file you need to compile the program with debug info, e.g

```<code>g++ -g filename.cpp
</code>```

Body:
rbreak filename.cpp:.* works fine for me.

Note that in order to put breakpoint in a file you need to compile the program with debug info, e.g

g++ -g filename.cpp


问:
maria db json support
My situation is: the php server uses MariaDB (the version which doesn't support json data type). Is it ok if I changed the data type from json to text? I am also using Eloquent so it casts data to json when retrieves it from db. I worry whether there will be some data loss or deformatrion if I store JSON arrays in TEXT?
Thank you!</p>

答: Yes, JSON values in MariaDB 10.2 are supposed to be stored in TEXT fields of a suitable size, so generally it should work all right. Whether it's properly compatible with the universe of 3rd-party applications, remains to be seen. Naturally, before making big changes, create a backup.

Title: maria db json support


问:
how to give more than one c file as input to GNU Cflow?
I was able to generate the callgraph of one file using gnu - cflow, but I was not able to find out how to generate the call graph for multiple files using cflow.

I tried following

cflow test.c,hello.c

It generates the callgraph for test.c and not creating it for hello.c

cflow test.c hello.c

It generates the callgraph for hello.c and not creating it for test.c

I don't know how to pass multiple files to cflow.

Any idea about this?

hello.c

```<code>int
 who_am_i (void)
 {
     struct passwd *pw;
     char *user = NULL;

     pw = getpwuid (geteuid ());
     if (pw)
     user = pw->pw_name;
     else if ((user = getenv ("USER")) == NULL)
     {
         fprintf (stderr, "I don't know!\n");
         return 1;
     }
     printf ("%s\n", user);
     unused_function();
     return 0;
 }

 int
 main (int argc, char **argv)
 {
     if (argc > 1)
     {
         fprintf (stderr, "usage: whoami\n");
         return 1;
     }
     return who_am_i ();
 }
 void unused_function()
 {
     printf();
     error1();
     printf();
 }
 void error1()
 {
     error2();
 }
 void error2()
 {

 }
</code>```

test.c

```<code>int tests()
{ return 0;}
</code>```

答:
Another convenient command is:

```<code>cflow *.c
</code>```

Note:

This command will ignore C source files in all sub-directories.

Reference:

GNU cflow manual: Chapter 6-Controlling Symbol Types

For cflow to be able to process such declarations, declare __P as a wrapper, for example:

  cflow --symbol __P:wrapper *.c

Body:
I was able to generate the callgraph of one file using gnu - cflow, but I was not able to find out how to generate the call graph for multiple files using cflow.

I tried following

cflow test.c,hello.c

It generates the callgraph for test.c and not creating it for hello.c

cflow test.c hello.c

It generates the callgraph for hello.c and not creating it for test.c

I don't know how to pass multiple files to cflow.

Any idea about this?

hello.c

int
 who_am_i (void)
 {
     struct passwd *pw;
     char *user = NULL;

     pw = getpwuid (geteuid ());
     if (pw)
     user = pw->pw_name;
     else if ((user = getenv ("USER")) == NULL)
     {
         fprintf (stderr, "I don't know!\n");
         return 1;
     }
     printf ("%s\n", user);
     unused_function();
     return 0;
 }

 int
 main (int argc, char **argv)
 {
     if (argc > 1)
     {
         fprintf (stderr, "usage: whoami\n");
         return 1;
     }
     return who_am_i ();
 }
 void unused_function()
 {
     printf();
     error1();
     printf();
 }
 void error1()
 {
     error2();
 }
 void error2()
 {

 }

test.c

int tests()
{ return 0;}

Body:
Another convenient command is:

cflow *.c

Note:

This command will ignore C source files in all sub-directories.

Reference:

GNU cflow manual: Chapter 6-Controlling Symbol Types

For cflow to be able to process such declarations, declare __P as a wrapper, for example:

  cflow --symbol __P:wrapper *.c


问:
Finding missing values
I have a couple of questions as I am new to this.

How can I read in data using \-\- to look for missing values?

How can I determine how many values are missing in each variable?
I tried using the summary command and is.na but can't's seem to get it right.

答:
the first question is not clear, for the second one you can use </p>

```<code>sapply(yourdataframe, function(x) sum(is.na(x))
</code>```

ContentLicense: CC BY-SA 4.0

Title: Finding missing values

Body:
the first question is not clear, for the second one you can use

sapply(yourdataframe, function(x) sum(is.na(x))


问:
Highlighting tile on Pygame tilemap
I'm making a simple tile-based game with Pygame.

Currently, it displays a 10x10 grid of randomly selected tiles. That part is working perfectly, but I have a problem with highlighting.

When you mouse over a tile, it should load a greyish tile at about half opacity. It loads, but the opacity isn't working correctly. If you put the mouse on a tile, it loads correctly with the opacity and all. But if you move the mouse around the tile, it turns normal, without opacity.

I think it's happening because it's loading the highlighting tile every time an event occurs, but I'm not sure how to fix it.

I'm using a class called Tilemap that I made to generate and draw the tilemap. I think it's something in the draw() function that's causing all of this.

```<code>import pygame
import sys
import random
from pygame.locals import *

running = True

class Tilemap:
    tilemap = []
    ht = None # ht = highlight texture

    def __init__(self, height, width, tilesize, textures):
        self.height = height # How many tiles high it is
        self.width = width # How many tiles wide it is
        self.tilesize = tilesize # How many pixels each tile is
        self.textures = textures # The textures
        self.size = (self.width*self.tilesize,self.height*self.tilesize)

    def generate_random(self):
        # Generate a random tilemap
        self.tilemap = [[random.randint(0, len(
            self.textures)-1) for e in range(self.width)] for e in range(
                self.height)]

    def draw(self, display, mouse=None):
        mouse = mouse
        # Draw the map
        for row in range(self.width):
            for column in range(self.height):

                texture = self.textures[self.tilemap[row][column]]
                # Highlight a tile (this is where the problem is)
                if self.ht != None:
                    if mouse[0] >= (column*self.tilesize) and mouse[0] <= (
                        column*self.tilesize)+self.tilesize:
                        if mouse[1] >= (row*self.tilesize) and mouse[1] <= (
                            row*self.tilesize)+self.tilesize:
                            texture = self.ht

                display.blit(texture,
                             (column*self.tilesize, row*self.tilesize))

tilemap = Tilemap(10,10,40,
                  # Load the textures
                  {0: pygame.image.load("tile1.png"),
                   1: pygame.image.load("tile2.png")
                   }
                  )

tilemap.generate_random() # Generate a random tilemap

pygame.init()
DISPLAYSURF = pygame.display.set_mode((tilemap.size))
# Load the highlighter
tilemap.ht = pygame.image.load("highlight.png").convert_alpha()

while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        # Draw the tilemap
        tilemap.draw(DISPLAYSURF, pygame.mouse.get_pos())

    pygame.display.update()
</code>```

If you need more explanation feel free to ask!

答:
Each time you draw to a surface in Pygame, the previous frame's data persists.
 Since you are drawing alpha, the previous, partially-transparent drawing is still in the same location, and you are drawing a partially-transparent tile over the same spot with each frame.  That causes that square to get closer and closer to the final color.  What you would typically do is erase the area you are blitting to and then re-draw. In this case you'd want to do this before your display.blit:

```<code>display.fill((0,0,0), (0, 0, column*self.tilesize, row*self.tilesize))
display.blit(texture, (column*self.tilesize, row*self.tilesize))
</code>```

This will work so long as your background is black.  If you end up having an image for a background, you would just blit the background image slice there instead.

This code is untested since I don't have your sample PNGs, but if you have an issue please let me know and I will update the answer.

Title: Highlighting tile on Pygame tilemap

Body:
I'm making a simple tile-based game with Pygame.

Currently, it displays a 10x10 grid of randomly selected tiles. That part is working perfectly, but I have a problem with highlighting.

When you mouse over a tile, it should load a greyish tile at about half opacity. It loads, but the opacity isn't working correctly. If you put the mouse on a tile, it loads correctly with the opacity and all. But if you move the mouse around the tile, it turns normal, without opacity.

I think it's happening because it's loading the highlighting tile every time an event occurs, but I'm not sure how to fix it.

I'm using a class called Tilemap that I made to generate and draw the tilemap. I think it's something in the draw() function that's causing all of this.

import pygame
import sys
import random
from pygame.locals import *

running = True

class Tilemap:
    tilemap = []
    ht = None # ht = highlight texture

    def __init__(self, height, width, tilesize, textures):
        self.height = height # How many tiles high it is
        self.width = width # How many tiles wide it is
        self.tilesize = tilesize # How many pixels each tile is
        self.textures = textures # The textures
        self.size = (self.width*self.tilesize,self.height*self.tilesize)

    def generate_random(self):
        # Generate a random tilemap
        self.tilemap = [[random.randint(0, len(
            self.textures)-1) for e in range(self.width)] for e in range(
                self.height)]

    def draw(self, display, mouse=None):
        mouse = mouse
        # Draw the map
        for row in range(self.width):
            for column in range(self.height):

                texture = self.textures[self.tilemap[row][column]]
                # Highlight a tile (this is where the problem is)
                if self.ht != None:
                    if mouse[0] >= (column*self.tilesize) and mouse[0] <= (
                        column*self.tilesize)+self.tilesize:
                        if mouse[1] >= (row*self.tilesize) and mouse[1] <= (
                            row*self.tilesize)+self.tilesize:
                            texture = self.ht

                display.blit(texture,
                             (column*self.tilesize, row*self.tilesize))

tilemap = Tilemap(10,10,40,
                  # Load the textures
                  {0: pygame.image.load("tile1.png"),
                   1: pygame.image.load("tile2.png")
                   }
                  )

tilemap.generate_random() # Generate a random tilemap

pygame.init()
DISPLAYSURF = pygame.display.set_mode((tilemap.size))
# Load the highlighter
tilemap.ht = pygame.image.load("highlight.png").convert_alpha()

while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        # Draw the tilemap
        tilemap.draw(DISPLAYSURF, pygame.mouse.get_pos())

    pygame.display.update()

If you need more explanation feel free to ask!

Body:
Each time you draw to a surface in Pygame, the previous frame's data persists.
 Since you are drawing alpha, the previous, partially-transparent drawing is still in the same location, and you are drawing a partially-transparent tile over the same spot with each frame.  That causes that square to get closer and closer to the final color.  What you would typically do is erase the area you are blitting to and then re-draw. In this case you'd want to do this before your display.blit:

display.fill((0,0,0), (0, 0, column*self.tilesize, row*self.tilesize))
display.blit(texture, (column*self.tilesize, row*self.tilesize))

This will work so long as your background is black.  If you end up having an image for a background, you would just blit the background image slice there instead.

This code is untested since I don't have your sample PNGs, but if you have an issue please let me know and I will update the answer.


问:
How to capture Log4net Appender errors when Log4net Debugging turned off
I am using Log4net.  I recently decided to add a trace listener to a file to my configuration, to capture any errors generated by Log4net itself. (The
Log4net FAQ includes an example configuration for this.)

(I'm talking about cases when Log4net generates an error message of its own, due to being unable to do its job.  I'm not talking about configuring it to log application errors.)

While testing this, I messed around with my Log4net configuration in a test project so as to force Log4net or ADO.Net Appender errors, to verify they were handled correctly by the Trace Listener setup.

What I have found suggests that intrinsic Log4net errors will be written to the trace listener, even if Log4net debugging is turned off.  This is what I want.

Here's an example error I generated by tweaking the type name of a Log4net.Layout in the app.config to refer to a non-existent type.  This was the only entry in the Trace Listener file, which is what I wanted.

```<code>log4net:ERROR Failed to find type [log4net.Layout.RawTimeStampLayoutXX]
System.TypeLoadException: Could not load type [log4net.Layout.RawTimeStampLayoutXX]. Tried assembly [log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a] and all loaded assemblies
  at log4net.Util.SystemInfo.GetTypeFromString(Assembly relativeAssembly, String typeName, Boolean throwOnError, Boolean ignoreCase)
  at log4net.Util.SystemInfo.GetTypeFromString(String typeName, Boolean throwOnError, Boolean ignoreCase)
  at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
log4net:ERROR Failed to create object to set param: layout
</code>```

But, I also found that if the error is in an external system (such as, in the example below, a SQL Server error), the error will only appear in the trace listener file if Log4net debugging is turned ON.  Which means that it's surrounded by a great deal of internal housekeeping information.

```<code>log4net:ERROR [AdoNetAppender] ErrorCode: GenericFailure. Exception while writing to database
System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "@log_date".
  at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
  at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
  at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
  at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
  at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
  at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
  at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
  at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
  at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
  at log4net.Appender.AdoNetAppender.SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)
  at log4net.Appender.AdoNetAppender.SendBuffer(LoggingEvent[] events)
ClientConnectionId:8ddb2758-4adc-495e-af8b-c16e0acc937a
Error Number:137,State:2,Class:15
</code>```

I don't want to run with debugging turned on all the time, just to catch this kind of error.  This app runs something like 70 times a day and generates 25KB of debug trace listener output per run, just from internal housekeeping.  I don't want to have to wade through megabytes of noise to find the one signal.

So, my questions:

Is it possible to capture errors that are fatal to an Appender in the trace listener, without having Log4net debugging turned on?

Is this behavior by design?

答:
I found a solution.  A nice, elegant one.

All Appender classes in Log4net have a public property called ErrorHandler.  By default, this is set to an instance of a class called OnlyOnceErrorHandler, that will log an error to the Debug feed (if enabled) and then stop reporting errors.

But you can override this, through configuration:

```<code>  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Logs\logfile.txt" />
      <rollingStyle value="Date" />
      <datePattern value="yyyyMMdd" />
      <maxSizeRollBackups value="-1" />
      <maximumFileSize value="50GB" />
      <errorHandler type="MyTraceLoggingErrorHandler, MyAssembly" />
</code>```

The ErrorHandler implements the very simple interface IErrorHandler, and can do whatever you want it to do.

In my case, I simply had it write the messages and exceptions it received to the TraceListener:

```<code>Trace.WriteLine(message);
Trace.WriteLine(errorCode);
Trace.WriteLine(e.Message);
Trace.WriteLine(e.StackTrace);
</code>```

And that solved my problem.

Body:
I am using Log4net.  I recently decided to add a trace listener to a file to my configuration, to capture any errors generated by Log4net itself. (The
Log4net FAQ includes an example configuration for this.)

(I'm talking about cases when Log4net generates an error message of its own, due to being unable to do its job.  I'm not talking about configuring it to log application errors.)

While testing this, I messed around with my Log4net configuration in a test project so as to force Log4net or ADO.Net Appender errors, to verify they were handled correctly by the Trace Listener setup.

What I have found suggests that intrinsic Log4net errors will be written to the trace listener, even if Log4net debugging is turned off.  This is what I want.

Here's an example error I generated by tweaking the type name of a Log4net.Layout in the app.config to refer to a non-existent type.  This was the only entry in the Trace Listener file, which is what I wanted.

log4net:ERROR Failed to find type [log4net.Layout.RawTimeStampLayoutXX]
System.TypeLoadException: Could not load type [log4net.Layout.RawTimeStampLayoutXX]. Tried assembly [log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a] and all loaded assemblies
  at log4net.Util.SystemInfo.GetTypeFromString(Assembly relativeAssembly, String typeName, Boolean throwOnError, Boolean ignoreCase)
  at log4net.Util.SystemInfo.GetTypeFromString(String typeName, Boolean throwOnError, Boolean ignoreCase)
  at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
log4net:ERROR Failed to create object to set param: layout

But, I also found that if the error is in an external system (such as, in the example below, a SQL Server error), the error will only appear in the trace listener file if Log4net debugging is turned ON.  Which means that it's surrounded by a great deal of internal housekeeping information.

log4net:ERROR [AdoNetAppender] ErrorCode: GenericFailure. Exception while writing to database
System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "@log_date".
  at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
  at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
  at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
  at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
  at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
  at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
  at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
  at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
  at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
  at log4net.Appender.AdoNetAppender.SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)
  at log4net.Appender.AdoNetAppender.SendBuffer(LoggingEvent[] events)
ClientConnectionId:8ddb2758-4adc-495e-af8b-c16e0acc937a
Error Number:137,State:2,Class:15

I don't want to run with debugging turned on all the time, just to catch this kind of error.  This app runs something like 70 times a day and generates 25KB of debug trace listener output per run, just from internal housekeeping.  I don't want to have to wade through megabytes of noise to find the one signal.

So, my questions:

Is it possible to capture errors that are fatal to an Appender in the trace listener, without having Log4net debugging turned on?

Is this behavior by design?

Body:
I found a solution.  A nice, elegant one.

All Appender classes in Log4net have a public property called ErrorHandler.  By default, this is set to an instance of a class called OnlyOnceErrorHandler, that will log an error to the Debug feed (if enabled) and then stop reporting errors.

But you can override this, through configuration:

  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Logs\logfile.txt" />
      <rollingStyle value="Date" />
      <datePattern value="yyyyMMdd" />
      <maxSizeRollBackups value="-1" />
      <maximumFileSize value="50GB" />
      <errorHandler type="MyTraceLoggingErrorHandler, MyAssembly" />

The ErrorHandler implements the very simple interface IErrorHandler, and can do whatever you want it to do.

In my case, I simply had it write the messages and exceptions it received to the TraceListener:

Trace.WriteLine(message);
Trace.WriteLine(errorCode);
Trace.WriteLine(e.Message);
Trace.WriteLine(e.StackTrace);

And that solved my problem.


问:
Exception while setting NSDictionary to UserDefaults
How to fix exception:

```<code>[User Defaults] Attempt to set a non-property-list object {
4 = 5;
} as an NSUserDefaults/CFPreferences value for key MyKey
</code>```

thrown by executing following code (Swift 3)

```<code>let ns = NSDictionary(dictionary: [4: 5])
UserDefaults.standard.set(ns, forKey: "MyKey")
</code>```

Code above correctly saves String type, but has problem with NSDictionary

答:
All property list keys are required to be String.

From the documentation

And although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.

```<code>let ns = ["4": 5]
UserDefaults.standard.set(ns, forKey: "MyKey")
</code>```

No need to use NSDictionary, Swift Dictionary works the same way and is implicitly bridged.

Body:
How to fix exception:

[User Defaults] Attempt to set a non-property-list object {
4 = 5;
} as an NSUserDefaults/CFPreferences value for key MyKey

thrown by executing following code (Swift 3)

let ns = NSDictionary(dictionary: [4: 5])
UserDefaults.standard.set(ns, forKey: "MyKey")

Code above correctly saves String type, but has problem with NSDictionary

Body:
All property list keys are required to be String.

From the documentation

And although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.

let ns = ["4": 5]
UserDefaults.standard.set(ns, forKey: "MyKey")

No need to use NSDictionary, Swift Dictionary works the same way and is implicitly bridged.


问:
Understanding mutable Seq
I'm pretty new to Scala and try to understand mutable Seq. Since it's in package mutable I expected there is a method that allows us to append element without copying the whole collection.

But there is no += method in the mutable.Seq, but in Buffer is. :+ and +: both copy the collection.

So why is it mutable?

答:
As explained in the documentation, mutable.Seq adds an update method to collection.Seq. += on the other hand is defined in Growable.

In Scala standard library, most mutable collections extend the immutable version, which is why they inherit copying :+, +:.

Title: Understanding mutable Seq


问:
Parse pnputil output to published name for specific class
In PowerShell, after I type "pnputil.exe -e", I get a list of driver info as below. I need to get class monitor's published name from the list and store "oem8.inf" into $monitor_name. Which command can I use to search for class = monitor and extract it's published name to a variable. Because the attribute "published name" has space, so I have no idea how to make this work.

```<code>Published name :            oem8.inf
Driver package provider :   HP
Class :                     Monitors
Driver date and version :   07/25/2013 2.2.0.0
Signer name :               Microsoft Windows Hardware Compatibility Publisher

Published name :            oem6.inf
Driver package provider :   Canon
Class :                     Printers
Driver date and version :   06/21/2006 6.1.7600.16385
Signer name :               Microsoft Windows

Published name :            oem1.inf
Driver package provider :   Microsoft
Class :                     Printers
Driver date and version :   06/21/2006 10.0.14393.0
Signer name :               Microsoft Windows
</code>```

答:
You can do this using WMI, via the Get-WMIObject cmdlet (alias gwmi):

```<code>gwmi Win32_PnPSignedDriver | ? DeviceClass -eq "MONITOR"
</code>```

will return some details, you can narrow it down to the InfName using this:

```<code>gwmi win32_PnPSignedDriver | ? DeviceClass -eq "MONITOR" | Select InfName

InfName
-------
oem30.inf
oem30.inf
</code>```

Body:
In PowerShell, after I type "pnputil.exe -e", I get a list of driver info as below. I need to get class monitor's published name from the list and store "oem8.inf" into $monitor_name. Which command can I use to search for class = monitor and extract it's published name to a variable. Because the attribute "published name" has space, so I have no idea how to make this work.

Published name :            oem8.inf
Driver package provider :   HP
Class :                     Monitors
Driver date and version :   07/25/2013 2.2.0.0
Signer name :               Microsoft Windows Hardware Compatibility Publisher

Published name :            oem6.inf
Driver package provider :   Canon
Class :                     Printers
Driver date and version :   06/21/2006 6.1.7600.16385
Signer name :               Microsoft Windows

Published name :            oem1.inf
Driver package provider :   Microsoft
Class :                     Printers
Driver date and version :   06/21/2006 10.0.14393.0
Signer name :               Microsoft Windows

Body:
You can do this using WMI, via the Get-WMIObject cmdlet (alias gwmi):

gwmi Win32_PnPSignedDriver | ? DeviceClass -eq "MONITOR"

will return some details, you can narrow it down to the InfName using this:

gwmi win32_PnPSignedDriver | ? DeviceClass -eq "MONITOR" | Select InfName

InfName
-------
oem30.inf
oem30.inf


问:
have python script send data to javascript using JSON to change web page
I am working on an interactive display with sensors on a raspberry pi. My display is showing a webpage. I am using a python script to interact with the sensors. I want it so that when a user walks by, a different web page is displayed in the web browser. I have already tried changing to a different web page doing it straight from the python script. Unfortunately, it does not work the way I want it to. JavaScript works just fine for changing to a different page. I am thinking it might be good to have my python script send a message to a javascript file to change the page using JSON. Does this sound like a practical solution? Thanks.</p>

答: Create your html file as a string in python.  This string can be modified in response to sensor input.  Write it to a file on your system where the html is source file exists; rewrite each time the sensor inputs change.  Set up a timer in Javascript, e.g. setTimeout() to refresh the page often.


问:
J2ObjC - Android Libraries
I'm trying to convert my Android project to an Objective C project with J2ObjC. So far, I managed to convert all my files which are not using any libraries. However, every class which uses a library receives an error. For example: error: package android.location does not exist.

In the documentation it states that you can't convert UI elements in J2ObjC. But the android.location package does not contain UI elements (for as far as I know). Is there a way to convert these classes anyway? Or is it only possible to convert code which is not using libraries?

Let me know if you need more info.

Thanks in advance :)

答:
j2objc supports the Java runtime API (JRE), and only a very small subset of the Android API.

There is no plan for j2objc to ever support the android.location API, since its package description states that its use is no longer recommended. For a cross-platform app, I suggest defining a minimum interface to meet your app's specific location needs, then implement that interface for each platform using the Google Places API libraries.

Title: J2ObjC - Android Libraries


问:
entry point for packager
I'm just starting out with react native. Everything was going ok but now when I run 'react-native run-ios' the packager is looking for js files in

```<code><project-root>/node_modules/react-native/packager
</code>```

instead of

```<code><project-root>
</code>```

If I run 'node node_modules/react-native/local-cli/cli.js start'
it looks for files in the correct location.

This is happening in my existing project and if I create a new project using react native init. It started after I installed a new npm module. I've since reverted the change, re-installed modules, cleared the tmpdir cache, rebooted computer etc. Can I explicitly configure the packager entry point?

Any help greatly appreciated

C

答:
This is a known issue with RN 0.45, I have also encountered this problem today after upgrading from 0.42.

https://github.com/facebook/react-native/issues/14246

The temporary solution until RN is fixed (next release?) is to run:

```<code>npm start -- -reset-cache
</code>```

You can also try:

```<code>npm run start -- --root <mydir>
</code>```

This will cause the packager to look in the correct location.

Until this is corrected it's a pain, as it means we have to invoke the reset every time the packager is started either from XCode or react-native run-ios.

The next release is later this month: https://github.com/facebook/react-native/releases/tag/v0.46.0-rc.0

Update
This has now been fixed in release 0.45.1

Title: entry point for packager

Body:
I'm just starting out with react native. Everything was going ok but now when I run 'react-native run-ios' the packager is looking for js files in

<project-root>/node_modules/react-native/packager

instead of

<project-root>

If I run 'node node_modules/react-native/local-cli/cli.js start'
it looks for files in the correct location.

This is happening in my existing project and if I create a new project using react native init. It started after I installed a new npm module. I've since reverted the change, re-installed modules, cleared the tmpdir cache, rebooted computer etc. Can I explicitly configure the packager entry point?

Any help greatly appreciated

C

Body:
This is a known issue with RN 0.45, I have also encountered this problem today after upgrading from 0.42.

https://github.com/facebook/react-native/issues/14246

The temporary solution until RN is fixed (next release?) is to run:

npm start -- -reset-cache

You can also try:

npm run start -- --root <mydir>

This will cause the packager to look in the correct location.

Until this is corrected it's a pain, as it means we have to invoke the reset every time the packager is started either from XCode or react-native run-ios.

The next release is later this month: https://github.com/facebook/react-native/releases/tag/v0.46.0-rc.0

Update
This has now been fixed in release 0.45.1


答:
Import statements in Java act like aliases for fully qualified type names. Trying to use the same alias for two or more types won't work because of ambiguity.

Therefore do either not use import statements for any of those conflicting types and use their fully qualified names (package plus type name) or import at most one of those types only.

Title: How to resolve class conflict in import statements

Body:
Im trying to write a program that will read an xml file and print to itext.

However, I getting a class conflict in import statements. I dont know how to resolve this issue.

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import org.w3c.dom.NodeList;
import org.w3c.dom.*;

import com.itextpdf.text.Annotation;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

The "Document" and "Element" classes between dom4j and itext are conflicting.

Does anyone know a workaround? Is there any eclipse magic I can do?


问:
document.getElementById class applies to the whole array instead of each element

elements of the array
```
</div>
</div>
</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>for(var i = 0; i < myarray.length; i++)
{
 var sr = (function(val) {
        btn = document.createElement('button');
        btn.data = val;
        btn.innerHTML = val;
        btn.addEventListener('click', checkAnswer);
        document.body.appendChild(btn);
  return btn.data = val;
    })//(myarray[i]);
document.getElementById("sr").innerHTML = myarray;
}</code>```

With this code the elements of the array appear in the html span. I want each element to appear as a button, as defined in the class "btn". However, the class changes the style of the array as a whole, not as single buttons. What is the correct way to define the style of each button?

I tried document.getElementById("sr").innerHTML = myarray.class="btn";. It does not work. Definitely not the correct syntax. Any idea?

答:
Use Element.dataset instead of creating a .data property. Pass i to IIFE. If you are trying to display the array myarray as .innerHTML of #sr, concatenate "[" to beginning and "]" to end of myarray setting at .innerHTML, as .innerHTML casts Array to String.

If you are trying to append created element to #sr, do not append element to document.body, but #sr.

function checkAnswer() {
  console.log(this.dataset.value)
}

var myarray = [1, 2, 3];

for (var i = 0; i < myarray.length; i++) {
  (function(val) {
    var btn = document.createElement('button');
    btn.dataset.value = val;
    btn.className = "btn"; // set `btn` `.className` to `"btn"`
    btn.innerHTML = val;
    btn.addEventListener('click', checkAnswer);
    document.body.appendChild(btn);
    // document.getElementById("sr").appendChild(btn);
  })(i);
}

document.getElementById("sr").innerHTML = "[" + myarray + "]";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><span id="sr" class="btn">elements of the array</span></p></code>```

Body:
elements of the array

for(var i = 0; i < myarray.length; i++)
{
 var sr = (function(val) {
        btn = document.createElement('button');
        btn.data = val;
        btn.innerHTML = val;
        btn.addEventListener('click', checkAnswer);
        document.body.appendChild(btn);
  return btn.data = val;
    })//(myarray[i]);
document.getElementById("sr").innerHTML = myarray;
}

With this code the elements of the array appear in the html span. I want each element to appear as a button, as defined in the class "btn". However, the class changes the style of the array as a whole, not as single buttons. What is the correct way to define the style of each button?

I tried document.getElementById("sr").innerHTML = myarray.class="btn";. It does not work. Definitely not the correct syntax. Any idea?

Body:
Use Element.dataset instead of creating a .data property. Pass i to IIFE. If you are trying to display the array myarray as .innerHTML of #sr, concatenate "[" to beginning and "]" to end of myarray setting at .innerHTML, as .innerHTML casts Array to String.

If you are trying to append created element to #sr, do not append element to document.body, but #sr.

function checkAnswer() {
  console.log(this.dataset.value)
}

var myarray = [1, 2, 3];

for (var i = 0; i < myarray.length; i++) {
  (function(val) {
    var btn = document.createElement('button');
    btn.dataset.value = val;
    btn.className = "btn"; // set `btn` `.className` to `"btn"`
    btn.innerHTML = val;
    btn.addEventListener('click', checkAnswer);
    document.body.appendChild(btn);
    // document.getElementById("sr").appendChild(btn);
  })(i);
}

document.getElementById("sr").innerHTML = "[" + myarray + "]";

<p><span id="sr" class="btn">elements of the array</span></p>


问:
java stop people from closing
hi i have a full screen program which i dont want people to close unless they have a password i have this code at the moment

```<code>public void windowClosing(WindowEvent arg0)
{
    System.out.println("HERE");
    String inputValue = JOptionPane.showInputDialog("Please input the closeword");

    if (inputValue != "closeplz")
    {

    }
}
</code>```

in the if statement i want it to stop the method so that the program doesent close. any help would be greatly aprecheated thanks ste

答:
Check out Closing an Applicaton for a simple class to help you with this. You would need to provide the custom close action that prompts the user for the password.

Using your simple example the code would be:

```<code>Action ca = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        JFrame frame = (JFrame)e.getSource();

        String inputValue = JOptionPane.showInputDialog("Please input the closeword");

        if (! inputValue.equals("closeplz"))
        {
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        }
    }
};

CloseListener cl = new CloseListener(ca);
</code>```

Title: java stop people from closing

Body:
hi i have a full screen program which i dont want people to close unless they have a password i have this code at the moment

public void windowClosing(WindowEvent arg0)
{
    System.out.println("HERE");
    String inputValue = JOptionPane.showInputDialog("Please input the closeword");

    if (inputValue != "closeplz")
    {

    }
}

in the if statement i want it to stop the method so that the program doesent close. any help would be greatly aprecheated thanks ste

Body:
Check out Closing an Applicaton for a simple class to help you with this. You would need to provide the custom close action that prompts the user for the password.

Using your simple example the code would be:

Action ca = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        JFrame frame = (JFrame)e.getSource();

        String inputValue = JOptionPane.showInputDialog("Please input the closeword");

        if (! inputValue.equals("closeplz"))
        {
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        }
    }
};

CloseListener cl = new CloseListener(ca);


问:
Session Validation/management Best Practice?
I am working on IOS app using Swift3. I am getting sessionToken once user is authenticated. I want to check that if user is logged on or not on each time user put application on background and open it again. Where to handle these checks? Should I use AppDelegate.swift overridden methods to verify these things? Or It should be done somewhere else?

Also, I want to know how to handle in-activeness of user. How to logout automatically if user is not active(No touch event detected , both in active and background state of app).

Application Structure:
1. LoginViewController(Default landing screen)
2. HomeScreen->2.1 UserList

答:
As Lion has mentioned you can handle in both the functions. Completing the use case you requested.

Case 1: When app is being terminated. Handle in

```<code>    func applicationWillTerminate(_ application: UIApplication) {
}
</code>```

case 2:

```<code> func applicationWillResignActive(_ application: UIApplication) {

      //Start a timer to invoke a method and handle your session clear and local notification to inform user in that method.

    }
</code>```

Invalidate the timer at

```<code>func applicationDidBecomeActive(_ application: UIApplication) {
    }
</code>```

and

```<code>    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
}
</code>```

Hope this helps.

Body:
As Lion has mentioned you can handle in both the functions. Completing the use case you requested.

Case 1: When app is being terminated. Handle in

    func applicationWillTerminate(_ application: UIApplication) {
}

case 2:

 func applicationWillResignActive(_ application: UIApplication) {

      //Start a timer to invoke a method and handle your session clear and local notification to inform user in that method.

    }

Invalidate the timer at

func applicationDidBecomeActive(_ application: UIApplication) {
    }

and

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
}

Hope this helps.


问:
iOS 10 Core Data Tutorial - NSPersistentContainer
I am attempting to follow Apples developer documentation to use CoreData.
I have just started learning Objective-C and now trying to wrap my head around CoreData. I think I have the concept under wraps OO Database.

For the life of me I can't get it to work and all searches I've done bring back either the tutorials for iOS 9 and previous, or for Swift.

Any help or guidance would be appreciated.

Core Data - Developer.Apple.Com

答:
If you want to keep things simple only deal with a single managedObjectContext.  If you are using NSPersistentContainer this is the viewContext.  Make sure to always read and write to core-data only from the main thread.  You will find similar simple setups with a single managedObjectContext in many tutorials.

Once you have mastered that you should learn how to use NSPersistentContainer properly.  It is not that hard there are a few simple rules to follow:

NEVER write to the viewContext

only write using performBackgroundTask.

Do not use any managedObjects or context from performBackgroundTask

Do not use any viewContext managedObject inside of performBackgroundTask - pass the objectID and refetch it inside the context.

don't use newBackgroundContext - it is useful only in very rare situations that you are unlikely to encounter.

discard all managedObject after a fetch.  If you need to keep a point to a managed object use a fetchedResultsController - even if it is for just one object


问:
For Multiple Tabs Single Fragment not working getItem called twice
Sir, I have to use single fragment for multiple tabs. I have implemented it using FragmentStatePagerAdapter but after debugging I have got that some of the tabs displays data but not correct. This is because getItem called twice please help me as early as possible.

I have passed arguments from getItem. it passes arguments two times as getItem calls twice. thus it overrides data of arguments. I have 6 tabs but only 1, 3 and 5 tab displays data but data is of 2, 4 and 6th tab and 2, 4 and 6th tab not showing anything on the screen.

not working any solution from previous questions.

ViewPager Code

```<code>public class ViewPagerAdapter extends FragmentStatePagerAdapter {

int TAB_COUNT=5;
Context mContext;
public ViewPagerAdapter(FragmentManager fm,Context context) {
    super(fm);
    mContext=context;
}

@Override
public Fragment getItem(int position) {
    NewsFragment fragment = new NewsFragment();
    Bundle args = new Bundle();
    args.putString("title", String.valueOf(getPageTitle(position)));
    args.putString("data", "data");
    fragment.setArguments(args);
    return fragment;

}

@Override
public CharSequence getPageTitle(int position) {

    return  mContext.getResources().getStringArray(R.array.tabs)[position];
}

@Override
public int getCount() {
    return TAB_COUNT;
}
</code>```

}

Listeners to change tab :

```<code>@Override
public void onTabSelected(TabLayout.Tab tab) {
    viewPager.setCurrentItem(tab.getPosition());

}

@Override
public void onPageSelected(int position) {

    TabLayout.Tab tab = tabLayout.getTabAt(position);
    if (tab != null) {
        tab.select();
    }
}
</code>```

Adapter setting

```<code> private void setUpTab() {
    viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), this);
    for (int i = 0; i < viewPagerAdapter.getCount(); i++) {
        tabLayout.addTab(
                tabLayout.newTab()
                        .setText(viewPagerAdapter.getPageTitle(i)));
    }
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    viewPager.setAdapter(viewPagerAdapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    viewPager.addOnPageChangeListener(this);
    tabLayout.addOnTabSelectedListener(this);
}
</code>```

答:
getItem gets called every time the adapter creates a new page for the first time. The reason you see it being called twice is that the viewPager prepares the next page in advance, so if you enter page 1, page 2 is already being created too for faster paging when you swipe right.

To help you further please show us the code for NewsFragment.

Also, you might consider using FragmentPagerAdapter instead of FragmentStatePagerAdapter because you seem to have a fixed number of tabs (5 in your example) and according to the documentation that is the use case for FragmentPagerAdapter.

Documentation from the page I linked above:

This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs.

Body:
Sir, I have to use single fragment for multiple tabs. I have implemented it using FragmentStatePagerAdapter but after debugging I have got that some of the tabs displays data but not correct. This is because getItem called twice please help me as early as possible.

I have passed arguments from getItem. it passes arguments two times as getItem calls twice. thus it overrides data of arguments. I have 6 tabs but only 1, 3 and 5 tab displays data but data is of 2, 4 and 6th tab and 2, 4 and 6th tab not showing anything on the screen.

not working any solution from previous questions.

ViewPager Code

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

int TAB_COUNT=5;
Context mContext;
public ViewPagerAdapter(FragmentManager fm,Context context) {
    super(fm);
    mContext=context;
}

@Override
public Fragment getItem(int position) {
    NewsFragment fragment = new NewsFragment();
    Bundle args = new Bundle();
    args.putString("title", String.valueOf(getPageTitle(position)));
    args.putString("data", "data");
    fragment.setArguments(args);
    return fragment;

}

@Override
public CharSequence getPageTitle(int position) {

    return  mContext.getResources().getStringArray(R.array.tabs)[position];
}

@Override
public int getCount() {
    return TAB_COUNT;
}

}

Listeners to change tab :

@Override
public void onTabSelected(TabLayout.Tab tab) {
    viewPager.setCurrentItem(tab.getPosition());

}

@Override
public void onPageSelected(int position) {

    TabLayout.Tab tab = tabLayout.getTabAt(position);
    if (tab != null) {
        tab.select();
    }
}

Adapter setting

 private void setUpTab() {
    viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), this);
    for (int i = 0; i < viewPagerAdapter.getCount(); i++) {
        tabLayout.addTab(
                tabLayout.newTab()
                        .setText(viewPagerAdapter.getPageTitle(i)));
    }
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    viewPager.setAdapter(viewPagerAdapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    viewPager.addOnPageChangeListener(this);
    tabLayout.addOnTabSelectedListener(this);
}


问:
Is @$array['possibly_missing_key'] an anti-pattern?
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

```<code>$value = @$array['possibly_missing_key'];
</code>```

The intended behavior:

```<code>if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}
</code>```

I want to know, before spreading the usage pattern.

答:
The @ operator suppresses error messages, and using it potentially sets up your code for other errors and unexpected behavior that end up hard to track down. Thus it's most certainly an antipattern.

Thus, I would very much prefer the second bit. It makes it much clearer

that it may not be present in the array, and

what the default value is if it's not present

To make it more concise you can use the ternary conditional operator ?:, as seen in Mark Baker's answer. Slightly less code and more symbols but the meaning is well-recognized.

Body:
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

$value = @$array['possibly_missing_key'];

The intended behavior:

if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}

I want to know, before spreading the usage pattern.


问:
WP/WC missing argument in WooCommerce Function
I have Wordpress with WooCommerce installed and I am trying to use this code to login an admin user:

```<code>if ( !is_user_logged_in() ) {
    $user = get_userdatabylogin( $username ); // get_user_by('login', $user_login);
    $id = $user->ID;

    wp_set_current_user( $id, $user->user_login );
    wp_set_auth_cookie( $id );
    do_action( 'wp_login', $user->user_login );
}
</code>```

But it is returning this error message:

Warning: Missing argument 2 for wc_maybe_store_user_agent() in
  plugins/woocommerce/includes/wc-core-functions.php
  on line 1516

I have tried looking around online but no one seems to have had this issue.

答:
```<code>if (!is_user_logged_in()) {

    //determine WordPress user account to impersonate
    $user_login = 'guest';

    //get user ID
    $user = get_userdatabylogin($user_login); // below WP 3.3.0

    //$user =  get_user_by('login', $user_login); above or equals WP 3.3.0

    $user_id = $user->ID;

    //login
    wp_set_current_user($user_id, $user_login);
    wp_set_auth_cookie($user_id);
    do_action('wp_login', $user_login);
}
</code>```

There is a hook in WooCommerce like this.

```<code>add_action( 'wp_login', 'wc_maybe_store_user_agent', 10, 2 );
</code>```

The "wc_maybe_store_user_agent" expects 2 parameter. If the user ID is not set, it will show the error you mentioned.
Test my snippet above

Function is at line 1516 in plugins/woocommerce/includes/wc-core-functions.php

```<code>function wc_maybe_store_user_agent( $user_login, $user ) {
    if ( 'yes' === get_option( 'woocommerce_allow_tracking', 'no' ) && user_can( $user, 'manage_woocommerce' ) ) {
        $admin_user_agents   = array_filter( (array) get_option( 'woocommerce_tracker_ua', array() ) );
        $admin_user_agents[] = wc_get_user_agent();
        update_option( 'woocommerce_tracker_ua', array_unique( $admin_user_agents ) );
    }
}
add_action( 'wp_login', 'wc_maybe_store_user_agent', 10, 2 );
</code>```

Body:
I have Wordpress with WooCommerce installed and I am trying to use this code to login an admin user:

if ( !is_user_logged_in() ) {
    $user = get_userdatabylogin( $username ); // get_user_by('login', $user_login);
    $id = $user->ID;

    wp_set_current_user( $id, $user->user_login );
    wp_set_auth_cookie( $id );
    do_action( 'wp_login', $user->user_login );
}

But it is returning this error message:

Warning: Missing argument 2 for wc_maybe_store_user_agent() in
  plugins/woocommerce/includes/wc-core-functions.php
  on line 1516

I have tried looking around online but no one seems to have had this issue.

Body:
if (!is_user_logged_in()) {

    //determine WordPress user account to impersonate
    $user_login = 'guest';

    //get user ID
    $user = get_userdatabylogin($user_login); // below WP 3.3.0

    //$user =  get_user_by('login', $user_login); above or equals WP 3.3.0

    $user_id = $user->ID;

    //login
    wp_set_current_user($user_id, $user_login);
    wp_set_auth_cookie($user_id);
    do_action('wp_login', $user_login);
}

There is a hook in WooCommerce like this.

add_action( 'wp_login', 'wc_maybe_store_user_agent', 10, 2 );

The "wc_maybe_store_user_agent" expects 2 parameter. If the user ID is not set, it will show the error you mentioned.
Test my snippet above

Function is at line 1516 in plugins/woocommerce/includes/wc-core-functions.php

function wc_maybe_store_user_agent( $user_login, $user ) {
    if ( 'yes' === get_option( 'woocommerce_allow_tracking', 'no' ) && user_can( $user, 'manage_woocommerce' ) ) {
        $admin_user_agents   = array_filter( (array) get_option( 'woocommerce_tracker_ua', array() ) );
        $admin_user_agents[] = wc_get_user_agent();
        update_option( 'woocommerce_tracker_ua', array_unique( $admin_user_agents ) );
    }
}
add_action( 'wp_login', 'wc_maybe_store_user_agent', 10, 2 );


问:
How to create a HashSet from a Set?
There is a foreign key in my entity :

```<code>@Entity
@Table(name = "role")
public class Role {

    @Id
    @Column(name = "role_code")
    private String code;

    @Column(name = "role_lib")
    private String lib;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "role_menu" , joinColumns = {@JoinColumn(name = "role_code")} , inverseJoinColumns = {@JoinColumn(name = "menu_id")} )
    @JsonManagedReference
    private Set<Menu> menus = new HashSet<Menu>();

    // getters and setters

}
</code>```

It is said in Hibernate documentation that relationship attributes should be of type Interface. Now my problem is when dealing with an instance of this class and using the getMenus() method :

```<code>    @Override
    @Transactional
    public Set<Menu> getListMenu(String role_code) {

        return ((Role)get(role_code)).getMenus();

    }
</code>```

I want to cast it to a HashSet , but I got castException of persistent object at runtime. So how to make it to be HashSet ?

答:
You cannot cast if the implementations of Set is not HashSet. But you can create a object:

```<code>new HashSet(obj.getMenus);
</code>```

But it's always better to use interfaces, not the implementation.

Here is a note from Hibernate doc:

Hibernate will actually replace the HashSet with an instance of
  Hibernate's own implementation of Set. Be aware of the following
  errors:

......

(HashSet) cat.getKittens(); // Error!

And here is why you don't actually need to cast nor to create a new object:

The persistent collections injected by Hibernate behave like HashMap,
  HashSet, TreeMap, TreeSet or ArrayList, depending on the interface
  type.

Title: How to create a HashSet from a Set?

Body:
There is a foreign key in my entity :

@Entity
@Table(name = "role")
public class Role {

    @Id
    @Column(name = "role_code")
    private String code;

    @Column(name = "role_lib")
    private String lib;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "role_menu" , joinColumns = {@JoinColumn(name = "role_code")} , inverseJoinColumns = {@JoinColumn(name = "menu_id")} )
    @JsonManagedReference
    private Set<Menu> menus = new HashSet<Menu>();

    // getters and setters

}

It is said in Hibernate documentation that relationship attributes should be of type Interface. Now my problem is when dealing with an instance of this class and using the getMenus() method :

    @Override
    @Transactional
    public Set<Menu> getListMenu(String role_code) {

        return ((Role)get(role_code)).getMenus();

    }

I want to cast it to a HashSet , but I got castException of persistent object at runtime. So how to make it to be HashSet ?

Body:
You cannot cast if the implementations of Set is not HashSet. But you can create a object:

new HashSet(obj.getMenus);

But it's always better to use interfaces, not the implementation.

Here is a note from Hibernate doc:

Hibernate will actually replace the HashSet with an instance of
  Hibernate's own implementation of Set. Be aware of the following
  errors:

......

(HashSet) cat.getKittens(); // Error!

And here is why you don't actually need to cast nor to create a new object:

The persistent collections injected by Hibernate behave like HashMap,
  HashSet, TreeMap, TreeSet or ArrayList, depending on the interface
  type.


问:
How to rewrite this promise chain to avoid need of multiple functions?
I'm just starting with mobx and react (which is a great team, btw.!) and I have a little problem with my store. I want to asynchronously fetch some data from an existing API and then use this data to update some existing observables in my store:

```<code>class StationStore {

  @observable stations = []

  loadStations() {
    fetch('http://localhost:3000/api/station/getStations')
    .then(function(response) { return response.json() })
    .then(stations=>this.parseStations(stations));
  }

  @action parseStations(stations) {
    var newStations = stations.map((station)=>{
      let s = new Station;
      s.id=station.id;
      s.name=station.Text;
      s.deviceType=station.DeviceType;
      return s;
    });
    this.stations.replace(newStations);
  }
}
</code>```

As you can see, I need to divide my logic into two separate functions in order to be able to access this.stations. I tried to include the map and replace part into the loadStations()'s second then(), but when I do so, I cannot access my store because this is undefined in there.

How can I fix this?

答:
Use var self = this; should solve your problem

```<code>class StationStore {
    @observable stations = [];

    loadStations() {
        var self = this;
        fetch('http://localhost:3000/api/station/getStations')
            .then(function (response) {
                return response.json()
            })
            .then(stations => {
                self.stations.replace(stations.map((station) => {
                    let s = new Station;
                    s.id = station.id;
                    s.name = station.Text;
                    s.deviceType = station.DeviceType;
                    return s;
                }));
            });
    }
}
</code>```

Body:
I'm just starting with mobx and react (which is a great team, btw.!) and I have a little problem with my store. I want to asynchronously fetch some data from an existing API and then use this data to update some existing observables in my store:

class StationStore {

  @observable stations = []

  loadStations() {
    fetch('http://localhost:3000/api/station/getStations')
    .then(function(response) { return response.json() })
    .then(stations=>this.parseStations(stations));
  }

  @action parseStations(stations) {
    var newStations = stations.map((station)=>{
      let s = new Station;
      s.id=station.id;
      s.name=station.Text;
      s.deviceType=station.DeviceType;
      return s;
    });
    this.stations.replace(newStations);
  }
}

As you can see, I need to divide my logic into two separate functions in order to be able to access this.stations. I tried to include the map and replace part into the loadStations()'s second then(), but when I do so, I cannot access my store because this is undefined in there.

How can I fix this?

Body:
Use var self = this; should solve your problem

class StationStore {
    @observable stations = [];

    loadStations() {
        var self = this;
        fetch('http://localhost:3000/api/station/getStations')
            .then(function (response) {
                return response.json()
            })
            .then(stations => {
                self.stations.replace(stations.map((station) => {
                    let s = new Station;
                    s.id = station.id;
                    s.name = station.Text;
                    s.deviceType = station.DeviceType;
                    return s;
                }));
            });
    }
}


问:
What is the meaning of using proxy ( dynamic proxy) in spring framework?
I don't know the meaning of using proxy in spring. what is efficient?</p>

答:
The other answers are good, but here's how I think of it in very simple terms.

An annotation means "add hidden code for extra behavior."

The framework (or whatever knows what the annotation means) adds bytecode, Spring at runtime, AspectJ at compile time, for example.

It adds code as a proxy along with an interceptor. (A wrapper, decorator, adapter are similar and may be easier to understand than "proxy".)

When the program runs, the interceptor sends execution to the proxy which does its thing, which then may or may not send execution to the class that you coded and that it "wraps".


问:
AttributeError: 'module' object has no attribute 'whois'
I tried to execute this code:

```<code>import whois
w = whois.whois('webscraping.com')
print w
</code>```

And I got the error above.
Why?

答:
Wrong library, solution is to remove old one and install new : </p>

```<code>pip uninstall whois
pip install python-whois
</code>```

Body:
I tried to execute this code:

import whois
w = whois.whois('webscraping.com')
print w

And I got the error above.
Why?

Body:
Wrong library, solution is to remove old one and install new :

pip uninstall whois
pip install python-whois


问:
Calculating an average temperature using Python and weather API
I am trying to calculate an average 10-day temperature by finding the average daily temperature between high and low, and then dividing the average in total time frame by 10. I am using the weather APi, running on the command line with a postcode. Currently I have invalid syntax errors but can't figure out what's wrong- perhaps I am missing a bracket or using an incorrect one.
Error is: print city ['city']
        ^
SyntaxError: invalid syntax

Any help would be appreciated.

```<code>from weather import Weather
import sys

if len(sys.argv) > 1:
    weather = Weather ()
    location = weather.lookup_by_location((sys.argv[1]))
    forecast = location.forecast()
    city = location.location()

    average = 0

for f in location.forecast():
    averageTotal = f(f[int('high')] + f[int('low')] / 2

   print city ['city']
   print "10 day average temperature:" + str(averageTotal / 10)

else:
    print "You must supply a postcode to get the atmospheric pressure."
</code>```

答:
Well your error tells you that print city ['city'] is invalid, it's quite explicit.

Are you trying to print the value of the key 'city' in the dict city?
Then you need to remove the white space before ['city'].

Otherwise, what is this line actually supposed to do?

Body:
I am trying to calculate an average 10-day temperature by finding the average daily temperature between high and low, and then dividing the average in total time frame by 10. I am using the weather APi, running on the command line with a postcode. Currently I have invalid syntax errors but can't figure out what's wrong- perhaps I am missing a bracket or using an incorrect one.
Error is: print city ['city']
        ^
SyntaxError: invalid syntax

Any help would be appreciated.

from weather import Weather
import sys

if len(sys.argv) > 1:
    weather = Weather ()
    location = weather.lookup_by_location((sys.argv[1]))
    forecast = location.forecast()
    city = location.location()

    average = 0

for f in location.forecast():
    averageTotal = f(f[int('high')] + f[int('low')] / 2

   print city ['city']
   print "10 day average temperature:" + str(averageTotal / 10)

else:
    print "You must supply a postcode to get the atmospheric pressure."


问:
Check if all rows are the same in a matrix
I'm looking to see if sample(..., replace=T) results in sampling the same row n times. I see the duplicated function checks if elements are repeated by returning a logical vector for each index, but I need to see if one element is repeated n times (single boolean value). What's the best way to go about this?

Here's just an example. Some function on this matrix should return TRUE

```<code>t(matrix(c(rep(c(rep(4,1),rep(5,1)),8)),nrow=2,ncol=8))
     [,1] [,2]
[1,]    4    5
[2,]    4    5
[3,]    4    5
[4,]    4    5
[5,]    4    5
[6,]    4    5
[7,]    4    5
[8,]    4    5
</code>```

答:
A little cleaner looking (and easier to tell what the code is doing):</p>

```<code>m <- t(matrix(c(rep(c(rep(4,1),rep(5,1)),8)),nrow=2,ncol=8))
apply(m, 2, function(x) all(x==x[1]))
[1] TRUE TRUE
</code>```

Body:
I'm looking to see if sample(..., replace=T) results in sampling the same row n times. I see the duplicated function checks if elements are repeated by returning a logical vector for each index, but I need to see if one element is repeated n times (single boolean value). What's the best way to go about this?

Here's just an example. Some function on this matrix should return TRUE

t(matrix(c(rep(c(rep(4,1),rep(5,1)),8)),nrow=2,ncol=8))
     [,1] [,2]
[1,]    4    5
[2,]    4    5
[3,]    4    5
[4,]    4    5
[5,]    4    5
[6,]    4    5
[7,]    4    5
[8,]    4    5

Body:
A little cleaner looking (and easier to tell what the code is doing):

m <- t(matrix(c(rep(c(rep(4,1),rep(5,1)),8)),nrow=2,ncol=8))
apply(m, 2, function(x) all(x==x[1]))
[1] TRUE TRUE


问:
Sql server row lock
I have developed an app with c# where a form displays a few details of a employee in a listview control. When a user clicks on a row, then another form will open and show that employee's record with more detail.

I want it to work so that a user will see the form where employee records are shown in more detail, that that record will be locked in such a way that another user will not be able to see that record until the original user closes the detail form. Please guide me how I can design this type of app with SQL Server lock.

答:
For row lock you could use:

```<code>BEGIN TRANSACTION
UPDATE someTable set SomeThing = 'new value' where someID = 1
-- this will lock 'someTable' in affected row as long as transaction alive.

-- in another connection
select * from someTable with (readpast)
-- this will skip locked rows
</code>```

but keep in mind that this is not a proper way to implement.

The user might panic and blame system for losing data or even say it's a bug.

When you lock a row, keep in mind that it will lock until the connection/transaction is timed out or until the user commits that row back.

No connection pooling.

Bad idea for web app, due to remote connection.

Any query involving someTable without a with (readpast) statement will have to wait.

Just let the user 'view' only in editing row. In ASP.NET for caching editing row:

```<code>Application[string.Format("{0}.{1}", tableName, primaryKey)] = true;
</code>```

Title: Sql server row lock

Body:
For row lock you could use:

BEGIN TRANSACTION
UPDATE someTable set SomeThing = 'new value' where someID = 1
-- this will lock 'someTable' in affected row as long as transaction alive.

-- in another connection
select * from someTable with (readpast)
-- this will skip locked rows

but keep in mind that this is not a proper way to implement.

The user might panic and blame system for losing data or even say it's a bug.

When you lock a row, keep in mind that it will lock until the connection/transaction is timed out or until the user commits that row back.

No connection pooling.

Bad idea for web app, due to remote connection.

Any query involving someTable without a with (readpast) statement will have to wait.

Just let the user 'view' only in editing row. In ASP.NET for caching editing row:

Application[string.Format("{0}.{1}", tableName, primaryKey)] = true;


问:
How to reduce the size of mp3 file in Android created using MediaRecorder
My app creates audio files using MediaRecorder class and I need to upload these created files to a server. Therefore I need these files to be of minimum size so that they can be easily uploaded.
Size reduction may include some degradation of quality.</p>

答:
I think these settings will be optimal for low size and low quality:</p>

```<code>mediaRecorder.setAudioChannels(1);
mediaRecorder.setAudioSamplingRate(5512);
mediaRecorder.setAudioEncodingBitRate(32000);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
</code>```

Body:
I think these settings will be optimal for low size and low quality:

mediaRecorder.setAudioChannels(1);
mediaRecorder.setAudioSamplingRate(5512);
mediaRecorder.setAudioEncodingBitRate(32000);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);


问:
Can Nginx insert a missing "/" or missing "/bla/" in a URL?
Looking through the error.log file of Nginx, we can see requests coming as one of two incorrect patterns:

http://www.example.com/app-contextmoduleA/controller1 -> should be http://www.example.com/app-context/moduleA/controller1

http://www.example.com/app-contextcontroller2 -> should be http://www.example.com/app-context/moduleB/controller2

The current Nginx configuration looks like this:

```<code>server {

  listen        8080;

  location /app-context/ {

    proxy_redirect     off;
    proxy_set_header   Host $host;
    proxy_pass http://localhost:8888/app-context/;
  }
}
</code>```

The challenge is inserting the missing / after app-context (for the first wrong URL) or missing /moduleB/ (for the second wrong URL). It doesn't look like try_files would support that, and I have not found a way to do it with rewrite.

Is there a way for Nginx to rewrite the URLs for both use cases? In particular, I would prefer not to have to know all the name of the modules or controllers in advance. There are many, so "hard-coding" them in the rewrite rule would be onerous.

答:
These should handle your example case:

```<code>    location /app-context {
        rewrite ^(/app-contextmoduleA)/(.*)$ /app-context/moduleA/$2 permanent;
        rewrite ^(/app-contextcontroller2) /app-context/moduleB/controller2 permanent;
        ...
    }
</code>```

Check the ngx_http_rewrite_module for more info.

Body:
Looking through the error.log file of Nginx, we can see requests coming as one of two incorrect patterns:

http://www.example.com/app-contextmoduleA/controller1 -> should be http://www.example.com/app-context/moduleA/controller1

http://www.example.com/app-contextcontroller2 -> should be http://www.example.com/app-context/moduleB/controller2

The current Nginx configuration looks like this:

server {

  listen        8080;

  location /app-context/ {

    proxy_redirect     off;
    proxy_set_header   Host $host;
    proxy_pass http://localhost:8888/app-context/;
  }
}

The challenge is inserting the missing / after app-context (for the first wrong URL) or missing /moduleB/ (for the second wrong URL). It doesn't look like try_files would support that, and I have not found a way to do it with rewrite.

Is there a way for Nginx to rewrite the URLs for both use cases? In particular, I would prefer not to have to know all the name of the modules or controllers in advance. There are many, so "hard-coding" them in the rewrite rule would be onerous.

Body:
These should handle your example case:

    location /app-context {
        rewrite ^(/app-contextmoduleA)/(.*)$ /app-context/moduleA/$2 permanent;
        rewrite ^(/app-contextcontroller2) /app-context/moduleB/controller2 permanent;
        ...
    }

Check the ngx_http_rewrite_module for more info.