问:
C++ EXC_BAD_ACCESS (Binary Tree)
My class assignment is to create a binary tree, and I decided to use a vector of nodes to do so. When I try to run my code, I keep getting a process 11 bad access error, and my IDE/debugger (CLion) always highlights my class declaration for nodes. The code is below. Can anyone tell me why exactly I keep getting this error? Where is the invalid memory access happening?</p>

```<code>//Genghis Khan
#include <iostream>
#include <vector>
using namespace std;

//Creating node class and initializing tree vector
class node
{
public:
    int key;
    double balance;
    string name;
    friend class binarytree;
    bool visited; //for use in traversal
};

class binarytree
{
public:
vector<node> tree;
int index; //index to iterate through the tree

//Constructor
binarytree()
{
    node sentinel;
    sentinel.key = 0;
    sentinel.balance = 0;
    sentinel.name = "";
    sentinel.visited = false;
    tree[0] = sentinel;
}

//Empty
bool empty()
{
    return(tree.size() == 1);
}

//set temp to root
void set()
{
    index = 1;
}

//create a new node
/*node create()
{
    node *v = new node;
    cout << "Enter name: ";
    getline(cin, v->name);
    cout << "Enter balance: ";
    cin >> v->balance;
    cout << "Enter key: ";
    cin >> v->key;
    return(*v);
}*/

//return left child for an index
int leftchild(int a)
{
    return(a*2);
}

//return right child for an index
int rightchild(int a)
{
    return(a*2+1);
}
//whether a node is a leaf
bool isleaf(int a)
{
    //if there are no nodes at tree[a]'s left and right children, a is a leaf
    try
    {
        cout << tree[leftchild(a)].key;
        cout << tree[rightchild(a)].key;
    }
    catch(const std::invalid_argument)
    {
        return true;
    }
    return false;
}

//insert
void insert(node a)
{
    while(!isleaf(index))
    {
        if(empty())
        {
            tree[1] = a; //set root to index 1
        }
        else
        {
            if(a.key < tree[index].key)
            {
                index = index * 2;
                insert(tree[index]);
            }
            else if(a.key > tree[index].key)
            {
                index = index * 2 + 1;
                insert(tree[index]);
            }
        }
    }
    tree[index] = a;
}

//visit
void visit(node a)
{
    cout << a.name << endl;
    cout << a.balance << endl;
    cout << a.key << endl;
}

//inorder
void inorder(int a) //will only pass root to this function
{
    if(!isleaf(a))
    {
        inorder(leftchild(a));
        visit(tree[a]);
        inorder(rightchild(a));
    }
}

};

int main()
{
    int n;
    cout << "How many people would you like to enter: ";
    cin >> n;

    binarytree b;
    node *v = new node;
    for(int i = 0; i < n; i++)
    {
        cout << "Enter name: ";
        getline(cin, v->name);
        cout << "Enter balance: ";
        cin >> v->balance;
        cout << "Enter key: ";
        cin >> v->key;
        b.set();
        b.insert(*v);
    }

    for(int j = 0; j < b.tree.size(); j++)
    {
        cout << b.tree[j].key << endl;
    }

    return 0;
}
</code>```

答:
There are various places in your code where you try to access non-existent vector elements via std::vector::operator[], which will never throw an exception, but instead may crash if you're attempting to access out-of-bounds elements. For a start, you could use std::vector::at() instead, which is similar but does throw an exception (rather than crash) giving you more information.

You seem to lack fundamental understanding of how std::vector works and is meant to be used. For example, in the constructor of binarytree, you should instead of

```<code>tree[0] = sentinel;
</code>```

have

```<code>tree.push_back(sentinel);
</code>```

Title: C++ EXC_BAD_ACCESS (Binary Tree)

Body:
My class assignment is to create a binary tree, and I decided to use a vector of nodes to do so. When I try to run my code, I keep getting a process 11 bad access error, and my IDE/debugger (CLion) always highlights my class declaration for nodes. The code is below. Can anyone tell me why exactly I keep getting this error? Where is the invalid memory access happening?

//Genghis Khan
#include <iostream>
#include <vector>
using namespace std;

//Creating node class and initializing tree vector
class node
{
public:
    int key;
    double balance;
    string name;
    friend class binarytree;
    bool visited; //for use in traversal
};

class binarytree
{
public:
vector<node> tree;
int index; //index to iterate through the tree

//Constructor
binarytree()
{
    node sentinel;
    sentinel.key = 0;
    sentinel.balance = 0;
    sentinel.name = "";
    sentinel.visited = false;
    tree[0] = sentinel;
}

//Empty
bool empty()
{
    return(tree.size() == 1);
}

//set temp to root
void set()
{
    index = 1;
}

//create a new node
/*node create()
{
    node *v = new node;
    cout << "Enter name: ";
    getline(cin, v->name);
    cout << "Enter balance: ";
    cin >> v->balance;
    cout << "Enter key: ";
    cin >> v->key;
    return(*v);
}*/

//return left child for an index
int leftchild(int a)
{
    return(a*2);
}

//return right child for an index
int rightchild(int a)
{
    return(a*2+1);
}
//whether a node is a leaf
bool isleaf(int a)
{
    //if there are no nodes at tree[a]'s left and right children, a is a leaf
    try
    {
        cout << tree[leftchild(a)].key;
        cout << tree[rightchild(a)].key;
    }
    catch(const std::invalid_argument)
    {
        return true;
    }
    return false;
}

//insert
void insert(node a)
{
    while(!isleaf(index))
    {
        if(empty())
        {
            tree[1] = a; //set root to index 1
        }
        else
        {
            if(a.key < tree[index].key)
            {
                index = index * 2;
                insert(tree[index]);
            }
            else if(a.key > tree[index].key)
            {
                index = index * 2 + 1;
                insert(tree[index]);
            }
        }
    }
    tree[index] = a;
}

//visit
void visit(node a)
{
    cout << a.name << endl;
    cout << a.balance << endl;
    cout << a.key << endl;
}

//inorder
void inorder(int a) //will only pass root to this function
{
    if(!isleaf(a))
    {
        inorder(leftchild(a));
        visit(tree[a]);
        inorder(rightchild(a));
    }
}

};

int main()
{
    int n;
    cout << "How many people would you like to enter: ";
    cin >> n;

    binarytree b;
    node *v = new node;
    for(int i = 0; i < n; i++)
    {
        cout << "Enter name: ";
        getline(cin, v->name);
        cout << "Enter balance: ";
        cin >> v->balance;
        cout << "Enter key: ";
        cin >> v->key;
        b.set();
        b.insert(*v);
    }

    for(int j = 0; j < b.tree.size(); j++)
    {
        cout << b.tree[j].key << endl;
    }

    return 0;
}

Body:
There are various places in your code where you try to access non-existent vector elements via std::vector::operator[], which will never throw an exception, but instead may crash if you're attempting to access out-of-bounds elements. For a start, you could use std::vector::at() instead, which is similar but does throw an exception (rather than crash) giving you more information.

You seem to lack fundamental understanding of how std::vector works and is meant to be used. For example, in the constructor of binarytree, you should instead of

tree[0] = sentinel;

have

tree.push_back(sentinel);


来源: stackexchange

问:
Boolean attribute in python object
It requires isgood to be a string only. I want it to be boolean.
Also self.__isgood = goodornot should throw an error, why not?

```<code>class Animal:
    Name = ""
    isgood = None

    def setisgood(self,goodornot):
        self.__isgood = goodornot

    def nameset(self,name):
        self.Name = name

dog = Animal()
dog.setisgood(False)
dog.nameset("jaang")
print("Your pet is:"+dog.isgood)
</code>```

答:
So then convert it to a string.</p>

```<code>print("Your pet is: {}".format(dog.isgood))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Boolean attribute in python object

Body:
It requires isgood to be a string only. I want it to be boolean.
Also self.__isgood = goodornot should throw an error, why not?

class Animal:
    Name = ""
    isgood = None

    def setisgood(self,goodornot):
        self.__isgood = goodornot

    def nameset(self,name):
        self.Name = name

dog = Animal()
dog.setisgood(False)
dog.nameset("jaang")
print("Your pet is:"+dog.isgood)

Body:
So then convert it to a string.

print("Your pet is: {}".format(dog.isgood))


问:
Laravel Class mailer does not exist
I updated my application from 5 to 5.2. Now when I call Mail::send() it return an exception Class mailer does not exist.

```<code>Mail::send('emails.mail', ['data' => $content], function ($m) use ($to, $subject,$toname) {

            $m->to($to, $toname)->subject($subject);

        });
</code>```

When I open Illuminate\Support\Facades\Mail class there is only one function

```<code>protected static function getFacadeAccessor()
{
    return 'mailer';
}
</code>```

Please help. If anyone have any idea

答:
Sometimes php artisan config:clear must be run in order to get rid of that kind of errors ("Class mailer does not exist").

I've migrated my project 1:1 (code, config, vhost) from old laptop to new one (Windows->Ubuntu) and I couldn't run the app without clearing config's cache.

Title: Laravel Class mailer does not exist

Body:
I updated my application from 5 to 5.2. Now when I call Mail::send() it return an exception Class mailer does not exist.

Mail::send('emails.mail', ['data' => $content], function ($m) use ($to, $subject,$toname) {

            $m->to($to, $toname)->subject($subject);

        });

When I open Illuminate\Support\Facades\Mail class there is only one function

protected static function getFacadeAccessor()
{
    return 'mailer';
}

Please help. If anyone have any idea


问:
Not able to get Costura.Fody to work, keeps asking for the DLL
I have installed costura.fody into my project using nuget package. I have updated the FodyWeavers.xml file with:

```<code><Costura
Unmanaged32Assemblies='dllname'
Unmanaged64Assemblies='dllname' />
</code>```

when I rebuild it and try to run the exe on seperate PC without the dll it doesnt work. Am I missing something ? Do I need to add anything else. I have also tried the following :

```<code><IncludeAssemblies>
    dllname
</IncludeAssemblies>
</code>```

Thank you for the help in advance.

答:
I wanted to add an element to this that is important for unmanaged dll's when they aren't formally part of the solution/project.

@Adds is right to use:

```<code><Costura
Unmanaged32Assemblies='dllname'
Unmanaged64Assemblies='dllname' />
</code>```

and @kdiddymcnasty is right to be careful about double-inclusion (but note that the IncludeAssemblies attribute is different from the Unmanaged##Assemblies attribute).

However, there's an additional piece to this, which is shown at this page.  Essentially, you need to create a pair of folders in the project, called Costura32 and Costura64 and put the appropriate version of the dll in there, and set them to 'Embedded resource'. Then the weaver can include them in the exe when building the solution.

In my case, I was using the LibGit2Sharp dll, which relies on git2-15e1193.dll, so I have this as part of my solution:

and for each of those dll's, I have the Build Action set to Embedded Resource:

Finally, the FodyWeavers.xml is:

```<code><?xml version="1.0" encoding="utf-8" ?>
<Weavers>
  <costura IncludeDebugSymbls='false'>
    <Unmanaged32Assemblies>
      git2-15e1193
    </Unmanaged32Assemblies>
    <Unmanaged64Assemblies>
      git2-15e1193
    </Unmanaged64Assemblies>
  </costura>
</Weavers>
</code>```

Make sure to leave the .dll off the dll names in the FodyWeavers.xml file.

Body:
I have installed costura.fody into my project using nuget package. I have updated the FodyWeavers.xml file with:

<Costura
Unmanaged32Assemblies='dllname'
Unmanaged64Assemblies='dllname' />

when I rebuild it and try to run the exe on seperate PC without the dll it doesnt work. Am I missing something ? Do I need to add anything else. I have also tried the following :

<IncludeAssemblies>
    dllname
</IncludeAssemblies>

Thank you for the help in advance.

Body:
I wanted to add an element to this that is important for unmanaged dll's when they aren't formally part of the solution/project.

@Adds is right to use:

<Costura
Unmanaged32Assemblies='dllname'
Unmanaged64Assemblies='dllname' />

and @kdiddymcnasty is right to be careful about double-inclusion (but note that the IncludeAssemblies attribute is different from the Unmanaged##Assemblies attribute).

However, there's an additional piece to this, which is shown at this page.  Essentially, you need to create a pair of folders in the project, called Costura32 and Costura64 and put the appropriate version of the dll in there, and set them to 'Embedded resource'. Then the weaver can include them in the exe when building the solution.

In my case, I was using the LibGit2Sharp dll, which relies on git2-15e1193.dll, so I have this as part of my solution:

and for each of those dll's, I have the Build Action set to Embedded Resource:

Finally, the FodyWeavers.xml is:

<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
  <costura IncludeDebugSymbls='false'>
    <Unmanaged32Assemblies>
      git2-15e1193
    </Unmanaged32Assemblies>
    <Unmanaged64Assemblies>
      git2-15e1193
    </Unmanaged64Assemblies>
  </costura>
</Weavers>

Make sure to leave the .dll off the dll names in the FodyWeavers.xml file.


问:
How to use AIR 2.0 NativeProcess API with Java?
How do you use this great new API in connection with Java? Do you use just pure native process API like nativeProcess.standardInput.write() and nativeProcess.standardOutput.read() with which you cannot debug Java side neither invoke remote java method. Or you are using some library that leverages remote method invocation such as flerry lib but that also cannot debug Java side? Or maybe you are using Merapi with which you can debug but cannot remotely invoke Java method? I'm asking this because this is maybe the most important question regarding this API and its ease of use.</p>

答: You could use Flerry to launch and communicate with java processes. </p>

ContentLicense: CC BY-SA 2.5


问:
Can you reuse a fragment in multiple activities but with different functionalities?
Say I have a fragment that has three buttons and I want to reuse it for at least three activities, but I want those buttons to do different things for each activity. For example, in ActivityA, I want button1 to open Google Maps while in ActivityB, button1 goes to the music player. Is this possible or even the right way?</p>

答:
Yes you can!</p>

```<code>if(getActivity() instanceOf ActivityA) {
    //do stuff related to ActivityA
} else if(getActivity() instanceOf ActivityB) {
    //do stuff related to ActivityB
}
</code>```

Body:
Yes you can!

if(getActivity() instanceOf ActivityA) {
    //do stuff related to ActivityA
} else if(getActivity() instanceOf ActivityB) {
    //do stuff related to ActivityB
}


问:
Unable to get PHP syntax right
I am unsure how to get the correct syntax to add in some php to this :

```<code>    $day = $workDays[$weekIndex][($col - 1) % 7] == TRUE ? '<SPAN class="' . $class . '"onclick="Materialize.toast(\'<?= "Hello World"\')" >' . $dkey  .'</SPAN>' : $dkey; // Defines SPAN to style related days, otherwise defaults
</code>```

The hello world echo is the part that I cant get right.

答:
If you're already processing the string with PHP, you do not need to include PHP tags to echo out Hello World. Instead, this value can be included inline with the other text.

```<code>$day = $workDays[$weekIndex][($col - 1) % 7] == TRUE
    ? '<SPAN class="' . $class . '" onclick="Materialize.toast(\'Hello World\')">' . $dkey  .'</SPAN>'
    : $dkey;
</code>```

Title: Unable to get PHP syntax right

Body:
I am unsure how to get the correct syntax to add in some php to this :

    $day = $workDays[$weekIndex][($col - 1) % 7] == TRUE ? '<SPAN class="' . $class . '"onclick="Materialize.toast(\'<?= "Hello World"\')" >' . $dkey  .'' : $dkey; // Defines SPAN to style related days, otherwise defaults

The hello world echo is the part that I cant get right.

Body:
If you're already processing the string with PHP, you do not need to include PHP tags to echo out Hello World. Instead, this value can be included inline with the other text.

$day = $workDays[$weekIndex][($col - 1) % 7] == TRUE
    ? '<SPAN class="' . $class . '" onclick="Materialize.toast(\'Hello World\')">' . $dkey  .'</SPAN>'
    : $dkey;


答:
Your activities have different logic, you can define the button logic in each of them and share the views in this way. You can use a fragment to accomplish this however you can be more direct by sharing a partial layout.

Create a partial layout called three_buttons.xml

three_buttons.xml

```<code><LinearLayout>
<BUtton android:text="button 1"/>
<BUtton android:text="button 2"/>
<BUtton android:text="button 3"/>
</LinearLayout>
</code>```

activity_a.xml

```<code><LinearLayout>
<TextView android:text="I am A"/>
<include
            android:id="@+id/three_buttons"
            layout="@layout/three_buttons"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
</LinearLayout>
</code>```

activity_b.xml

```<code><LinearLayout>
<TextView android:text="I am B"/>
<include
            android:id="@+id/three_buttons"
            layout="@layout/three_buttons"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
</LinearLayout>
</code>```

Title: Can you reuse a fragment in multiple activities but with different functionalities?

Body: Say I have a fragment that has three buttons and I want to reuse it for at least three activities, but I want those buttons to do different things for each activity. For example, in ActivityA, I want button1 to open Google Maps while in ActivityB, button1 goes to the music player. Is this possible or even the right way?

Body:
Your activities have different logic, you can define the button logic in each of them and share the views in this way. You can use a fragment to accomplish this however you can be more direct by sharing a partial layout.

Create a partial layout called three_buttons.xml

three_buttons.xml

<LinearLayout>
<BUtton android:text="button 1"/>
<BUtton android:text="button 2"/>
<BUtton android:text="button 3"/>
</LinearLayout>

activity_a.xml

<LinearLayout>
<TextView android:text="I am A"/>
<include
            android:id="@+id/three_buttons"
            layout="@layout/three_buttons"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
</LinearLayout>

activity_b.xml

<LinearLayout>
<TextView android:text="I am B"/>
<include
            android:id="@+id/three_buttons"
            layout="@layout/three_buttons"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
</LinearLayout>


问:
Contour of KNN model in ggplot?
I have a KNN model which I am plotting using the contour function.  This is a simple example of the kind of thing that I'm doing (based on this Purdue exam):

```<code>library(class)
library(nnet)

TrainC<-read.table("http://miner.chem.purdue.edu/Exam1/TrainC.dat")
names(TrainC)<-c("x1","x2","y")

K=15

p <- as.matrix(TrainC[, -3])
xp <- seq(min(TrainC$x1), max(TrainC$x1), length = 50); np <- length(xp)
yp <- seq(min(TrainC$x2), max(TrainC$x2), length = 50)
tp<-TrainC$y

yhat <- knn(p, p, tp, k = K)

plot(TrainC[, 1], TrainC[, 2], xlab = "x1", ylab = "x2", col=as.numeric(TrainC$y)+1)
pt <- expand.grid(x1 = xp, x2 = yp)
Z <- knn(p, pt, tp, k = K)
zp<-class.ind(Z)[,1] - class.ind(Z)[,2]

contour(xp, yp, matrix(zp, np), add = T, levels = 0, labex = 0)
</code>```

My question is: how can I make this same plot in ggplot?  In particular, how I can I do the equivalent of contour?

答:
After your code try this:

```<code>library(ggplot2)

p <- ggplot(TrainC, aes(x1, x2))
p + geom_point(aes(colour = as.numeric(y) + 1))

df <- data.frame(x = rep(xp, np), y = rep(yp, each = np), z = zp)
p <- ggplot(df, aes(x, y, z = z))
p + stat_contour(bins = 1)
</code>```

That's two separate plots. Not sure how to combine them but digging in the documentation here should get you started.

Title: Contour of KNN model in ggplot?

Body:
I have a KNN model which I am plotting using the contour function.  This is a simple example of the kind of thing that I'm doing (based on this Purdue exam):

library(class)
library(nnet)

TrainC<-read.table("http://miner.chem.purdue.edu/Exam1/TrainC.dat")
names(TrainC)<-c("x1","x2","y")

K=15

p <- as.matrix(TrainC[, -3])
xp <- seq(min(TrainC$x1), max(TrainC$x1), length = 50); np <- length(xp)
yp <- seq(min(TrainC$x2), max(TrainC$x2), length = 50)
tp<-TrainC$y

yhat <- knn(p, p, tp, k = K)

plot(TrainC[, 1], TrainC[, 2], xlab = "x1", ylab = "x2", col=as.numeric(TrainC$y)+1)
pt <- expand.grid(x1 = xp, x2 = yp)
Z <- knn(p, pt, tp, k = K)
zp<-class.ind(Z)[,1] - class.ind(Z)[,2]

contour(xp, yp, matrix(zp, np), add = T, levels = 0, labex = 0)

My question is: how can I make this same plot in ggplot?  In particular, how I can I do the equivalent of contour?

Body:
After your code try this:

library(ggplot2)

p <- ggplot(TrainC, aes(x1, x2))
p + geom_point(aes(colour = as.numeric(y) + 1))

df <- data.frame(x = rep(xp, np), y = rep(yp, each = np), z = zp)
p <- ggplot(df, aes(x, y, z = z))
p + stat_contour(bins = 1)

That's two separate plots. Not sure how to combine them but digging in the documentation here should get you started.


问:
How to use spring boot making a common library
Now I want to develop a common mail service for our systems.
As we design, we want to develop a RabbitMQ producer and consumer. On consumer side, we could develop and deploy a Spring Boot or Spring Cloud application, but on producer side we want to give a common mail client like the interface below and make a jar dependency for other system.

```<code>interface MailClient {
  ListentableFuture send(Message message);
}
</code>```

But i see spring boot and spring cloud using many declarative method and seems must use a application class, but i just want a class reference and not need deploy. i do not know how to implement it.

答:
I had a similar need as yours, so far I managed to build a library usable on other projects with following configuration:

`

```<code><modelVersion>4.0.0</modelVersion>
<groupId>mx.grailscoder</groupId>
<artifactId>library</artifactId>
<version>1.0-SNAPSHOT</version>
<name>My Custom Library built on Spring Boot</name>
<description>Spring Boot Project library</description>
<packaging>jar</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <logentries-appender>RELEASE</logentries-appender>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

`

It's important to mention I skipped the repackage task since my library didn't have any main class, then issuing the mvn install task does not fail.

Body:
Now I want to develop a common mail service for our systems.
As we design, we want to develop a RabbitMQ producer and consumer. On consumer side, we could develop and deploy a Spring Boot or Spring Cloud application, but on producer side we want to give a common mail client like the interface below and make a jar dependency for other system.

interface MailClient {
  ListentableFuture send(Message message);
}

But i see spring boot and spring cloud using many declarative method and seems must use a application class, but i just want a class reference and not need deploy. i do not know how to implement it.

Body:
I had a similar need as yours, so far I managed to build a library usable on other projects with following configuration:

`

<modelVersion>4.0.0</modelVersion>
<groupId>mx.grailscoder</groupId>
<artifactId>library</artifactId>
<version>1.0-SNAPSHOT</version>
<name>My Custom Library built on Spring Boot</name>
<description>Spring Boot Project library</description>
<packaging>jar</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <logentries-appender>RELEASE</logentries-appender>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

`

It's important to mention I skipped the repackage task since my library didn't have any main class, then issuing the mvn install task does not fail.


问:
How to handle click event in Button Column in Datagridview?
I am developing a windows application using C#. I am using DataGridView to display data. I have added a button column in that. I want to know how can I handle click event on that button in DataGridView.

答:
For example for ClickCell Event in Windows Forms.

```<code>private void GridViewName_CellClick(object sender, DataGridViewCellEventArgs e)
            {
               //Capture index Row Event
                    int  numberRow = Convert.ToInt32(e.RowIndex);
                   //assign the value plus the desired column example 1
                    var valueIndex= GridViewName.Rows[numberRow ].Cells[1].Value;
                    MessageBox.Show("ID: " +valueIndex);
                }
</code>```

Regards :)

ContentLicense: CC BY-SA 4.0

Body:
For example for ClickCell Event in Windows Forms.

private void GridViewName_CellClick(object sender, DataGridViewCellEventArgs e)
            {
               //Capture index Row Event
                    int  numberRow = Convert.ToInt32(e.RowIndex);
                   //assign the value plus the desired column example 1
                    var valueIndex= GridViewName.Rows[numberRow ].Cells[1].Value;
                    MessageBox.Show("ID: " +valueIndex);
                }

Regards :)


问:
Consuming OSX mouse/trackpad events with an event tap
I'm trying to add an event trap to enable/disable event from my magic trackpad.  I thought this would be straight forward, i.e. register an event trap and when required, discard the event by returning NULL.  The idea is to use the pad for some specific, time consuming data entry, the applications to enter the data into are third party ones so I can't just add code to do want I want there.  So i figured I'd monitor the system events and then send the desired input via a bunch of CGEventCreateKeyboardEvents.

The problem is returning null does not seem to discard the events, a bit more investigation suggests that this is not restricted to those coming from the trackpad but also my default usb mouse.

My code is below.  With what is below i'd expect not to be able to move the mouse, if I change (A) to use kCGEventScrollWheel or kCGEventLeftMouseDragged then event is consumed, i.e. scrolling or left btn drag don't occur.  Does this mean that not all events can be discarded?  Hopefully I'm just missing something obvious here

```<code>  #define case_print(a) case a: printf("%s - %d\n",#a,a); break;

  CGEventRef eventOccurred(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) {
    int subType =  CGEventGetIntegerValueField(event, kCGMouseEventSubtype);
    if (type == NSEventTypeGesture || subType == NX_SUBTYPE_MOUSE_TOUCH) {
        printf("touchpad\n");

        switch(type) {
                case_print(kCGEventNull)
                case_print(kCGEventLeftMouseDown)
                case_print(kCGEventLeftMouseUp)
                case_print(kCGEventRightMouseDown)
                case_print(kCGEventRightMouseUp)
                case_print(kCGEventMouseMoved)
                case_print(kCGEventLeftMouseDragged)
                case_print(kCGEventRightMouseDragged)
                case_print(kCGEventScrollWheel)
                case_print(kCGEventOtherMouseDown)
                case_print(kCGEventOtherMouseUp)
                case_print(kCGEventOtherMouseDragged)
                case_print(kCGEventTapDisabledByTimeout)
                case_print(kCGEventTapDisabledByUserInput)
                case_print(NSEventTypeGesture)
                case_print(NSEventTypeMagnify)
                case_print(NSEventTypeSwipe)
                case_print(NSEventTypeRotate)
                case_print(NSEventTypeBeginGesture)
                case_print(NSEventTypeEndGesture)
            default:
                printf("default: %d\n",type);
                break;
        }

        event = NULL;
    }  else {
        if (type == kCGEventMouseMoved) {  // (A)
            printf("discarding mouse event");
            event = NULL;
        }
    }

    return event;
}

CFMachPortRef createEventTap() {
    CGEventMask eventMask = NSAnyEventMask;

    if (!AXAPIEnabled() && !AXIsProcessTrusted()) {
        printf("axapi not enabled");
    }

    return CGEventTapCreate(kCGHIDEventTap,
                            kCGHeadInsertEventTap,
                            kCGEventTapOptionDefault,
                            eventMask,
                            eventOccurred,
                            NULL);
}

int main (int argc, const char * argv[]) {
    CFMachPortRef tap = createEventTap();

    if (tap) {
        CFRunLoopSourceRef rl = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0);
        CFRunLoopAddSource(CFRunLoopGetMain(), rl, kCFRunLoopCommonModes);
        CGEventTapEnable(tap, true);
        CFRunLoopRun();

        printf("Tap created.\n");
        sleep(-1);
    } else {
        printf("failed!\n");
    }

    return 0;
}
</code>```

Note, "axapi not enabled" is not output although i don't think the accessibility option affects anything but the keyboard events.

BTW, I've seen a few similar posts on how to get the events from the touch pad, just nothing applicable to discarding them (other than returning null should work).

答:
If your tap is passive, returning NULL will leave the event stream unaffected. From the CGEventTapCallBack reference documentation:

"If the event tap is an passive
  listener, your callback function may
  return the event that is passed in, or
  NULL. In either case, the event stream
  is not affected."

However, it looks like your tap is active. Thus your returning NULL should delete the event. Have you considered modifying the event to nullify the action?

Also note that the call CGEventTapCreate requires root user permissions to intercept all events. Is your process running as root?

Body:
I'm trying to add an event trap to enable/disable event from my magic trackpad.  I thought this would be straight forward, i.e. register an event trap and when required, discard the event by returning NULL.  The idea is to use the pad for some specific, time consuming data entry, the applications to enter the data into are third party ones so I can't just add code to do want I want there.  So i figured I'd monitor the system events and then send the desired input via a bunch of CGEventCreateKeyboardEvents.

The problem is returning null does not seem to discard the events, a bit more investigation suggests that this is not restricted to those coming from the trackpad but also my default usb mouse.

My code is below.  With what is below i'd expect not to be able to move the mouse, if I change (A) to use kCGEventScrollWheel or kCGEventLeftMouseDragged then event is consumed, i.e. scrolling or left btn drag don't occur.  Does this mean that not all events can be discarded?  Hopefully I'm just missing something obvious here

  #define case_print(a) case a: printf("%s - %d\n",#a,a); break;

  CGEventRef eventOccurred(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) {
    int subType =  CGEventGetIntegerValueField(event, kCGMouseEventSubtype);
    if (type == NSEventTypeGesture || subType == NX_SUBTYPE_MOUSE_TOUCH) {
        printf("touchpad\n");

        switch(type) {
                case_print(kCGEventNull)
                case_print(kCGEventLeftMouseDown)
                case_print(kCGEventLeftMouseUp)
                case_print(kCGEventRightMouseDown)
                case_print(kCGEventRightMouseUp)
                case_print(kCGEventMouseMoved)
                case_print(kCGEventLeftMouseDragged)
                case_print(kCGEventRightMouseDragged)
                case_print(kCGEventScrollWheel)
                case_print(kCGEventOtherMouseDown)
                case_print(kCGEventOtherMouseUp)
                case_print(kCGEventOtherMouseDragged)
                case_print(kCGEventTapDisabledByTimeout)
                case_print(kCGEventTapDisabledByUserInput)
                case_print(NSEventTypeGesture)
                case_print(NSEventTypeMagnify)
                case_print(NSEventTypeSwipe)
                case_print(NSEventTypeRotate)
                case_print(NSEventTypeBeginGesture)
                case_print(NSEventTypeEndGesture)
            default:
                printf("default: %d\n",type);
                break;
        }

        event = NULL;
    }  else {
        if (type == kCGEventMouseMoved) {  // (A)
            printf("discarding mouse event");
            event = NULL;
        }
    }

    return event;
}

CFMachPortRef createEventTap() {
    CGEventMask eventMask = NSAnyEventMask;

    if (!AXAPIEnabled() && !AXIsProcessTrusted()) {
        printf("axapi not enabled");
    }

    return CGEventTapCreate(kCGHIDEventTap,
                            kCGHeadInsertEventTap,
                            kCGEventTapOptionDefault,
                            eventMask,
                            eventOccurred,
                            NULL);
}

int main (int argc, const char * argv[]) {
    CFMachPortRef tap = createEventTap();

    if (tap) {
        CFRunLoopSourceRef rl = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0);
        CFRunLoopAddSource(CFRunLoopGetMain(), rl, kCFRunLoopCommonModes);
        CGEventTapEnable(tap, true);
        CFRunLoopRun();

        printf("Tap created.\n");
        sleep(-1);
    } else {
        printf("failed!\n");
    }

    return 0;
}

Note, "axapi not enabled" is not output although i don't think the accessibility option affects anything but the keyboard events.

BTW, I've seen a few similar posts on how to get the events from the touch pad, just nothing applicable to discarding them (other than returning null should work).


问:
How do I sort a Laravel Collection by multiple properties with both asc and desc?
If I have an Illuminate\Support\Collection, how do I sort by multiple properties with both asc and desc?  (This is a simple hypothetical - not at all looking for tips on query building.)</p>

```<code>$collection = User::all(); // not looking for User::orderBy()->get() solutions.  Read the question.
$sorting_insructions = [
    ['column'=>'first_name', 'order'=>'asc'],
    ['column'=>'date_of_birth', 'order'=>'desc'],
];
$collection->sort(function($a,$b) use ($sorting_instructions){
    // something...
});
</code>```

答:
Whoever uses this, just keep in mind - you'll need to tweak it depending if your using collection of objects or associative arrays.  Should be an easy tweak.  Just change the $a[]/$b[] stuff to $a-> and $b-></p>

```<code>    public static function multiPropertySort(Collection $collection, array $sorting_instructions){

        return $collection->sort(function ($a, $b) use ($sorting_instructions){

            //stuff starts here to answer question...

            foreach($sorting_instructions as $sorting_instruction){

                $a[$sorting_instruction['column']] = (isset($a[$sorting_instruction['column']])) ? $a[$sorting_instruction['column']] : '';
                $b[$sorting_instruction['column']] = (isset($b[$sorting_instruction['column']])) ? $b[$sorting_instruction['column']] : '';

                if(empty($sorting_instruction['order']) or strtolower($sorting_instruction['order']) == 'asc'){
                    $x = ($a[$sorting_instruction['column']] <=> $b[$sorting_instruction['column']]);
                }else{
                    $x = ($b[$sorting_instruction['column']] <=> $a[$sorting_instruction['column']]);

                }

                if($x != 0){
                    return $x;
                }

            }

            return 0;

        })->values();
    }
</code>```

Body:
If I have an Illuminate\Support\Collection, how do I sort by multiple properties with both asc and desc?  (This is a simple hypothetical - not at all looking for tips on query building.)

$collection = User::all(); // not looking for User::orderBy()->get() solutions.  Read the question.
$sorting_insructions = [
    ['column'=>'first_name', 'order'=>'asc'],
    ['column'=>'date_of_birth', 'order'=>'desc'],
];
$collection->sort(function($a,$b) use ($sorting_instructions){
    // something...
});

Body:
Whoever uses this, just keep in mind - you'll need to tweak it depending if your using collection of objects or associative arrays.  Should be an easy tweak.  Just change the $a[]/$b[] stuff to $a-> and $b->

    public static function multiPropertySort(Collection $collection, array $sorting_instructions){

        return $collection->sort(function ($a, $b) use ($sorting_instructions){

            //stuff starts here to answer question...

            foreach($sorting_instructions as $sorting_instruction){

                $a[$sorting_instruction['column']] = (isset($a[$sorting_instruction['column']])) ? $a[$sorting_instruction['column']] : '';
                $b[$sorting_instruction['column']] = (isset($b[$sorting_instruction['column']])) ? $b[$sorting_instruction['column']] : '';

                if(empty($sorting_instruction['order']) or strtolower($sorting_instruction['order']) == 'asc'){
                    $x = ($a[$sorting_instruction['column']] <=> $b[$sorting_instruction['column']]);
                }else{
                    $x = ($b[$sorting_instruction['column']] <=> $a[$sorting_instruction['column']]);

                }

                if($x != 0){
                    return $x;
                }

            }

            return 0;

        })->values();
    }


问:
Why is XPath returning nodes from my entire document, and not just the select node
Given:

```<code>public class XPathTest {

    public static void main(String args[]) throws Exception {
        String xmlString
                = "<a>"
                + "<b c=\"1\"/>"
                + "<b c=\"2\"/>"
                + "</a>";

        ByteArrayInputStream bis = new ByteArrayInputStream(xmlString.getBytes());
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(bis));

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile("//b");

        NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        dumpNodeList(nl);
        for (int i = 0; i < nl.getLength(); i++) {
            Node n = nl.item(i);
            NodeList nl2 = (NodeList) expr.evaluate(n, XPathConstants.NODESET);
            dumpNodeList(nl2);
        }

    }

    public static void dumpNodeList(NodeList nl) {
        System.out.println("NodeList length = " + nl.getLength());
        for (int i = 0; i < nl.getLength(); i++) {
            System.out.println("Node #" + i);
            Element e = (Element) nl.item(i);
            System.out.println("Name = " + e.getTagName());
            System.out.println("Attr = " + e.getAttribute("c"));
        }
        System.out.println();
    }
}
</code>```

Sample result:

```<code>NodeList length = 2
Node #0
Name = b
Attr = 1
Node #1
Name = b
Attr = 2

NodeList length = 2
Node #0
Name = b
Attr = 1
Node #1
Name = b
Attr = 2

NodeList length = 2
Node #0
Name = b
Attr = 1
Node #1
Name = b
Attr = 2
</code>```

I evaluate the XPath expression //b, passing in the root document node to the evaluator. It, expectedly, returns the two b nodes.

What I'm confused about is when I evaluate the same expression, but instead of passing in the root node as he parameter I pass in one of the children nodes I located earlier. According to XPathExpression.evaluate(Object item), it says Evaluate the compiled XPath expression in the specified context and return the result as the specified type.

The expression, //b, means "give me all of the b nodes".

Intuitively, I would think that if I pass in a Node to XPathExpression.evalute(Object item), that the expression would be evaluated starting with that node as its root for the "give me all" part, rather than the entire document. So I would expect a resulting NodeList of one node, not two.

But instead, I get the same two nodes as if from the entire document.

So, the two questions are:

Why is the expression being evaluated relative to the entire document, and not to just using the pass Node as a synthetic root for the evaluation?

How can I get the expression to evaluate using the passed in Node as the synthetic root for the evaluation?

答: It works as it should.. Instead of //b, please try with ./b. Maybe M$ help is not very helpful, but here they have some handy examples.

Body:
Given:

public class XPathTest {

    public static void main(String args[]) throws Exception {
        String xmlString
                = ""
                + ""
                + ""
                + "";

        ByteArrayInputStream bis = new ByteArrayInputStream(xmlString.getBytes());
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(bis));

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile("//b");

        NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        dumpNodeList(nl);
        for (int i = 0; i < nl.getLength(); i++) {
            Node n = nl.item(i);
            NodeList nl2 = (NodeList) expr.evaluate(n, XPathConstants.NODESET);
            dumpNodeList(nl2);
        }

    }

    public static void dumpNodeList(NodeList nl) {
        System.out.println("NodeList length = " + nl.getLength());
        for (int i = 0; i < nl.getLength(); i++) {
            System.out.println("Node #" + i);
            Element e = (Element) nl.item(i);
            System.out.println("Name = " + e.getTagName());
            System.out.println("Attr = " + e.getAttribute("c"));
        }
        System.out.println();
    }
}

Sample result:

NodeList length = 2
Node #0
Name = b
Attr = 1
Node #1
Name = b
Attr = 2

NodeList length = 2
Node #0
Name = b
Attr = 1
Node #1
Name = b
Attr = 2

NodeList length = 2
Node #0
Name = b
Attr = 1
Node #1
Name = b
Attr = 2

I evaluate the XPath expression //b, passing in the root document node to the evaluator. It, expectedly, returns the two b nodes.

What I'm confused about is when I evaluate the same expression, but instead of passing in the root node as he parameter I pass in one of the children nodes I located earlier. According to XPathExpression.evaluate(Object item), it says Evaluate the compiled XPath expression in the specified context and return the result as the specified type.

The expression, //b, means "give me all of the b nodes".

Intuitively, I would think that if I pass in a Node to XPathExpression.evalute(Object item), that the expression would be evaluated starting with that node as its root for the "give me all" part, rather than the entire document. So I would expect a resulting NodeList of one node, not two.

But instead, I get the same two nodes as if from the entire document.

So, the two questions are:

Why is the expression being evaluated relative to the entire document, and not to just using the pass Node as a synthetic root for the evaluation?

How can I get the expression to evaluate using the passed in Node as the synthetic root for the evaluation?


问:
devise change password not working (unknown attribute: current_password)
I'm not quite sure what I'm doing wrong but when a user tries to change their password on my app, it gives an error that current_password is an unknown attribute.

Here's my code:

```<code>def configure_devise_permitted_parameters
  registration_params = [:email, :password, :password_confirmation, :first_name, :last_name]

  if params[:action] == 'update'
    devise_parameter_sanitizer.for(:user_update) {
      |u| u.permit(registration_params << :current_password)
    }
  elsif params[:action] == 'create'
    devise_parameter_sanitizer.for(:sign_up) {
      |u| u.permit(registration_params)
    }
  end
end

class RegistrationsController < Devise::RegistrationsController
  def update
    account_update_params = devise_parameter_sanitizer.sanitize(:user_update)

    if account_update_params[:password].blank?
      account_update_params.delete("password")
      account_update_params.delete("password_confirmation")
      account_update_params.delete("current_password")
    end

    @user = User.find(current_user.id)
    if @user.update_attributes(account_update_params)
      set_flash_message :notice, :updated
      sign_in @user, bypass: true
      redirect_to after_update_path_for(@user)
    else
      render "edit"
    end
  end
</code>```

what am i doing wrong here?  what should I be doing with current_password to check it is correct before saving their new password correctly?

EDIT:stack trace

```<code>activerecord (4.0.3) lib/active_record/attribute_assignment.rb:47:in `rescue in _assign_attribute'
activerecord (4.0.3) lib/active_record/attribute_assignment.rb:42:in `_assign_attribute'
activerecord (4.0.3) lib/active_record/attribute_assignment.rb:29:in `block in assign_attributes'
activerecord (4.0.3) lib/active_record/attribute_assignment.rb:23:in `each'
activerecord (4.0.3) lib/active_record/attribute_assignment.rb:23:in `assign_attributes'
</code>```

答:
As of Devise 4,

When getting the unknown attribute for 'current_password',
no need to play with the devise_parameter_sanitizer

Go into app/controllers/registrations_controller.rb

Change

```<code>def update_resource(resource, params)
    resource.update_without_password(params)
end
</code>```

By

```<code>def update_resource(resource, params)
    resource.update_with_password(params)
end
</code>```

Body:
I'm not quite sure what I'm doing wrong but when a user tries to change their password on my app, it gives an error that current_password is an unknown attribute.

Here's my code:

def configure_devise_permitted_parameters
  registration_params = [:email, :password, :password_confirmation, :first_name, :last_name]

  if params[:action] == 'update'
    devise_parameter_sanitizer.for(:user_update) {
      |u| u.permit(registration_params << :current_password)
    }
  elsif params[:action] == 'create'
    devise_parameter_sanitizer.for(:sign_up) {
      |u| u.permit(registration_params)
    }
  end
end

class RegistrationsController < Devise::RegistrationsController
  def update
    account_update_params = devise_parameter_sanitizer.sanitize(:user_update)

    if account_update_params[:password].blank?
      account_update_params.delete("password")
      account_update_params.delete("password_confirmation")
      account_update_params.delete("current_password")
    end

    @user = User.find(current_user.id)
    if @user.update_attributes(account_update_params)
      set_flash_message :notice, :updated
      sign_in @user, bypass: true
      redirect_to after_update_path_for(@user)
    else
      render "edit"
    end
  end

what am i doing wrong here?  what should I be doing with current_password to check it is correct before saving their new password correctly?

EDIT:stack trace

activerecord (4.0.3) lib/active_record/attribute_assignment.rb:47:in `rescue in _assign_attribute'
activerecord (4.0.3) lib/active_record/attribute_assignment.rb:42:in `_assign_attribute'
activerecord (4.0.3) lib/active_record/attribute_assignment.rb:29:in `block in assign_attributes'
activerecord (4.0.3) lib/active_record/attribute_assignment.rb:23:in `each'
activerecord (4.0.3) lib/active_record/attribute_assignment.rb:23:in `assign_attributes'

Body:
As of Devise 4,

When getting the unknown attribute for 'current_password',
no need to play with the devise_parameter_sanitizer

Go into app/controllers/registrations_controller.rb

Change

def update_resource(resource, params)
    resource.update_without_password(params)
end

By

def update_resource(resource, params)
    resource.update_with_password(params)
end


问:
Dynamic radio VBA
On this internal website it allow me enter a  data and depending on the data the radio box will be enable. How do I know when the radio box is enabled.

Enabled

```<code>input id="Answer1" name="Answer" type="radio" value="C"
</code>```

Disabled

```<code>input id="Answer1" name="Answer" disabled="disabled" type="radio" value="C"
</code>```

When it is disabled the getAttribute will return "disabled" but when it is enabled it will return run time error

Invalid use of Null (Error 94)

if I used

```<code>msgbox ie.document.all("Answer1").getAttribute("disabled")
</code>```

I tried the following if statement and none will caught it when it is enabled

```<code>ie.document.all("Answer1").getAttribute("disabled")  = ""
ie.document.all("Answer1").getAttribute("disabled")  = Null
ie.document.all("Answer1").getAttribute("disabled")  <> "disabled"
ie.document.all("Answer1").getAttribute("disabled")  = "disabled"
</code>```

答:
I also find this worked too in if statement

if isnull(ie.document.all("Answer1").disabled) then
 msgbox "Radio box disabled"
else
msgbox "Radio box enabled"
end if

Title: Dynamic radio VBA

Body:
On this internal website it allow me enter a  data and depending on the data the radio box will be enable. How do I know when the radio box is enabled.

Enabled

input id="Answer1" name="Answer" type="radio" value="C"

Disabled

input id="Answer1" name="Answer" disabled="disabled" type="radio" value="C"

When it is disabled the getAttribute will return "disabled" but when it is enabled it will return run time error

Invalid use of Null (Error 94)

if I used

msgbox ie.document.all("Answer1").getAttribute("disabled")

I tried the following if statement and none will caught it when it is enabled

ie.document.all("Answer1").getAttribute("disabled")  = ""
ie.document.all("Answer1").getAttribute("disabled")  = Null
ie.document.all("Answer1").getAttribute("disabled")  <> "disabled"
ie.document.all("Answer1").getAttribute("disabled")  = "disabled"


问:
Count New Lines in Text File
I would like to count the number of shift+enters in a text file using PHP.

Please help me with this.

Thanks

答: You can perform this task by key-events.  I think php don't have any key event, so you can use any scripting language like java-script that have key events.</p>

Title: Count New Lines in Text File


问:
Send several parameters when combo box activated
```<code>self.comboBox.activated[str].connect(self.on_combo_activated)
</code>```

At the moment when a combo box gets selected only the value of the combo box gets passed on to the function on_combo_activated.

How would I do if I wanted to send another two variables?

答:
One way to solve this is by using a lambda function:

```<code>self.comboBox.activated[str].connect(
    lambda text: self.on_combo_activated(text, 'str1', 'str2'))
...

def on_combo_activated(self, text, arg1, arg2):
    print(text, arg1, arg2)
</code>```

The functools.partial function does something similar, but it can sometimes be awkward to use it with positional arguments. If you used it to connect the above slot like this:

```<code>self.comboBox.activated[str].connect(
    partial(self.on_combo_activated, 'str1', 'str1')
</code>```

the slot would actually print str1 str2 text, because extra positional arguments are always appended, rather than inserted. However, with keyword arguments, it would work as expected:

```<code>self.comboBox.activated[str].connect(
    partial(self.on_combo_activated, arg1='str1', arg2='str1'))
</code>```

This last approach might be preferred over the others as it is self-documenting, and therefore perhaps more readable.

Body:
self.comboBox.activated[str].connect(self.on_combo_activated)

At the moment when a combo box gets selected only the value of the combo box gets passed on to the function on_combo_activated.

How would I do if I wanted to send another two variables?

Body:
One way to solve this is by using a lambda function:

self.comboBox.activated[str].connect(
    lambda text: self.on_combo_activated(text, 'str1', 'str2'))
...

def on_combo_activated(self, text, arg1, arg2):
    print(text, arg1, arg2)

The functools.partial function does something similar, but it can sometimes be awkward to use it with positional arguments. If you used it to connect the above slot like this:

self.comboBox.activated[str].connect(
    partial(self.on_combo_activated, 'str1', 'str1')

the slot would actually print str1 str2 text, because extra positional arguments are always appended, rather than inserted. However, with keyword arguments, it would work as expected:

self.comboBox.activated[str].connect(
    partial(self.on_combo_activated, arg1='str1', arg2='str1'))

This last approach might be preferred over the others as it is self-documenting, and therefore perhaps more readable.


问:
Get Param from .htaccess in angularjs + ui-router
My app is a multi-language (angular-translate) angularjs app with ui-router. And I am having a problem getting the parameter from the .htaccess redirect.

What I want is the following routing.

www.example.com/en = The English version.

www.example.com/he = The Hebrew version.

www.example.com/ar = The Arabic version.

Anything else redirected to the English version.

On the Client Side

my app.config looks like this:

Language State

```<code>$stateProvider.state('app', {
    abstract: true,
    url: '/:lang',
    template: '<sh-app/>',
    controller: function ($translate, $state, $rootScope) {
        $translate.use($state.params.lang);

        if (/he|ar/.test($state.params.lang)) {
            $rootScope.dir = 'rtl';
        }
    }
});
</code>```

Home State

```<code>$stateProvider.state('app.home', {
    url: '/',
    template: '<sh-main/>'
});
</code>```

And of course to remove the hashbang

```<code>$locationProvider.html5Mode(true);
</code>```

Now to the Server Side.

I added an .htaccess file, with the following:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /7for70/index.html [L]
</IfModule>
</code>```

The problem is that if I try and navigate to www.example.com/ar it just redirects to www.example.com/en/ and $stateParams.lang === 'en'.

How can I get the end of the url forwarded to ui-router.

答:
For anyone who ends up with the same problem, after two days of tearing my hears, I got an idea.

I appended a trailing slash to my url's like this:

www.example.com/en => www.example.com/en/

www.example.com/he => www.example.com/he/

www.example.com/ar => www.example.com/ar/

and viola, it worked!

From there it was very easy to find the solution in the ui-router docs to deal with the trailing slash.

For older version of ui-router, add this snippet to your module's config function. It creates a rule on $urlRouterProvider that maps all urls that are missing a trailing slash to the same url but with the trailing slash appended.

```<code>$urlRouterProvider.rule(function ($injector, $location) {
    var path = $location.url();

    // check to see if the path already has a slash where it should be
    if (path[path.length - 1] === '/' || path.indexOf('/?') > -1) {
        return;
    }

    if (path.indexOf('?') > -1) {
        return path.replace('?', '/?');
    }

    return path + '/';
});
</code>```

EDIT: (After ~20 minutes)

Seems like you need to add a trailing slash to the abstract state, and remove it from the rest.

So the abstract state is: url: '/:lang/'

And then the home state will be url: ''

Body:
My app is a multi-language (angular-translate) angularjs app with ui-router. And I am having a problem getting the parameter from the .htaccess redirect.

What I want is the following routing.

www.example.com/en = The English version.

www.example.com/he = The Hebrew version.

www.example.com/ar = The Arabic version.

Anything else redirected to the English version.

On the Client Side

my app.config looks like this:

Language State

$stateProvider.state('app', {
    abstract: true,
    url: '/:lang',
    template: '<sh-app/>',
    controller: function ($translate, $state, $rootScope) {
        $translate.use($state.params.lang);

        if (/he|ar/.test($state.params.lang)) {
            $rootScope.dir = 'rtl';
        }
    }
});

Home State

$stateProvider.state('app.home', {
    url: '/',
    template: '<sh-main/>'
});

And of course to remove the hashbang

$locationProvider.html5Mode(true);

Now to the Server Side.

I added an .htaccess file, with the following:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /7for70/index.html [L]
</IfModule>

The problem is that if I try and navigate to www.example.com/ar it just redirects to www.example.com/en/ and $stateParams.lang === 'en'.

How can I get the end of the url forwarded to ui-router.

Body:
For anyone who ends up with the same problem, after two days of tearing my hears, I got an idea.

I appended a trailing slash to my url's like this:

www.example.com/en => www.example.com/en/

www.example.com/he => www.example.com/he/

www.example.com/ar => www.example.com/ar/

and viola, it worked!

From there it was very easy to find the solution in the ui-router docs to deal with the trailing slash.

For older version of ui-router, add this snippet to your module's config function. It creates a rule on $urlRouterProvider that maps all urls that are missing a trailing slash to the same url but with the trailing slash appended.

$urlRouterProvider.rule(function ($injector, $location) {
    var path = $location.url();

    // check to see if the path already has a slash where it should be
    if (path[path.length - 1] === '/' || path.indexOf('/?') > -1) {
        return;
    }

    if (path.indexOf('?') > -1) {
        return path.replace('?', '/?');
    }

    return path + '/';
});

EDIT: (After ~20 minutes)

Seems like you need to add a trailing slash to the abstract state, and remove it from the rest.

So the abstract state is: url: '/:lang/'

And then the home state will be url: ''


问:
Container Blobs with metadata
We have created a storage account for images and uploaded many images with the metadata property set. (as given below)

```<code> public async Task<bool> UploadFileToBlob(CustomFile file)
    {
        // Get Blob Container
        CloudBlobContainer container = BlobUtilities.GetBlobClient.GetContainerReference("documents");
        container.CreateIfNotExists();

        // Get reference to blob (binary content)
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(file.FileName);

        // set its properties
        blockBlob.Properties.ContentType = file.FileMime;
        blockBlob.Metadata["tag"] = "computer";
        :
        :
}
</code>```

There could be multiple images could have uploaded with the same tag name as a meta data property.

Now, I need to just get the list of images from the blob container which are mapped with the same tag name (I saw samples to download all the blobcontent but I want to specifically get the filtered list with the specific tag name which was set in the meta data of the uploaded file)

Thanks

答: It's not supported to filter metadata in a server query. You would need to list all the blobs with BlobListingDetails.Metadata, and filter the tag name on client side.</p>

Title: Container Blobs with metadata

Body:
We have created a storage account for images and uploaded many images with the metadata property set. (as given below)

 public async Task<bool> UploadFileToBlob(CustomFile file)
    {
        // Get Blob Container
        CloudBlobContainer container = BlobUtilities.GetBlobClient.GetContainerReference("documents");
        container.CreateIfNotExists();

        // Get reference to blob (binary content)
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(file.FileName);

        // set its properties
        blockBlob.Properties.ContentType = file.FileMime;
        blockBlob.Metadata["tag"] = "computer";
        :
        :
}

There could be multiple images could have uploaded with the same tag name as a meta data property.

Now, I need to just get the list of images from the blob container which are mapped with the same tag name (I saw samples to download all the blobcontent but I want to specifically get the filtered list with the specific tag name which was set in the meta data of the uploaded file)

Thanks


问:
How to get calendar date from only year and julian day (yday) in R
I have a data set that has column containing year, and a column containing the ordinal (yday) day for each year. I would like to convert this information into a calendar date, so I can better filter the data set. The data looks like this, but is from 1980-2016 and has an entry for each day of the year:

year  yday  temp

1980     1   0.5

1980     2  -5.0

1980     3  -3.5

1980     4   1.0

1980     5  -1.0

```<code>temps<-structure(list(year = c(1980L, 1980L, 1980L, 1980L, 1980L), yday = 1:5,
    temp = c(0.5, -5, -3.5, 1, -1)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"), .Names = c("year", "yday", "temp"))
</code>```

I tried the following code, but could not get the correct calendar date:
Convert day of year to date

Body:
I have a data set that has column containing year, and a column containing the ordinal (yday) day for each year. I would like to convert this information into a calendar date, so I can better filter the data set. The data looks like this, but is from 1980-2016 and has an entry for each day of the year:

year  yday  temp

1980     1   0.5

1980     2  -5.0

1980     3  -3.5

1980     4   1.0

1980     5  -1.0

temps<-structure(list(year = c(1980L, 1980L, 1980L, 1980L, 1980L), yday = 1:5,
    temp = c(0.5, -5, -3.5, 1, -1)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"), .Names = c("year", "yday", "temp"))

I tried the following code, but could not get the correct calendar date:
Convert day of year to date

Body:
library(lubridate)
library(dplyr)

temps <- tibble::tribble(
  ~year, ~yday, ~temp,
  1980L,    1L,    0.5,
  1980L,    2L,     -5,
  1980L,    3L,   -3.5,
  1980L,    4L,      1,
  1980L,    5L,     -1,
  1980L,    99L,    -1,
  1980L,    50L,    -1
)

temps %>%
  mutate(date = make_date(year) + yday - 1)

#> # A tibble: 7 x 4
#>    year  yday  temp       date
#>   <int> <int> <dbl>     <date>
#> 1  1980     1   0.5 1980-01-01
#> 2  1980     2  -5.0 1980-01-02
#> 3  1980     3  -3.5 1980-01-03
#> 4  1980     4   1.0 1980-01-04
#> 5  1980     5  -1.0 1980-01-05
#> 6  1980    99  -1.0 1980-04-08
#> 7  1980    50  -1.0 1980-02-19


问:
using mod_rewrite to create SEO friendly URLS
I've been searching google for this but can't find the solution to my exact needs. Basically I've already got my URL's named how I like them i.e. "http://mysite.com/blog/page1.php"

What I'm trying to achieve (if it's possible!) is to use rewrite to alter the existing URLS to: "http://mysite.com/blog/page1"

The problem I've come across is I've found examples that will do this if the user enters "http://mysite.com/blog/page1" into the broweser which is great, however I need it to work for the existing links in google as not to loose traffic, so incoming URLS "http://mysite.com/blog/page1.php" are directed to "http://mysite.com/blog/page1".

答:
You will need to write a rewrite rule for mapping your old url's to your new url as a permanent redirect. This will let the search engine know that the new, seo friendly url's are the ones to be used.</p>

```<code>RewriteRule blog/page1.php blog/page1 [R=301,L]
</code>```

Body:
You will need to write a rewrite rule for mapping your old url's to your new url as a permanent redirect. This will let the search engine know that the new, seo friendly url's are the ones to be used.

RewriteRule blog/page1.php blog/page1 [R=301,L]


问:
Is it possible to read the health check state out of Traefik?
Is it possible to read out or receive webhook events when the health state of a backend changes?

We would like to post the events to an emergency slack channel so that we can remediate the situation whenever a backend is unhealthy. We could set a different monitoring solution, such as Rancher's health checks or Grafana alerts. It seems it would be less trouble and more reliable to obtain our operations alert from our Traefik instance directly.

答:
That is not feasible right now to my knowledge.

The closest you can get to is to use a metrics system like Prometheus and set up a proper alert for too many failing health checks.


问:
wxpython scroll panel won't resize
i  am using wxpython and trying to make a frame panel with scroll bar that resizes, but when i resize the frame the scroll bar panel, won't resize, what i need to change? AdressGUI is a class that make wxpython frame. python verison 2.7 python verison 2.7</p>

```<code>def OpenShowAddressList(self,e):
self.ShowAdressFrame=AdressGUI(self,"Frame")
panel=self.ShowAdressFrame.panel

panel2 = wx.lib.scrolledpanel.ScrolledPanel(panel,-1, size=(AdressWidthSize-15,AdressHeightSize-10),pos=(0,0), style=wx.SIMPLE_BORDER)
panel2.SetupScrolling()

font = wx.Font(18, wx.DEFAULT, wx.ITALIC, wx.NORMAL)
font.SetPointSize(9)
vbox = wx.BoxSizer(wx.VERTICAL)
bmp = wx.Bitmap(PATHIMAGES+"xbutton.jpg", wx.BITMAP_TYPE_ANY)
hboxlis=[]

hbox1 = wx.BoxSizer(wx.HORIZONTAL)
iptext = wx.StaticText(panel2, label="כתובת")
usernametext = wx.StaticText(panel2, label="משתמש")
passwordtext=wx.StaticText(panel2, label="סיסמא")
bmaptxt=wx.StaticText(panel2,label="מחק")
iptext.SetFont(font)
usernametext.SetFont(font)
passwordtext.SetFont(font)
bmaptxt.SetFont(font)
hbox1.Add(iptext,proportion=3 ,flag=wx.RIGHT, border=0)
hbox1.Add(usernametext,proportion=2, flag=wx.RIGHT, border=0)
hbox1.Add(passwordtext, proportion=2,flag=wx.RIGHT, border=8)
hbox1.Add(bmaptxt, proportion=0)
hbox1.Add(wx.StaticText(panel2), proportion=4,flag=wx.RIGHT, border=8) # add just for empty space to fit the sizer
hboxlis.append(hbox1)
vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
for add in self.DevicesList:
    bmapBtn = wx.BitmapButton(panel2, id=wx.ID_ANY, bitmap=bmp,size=(bmp.GetWidth(), bmp.GetHeight()),name=add['IP'])
    hbox1 = wx.BoxSizer(wx.HORIZONTAL)
    iptext = wx.StaticText(panel2, label=add['IP'])
    usernametext = wx.StaticText(panel2, label=add['user'])
    passwordtext=wx.StaticText(panel2, label=add['pas'])
    iptext.SetFont(font)
    usernametext.SetFont(font)
    passwordtext.SetFont(font)
    hbox1.Add(iptext,proportion=3, flag=wx.RIGHT, border=8)
    hbox1.Add(usernametext,proportion=2, flag=wx.RIGHT, border=8)
    hbox1.Add(passwordtext,proportion=2, flag=wx.RIGHT, border=8)
    hbox1.Add(bmapBtn, proportion=0)
    hbox1.Add(wx.StaticText(panel2), proportion=4,flag=wx.RIGHT, border=2) # add just for empty space to fit the sizer
    hboxlis.append(hbox1)
    vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
    bmapBtn.Bind(wx.EVT_BUTTON, lambda event: self.DeleteIPFromList(event,hboxlis ,vbox,panel2) )

hbox5 = wx.BoxSizer(wx.HORIZONTAL)
hbox5.Add(wx.StaticText(panel2), proportion=2,flag=wx.EXPAND, border=8) # add just for empty space to fit the sizer
btn1 = wx.Button(panel2, label='ADD', size=(70, 30))
btn1.Bind(wx.EVT_BUTTON,self.CloseShowAddressAndOpenAddAdressList)
hbox5.Add(btn1, proportion=1)
btn2 = wx.Button(panel2, label='CLOSE', size=(70, 30))
btn2.Bind(wx.EVT_BUTTON,self.ShowAdressFrame.CloseWindow) #send show address frame as self
hbox5.Add(btn2,proportion=1)

vbox.Add(hbox5)
panel2.SetSizer(vbox)
panel2.Layout()
panel.Fit(panel2)
</code>```

答: The SetupScrolling method should be called after the child items have been added and after the scrolled panel's SetSizer has been called.

Title: wxpython scroll panel won't resize

Body:
i  am using wxpython and trying to make a frame panel with scroll bar that resizes, but when i resize the frame the scroll bar panel, won't resize, what i need to change? AdressGUI is a class that make wxpython frame. python verison 2.7 python verison 2.7

def OpenShowAddressList(self,e):
self.ShowAdressFrame=AdressGUI(self,"Frame")
panel=self.ShowAdressFrame.panel

panel2 = wx.lib.scrolledpanel.ScrolledPanel(panel,-1, size=(AdressWidthSize-15,AdressHeightSize-10),pos=(0,0), style=wx.SIMPLE_BORDER)
panel2.SetupScrolling()

font = wx.Font(18, wx.DEFAULT, wx.ITALIC, wx.NORMAL)
font.SetPointSize(9)
vbox = wx.BoxSizer(wx.VERTICAL)
bmp = wx.Bitmap(PATHIMAGES+"xbutton.jpg", wx.BITMAP_TYPE_ANY)
hboxlis=[]

hbox1 = wx.BoxSizer(wx.HORIZONTAL)
iptext = wx.StaticText(panel2, label="כתובת")
usernametext = wx.StaticText(panel2, label="משתמש")
passwordtext=wx.StaticText(panel2, label="סיסמא")
bmaptxt=wx.StaticText(panel2,label="מחק")
iptext.SetFont(font)
usernametext.SetFont(font)
passwordtext.SetFont(font)
bmaptxt.SetFont(font)
hbox1.Add(iptext,proportion=3 ,flag=wx.RIGHT, border=0)
hbox1.Add(usernametext,proportion=2, flag=wx.RIGHT, border=0)
hbox1.Add(passwordtext, proportion=2,flag=wx.RIGHT, border=8)
hbox1.Add(bmaptxt, proportion=0)
hbox1.Add(wx.StaticText(panel2), proportion=4,flag=wx.RIGHT, border=8) # add just for empty space to fit the sizer
hboxlis.append(hbox1)
vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
for add in self.DevicesList:
    bmapBtn = wx.BitmapButton(panel2, id=wx.ID_ANY, bitmap=bmp,size=(bmp.GetWidth(), bmp.GetHeight()),name=add['IP'])
    hbox1 = wx.BoxSizer(wx.HORIZONTAL)
    iptext = wx.StaticText(panel2, label=add['IP'])
    usernametext = wx.StaticText(panel2, label=add['user'])
    passwordtext=wx.StaticText(panel2, label=add['pas'])
    iptext.SetFont(font)
    usernametext.SetFont(font)
    passwordtext.SetFont(font)
    hbox1.Add(iptext,proportion=3, flag=wx.RIGHT, border=8)
    hbox1.Add(usernametext,proportion=2, flag=wx.RIGHT, border=8)
    hbox1.Add(passwordtext,proportion=2, flag=wx.RIGHT, border=8)
    hbox1.Add(bmapBtn, proportion=0)
    hbox1.Add(wx.StaticText(panel2), proportion=4,flag=wx.RIGHT, border=2) # add just for empty space to fit the sizer
    hboxlis.append(hbox1)
    vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
    bmapBtn.Bind(wx.EVT_BUTTON, lambda event: self.DeleteIPFromList(event,hboxlis ,vbox,panel2) )

hbox5 = wx.BoxSizer(wx.HORIZONTAL)
hbox5.Add(wx.StaticText(panel2), proportion=2,flag=wx.EXPAND, border=8) # add just for empty space to fit the sizer
btn1 = wx.Button(panel2, label='ADD', size=(70, 30))
btn1.Bind(wx.EVT_BUTTON,self.CloseShowAddressAndOpenAddAdressList)
hbox5.Add(btn1, proportion=1)
btn2 = wx.Button(panel2, label='CLOSE', size=(70, 30))
btn2.Bind(wx.EVT_BUTTON,self.ShowAdressFrame.CloseWindow) #send show address frame as self
hbox5.Add(btn2,proportion=1)

vbox.Add(hbox5)
panel2.SetSizer(vbox)
panel2.Layout()
panel.Fit(panel2)


问:
Using Gradle, how can I list just the JSON library of the Play framework as a dependency?
I need to parse some complex JSON with Scala and put it in a case class. After googling, it appears the JSON library of the Play framework is my best bet. However, I don't want to use the entire framework. I found this advice:

You don't have to install the full frameworks -- you can just list the json library as a dependency.

I'm using Gradle as a build tool but I really don't know how to do what he is suggesting.

答:
Add the following:</p>

```<code>// https://mvnrepository.com/artifact/com.typesafe.play/play-json
compile group: 'com.typesafe.play', name: 'play-json_2.11', version: '2.6.7'
</code>```

Body:
Add the following:

// https://mvnrepository.com/artifact/com.typesafe.play/play-json
compile group: 'com.typesafe.play', name: 'play-json_2.11', version: '2.6.7'


问:
Where to setAdapter in AsyncTask?
I'm trying to improve the performance of my mobile App. I'm attempting to use AsyncTask. I've looked at quite a lot of documentation on AsyncTask, also looked at numerous questions on here, but can't seem to get my code to run correctly.

I've seen examples where the Adapter is set in the onPostExecute method, but that does not work for me..

```<code> @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_travel_updates);

        Twitter.initialize(this);

        new getTweets().execute();
    }

private class getTweets extends AsyncTask<Void, Void, Void>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(travel_updates.this));
    }

    @Override
    protected Void doInBackground(Void... params) {
        final UserTimeline searchTimeline = new UserTimeline.Builder().screenName("TflTravelAlerts")
                .maxItemsPerRequest(5)
                .build();

        final TweetTimelineRecyclerViewAdapter tweetAdapter =
                new TweetTimelineRecyclerViewAdapter.Builder(travel_updates.this)
                        .setTimeline(searchTimeline)
                        .setViewStyle(R.style.tw__TweetLightWithActionsStyle)
                        .build();
        return null;
    }

    @Override
    protected void onPostExecute(Void Void) {

recyclerView.setAdapter(tweetAdapter);

    }
  }
}
</code>```

Thanks

答:
Define your RecycleView in your MainActivity not in the onPreExecute method of your AsyncTask.

With in your onCreate method you can set the RecyclerView.

```<code>private RecyclerView recyclerView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_travel_updates);

    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(travel_updates.this));

    Twitter.initialize(this);

    new getTweets().execute();
}
</code>```

Because you have UserTimeline and TweetTimelineRecyclerViewAdapter inside the doInBackground method (which is not on the same Thread as you UI) you cannot set the adapter in doInBackground. Set the adapter on the UI thread.

```<code>@Override
protected Void doInBackground(Void... params) {
    final UserTimeline searchTimeline = new UserTimeline.Builder().screenName("TflTravelAlerts")
            .maxItemsPerRequest(5)
            .build();

    final TweetTimelineRecyclerViewAdapter tweetAdapter =
            new TweetTimelineRecyclerViewAdapter.Builder(travel_updates.this)
                    .setTimeline(searchTimeline)
                    .setViewStyle(R.style.tw__TweetLightWithActionsStyle)
                    .build();

     runOnUiThread(new Runnable() {
        @Override
        public void run() {
            recyclerView.setAdapter(tweetAdapter);
    });

    // I don't think you need to return anything if your method uses void??
    return null;
}
</code>```

Then  onPostExecute should be empty.

Title: Where to setAdapter in AsyncTask?

Body:
I'm trying to improve the performance of my mobile App. I'm attempting to use AsyncTask. I've looked at quite a lot of documentation on AsyncTask, also looked at numerous questions on here, but can't seem to get my code to run correctly.

I've seen examples where the Adapter is set in the onPostExecute method, but that does not work for me..

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_travel_updates);

        Twitter.initialize(this);

        new getTweets().execute();
    }

private class getTweets extends AsyncTask<Void, Void, Void>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(travel_updates.this));
    }

    @Override
    protected Void doInBackground(Void... params) {
        final UserTimeline searchTimeline = new UserTimeline.Builder().screenName("TflTravelAlerts")
                .maxItemsPerRequest(5)
                .build();

        final TweetTimelineRecyclerViewAdapter tweetAdapter =
                new TweetTimelineRecyclerViewAdapter.Builder(travel_updates.this)
                        .setTimeline(searchTimeline)
                        .setViewStyle(R.style.tw__TweetLightWithActionsStyle)
                        .build();
        return null;
    }

    @Override
    protected void onPostExecute(Void Void) {

recyclerView.setAdapter(tweetAdapter);

    }
  }
}

Thanks

Body:
Define your RecycleView in your MainActivity not in the onPreExecute method of your AsyncTask.

With in your onCreate method you can set the RecyclerView.

private RecyclerView recyclerView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_travel_updates);

    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(travel_updates.this));

    Twitter.initialize(this);

    new getTweets().execute();
}

Because you have UserTimeline and TweetTimelineRecyclerViewAdapter inside the doInBackground method (which is not on the same Thread as you UI) you cannot set the adapter in doInBackground. Set the adapter on the UI thread.

@Override
protected Void doInBackground(Void... params) {
    final UserTimeline searchTimeline = new UserTimeline.Builder().screenName("TflTravelAlerts")
            .maxItemsPerRequest(5)
            .build();

    final TweetTimelineRecyclerViewAdapter tweetAdapter =
            new TweetTimelineRecyclerViewAdapter.Builder(travel_updates.this)
                    .setTimeline(searchTimeline)
                    .setViewStyle(R.style.tw__TweetLightWithActionsStyle)
                    .build();

     runOnUiThread(new Runnable() {
        @Override
        public void run() {
            recyclerView.setAdapter(tweetAdapter);
    });

    // I don't think you need to return anything if your method uses void??
    return null;
}

Then  onPostExecute should be empty.


问:
Pull data from multiple tables in Rails
I am new in Ruby on Rails and I am trying to make a book registration website. Everything works fine except category section. When a user assign a category to his book, my database copies book_categories.id and put it in book.book_categories_id. The website also have a profile page, where you can view user's book(s). My problem is to display a category.name, I searched a lot of similar problems but I have not found the right answer.

Here is my book controller:

```<code>before_action :set_book, except: [:index, :new, :create]
before_action :authenticate_user!, except: [:show]

def show
  @photos = @book.photos
end

def index
  @books = current_user.books
end

def new
  @book = current_user.books.build
end

def create
  @book = current_user.books.build(books_params)
  if @book.save
    redirect_to listing_book_path(@book), notice: "Saved."
  else
    flash[:alert] = "Failed."
    render :new
  end
end

private
  def set_book
    @book = Book.find(params[:id])
  end

  def book_params
    params.require(:book).permit(:book_categories_id, :book_name, :summary, :address, :price, :company_name)
  end
</code>```

As long as I understand, I have to allow my controller to have access to my category table but I do not know how. Also, all of my categories store in seed.rb.

This is my BookCategory.rb model:

```<code>class BookCategory < ActiveRecord::Base
  has_many :books, :foreign_key => :book_categories_id
end
</code>```

Book.rb model:

```<code>class Book < ApplicationRecord
  belongs_to :user, :foreign_key => 'user_id'
  has_many :photos, dependent: :delete_all

  validates :book_name, presence: true
  validates :book_categories_id, presence: true

  def cover_photo
    if self.photos.length > 0
      self.photos[0].image.url
    else
      "default/image-default.jpg"
    end
  end

end
</code>```

My schema.rb:

```<code>create_table "book_categories", force: :cascade do |t|
  t.string "name"
  t.string "subcategory"
  t.text "description"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

create_table "book", force: :cascade do |t|
  t.string "book_name"
  t.text "summary"
  t.string "address"
  t.decimal "price", precision: 8, scale: 2
  t.boolean "active"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.integer "user_id"
  t.float "latitude"
  t.float "longitude"
  t.string "company_name"
  t.integer "book_categories_id"
  t.index ["book_categories_id"], name: "index_books_on_book_categories_id"
end
</code>```

Usually, when I type @book_categories.name, I get an error:

```<code>undefined method `name' for nil:NilClass
</code>```

And at the very end, it says Parameters: {"id"=>"15"} whereas the category.id is different, and it passes book.id instead.

What I am doing wrong?

答: I think you need to setup as has_many through relationship. This is a good place to start http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Title: Pull data from multiple tables in Rails

Body:
I am new in Ruby on Rails and I am trying to make a book registration website. Everything works fine except category section. When a user assign a category to his book, my database copies book_categories.id and put it in book.book_categories_id. The website also have a profile page, where you can view user's book(s). My problem is to display a category.name, I searched a lot of similar problems but I have not found the right answer.

Here is my book controller:

before_action :set_book, except: [:index, :new, :create]
before_action :authenticate_user!, except: [:show]

def show
  @photos = @book.photos
end

def index
  @books = current_user.books
end

def new
  @book = current_user.books.build
end

def create
  @book = current_user.books.build(books_params)
  if @book.save
    redirect_to listing_book_path(@book), notice: "Saved."
  else
    flash[:alert] = "Failed."
    render :new
  end
end

private
  def set_book
    @book = Book.find(params[:id])
  end

  def book_params
    params.require(:book).permit(:book_categories_id, :book_name, :summary, :address, :price, :company_name)
  end

As long as I understand, I have to allow my controller to have access to my category table but I do not know how. Also, all of my categories store in seed.rb.

This is my BookCategory.rb model:

class BookCategory < ActiveRecord::Base
  has_many :books, :foreign_key => :book_categories_id
end

Book.rb model:

class Book < ApplicationRecord
  belongs_to :user, :foreign_key => 'user_id'
  has_many :photos, dependent: :delete_all

  validates :book_name, presence: true
  validates :book_categories_id, presence: true

  def cover_photo
    if self.photos.length > 0
      self.photos[0].image.url
    else
      "default/image-default.jpg"
    end
  end

end

My schema.rb:

create_table "book_categories", force: :cascade do |t|
  t.string "name"
  t.string "subcategory"
  t.text "description"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

create_table "book", force: :cascade do |t|
  t.string "book_name"
  t.text "summary"
  t.string "address"
  t.decimal "price", precision: 8, scale: 2
  t.boolean "active"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.integer "user_id"
  t.float "latitude"
  t.float "longitude"
  t.string "company_name"
  t.integer "book_categories_id"
  t.index ["book_categories_id"], name: "index_books_on_book_categories_id"
end

Usually, when I type @book_categories.name, I get an error:

undefined method `name' for nil:NilClass

And at the very end, it says Parameters: {"id"=>"15"} whereas the category.id is different, and it passes book.id instead.

What I am doing wrong?


问:
How do I access a public page variable of the only page from the master page?
I have a page - only ONE page for the entire site:

```<code>using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class CMSPageViewer : System.Web.UI.Page
{
    public int myPageID;

    protected void Page_PreInit(object sender, EventArgs e)
    {
         // Get stuff from the database

         myPageID = 1;

         // Set the Page.MasterPageFile
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Fill in the page contents
        // This looks for and fills in asp:ContentPlaceHolder controls based on ID
    }
}
</code>```

And the master page:

```<code>using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Standard_Page : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int myID = (this.Page as CMSPageViewer).myPageID;
    }
}
</code>```

How can I access ID from the MasterPage that is used?

Casting the page doesn't seem to work. I get the following error:

```<code>Compiler Error Message: CS0246: The type or namespace name 'CMSPageViewer' could not be found (are you missing a using directive or an assembly reference?)
</code>```

答:
Couldn't you use a session variable that you could access from both the page and the master page.</p>

```<code>HttpContext.Current.Session[key] = value;
</code>```

Body:
I have a page - only ONE page for the entire site:

using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class CMSPageViewer : System.Web.UI.Page
{
    public int myPageID;

    protected void Page_PreInit(object sender, EventArgs e)
    {
         // Get stuff from the database

         myPageID = 1;

         // Set the Page.MasterPageFile
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Fill in the page contents
        // This looks for and fills in asp:ContentPlaceHolder controls based on ID
    }
}

And the master page:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Standard_Page : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int myID = (this.Page as CMSPageViewer).myPageID;
    }
}

How can I access ID from the MasterPage that is used?

Casting the page doesn't seem to work. I get the following error:

Compiler Error Message: CS0246: The type or namespace name 'CMSPageViewer' could not be found (are you missing a using directive or an assembly reference?)

Body:
Couldn't you use a session variable that you could access from both the page and the master page.

HttpContext.Current.Session[key] = value;


问:
File.mkdirs() returns false
I'm creating an social media platform where photos that are already on the device can be uploaded to the platform. I found a sample on github that (in theory) should enable me to read all the jpg/png files and show them in a recyclerview. The code to obtain the files is shown below.

```<code>private void createImageGallery() {
        File storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        mGalleryFolder = new File(storageDirectory, GALLERY_LOCATION);
        Log.i("gallery", "" + (mGalleryFolder != null));
        Log.i("gallery", mGalleryFolder.toString());
        if (!mGalleryFolder.exists()) {
            boolean mk = mGalleryFolder.mkdirs();
            Log.i("gallery", "mkdirs returns " + mk);
        }
    }
</code>```

The first log statement equates to true, the second shows the string

"/storage/emulated/0/Pictures/hilarity_image"

the third log statement says the boolean mk is false. The File object mGalleryFolder is then passed into the constructor for a recyclerview adapter. The error is thrown when adapter.getItemCount() is called. Code is shown below

```<code>public int getItemCount() {
        return mGalleryFolder.listFiles().length;
    }
</code>```

The some of the permissions from the manifest are shown below

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
</code>```

Apparently, .length() is being called on a null object. I assumed this had something to do with mkdirs() returning false. Is this assumption correct? How do I make it so mkdirs() returns true? Remember, the desired result is showing all the photos that are already on the device in a recyclerview, if my approach to this problem is incorrect, please correct me.

答:
The directory is not created. So you should not continue with your code but stop.

Now you try to list the files in a directory that does not exist. No wonder that listFiles returns null then.

For Android 6+ you need to add code to ask the user to confirm the permissions you request in manifest.

Google for runtime permissions.

After adding the code you can create that directory.

Title: File.mkdirs() returns false

Body:
I'm creating an social media platform where photos that are already on the device can be uploaded to the platform. I found a sample on github that (in theory) should enable me to read all the jpg/png files and show them in a recyclerview. The code to obtain the files is shown below.

private void createImageGallery() {
        File storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        mGalleryFolder = new File(storageDirectory, GALLERY_LOCATION);
        Log.i("gallery", "" + (mGalleryFolder != null));
        Log.i("gallery", mGalleryFolder.toString());
        if (!mGalleryFolder.exists()) {
            boolean mk = mGalleryFolder.mkdirs();
            Log.i("gallery", "mkdirs returns " + mk);
        }
    }

The first log statement equates to true, the second shows the string

"/storage/emulated/0/Pictures/hilarity_image"

the third log statement says the boolean mk is false. The File object mGalleryFolder is then passed into the constructor for a recyclerview adapter. The error is thrown when adapter.getItemCount() is called. Code is shown below

public int getItemCount() {
        return mGalleryFolder.listFiles().length;
    }

The some of the permissions from the manifest are shown below

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Apparently, .length() is being called on a null object. I assumed this had something to do with mkdirs() returning false. Is this assumption correct? How do I make it so mkdirs() returns true? Remember, the desired result is showing all the photos that are already on the device in a recyclerview, if my approach to this problem is incorrect, please correct me.


问:
Can I cancel just the array job in slurm?
I have a bunch of jobs running as an array job in slurm:

```<code>123_[1-500] PD my_job 0:00 me
123_2       R  my_job 9:99 me
123_3       R  my_job 9:99 me
123_4       R  my_job 9:99 me
123_5       R  my_job 9:99 me
...
</code>```

As I read the man page on scancel, it seems to indicate that if I execute scancel 123 it will stop everything

Am I wrong, or is there another way to stop just the array job? I want the already running jobs to finish, I just don't want any more jobs created by 123, and I really don't want to have to figure out which jobs need to be re-run if I accidentally kill them mid-way

答: I put a hold on the job: scontrol hold 123 Once all the jobs reported by squeue were done, I was able to cancel it.

Body:
I have a bunch of jobs running as an array job in slurm:

123_[1-500] PD my_job 0:00 me
123_2       R  my_job 9:99 me
123_3       R  my_job 9:99 me
123_4       R  my_job 9:99 me
123_5       R  my_job 9:99 me
...

As I read the man page on scancel, it seems to indicate that if I execute scancel 123 it will stop everything

Am I wrong, or is there another way to stop just the array job? I want the already running jobs to finish, I just don't want any more jobs created by 123, and I really don't want to have to figure out which jobs need to be re-run if I accidentally kill them mid-way


问:
Why do lots of (old) programs use floor(0.5 + input) instead of round(input)?
The differences reside in the returned value giving inputs around tie-breaking I believe, such as this code:

```<code>int main()
{
    std::cout.precision(100);

    double input = std::nextafter(0.05, 0.0) / 0.1;
    double x1 = floor(0.5 + input);
    double x2 = round(input);

    std::cout << x1 << std::endl;
    std::cout << x2 << std::endl;
}
</code>```

which outputs:

```<code>1
0
</code>```

But they are just different results in the end, one chooses its preferred one. I see lots of "old" C/C++ programs using floor(0.5 + input) instead of round(input).

Is there any historic reason? Cheapest on the CPU?

答:
Many programmers adapt idioms that they learned when programming with other languages. Not all languages have a round() function, and in those languages it's normal to use floor(x + 0.5) as a substitute. When these programmers start using C++, they don't always realize that there's a built-in round(), they continue to use the style they're used to.

In other words, just because you see lots of code that does something, it doesn't mean there's a good reason to do it. You can find examples of this in every programming language. Remember Sturgeon's Law:

ninety percent of everything is crap

Body:
The differences reside in the returned value giving inputs around tie-breaking I believe, such as this code:

int main()
{
    std::cout.precision(100);

    double input = std::nextafter(0.05, 0.0) / 0.1;
    double x1 = floor(0.5 + input);
    double x2 = round(input);

    std::cout << x1 << std::endl;
    std::cout << x2 << std::endl;
}

which outputs:

1
0

But they are just different results in the end, one chooses its preferred one. I see lots of "old" C/C++ programs using floor(0.5 + input) instead of round(input).

Is there any historic reason? Cheapest on the CPU?