问:
Read mutliple data from table and create textboxes in form
My table in MySQL is like this:

I have a panel in my Form, and I want to create a TextBox for each data on this table and write sikicerik data to that TextBox's text.
Actually I did it but it creates only one TextBox and selects only the first data on the table.

My code is like this:

```<code>int count = oku.FieldCount;

reader.Read();
{
    for (int i = 0; i < count; i++)
    {
        TextBox txt1 = new TextBox();
        Point txtyer = new Point(x, y);
        txt1.Text = reader["sikicerik"].ToString();
        txt1.Name = i.ToString();
        x = x + 25;
        y = y + 25;
        panel1.Controls.Add(txt1);
    }
}
</code>```

It creates just one TextBox and writes "5" in it.

How can I do that repeatedly?

答:
What you need to understand is that you need to call reader.Read() after going through each record. Let's say your result data set has 5 records, so in order to read the 1st record, you need to call reader.Read() which would populate the reader object with the appropriate data. In order to read the 2nd record, you need to again call reader.Read(). Something like this:

```<code>int count = reader.FieldCount;

for (int i = 0; i < count; i++)
{
    reader.Read();
    TextBox txt1 = new TextBox();
    Point txtyer = new Point(x, y);
    txt1.Location = txtyer;
    txt1.Text = reader["sikicerik"].ToString();
    txt1.Name = i.ToString();
    y = y + 25;
    panel1.Controls.Add(txt1);
 }
</code>```

The reason why you may not be able to view all TextBoxes is that you are updating both x and y coordinates of the TextBox. What you may probably want to do is just increment the y coordinate as above and all the TextBoxes would appear vertically. You may also want to resize your form so that the TextBoxes don't get hidden.

Also, as @Steve mentioned in the comments above (which I missed), you need to assign the location of the new TextBoxes created as is done in the code above.

Body:
My table in MySQL is like this:

I have a panel in my Form, and I want to create a TextBox for each data on this table and write sikicerik data to that TextBox's text.
Actually I did it but it creates only one TextBox and selects only the first data on the table.

My code is like this:

int count = oku.FieldCount;

reader.Read();
{
    for (int i = 0; i < count; i++)
    {
        TextBox txt1 = new TextBox();
        Point txtyer = new Point(x, y);
        txt1.Text = reader["sikicerik"].ToString();
        txt1.Name = i.ToString();
        x = x + 25;
        y = y + 25;
        panel1.Controls.Add(txt1);
    }
}

It creates just one TextBox and writes "5" in it.

How can I do that repeatedly?

Body:
What you need to understand is that you need to call reader.Read() after going through each record. Let's say your result data set has 5 records, so in order to read the 1st record, you need to call reader.Read() which would populate the reader object with the appropriate data. In order to read the 2nd record, you need to again call reader.Read(). Something like this:

int count = reader.FieldCount;

for (int i = 0; i < count; i++)
{
    reader.Read();
    TextBox txt1 = new TextBox();
    Point txtyer = new Point(x, y);
    txt1.Location = txtyer;
    txt1.Text = reader["sikicerik"].ToString();
    txt1.Name = i.ToString();
    y = y + 25;
    panel1.Controls.Add(txt1);
 }

The reason why you may not be able to view all TextBoxes is that you are updating both x and y coordinates of the TextBox. What you may probably want to do is just increment the y coordinate as above and all the TextBoxes would appear vertically. You may also want to resize your form so that the TextBoxes don't get hidden.

Also, as @Steve mentioned in the comments above (which I missed), you need to assign the location of the new TextBoxes created as is done in the code above.


来源: stackexchange

问:
How do I make a scanner for a char array?
Like how do I make it so that the user can input the values for a char array?

Here's my attempt at trying to make it, but got a syntax error:

```<code>    char [] bacteriaStrand = new char[9];
    String bacteria = bac.next();
    bacteriaStrand = bacteria;
</code>```

Here's my entire code so far:

```<code>import java.util.Scanner;
public class SodiknBrukDNAAnalysispt3v1
{
    public static void main(String[] args)
    {
        Scanner bac = new Scanner(System.in);
        char [] treatmentStrand = {'T','C','G','A','G','A','G','T','A','T','C','C','C','A','G'};
        char [] bacteriaStrand = new char[9];
        char [] splicedStrand = new char[treatmentStrand.length + bacteriaStrand.length];
        System.out.println("NIH Treatment Splicer v. 1");
        System.out.println(" ");
        System.out.print("Treatment Strand: ");
        for (int t = 0; t < treatmentStrand.length; t++)
        {
            System.out.print(treatmentStrand[t]);
        }
        System.out.println(" ");
        System.out.print("Bacterium Strand: ");
        String bacteria = bac.next();
        bacteriaStrand = bacteria;
        for (int b = 0; b < bacteriaStrand.length; b++)
        {
            System.out.print(bacteriaStrand[b]);
            if (bacteriaStrand[b] != 'A' || bacteriaStrand[b] !='C' || bacteriaStrand[b] !='T' || bacteriaStrand[b] !='G')
            {
                System.out.println("Error! You can only input capital A, C, T, and G.");
            }
        }
    }
}
</code>```

答:
You are assigning String to Char[] so it's type missmatch,either assign String to String Array or do bacteriaStrand=bacteria.toCharArray();to convert String bacteriaStrand to Char[] bacteria.or try

```<code>for(int i=0;i<bacteriaStrand.length;i++){
bacteriaStrand[i]=bac.next().charAt(0);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Like how do I make it so that the user can input the values for a char array?

Here's my attempt at trying to make it, but got a syntax error:

    char [] bacteriaStrand = new char[9];
    String bacteria = bac.next();
    bacteriaStrand = bacteria;

Here's my entire code so far:

import java.util.Scanner;
public class SodiknBrukDNAAnalysispt3v1
{
    public static void main(String[] args)
    {
        Scanner bac = new Scanner(System.in);
        char [] treatmentStrand = {'T','C','G','A','G','A','G','T','A','T','C','C','C','A','G'};
        char [] bacteriaStrand = new char[9];
        char [] splicedStrand = new char[treatmentStrand.length + bacteriaStrand.length];
        System.out.println("NIH Treatment Splicer v. 1");
        System.out.println(" ");
        System.out.print("Treatment Strand: ");
        for (int t = 0; t < treatmentStrand.length; t++)
        {
            System.out.print(treatmentStrand[t]);
        }
        System.out.println(" ");
        System.out.print("Bacterium Strand: ");
        String bacteria = bac.next();
        bacteriaStrand = bacteria;
        for (int b = 0; b < bacteriaStrand.length; b++)
        {
            System.out.print(bacteriaStrand[b]);
            if (bacteriaStrand[b] != 'A' || bacteriaStrand[b] !='C' || bacteriaStrand[b] !='T' || bacteriaStrand[b] !='G')
            {
                System.out.println("Error! You can only input capital A, C, T, and G.");
            }
        }
    }
}

Body:
You are assigning String to Char[] so it's type missmatch,either assign String to String Array or do bacteriaStrand=bacteria.toCharArray();to convert String bacteriaStrand to Char[] bacteria.or try

for(int i=0;i<bacteriaStrand.length;i++){
bacteriaStrand[i]=bac.next().charAt(0);
}


问:
Facebook share error : "the page you requested cannot be displayed right now"
I have used custom stories to do the facebook share and the share happens correctly and displays in posted user's facebook wall. See below:

The issue when when I click on the name of the page ("page" in the picture), via the facebook mobile app it gives me the following error:

```<code>the page you requested cannot be displayed right now. It may be temporarily unavailable, the link you clicked on may be broken or expired, or you may not have permission to view this page
</code>```

The link entered for "Site URL" in facebook application opens when I click on "Page"("page" in the picture) from machine browser but not with mobile facebook app. Any help is really appreciated since there is no / very less information about this issue.

答:
Go to yourfacebook App dashboard

Go to Settings

Then switch to YES Single Sign On

Then switch to YES Deep Linking

Body:
I have used custom stories to do the facebook share and the share happens correctly and displays in posted user's facebook wall. See below:

The issue when when I click on the name of the page ("page" in the picture), via the facebook mobile app it gives me the following error:

the page you requested cannot be displayed right now. It may be temporarily unavailable, the link you clicked on may be broken or expired, or you may not have permission to view this page

The link entered for "Site URL" in facebook application opens when I click on "Page"("page" in the picture) from machine browser but not with mobile facebook app. Any help is really appreciated since there is no / very less information about this issue.


问:
reverse printing on python 3.x function
```<code>import time
def close_garage_dors():
        a= '_ _ _'
        for i in range(5):
            time.sleep(1)
            print(a)

        return 'Doors are closed'
</code>```

Now my question is: How to open this doors :) Basically how to reverse this function, how to delete 5 lines of _ _ _ ? Any ideas?

答:
Once you print a newline, you can't delete it. So it is not possible to print over the previous 5 lines with blank lines, for instance.

Instead, you may try to print a very large number (i.e. the height of the screen in lines) of blank lines in order to present a new empty screen.

Title: reverse printing on python 3.x function

Body:
import time
def close_garage_dors():
        a= '_ _ _'
        for i in range(5):
            time.sleep(1)
            print(a)

        return 'Doors are closed'

Now my question is: How to open this doors :) Basically how to reverse this function, how to delete 5 lines of _ _ _ ? Any ideas?


问:
CTE Recursive Queries in Doctrine 2.5
I have a table Users that has 2 key columns of referrer and referral_code which is a simple implementation of a tree structure. target is to get a trail of users based on who referred them to use this application.

```<code>NAME       |     Referrer     | Referral_Code
----------------------------------------------
Super User |     000          |  001
User A     |     001          |  002
User B     |     002          |  003
User C     |     003          |  004
User n     |     00n          |  00n-1
</code>```

I need a recursive query where based on a trigger e.g a report of User C activities can yield a trace string on referrers to a depth of 4 maximum.
My desired output string is 004-003-002-001 which implies the trace of referrals based on the users activity. The tree can grow infinitely in depth so a trace of say User QA can yield a stack trace of the 4 people up the tree joined on the referral codes.
I'm using doctrine 2.5 as the ORM.
Constraints

A user must be referred to use the system

A user can refer multiple users to use the system

答:
If the depths of 4 is fixed, you don't need recursion, just a self join 4 times.
If you really want to use recursion, you can write your own DQL Function for your dbms. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/dql-user-defined-functions.html</p>

Title: CTE Recursive Queries in Doctrine 2.5

Body:
I have a table Users that has 2 key columns of referrer and referral_code which is a simple implementation of a tree structure. target is to get a trail of users based on who referred them to use this application.

NAME       |     Referrer     | Referral_Code
----------------------------------------------
Super User |     000          |  001
User A     |     001          |  002
User B     |     002          |  003
User C     |     003          |  004
User n     |     00n          |  00n-1

I need a recursive query where based on a trigger e.g a report of User C activities can yield a trace string on referrers to a depth of 4 maximum.
My desired output string is 004-003-002-001 which implies the trace of referrals based on the users activity. The tree can grow infinitely in depth so a trace of say User QA can yield a stack trace of the 4 people up the tree joined on the referral codes.
I'm using doctrine 2.5 as the ORM.
Constraints

A user must be referred to use the system

A user can refer multiple users to use the system


问:
create layout using CSS for following design
We are trying to achieve the following layout based on dynamic html string.

Here we are facing when it is second page content layout not going up & we can not add images in first page.

The sample code tried in native code as below:

```<code> func setData(){

        let dic = arrayData[currentIndex]
        url = dic["ImageLink"] as! String
        self.url = self.url + "_MEDVPF.gif"
        content = dic["ArticleXML"] as! String

        let height = String(describing:webViewObj.frame.size.height - 100) + "px"
        let width = String(describing: self.view.frame.size.width / 3 - 20) + "px"

//        let style = "<div style=color:#0000FF>" + String(describing: dic["HeadLine"]!) + "<br /><br />" +  String(describing: dic["Abstract"]!) + "</div>"

        self.headlineLabel.text = dic["HeadLine"] as? String
        self.abstractLabel.text =  dic["Abstract"] as? String
        var styleCSS = "font-family: TAUN_Elango_Abirami; font-size: 18px; column-width: %@; column-gap: 10px; height:%@;>"
        styleCSS = String(format:styleCSS,width,height)

        let bodyStyle = "<div style= \"%@\""  + content + "</div>"
        let bodyStyleConten = String(format:bodyStyle,styleCSS)

        let htmlString =   String(format:bodyStyleConten)
        let finalDiv = "<div>" + htmlString + "</div>"
        webViewObj.loadHTMLString(finalDiv, baseURL: nil)

    }
</code>```

How can I do this Html5 with CSS, that should be horizontal scrolling?

We have tried with core text in iOs,but we have facing slowness issue.So we decided to go with uiwebview?

We did this with CoreText framework, only issue with this layout is slowness when its content very very large.We checked many way, but no lucks? We are not able to fix slowness, help would be appreciated, i will share sample also if anyone interested to contribute.

答:
Maybe this should be a comment but it's a little long so instead I'm leaving an answer to explain why I'm downvoting this question: it's a request for someone to do free work. You don't offer any truly specific information about solutions you've tried and how they've failed, instead you're asking the very broad question of "Is it possible to implement this layout, can you do it for me?" The answer to that question is usually, "Yes, but there are many ways to do it, and if we were to have a conversation to solve the problem I'd prefer to charge you." There are a number of separate issues that make up your problem and layout is just one of them.

I'm sure that there's no ill intent. I do hope that you're able to solve the problem! But you should also read this guide https://stackoverflow.com/help/how-to-ask and either learn the HTML/CSS/JS necessary to solve the problem or contract a developer who has the expertise.

If you're going to tackle it yourself in HTML/CSS, I'd recommend starting with overflow-x: scroll; on the container which holds your content, and looking at this information about CSS columns https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Columns/Using_multi-column_layouts, but with a caveat that columns aren't uniformly supported across browsers, so it might be wise to avoid them or implement them differently.

Body:
We are trying to achieve the following layout based on dynamic html string.

Here we are facing when it is second page content layout not going up & we can not add images in first page.

The sample code tried in native code as below:

 func setData(){

        let dic = arrayData[currentIndex]
        url = dic["ImageLink"] as! String
        self.url = self.url + "_MEDVPF.gif"
        content = dic["ArticleXML"] as! String

        let height = String(describing:webViewObj.frame.size.height - 100) + "px"
        let width = String(describing: self.view.frame.size.width / 3 - 20) + "px"

//        let style = "
" + String(describing: dic["HeadLine"]!) + "

" +  String(describing: dic["Abstract"]!) + "
"

        self.headlineLabel.text = dic["HeadLine"] as? String
        self.abstractLabel.text =  dic["Abstract"] as? String
        var styleCSS = "font-family: TAUN_Elango_Abirami; font-size: 18px; column-width: %@; column-gap: 10px; height:%@;>"
        styleCSS = String(format:styleCSS,width,height)

        let bodyStyle = "<div style= \"%@\""  + content + "
"
        let bodyStyleConten = String(format:bodyStyle,styleCSS)

        let htmlString =   String(format:bodyStyleConten)
        let finalDiv = "
" + htmlString + "
"
        webViewObj.loadHTMLString(finalDiv, baseURL: nil)

    }

How can I do this Html5 with CSS, that should be horizontal scrolling?

We have tried with core text in iOs,but we have facing slowness issue.So we decided to go with uiwebview?

We did this with CoreText framework, only issue with this layout is slowness when its content very very large.We checked many way, but no lucks? We are not able to fix slowness, help would be appreciated, i will share sample also if anyone interested to contribute.


问:
Run sql command line, issue. Creating tables
I'm trying to create a table in run sql command line of oracle database 11 xe.

My problem is when I finish typing my code:

```<code>create table vigilantes(
idVigilantes integer(3) not null,
nombre varchar(100) not null,
paterno varchar(100) not null,
materno varchar(100) not null,
id_caseta integer(3) null,
id_turno integer(3) null,
edad integer(3) not null,
id_genero integer(1) not null,
idEmpresa integer(3) not null,
constraint pk_idVigilantes PRIMARY KEY (idVigilantes)
constraint fk_id_caseta FOREIGN KEY (id_caseta)
references Caseta(id_caseta)
constraint fk_id_turno FOREIGN KEY(id_turno)
references Turno(id_turno)
constraint fk_id_genero FOREIGN KEY(id_genero)
references Generos(id_genero)
constraint fk_idEmpresa FOREIGN KEY(idEmpresa)
references Empresa(idEmpresa)
);
</code>```

I get "ORA-00907: missing right parenthesis" issue.
I read that this is often caused by not defining a value.
e.g:

```<code>create table vigilantes(
idVigilantes integer not null,
.......
</code>```

But still no solution here.
Any help or clue will be a lot of help.

答:
You are missing comma after constraints. Also, integer has no precision.

```<code>create table vigilantes (
    idVigilantes integer not null,
    nombre varchar(100) not null,
    paterno varchar(100) not null,
    materno varchar(100) not null,
    id_caseta integer null,
    id_turno integer null,
    edad integer not null,
    id_genero integer not null,
    idEmpresa integer not null,
    constraint pk_idVigilantes primary key (idVigilantes),
    constraint fk_id_caseta foreign key (id_caseta) references Caseta(id_caseta),
    constraint fk_id_turno foreign key (id_turno) references Turno(id_turno),
    constraint fk_id_genero foreign key (id_genero) references Generos(id_genero),
    constraint fk_idEmpresa foreign key (idEmpresa) references Empresa(idEmpresa)
    );
</code>```

If you must define precision, use number datatype:

```<code>create table vigilantes (
    idVigilantes number(3, 0) not null,
    nombre varchar(100) not null,
    paterno varchar(100) not null,
    materno varchar(100) not null,
    id_caseta number(3, 0) null,
    id_turno number(3, 0) null,
    edad number(3, 0) not null,
    id_genero number(1, 0) not null,
    idEmpresa number(3, 0) not null,
    constraint pk_idVigilantes primary key (idVigilantes),
    constraint fk_id_caseta foreign key (id_caseta) references Caseta(id_caseta),
    constraint fk_id_turno foreign key (id_turno) references Turno(id_turno),
    constraint fk_id_genero foreign key (id_genero) references Generos(id_genero),
    constraint fk_idEmpresa foreign key (idEmpresa) references Empresa(idEmpresa)
    );
</code>```

Body:
I'm trying to create a table in run sql command line of oracle database 11 xe.

My problem is when I finish typing my code:

create table vigilantes(
idVigilantes integer(3) not null,
nombre varchar(100) not null,
paterno varchar(100) not null,
materno varchar(100) not null,
id_caseta integer(3) null,
id_turno integer(3) null,
edad integer(3) not null,
id_genero integer(1) not null,
idEmpresa integer(3) not null,
constraint pk_idVigilantes PRIMARY KEY (idVigilantes)
constraint fk_id_caseta FOREIGN KEY (id_caseta)
references Caseta(id_caseta)
constraint fk_id_turno FOREIGN KEY(id_turno)
references Turno(id_turno)
constraint fk_id_genero FOREIGN KEY(id_genero)
references Generos(id_genero)
constraint fk_idEmpresa FOREIGN KEY(idEmpresa)
references Empresa(idEmpresa)
);

I get "ORA-00907: missing right parenthesis" issue.
I read that this is often caused by not defining a value.
e.g:

create table vigilantes(
idVigilantes integer not null,
.......

But still no solution here.
Any help or clue will be a lot of help.

Body:
You are missing comma after constraints. Also, integer has no precision.

create table vigilantes (
    idVigilantes integer not null,
    nombre varchar(100) not null,
    paterno varchar(100) not null,
    materno varchar(100) not null,
    id_caseta integer null,
    id_turno integer null,
    edad integer not null,
    id_genero integer not null,
    idEmpresa integer not null,
    constraint pk_idVigilantes primary key (idVigilantes),
    constraint fk_id_caseta foreign key (id_caseta) references Caseta(id_caseta),
    constraint fk_id_turno foreign key (id_turno) references Turno(id_turno),
    constraint fk_id_genero foreign key (id_genero) references Generos(id_genero),
    constraint fk_idEmpresa foreign key (idEmpresa) references Empresa(idEmpresa)
    );

If you must define precision, use number datatype:

create table vigilantes (
    idVigilantes number(3, 0) not null,
    nombre varchar(100) not null,
    paterno varchar(100) not null,
    materno varchar(100) not null,
    id_caseta number(3, 0) null,
    id_turno number(3, 0) null,
    edad number(3, 0) not null,
    id_genero number(1, 0) not null,
    idEmpresa number(3, 0) not null,
    constraint pk_idVigilantes primary key (idVigilantes),
    constraint fk_id_caseta foreign key (id_caseta) references Caseta(id_caseta),
    constraint fk_id_turno foreign key (id_turno) references Turno(id_turno),
    constraint fk_id_genero foreign key (id_genero) references Generos(id_genero),
    constraint fk_idEmpresa foreign key (idEmpresa) references Empresa(idEmpresa)
    );


问:
Drag and Drop Windows Forms: Controls disappear after dragging
I need to drag labels between the panels. But when I'm trying to drop a label even within the initial panel, it disappears. Here is the code of the methods I use:

```<code>private void label1_MouseDown(object sender, MouseEventArgs e)
{
     if (e.Button == MouseButtons.Left)
     DoDragDrop(sender, DragDropEffects.All);
}

private void panel_DragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.All;
}

private void panel_DragDrop(object sender, DragEventArgs e)
{
    Label src = e.Data.GetData(typeof(Label)) as Label;
    src.Location = PointToClient(new Point(e.X, e.Y));
}
</code>```

AllowDrop is enabled for the panels. Why do the labels disappear and how can I fix it?

答:
The Label is still contained by the Form, so it is simply going behind the Panel.

Either...

(1) Bring the Label to the Front:

```<code>    private void panel1_DragDrop(object sender, DragEventArgs e)
    {
        Label src = e.Data.GetData(typeof(Label)) as Label;
        src.Location = this.PointToClient(new Point(e.X, e.Y));
        src.BringToFront();
    }
</code>```

or,

(2) Make the Panel contain the Label, and adjust the coordinates to the Panel's client coord system:

```<code>    private void panel1_DragDrop(object sender, DragEventArgs e)
    {
        Panel pnl = sender as Panel;
        Label src = e.Data.GetData(typeof(Label)) as Label;
        src.Location = pnl.PointToClient(new Point(e.X, e.Y));
        pnl.Controls.Add(src);
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to drag labels between the panels. But when I'm trying to drop a label even within the initial panel, it disappears. Here is the code of the methods I use:

private void label1_MouseDown(object sender, MouseEventArgs e)
{
     if (e.Button == MouseButtons.Left)
     DoDragDrop(sender, DragDropEffects.All);
}

private void panel_DragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.All;
}

private void panel_DragDrop(object sender, DragEventArgs e)
{
    Label src = e.Data.GetData(typeof(Label)) as Label;
    src.Location = PointToClient(new Point(e.X, e.Y));
}

AllowDrop is enabled for the panels. Why do the labels disappear and how can I fix it?

Body:
The Label is still contained by the Form, so it is simply going behind the Panel.

Either...

(1) Bring the Label to the Front:

    private void panel1_DragDrop(object sender, DragEventArgs e)
    {
        Label src = e.Data.GetData(typeof(Label)) as Label;
        src.Location = this.PointToClient(new Point(e.X, e.Y));
        src.BringToFront();
    }

or,

(2) Make the Panel contain the Label, and adjust the coordinates to the Panel's client coord system:

    private void panel1_DragDrop(object sender, DragEventArgs e)
    {
        Panel pnl = sender as Panel;
        Label src = e.Data.GetData(typeof(Label)) as Label;
        src.Location = pnl.PointToClient(new Point(e.X, e.Y));
        pnl.Controls.Add(src);
    }


问:
Is there a plugin that allows me to automatically unminify the Javascript included on a site?
Is there a plugin, add-on, Greasemonkey script or something similar (at worst, an easy to use proxy?) that automatically unminifies the Javascript files included on a site?

I know about e.g. jsbeautifier.org but doing this externally doesn't allow me to set breakpoints in the unminified code, for example.

Typical use cases for me:

Analysing and learning from complex web frontends.

Debugging Greasemonkey scripts which interact with the existing code.

I'm primarily interested in a solution that works with Firebug, but if there's something for the dev tools of Chrome or Opera, I'd like to hear about it as well.

答:
Is not possible with current tools. Show eval scripts is the most you can get.
Jsbeautifier.org is nice open thing, and someone can integrate it info firebug.

ContentLicense: CC BY-SA 2.5


问:
Listen to element visibility in Angular 2
I'm using Bootstrap and Angular 2 (v4) for my webapp. I would like to listen to an element in a directive for visibility changes. My element has a parent that can hide its children with hidden-sm-up and I need to trigger a function each time it is hidden or displayed.

```<code>div.hidden-sm-up
   input.form-control(myDirective, type='number')
</code>```

and in my directive:

```<code>@Directive({
    selector: '[myDirective]'
})

export class myDirective {
    constructor(private element: ElementRef, private renderer: Renderer){

    }

    ngAfterViewInit(): void{
        // listen to visibility change here
    }
}
</code>```

答:
ngDoCheck is run when change detection is run, therefore I think it's the right place if you want to monitor it instead of just get it once at component creation time:

```<code>@HostListener('window:resize')
ngDoCheck() {
  this.isVisible = this.element.nativeElement.offsetParent !== null;
}
</code>```

There might be better option, like some events that are emitted somewhere, but for the general case ngDoCheck should work fine.

Body:
I'm using Bootstrap and Angular 2 (v4) for my webapp. I would like to listen to an element in a directive for visibility changes. My element has a parent that can hide its children with hidden-sm-up and I need to trigger a function each time it is hidden or displayed.

div.hidden-sm-up
   input.form-control(myDirective, type='number')

and in my directive:

@Directive({
    selector: '[myDirective]'
})

export class myDirective {
    constructor(private element: ElementRef, private renderer: Renderer){

    }

    ngAfterViewInit(): void{
        // listen to visibility change here
    }
}

Body:
ngDoCheck is run when change detection is run, therefore I think it's the right place if you want to monitor it instead of just get it once at component creation time:

@HostListener('window:resize')
ngDoCheck() {
  this.isVisible = this.element.nativeElement.offsetParent !== null;
}

There might be better option, like some events that are emitted somewhere, but for the general case ngDoCheck should work fine.


问:
Drop Down List Across Views/Models
I am trying to create a dropdown list, which is simple enough if the list is in the same view as the model/controller, however I am trying to create the dropdown list in another view. I am including the "using.samplemodel.Models;" using statement which seems to work as far as being able to access the right database, however no matter which method I use to call the list items in the Database (which is already populate) I keep getting the error "there is no key "Categories" or even i use the Id field in the statement, I am currently using the Viewbag option to call the database information, however, no matter which method I try, I still get the same error.

```<code> The class of the view I am wanting to use drop down list in:

namespace Fake.Models
{
    public class Fake
    {
        public int Id { get; set; }
        public List<SelectList> Categories { get; set; }

      }
}

 Model of the Category class pulling from database:

namespace Fake.Models
{
    public class Categories
    {
        public int Id { get; set; }
        public string CategoryName { get; set; }
    }
}

 controller of the view intended to use dropdown list:

namespace Fake.Controllers
{
    public class FakeController : Controller
    {

        FakeDb _db = new FakeDb();

        public ActionResult Index()
        {
            var model = from a in _db.Fake1 orderby a.Date ascending select a;
            ViewBag.Categories = new SelectList(_db.Categories, "Id", "CategoryName");
            return View(model);
        }

The view I am trying to get dropdown list to work in:

@model fakename.Models.Modelname
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
<div class="form-group col-md-offset-2 col-md-10">
            @Html.DropDownList("Categories", "Select Category")
            // Omitted Info not related
        </div>
}
</code>```

Sorry the Snippets here dont exatly match up as I intended with this form. So I am including a window snip of the code as jpeg here Code in Notepad Snip Just in case.

答: Well the answer was simple. But still complicated to a newbie like me...needed ado.net entity  for it to work.</p>

Title: Drop Down List Across Views/Models

Body:
I am trying to create a dropdown list, which is simple enough if the list is in the same view as the model/controller, however I am trying to create the dropdown list in another view. I am including the "using.samplemodel.Models;" using statement which seems to work as far as being able to access the right database, however no matter which method I use to call the list items in the Database (which is already populate) I keep getting the error "there is no key "Categories" or even i use the Id field in the statement, I am currently using the Viewbag option to call the database information, however, no matter which method I try, I still get the same error.

 The class of the view I am wanting to use drop down list in:

namespace Fake.Models
{
    public class Fake
    {
        public int Id { get; set; }
        public List<SelectList> Categories { get; set; }

      }
}

 Model of the Category class pulling from database:

namespace Fake.Models
{
    public class Categories
    {
        public int Id { get; set; }
        public string CategoryName { get; set; }
    }
}

 controller of the view intended to use dropdown list:

namespace Fake.Controllers
{
    public class FakeController : Controller
    {

        FakeDb _db = new FakeDb();

        public ActionResult Index()
        {
            var model = from a in _db.Fake1 orderby a.Date ascending select a;
            ViewBag.Categories = new SelectList(_db.Categories, "Id", "CategoryName");
            return View(model);
        }

The view I am trying to get dropdown list to work in:

@model fakename.Models.Modelname
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

            @Html.DropDownList("Categories", "Select Category")
            // Omitted Info not related

}

Sorry the Snippets here dont exatly match up as I intended with this form. So I am including a window snip of the code as jpeg here Code in Notepad Snip Just in case.


问:
Finding Symmetric Difference in an array test fail
sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]) should return [1, 4, 5]
The expected return is shown above. But I couldn't find why it fails this test. What kind of fix is needed to code below?

function sym(args) {
 //debugger;
 var arr=Array.from(arguments);
  var resArr=[];

  arr.forEach(function(arrVal){
        var c=0;

      arrVal.forEach(function(val,index){
      console.log("arrVal",arrVal,"index",index,"val",val,"|",arrVal.slice(index+1-c));
        if(index<arrVal.length-1 && arrVal.slice(index+1-c).indexOf(val)!==-1){
        console.log("here");

          arrVal.splice(index-c,1);
          c++;
        }
                    console.log("arrVal",arrVal,"index",index,"|",arrVal);

      });

      resArr.push(arrVal);
    });
  console.log(resArr);

  resArr=resArr.reduce(function(acc,curr){
   return acc.concat(curr.filter(function(val){
     var notContains=acc.indexOf(val)==-1;
     if(!notContains)
       acc.splice(acc.indexOf(val),1);
     return notContains;
    }));
  },[]);

 console.log(resArr);
  return resArr;
}

sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]);```

答:
You could use a more concise version with filtering duplicates.

function sym(array) {
    return array.reduce(function (r, a) {
        return r.concat(a.filter(function (a, i, aa) {
            return i === aa.indexOf(a);
        })).filter(function (a, i, aa) {
            return aa.indexOf(a) === aa.lastIndexOf(a);
        });
    }, []);
}

console.log(sym([[1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]])); // [1, 4, 5]```


问:
Link a Library within a Library with externs?
Im creating a library to interface into drawing a specific file type. This library needs to pull in a 3rd party library to do some processing on this specific file type. This 3rd party lib requires the users of it to create some extern functions that it uses to make data types on target hardware.

So, it looks like this:

```<code>----------------
|              |
| 3rd Party    |
|   Lib        |
|              |
----------------
      |
      |
     \/
---------------
|             |
|  My Lib     |
---------------
|  externs    |
---------------
      |
      |
     \/
---------------
|             |
|  My App     |
|             |
|             |
---------------
</code>```

My App calls My Lib and says "draw me file X", My Lib does a bunch of junk eventually calling 3rd Party Lib and says "process file X". 3rd Party Lib requires several externs to be declared that it uses.

I made all these externs inside My Lib. My problem is, when I link My App, its telling me undefined references to all the extern functions. I can't figure out why. Heres one of the externs inside My Lib to be called by 3rd Party Lib:

```<code>// inside typeConversions.c

extern int CreateShort(short* shortList, int numShorts)
{
    int i;

    for(i = 0; i < numShorts; i++)
    {
        BYTE_SWAP_SHORT(shortList[i]);
    }

    return ERROR_OK;
}
</code>```

When I link My App I get (among several other similar errors):

open.cpp: undefined reference to `CreateShort'

Where open.cpp is inside the 3rd Party Lib.

I have both My Lib and 3rd Party Lib included in My App. Ideally, I want to not expose users of My Lib to 3rd Party Lib, so for example My App would not have to include 3rd Party Lib at all, they dont know it even exists. All that should be exposed is My Lib. Is this possible? Anyone know how to fix my linking problem?

答:
1) Look up "calling conventions" in your compiler and linker documentation.  You most likely have a mismatch.

2) In C, (not C++) The extern keyword should be used in the header, not on the function definition.  Make sure you include the header in all files that use the declarations, including the .C file that implements what the header declares.

```
    // This goes in a header file
    extern int CreateShort(short* shortList, int numShorts)

    // This goes in a .c file.
    int CreateShort(short* shortList, int numShorts)
    {
        ...
        return ERROR_OK;
    }
```

3) If you are using C++ to write the functions that the 3rd party lib calls, and the 3rd party lib expects things to work like C, you'll have to use extern "C" to prevent name mangling.

```
    // This goes in a header file
    extern "C" int CreateShort(short* shortList, int numShorts)
    // You can also wrap it in a block:
    // extern "C" {
    // int someFunc1( int x );
    // int someFunc2( int y );
    // }

    // This goes in a .cpp file.
    extern "C" int CreateShort(short* shortList, int numShorts)
    {
        ...
        return ERROR_OK;
    }
```

Body:
Im creating a library to interface into drawing a specific file type. This library needs to pull in a 3rd party library to do some processing on this specific file type. This 3rd party lib requires the users of it to create some extern functions that it uses to make data types on target hardware.

So, it looks like this:

----------------
|              |
| 3rd Party    |
|   Lib        |
|              |
----------------
      |
      |
     \/
---------------
|             |
|  My Lib     |
---------------
|  externs    |
---------------
      |
      |
     \/
---------------
|             |
|  My App     |
|             |
|             |
---------------

My App calls My Lib and says "draw me file X", My Lib does a bunch of junk eventually calling 3rd Party Lib and says "process file X". 3rd Party Lib requires several externs to be declared that it uses.

I made all these externs inside My Lib. My problem is, when I link My App, its telling me undefined references to all the extern functions. I can't figure out why. Heres one of the externs inside My Lib to be called by 3rd Party Lib:

// inside typeConversions.c

extern int CreateShort(short* shortList, int numShorts)
{
    int i;

    for(i = 0; i < numShorts; i++)
    {
        BYTE_SWAP_SHORT(shortList[i]);
    }

    return ERROR_OK;
}

When I link My App I get (among several other similar errors):

open.cpp: undefined reference to `CreateShort'

Where open.cpp is inside the 3rd Party Lib.

I have both My Lib and 3rd Party Lib included in My App. Ideally, I want to not expose users of My Lib to 3rd Party Lib, so for example My App would not have to include 3rd Party Lib at all, they dont know it even exists. All that should be exposed is My Lib. Is this possible? Anyone know how to fix my linking problem?

Body:
1) Look up "calling conventions" in your compiler and linker documentation.  You most likely have a mismatch.

2) In C, (not C++) The extern keyword should be used in the header, not on the function definition.  Make sure you include the header in all files that use the declarations, including the .C file that implements what the header declares.

    // This goes in a header file
    extern int CreateShort(short* shortList, int numShorts)

    // This goes in a .c file.
    int CreateShort(short* shortList, int numShorts)
    {
        ...
        return ERROR_OK;
    }

3) If you are using C++ to write the functions that the 3rd party lib calls, and the 3rd party lib expects things to work like C, you'll have to use extern "C" to prevent name mangling.

    // This goes in a header file
    extern "C" int CreateShort(short* shortList, int numShorts)
    // You can also wrap it in a block:
    // extern "C" {
    // int someFunc1( int x );
    // int someFunc2( int y );
    // }

    // This goes in a .cpp file.
    extern "C" int CreateShort(short* shortList, int numShorts)
    {
        ...
        return ERROR_OK;
    }


问:
Python numpy Error
My code needs to collect some information on the Internet and that the work I have done well. Now i need to take that data from database and import in numpy array.
But somewhere I have a mistake..

I'm pretty new at this all and still there are so many things I do not fully understand. Any kind of help is appreciated.

This is error:

ValueError: could not broadcast input array from shape (1818,2) into
  shape (1818)

And this is my code:

```<code>import numpy as np
import sqlite3 as db
import selenium
from selenium import webdriver
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from sklearn.neighbors import KNeighborsClassifier

driver = webdriver.Chrome()
driver.get("http://www.rezultati.com/utakmica/nZudUKkp/#detalji")

#Collecting data
try:
    d_kvz = driver.find_element_by_xpath('//*[@id="default-odds"]/tbody/tr[1]/td[2]/span').text
    try:
        d_kv = float(d_kvz)
    except ValueError:
        d_kv = 1.00
except NoSuchElementException:
    d_kvz = 1.00
    d_kv = 1.00

print(d_kv)

# open new link
driver.find_element_by_id('a-match-odds-comparison').click()
newtab = driver.current_window_handle
driver.switch_to.window(newtab)
time.sleep(2)

# open new link and collect more data
driver.find_element_by_id("bookmark-under-over").click()

try:
    granicax = driver.find_elements_by_xpath(
            "//*[@id='block-under-over-ft-include-ot']/table/tbody/tr/td[preceding-sibling::td[1]/div/a[@title='bet365'] and following-sibling::td/span[@class=' odds-wrap ']]")
    granicaz = granicax[0].text

except IndexError:
    granicaz = 0

granica = float(granicaz)

print(granica)

# Collecting data from db1
conn = db.connect('rezultati.db')
print("Connected with db1!")
conn.row_factory = lambda cursor, row: row[0]
c = conn.cursor()

br_po = c.execute("SELECT BR_PO FROM model").fetchall()
granica = c.execute("SELECT GRANICA FROM model").fetchall()
kvota = c.execute("SELECT D_KV FROM model").fetchall()

x = np.vstack((granica,kvota)).T
y = np.vstack((br_po))

print(x)
print(y)

c.close()
conn.close()
print("Connection closed")

knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(x,y)

knn2 = KNeighborsClassifier(n_neighbors=5)
knn2.fit(x,y)

b = (knn.predict([x,y]))[0]
u = (knn2.predict([x,y]))[0]

t = b.tolist()
r = u.tolist()

print(t)
print(r)

rezultat = 0

conn2 = db.connect('ProbaStatistike.db')
print("Connected with db2")
c2 = conn2.cursor()
c2.execute("INSERT INTO Probica VALUES (?,?,?,?)",
              (granica,t,r,rezultat,))

conn2.commit()
driver.close()
c2.close()
conn2.close()
print("Connection closed")
</code>```

答:
The error is trying to tell you that two arrays are being used together where they should be the same size but they are different (e.g. x+y where x and y are numpy arrays of different sizes will give an error).

It's hard to say for sure where this is happening without further information but at a guess, this looks wrong:

```<code>knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(x,y)

knn2 = KNeighborsClassifier(n_neighbors=5)
knn2.fit(x,y)

b = (knn.predict([x,y]))[0]
u = (knn2.predict([x,y]))[0]
</code>```

Specifically, having done fit using (x,y), its unlikely that you mean to do predict using both x and y also, you'd normally call predict with just x (or better, a test set that is distinct from but statistically related to the original x).

See the Iris example here for more information:

http://scikit-learn.org/stable/tutorial/statistical_inference/supervised_learning.html

Title: Python numpy Error

Body:
My code needs to collect some information on the Internet and that the work I have done well. Now i need to take that data from database and import in numpy array.
But somewhere I have a mistake..

I'm pretty new at this all and still there are so many things I do not fully understand. Any kind of help is appreciated.

This is error:

ValueError: could not broadcast input array from shape (1818,2) into
  shape (1818)

And this is my code:

import numpy as np
import sqlite3 as db
import selenium
from selenium import webdriver
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from sklearn.neighbors import KNeighborsClassifier

driver = webdriver.Chrome()
driver.get("http://www.rezultati.com/utakmica/nZudUKkp/#detalji")

#Collecting data
try:
    d_kvz = driver.find_element_by_xpath('//*[@id="default-odds"]/tbody/tr[1]/td[2]/span').text
    try:
        d_kv = float(d_kvz)
    except ValueError:
        d_kv = 1.00
except NoSuchElementException:
    d_kvz = 1.00
    d_kv = 1.00

print(d_kv)

# open new link
driver.find_element_by_id('a-match-odds-comparison').click()
newtab = driver.current_window_handle
driver.switch_to.window(newtab)
time.sleep(2)

# open new link and collect more data
driver.find_element_by_id("bookmark-under-over").click()

try:
    granicax = driver.find_elements_by_xpath(
            "//*[@id='block-under-over-ft-include-ot']/table/tbody/tr/td[preceding-sibling::td[1]/div/a[@title='bet365'] and following-sibling::td/span[@class=' odds-wrap ']]")
    granicaz = granicax[0].text

except IndexError:
    granicaz = 0

granica = float(granicaz)

print(granica)

# Collecting data from db1
conn = db.connect('rezultati.db')
print("Connected with db1!")
conn.row_factory = lambda cursor, row: row[0]
c = conn.cursor()

br_po = c.execute("SELECT BR_PO FROM model").fetchall()
granica = c.execute("SELECT GRANICA FROM model").fetchall()
kvota = c.execute("SELECT D_KV FROM model").fetchall()

x = np.vstack((granica,kvota)).T
y = np.vstack((br_po))

print(x)
print(y)

c.close()
conn.close()
print("Connection closed")

knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(x,y)

knn2 = KNeighborsClassifier(n_neighbors=5)
knn2.fit(x,y)

b = (knn.predict([x,y]))[0]
u = (knn2.predict([x,y]))[0]

t = b.tolist()
r = u.tolist()

print(t)
print(r)

rezultat = 0

conn2 = db.connect('ProbaStatistike.db')
print("Connected with db2")
c2 = conn2.cursor()
c2.execute("INSERT INTO Probica VALUES (?,?,?,?)",
              (granica,t,r,rezultat,))

conn2.commit()
driver.close()
c2.close()
conn2.close()
print("Connection closed")

Body:
The error is trying to tell you that two arrays are being used together where they should be the same size but they are different (e.g. x+y where x and y are numpy arrays of different sizes will give an error).

It's hard to say for sure where this is happening without further information but at a guess, this looks wrong:

knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(x,y)

knn2 = KNeighborsClassifier(n_neighbors=5)
knn2.fit(x,y)

b = (knn.predict([x,y]))[0]
u = (knn2.predict([x,y]))[0]

Specifically, having done fit using (x,y), its unlikely that you mean to do predict using both x and y also, you'd normally call predict with just x (or better, a test set that is distinct from but statistically related to the original x).

See the Iris example here for more information:

http://scikit-learn.org/stable/tutorial/statistical_inference/supervised_learning.html


问:
Replace current super class of an individual with the inferred superclass
Greetings Professor Ignazio Palmisano,

Kindly i have a question in regards to owl-API V5

Scenario:

I have an owl ontology that contains some individuals and some defined classes (has equivalent axioms).

i add a new individual "X" as a subclass of Thing, and i add the individual properties.

i initialise the reasoner and precomputeInferences()

Goal:

if the new individual "X" was classified under an existing defined class, i want to retrieve this inferred class and replace the current individual superclass Thing with the inferred superclass.

Main question:

1) Kindly what is the best way to do this?

Sub question:

2) do i have to save the new inferred ontology and then deal with it as asserted, in order to retrieve that class? i do not like to do this since my interest is only to replace the current individual superclass with the inferred superclass.

i was trying to find how to do this, i came across:
EntitySearcher.getTypes(OWLIndividual, OWLOntology), however this retrieves only the original asserted superclass not the inferred.

Thanks for your time.

Sincere regards.

答:
In order to replace the asserted class with the inferred one (or ones - there might be more than one), you need to do the following:

Retrieve the inferred types

Remove asserted types

Add inferred types

So, called r the OWLReasoner instance, i the OWLIndividual, t its original type and T the inferred type:

```<code>OWLOntology o = ...
OWLReasoner r = ...
// This returns the node of direct types - i.e., the set of equivalent classes that are the most specific named types including i among their instances
// This will always be a Node even for a single class. If the reasoner can infer that there are equivalent classes, they all will appear in the Node
Node<OWLClass> types = r.getTypes(i, true);

// remove existing type assertions
o.removeAxioms(o.getClassAssertionAxioms(i));

// add the new ones
OWLDataFactory df = ...
Stream<OWLAxiom> axiomsToAdd = types.entities().map(T->df.getOWLClassAssertionAxiom(T, i));
o.addAxioms(OWLAPIStreamUtils.asList(axiomsToAdd));
</code>```

Now o contains the new assertions in place of the old ones. Save or further elaborate the ontology as needed.

Body:
In order to replace the asserted class with the inferred one (or ones - there might be more than one), you need to do the following:

Retrieve the inferred types

Remove asserted types

Add inferred types

So, called r the OWLReasoner instance, i the OWLIndividual, t its original type and T the inferred type:

OWLOntology o = ...
OWLReasoner r = ...
// This returns the node of direct types - i.e., the set of equivalent classes that are the most specific named types including i among their instances
// This will always be a Node even for a single class. If the reasoner can infer that there are equivalent classes, they all will appear in the Node
Node<OWLClass> types = r.getTypes(i, true);

// remove existing type assertions
o.removeAxioms(o.getClassAssertionAxioms(i));

// add the new ones
OWLDataFactory df = ...
Stream<OWLAxiom> axiomsToAdd = types.entities().map(T->df.getOWLClassAssertionAxiom(T, i));
o.addAxioms(OWLAPIStreamUtils.asList(axiomsToAdd));

Now o contains the new assertions in place of the old ones. Save or further elaborate the ontology as needed.


问:
Sending message to Azure IoT hub partition
Does anyone know if there is a library that allows you to send a message to a specific partition on an IoT hub with Azure.
I was previously able to achieve this with azuresblite library, unfortunatelly which I Cannot use.
https://github.com/ppatierno/azuresblite</p>

答:
There is no way to send a message to a specific partition. Period.
Partitions are used internally to allow scaling of the IoT (Event Hub) and allow for scaling out the consumer app (the one that reads the events out of the Hub).

While you can specify a Partition Key when using Event Hub, this does identify a Partition ID. And using IoT Hub, the option to specify Partition Key is anyway hidden and you cannot influence it. Specifying a Partition Key for a message in Event Hub will just make sure that all messages with the same partition key will fall into the same partition. But you cannot tell which partition (0,1,2..n). I have seen projects which try to literary abuse the Partitions and use them as "tenants". Very wrong way of completely abusing scalability of Event Hubs.

Please do not abuse the partitioning of Event Hub (which is anyway the back-end system for an IoT Hub). Do not force Partition Keys. Thus you are unbalancing the Event Hub and may go into a wrong direction. Instead please clearly define a technical issue you are trying to solve and we may be able to help you.


问:
Unable to set MBProgressHUD mode to determinate
In a Swift 3 project I'm working on, I have a simple view controller with a MBProgressHUD. I can get the hud to show, and even though I set the mode property and the label's text, all I get is a spinning UIActivityIndicator. Does anybody know how to fix this?

```<code>// Property declaration
var transferHUD = MBProgressHUD()

// Configured in viewDidLoad()
transferHUD = MBProgressHUD.init(view: self.view)
transferHUD.mode = MBProgressHUDMode.determinate
transferHUD.hide(animated: false)

// from the progressUpdated function
transferHUD.progress = Float(progress.fractionCompleted)
transferHUD.label.text = "Transferring..."

// I logged the mode and this is what it said
// print("HUD mode -- \(transferHUD.mode)")
// Output == transferHUD mode -- MBProgressHUDMode

// Here is where I show it again. I've tried a few different ways, but neither way changes the appearance
DispatchQueue.main.async {
    // self.transferHUD.show(animated: true)
    MBProgressHUD.showAdded(to: self.view, animated: true)
}
</code>```

答:
When you call showAdded:, it will create a new instance of MBProgressHUD. You can either call the show method or change the code like:

```<code>let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.mode = MBProgressHUDMode.determinate
hud.label.text = "Transferring..."
</code>```

Body:
In a Swift 3 project I'm working on, I have a simple view controller with a MBProgressHUD. I can get the hud to show, and even though I set the mode property and the label's text, all I get is a spinning UIActivityIndicator. Does anybody know how to fix this?

// Property declaration
var transferHUD = MBProgressHUD()

// Configured in viewDidLoad()
transferHUD = MBProgressHUD.init(view: self.view)
transferHUD.mode = MBProgressHUDMode.determinate
transferHUD.hide(animated: false)

// from the progressUpdated function
transferHUD.progress = Float(progress.fractionCompleted)
transferHUD.label.text = "Transferring..."

// I logged the mode and this is what it said
// print("HUD mode -- \(transferHUD.mode)")
// Output == transferHUD mode -- MBProgressHUDMode

// Here is where I show it again. I've tried a few different ways, but neither way changes the appearance
DispatchQueue.main.async {
    // self.transferHUD.show(animated: true)
    MBProgressHUD.showAdded(to: self.view, animated: true)
}

Body:
When you call showAdded:, it will create a new instance of MBProgressHUD. You can either call the show method or change the code like:

let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.mode = MBProgressHUDMode.determinate
hud.label.text = "Transferring..."


问:
Naming Laravel view routes when using resource routes

Problem

I have been struggling all day to find a good convention to name view routes in Laravel (5.4).

Let's say that I am using resource routes. But I also need to declare a lot of view routes, what is a safe and best practice for declaring such routes?

Example:

I have the following resource routes:

```<code>GET /tickets/12/messages
GET /tickets/12/messages/5
POST /tickets/12/messages
PUT /tickets/12/messages/5
PATCH /tickets/12/messages/5
DELETE /tickets/12/messages/5
</code>```

I also need to define routes for:

Displaying the view to edit a particular message.

Displaying the view to add a particular message to a ticket.

Displaying the view to create a particular ticket.

Displaying the view to show all the tickets in the system.

Displaying the view to show all the tickets that belong to a particular user.

And many others... The question is: How would you define the routes I described?

Many thanks!

答:
IMHO you can try to use nested resources, in your case:

```<code>Route::resource('tickets.messages', 'TicketMessageController');
Route::resource('users.tickets', 'UserTicketController');
</code>```

they generate this kind of routes:

```<code>tickets/{ticket}/messages/{message}
users/{user}/tickets/{ticket}
</code>```

In the controller you will have both parameters injected in function calls, i.e.:

```<code>class TicketMessageController

// show message for ticket
public function show(Ticket $ticket, Message $message)

// show all messages for a ticket
public function index(Ticket $ticket)
</code>```

Its documented only for Laravel 5.1 but it works with 5.4

As always you can review all the generated routes with php artisan route:list

Body:
Problem

I have been struggling all day to find a good convention to name view routes in Laravel (5.4).

Let's say that I am using resource routes. But I also need to declare a lot of view routes, what is a safe and best practice for declaring such routes?

Example:

I have the following resource routes:

GET /tickets/12/messages
GET /tickets/12/messages/5
POST /tickets/12/messages
PUT /tickets/12/messages/5
PATCH /tickets/12/messages/5
DELETE /tickets/12/messages/5

I also need to define routes for:

Displaying the view to edit a particular message.

Displaying the view to add a particular message to a ticket.

Displaying the view to create a particular ticket.

Displaying the view to show all the tickets in the system.

Displaying the view to show all the tickets that belong to a particular user.

And many others... The question is: How would you define the routes I described?

Many thanks!

Body:
IMHO you can try to use nested resources, in your case:

Route::resource('tickets.messages', 'TicketMessageController');
Route::resource('users.tickets', 'UserTicketController');

they generate this kind of routes:

tickets/{ticket}/messages/{message}
users/{user}/tickets/{ticket}

In the controller you will have both parameters injected in function calls, i.e.:

class TicketMessageController

// show message for ticket
public function show(Ticket $ticket, Message $message)

// show all messages for a ticket
public function index(Ticket $ticket)

Its documented only for Laravel 5.1 but it works with 5.4

As always you can review all the generated routes with php artisan route:list


问:
Test PendingIntent send without sleep
I got the following test case:

```<code>Intent intent = new Intent("test");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("test");
testReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    recieved=true;
  }
};
getContext().registerReceiver(testReceiver,intentFilter );
pendingIntent.send();
Thread.sleep(100);

assertTrue(recieved);
</code>```

Is there a way to make this test pass without the Thread.sleep ?

答:
You can use a CountDownLatch to wait on something like that to occur.  You initialize it with a count.  The await() methods will wait on the count to hit 0.  When it does they stop blocking (or if you specify a timeout it will return false if it timed out before the count reached 0).

Here's your sample code modified to use a CountDownLatch:

```<code>CountIntent intent = new Intent("test");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("test");

final CountDownLatch countDownLatch = new CountDownLatch(1);
testReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    countDownLatch.countDown();
  }
};
getContext().registerReceiver(testReceiver,intentFilter );
pendingIntent.send();

assertTrue(countDownLatch.await(1, TimeUnit.SECONDS));
</code>```

Title: Test PendingIntent send without sleep

Body:
I got the following test case:

Intent intent = new Intent("test");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("test");
testReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    recieved=true;
  }
};
getContext().registerReceiver(testReceiver,intentFilter );
pendingIntent.send();
Thread.sleep(100);

assertTrue(recieved);

Is there a way to make this test pass without the Thread.sleep ?

Body:
You can use a CountDownLatch to wait on something like that to occur.  You initialize it with a count.  The await() methods will wait on the count to hit 0.  When it does they stop blocking (or if you specify a timeout it will return false if it timed out before the count reached 0).

Here's your sample code modified to use a CountDownLatch:

CountIntent intent = new Intent("test");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("test");

final CountDownLatch countDownLatch = new CountDownLatch(1);
testReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    countDownLatch.countDown();
  }
};
getContext().registerReceiver(testReceiver,intentFilter );
pendingIntent.send();

assertTrue(countDownLatch.await(1, TimeUnit.SECONDS));


问:
Rails - Updating a value through rails seed for a given user
Apologies for the question, I'm still learning rails. Trying to update a specific user's home cities through a drop down. I followed all the steps as outlined in this question How to have a drop down <select> field in a rails form? and I'm not getting any errors. However, when I go to my rails console and do User.first - the homecities_id is still set as nil. Thank you guys so much for your help.

edit.html.erb

```<code><div class="field">
  <%= f.label :homecity %><br>
  <%= f.collection_select :homecities_id, Homecity.all, :id, :Hometown %>
</div>
</code>```

User.rb

```<code>class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
  :recoverable, :rememberable, :trackable,
  :validatable, :omniauthable, omniauth_providers: [:facebook]

  cattr_accessor :current_user

  belongs_to :homecity, optional: true
end
</code>```

Homecity.rb

```<code>class Homecity < ApplicationRecord
  has_many :users
end
</code>```

Application_controller.rb

```<code>class ApplicationController < ActionController::Base
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :name, :avatar, :homecities])
    devise_parameter_sanitizer.permit(:account_update, keys: [:username,:name, :avatar, :homecities])
  end
end
</code>```

Migrations

```<code>class CreateHomecities < ActiveRecord::Migration[5.0]
  def change
    create_table :homecities do |t|
      t.string :Hometown
      t.timestamps
    end
  end
end

class AddHomecitiesRefToUsers < ActiveRecord::Migration[5.0]
  def change
    add_reference :users, :homecities, foreign_key: true
  end
end
</code>```

seed.rb

```<code>Homecity.destroy_all
bigapple = Homecity.create!(Hometown:"New York City")
techhub = Homecity.create!(Hometown:"San Francisco")
longhorns = Homecity.create!(Hometown:"Austin")
angels = Homecity.create!(Hometown:"Los Angeles")
windycity = Homecity.create!(Hometown:"Chicago")
hcards = Homecity.create!(Hometown:"Washington DC")
amazon = Homecity.create!(Hometown:"Seattle")
</code>```

答:
Since it's a belongs_to it's only one homecity and it's actually the homecity_id you're trying to pass to devise.

So instead of...

```<code>class ApplicationController < ActionController::Base
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :name, :avatar, :homecities])
    devise_parameter_sanitizer.permit(:account_update, keys: [:username,:name, :avatar, :homecities])
  end
end
</code>```

You should do...

```<code>class ApplicationController < ActionController::Base
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :name, :avatar, :homecity_id])
    devise_parameter_sanitizer.permit(:account_update, keys: [:username,:name, :avatar, :homecity_id])
  end
end
</code>```

And you'll need to modify your edit view to the singular...

```<code><%= f.collection_select :homecity_id, Homecity.all, :id, :Hometown %>
</code>```

Finally, do rake db:rollback and change homecities to homecity in your migration and then do rake db:migrate again.

Body:
Apologies for the question, I'm still learning rails. Trying to update a specific user's home cities through a drop down. I followed all the steps as outlined in this question How to have a drop down <select> field in a rails form? and I'm not getting any errors. However, when I go to my rails console and do User.first - the homecities_id is still set as nil. Thank you guys so much for your help.

edit.html.erb

  <%= f.label :homecity %>

  <%= f.collection_select :homecities_id, Homecity.all, :id, :Hometown %>

User.rb

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
  :recoverable, :rememberable, :trackable,
  :validatable, :omniauthable, omniauth_providers: [:facebook]

  cattr_accessor :current_user

  belongs_to :homecity, optional: true
end

Homecity.rb

class Homecity < ApplicationRecord
  has_many :users
end

Application_controller.rb

class ApplicationController < ActionController::Base
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :name, :avatar, :homecities])
    devise_parameter_sanitizer.permit(:account_update, keys: [:username,:name, :avatar, :homecities])
  end
end

Migrations

class CreateHomecities < ActiveRecord::Migration[5.0]
  def change
    create_table :homecities do |t|
      t.string :Hometown
      t.timestamps
    end
  end
end

class AddHomecitiesRefToUsers < ActiveRecord::Migration[5.0]
  def change
    add_reference :users, :homecities, foreign_key: true
  end
end

seed.rb

Homecity.destroy_all
bigapple = Homecity.create!(Hometown:"New York City")
techhub = Homecity.create!(Hometown:"San Francisco")
longhorns = Homecity.create!(Hometown:"Austin")
angels = Homecity.create!(Hometown:"Los Angeles")
windycity = Homecity.create!(Hometown:"Chicago")
hcards = Homecity.create!(Hometown:"Washington DC")
amazon = Homecity.create!(Hometown:"Seattle")

Body:
Since it's a belongs_to it's only one homecity and it's actually the homecity_id you're trying to pass to devise.

So instead of...

class ApplicationController < ActionController::Base
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :name, :avatar, :homecities])
    devise_parameter_sanitizer.permit(:account_update, keys: [:username,:name, :avatar, :homecities])
  end
end

You should do...

class ApplicationController < ActionController::Base
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :name, :avatar, :homecity_id])
    devise_parameter_sanitizer.permit(:account_update, keys: [:username,:name, :avatar, :homecity_id])
  end
end

And you'll need to modify your edit view to the singular...

<%= f.collection_select :homecity_id, Homecity.all, :id, :Hometown %>

Finally, do rake db:rollback and change homecities to homecity in your migration and then do rake db:migrate again.


问:
What's the difference between RewriteRule and redirect 301
I was using something like this...

```<code>RewriteRule here/(.*) http://www.there.com/$1 [R=301,L]
</code>```

but couldn't get it to work

So I used this...

```<code>redirect 301 /here http://www.there.com
</code>```

and it worked fine.

Can someone explain the difference?
Do you need both?

Also... how do I exclude paths from the redirect?

Like...
redirect 301 all...

```<code>redirect 301 /here http://www.there.com
</code>```

but

```<code>/here/stayhere.html
</code>```

Thanks

答:
RewriteRule is handled by Apache's mod_rewrite, while Redirect is handled by mod_alias. No, you don't need both.

Your RewriteRule (which uses regex) will not match /here (but will match such paths as /here/foo.html) because it is looking for a slash immediately after. You can make that optional by using a question mark:

```<code>RewriteRule ^here(/?.*) http://www.there.com$1 [R=301,L]
</code>```

Now that will have the same effect as your Redirect. RewriteCond can be added to exclude certain paths:

```<code>RewriteCond $0 !/here/stayhere\.html
</code>```

Note that some servers do not have mod_rewrite turned on by default. If adding RewriteEngine on to your configuration does not fix the problem and you cannot switch mod_rewrite on, at least mod_alias provides the RedirectMatch directive, which may be good enough:

```<code>RedirectMatch 301 ^/here(?!/stayhere\.html)(/?.*) http://www.there.com$1
</code>```

Body:
I was using something like this...

RewriteRule here/(.*) http://www.there.com/$1 [R=301,L]

but couldn't get it to work

So I used this...

redirect 301 /here http://www.there.com

and it worked fine.

Can someone explain the difference?
Do you need both?

Also... how do I exclude paths from the redirect?

Like...
redirect 301 all...

redirect 301 /here http://www.there.com

but

/here/stayhere.html

Thanks

Body:
RewriteRule is handled by Apache's mod_rewrite, while Redirect is handled by mod_alias. No, you don't need both.

Your RewriteRule (which uses regex) will not match /here (but will match such paths as /here/foo.html) because it is looking for a slash immediately after. You can make that optional by using a question mark:

RewriteRule ^here(/?.*) http://www.there.com$1 [R=301,L]

Now that will have the same effect as your Redirect. RewriteCond can be added to exclude certain paths:

RewriteCond $0 !/here/stayhere\.html

Note that some servers do not have mod_rewrite turned on by default. If adding RewriteEngine on to your configuration does not fix the problem and you cannot switch mod_rewrite on, at least mod_alias provides the RedirectMatch directive, which may be good enough:

RedirectMatch 301 ^/here(?!/stayhere\.html)(/?.*) http://www.there.com$1


问:
json2html from json file (python on server side)
I have the python code where I pass the json file

```<code>def home():
    with open('file.json', 'a+') as f:
        return render_template('index.html', json_data=f.read())
</code>```

The file look like this

```<code>{"hosts": [{"shortname": "serv1", "ipadr": "10.0.0.1", "longname": "server1"}, {"shortname": "serv2", "ipadr": "10.0.0.2", "longname": "server2"}]}
</code>```

On the client side, I wrote this code

```<code><table id="placar" class="table table-condensed  table-bordered">
      <thead>
        <tr>
          <th>shortname</th>
          <th>longname</th>
          <th>ipadress</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
</div>
<script>
var data = {{ json_data }}

var transform = {
    tag: 'tr',
    children: [{
        "tag": "td",
            "html": "${shortname}"
    }, {
        "tag": "td",
            "html": "${ipadr}"
    }, {
        "tag": "td",
            "html": "${longname}"
    }]
};

$('#placar > tbody ').json2html(data, transform);
</script>
</code>```

But it doesn't work with my file, if write the simple array it works perfectly. Can anyone say what I did wrong, pass the file or create a table?

答:
You're gonna want to transform the data.hosts rather than just the data object like so

```<code>$('#placar > tbody ').json2html(data.hosts, transform);
</code>```

so all together you'll have

```<code>var data = {"hosts": [{"shortname": "serv1", "ipadr": "10.0.0.1", "longname": "server1"}, {"shortname": "serv2", "ipadr": "10.0.0.2", "longname": "server2"}]};

var transform = {
    tag: 'tr',
    children: [{
        "tag": "td",
            "html": "${shortname}"
    }, {
        "tag": "td",
            "html": "${ipadr}"
    }, {
        "tag": "td",
            "html": "${longname}"
    }]
};

$('#placar > tbody ').json2html(data.hosts, transform);
</code>```

Body:
I have the python code where I pass the json file

def home():
    with open('file.json', 'a+') as f:
        return render_template('index.html', json_data=f.read())

The file look like this

{"hosts": [{"shortname": "serv1", "ipadr": "10.0.0.1", "longname": "server1"}, {"shortname": "serv2", "ipadr": "10.0.0.2", "longname": "server2"}]}

On the client side, I wrote this code

          shortname
          longname
          ipadress

But it doesn't work with my file, if write the simple array it works perfectly. Can anyone say what I did wrong, pass the file or create a table?

Body:
You're gonna want to transform the data.hosts rather than just the data object like so

$('#placar > tbody ').json2html(data.hosts, transform);

so all together you'll have

var data = {"hosts": [{"shortname": "serv1", "ipadr": "10.0.0.1", "longname": "server1"}, {"shortname": "serv2", "ipadr": "10.0.0.2", "longname": "server2"}]};

var transform = {
    tag: 'tr',
    children: [{
        "tag": "td",
            "html": "${shortname}"
    }, {
        "tag": "td",
            "html": "${ipadr}"
    }, {
        "tag": "td",
            "html": "${longname}"
    }]
};

$('#placar > tbody ').json2html(data.hosts, transform);


问:
Python nested dictionary traversal
I am new to python and I am having some trouble with finding a nice way to complete my task

given i have a dictionary similar to this

```<code>x = {
"rackList": [
    {
        "rackType": "apc",
        "serverList": [
            {
                "serverType": "x4950",
                "serverIp": "192.168.0.1",
            }
        ],
        "position": 1
    },
    {
        "rackType": "apc",
        "serverList": [
            {
                "serverType": "x4950",
                "serverIp": "192.168.0.2",
            }
        ],
        "position": 2
    },
    {
        "rackType": "apc",
        "serverList": [
            {
                "serverType": "x4950",
                "serverIp": "192.168.0.3",
            }
        ],
        "position": 3
    },
    {
        "rackType": "apc",
        "serverList": [
            {
                "serverType": "x4950",
                "serverIp": "192.168.0.4",
            }
        ],
        "position": 4
    }
]}
</code>```

I need to extract the server IP from each serverList, so currently I am doing this:

```<code>y = []

for i in x['rackList']:
    for j in i['serverList']:
        y.append(j['serverIp'])
</code>```

I would like to know if there is a more python like or more elagent way of achieving the same result.

Thanks in advance

答:
Yes, it's called a list comprehension:</p>

```<code>y = [server['serverIp'] for rack in x['rackList'] for server in rack['serverList']]
# ['192.168.0.1', '192.168.0.2', '192.168.0.3', '192.168.0.4']
</code>```

Title: Python nested dictionary traversal

Body:
I am new to python and I am having some trouble with finding a nice way to complete my task

given i have a dictionary similar to this

x = {
"rackList": [
    {
        "rackType": "apc",
        "serverList": [
            {
                "serverType": "x4950",
                "serverIp": "192.168.0.1",
            }
        ],
        "position": 1
    },
    {
        "rackType": "apc",
        "serverList": [
            {
                "serverType": "x4950",
                "serverIp": "192.168.0.2",
            }
        ],
        "position": 2
    },
    {
        "rackType": "apc",
        "serverList": [
            {
                "serverType": "x4950",
                "serverIp": "192.168.0.3",
            }
        ],
        "position": 3
    },
    {
        "rackType": "apc",
        "serverList": [
            {
                "serverType": "x4950",
                "serverIp": "192.168.0.4",
            }
        ],
        "position": 4
    }
]}

I need to extract the server IP from each serverList, so currently I am doing this:

y = []

for i in x['rackList']:
    for j in i['serverList']:
        y.append(j['serverIp'])

I would like to know if there is a more python like or more elagent way of achieving the same result.

Thanks in advance

Body:
Yes, it's called a list comprehension:

y = [server['serverIp'] for rack in x['rackList'] for server in rack['serverList']]
# ['192.168.0.1', '192.168.0.2', '192.168.0.3', '192.168.0.4']


问:
Required Attribute Not work in Safari Browser
I have tried following code for make the required field to notify the required field but its not working in safari browser.
Code:

```<code> <form action="" method="POST">
        <input  required />Your name:
        <br />
        <input type="submit" />
    </form>
</code>```

Above the code work in firefox. http://jsfiddle.net/X8UXQ/179/

Can you let me know the javascript code or any workarround? am new in javascript

Thanks

答:
The new Safari 10.1 released Mar 26, 2017, now supports the "required" attribute.

http://caniuse.com/#search=required

Body:
I have tried following code for make the required field to notify the required field but its not working in safari browser.
Code:

 <form action="" method="POST">
        <input  required />Your name:

        <input type="submit" />
    </form>

Above the code work in firefox. http://jsfiddle.net/X8UXQ/179/

Can you let me know the javascript code or any workarround? am new in javascript

Thanks


问:
How to only make one legend name italic in base R plot?
I want to add a legend to a plot in which only one of the legend names is italicized. I'm using plot() in base R.

However, I need that italicized line to contain variable numbers, so I use bquote.

What I've tried does not work:

```<code>  a <- 2 ; b <- 5
  plot(a,b)
  l1 <- bquote(Italic ~ .(a) + .(b))
  l2 <- bquote(a + b)
  legend(x='topright',legend = bquote(italic(.(l1))))
  legend(x='topleft',legend = c(bquote(italic(.(l1))),l2))
</code>```

Notice that when I leave the expression on its own (RIGHT LEGEND), it italicizes correctly. However, when I add the text for other legend lines, it messes up (LEFT LEGEND).

How do I properly do this?

 Note: I'd rather have a solution that doesn't require multiple calls to legend().

答:
You should use as.expression to coerce everything into an expression object.

```<code>a <- 2
b <- 5
plot(a,b)
legend("topleft", legend = c(as.expression(bquote(italic("Italic: "*.(a)*" + "*.(b)))),
    as.expression(bquote("Non Italic: "*.(a)*" + "*.(b)))) )
</code>```

To modify your example

```<code>a <- 2
b <- 5
plot(a,b)
l1 <- bquote(Italic ~ .(a) + .(b))
l2 <- bquote(a + b)
legend("topleft", legend =  c(as.expression(bquote(italic(.(l1)))),
                            as.expression(bquote(.(l2))) ))
</code>```

Body:
I want to add a legend to a plot in which only one of the legend names is italicized. I'm using plot() in base R.

However, I need that italicized line to contain variable numbers, so I use bquote.

What I've tried does not work:

  a <- 2 ; b <- 5
  plot(a,b)
  l1 <- bquote(Italic ~ .(a) + .(b))
  l2 <- bquote(a + b)
  legend(x='topright',legend = bquote(italic(.(l1))))
  legend(x='topleft',legend = c(bquote(italic(.(l1))),l2))

Notice that when I leave the expression on its own (RIGHT LEGEND), it italicizes correctly. However, when I add the text for other legend lines, it messes up (LEFT LEGEND).

How do I properly do this?

 Note: I'd rather have a solution that doesn't require multiple calls to legend().

Body:
You should use as.expression to coerce everything into an expression object.

a <- 2
b <- 5
plot(a,b)
legend("topleft", legend = c(as.expression(bquote(italic("Italic: "*.(a)*" + "*.(b)))),
    as.expression(bquote("Non Italic: "*.(a)*" + "*.(b)))) )

To modify your example

a <- 2
b <- 5
plot(a,b)
l1 <- bquote(Italic ~ .(a) + .(b))
l2 <- bquote(a + b)
legend("topleft", legend =  c(as.expression(bquote(italic(.(l1)))),
                            as.expression(bquote(.(l2))) ))


问:
Waterline Update Through Association
I have a through association for two objects, Assignment and Tags. They are joined through the model AssignmentTag. I am able to read & write between these objects fine, but when I try to update, it doesn't drop the existing associations prior see notes for .update().

I believe I should be able to pass an array of Tag IDs to the Assignment model and it drop the current associations and update the new associations.

```<code>    Assignment.update({id: req.param("assignmentId")}, {tags: tags})
                .exec(function (err, updated) {
                    if (err) {
                        return res.serverError(err);
                    }

                    return res.json({
                        updated
                    }
                });
</code>```

Assignment.js model is:

```<code>    module.exports = {
        connection: db_connection,
        tableName: 'assignments',
        attributes: {
            id: {
                type: 'integer',
                primaryKey: true,
                autoIncrement: true,
                unique: true
            },
            title: {
                type: 'string'
            }, // varchar(255)
            description: {
                type: 'text'
            }, // text
            // an assignment may have many tags
            tags: {
                collection: 'tag',
                via: 'assignment',
                through: 'assignmenttag'
            },
        }
    };
</code>```

Tag.js model is:

```<code>    module.exports = {
        connection: db_connection,
        tableName: 'tags',
        attributes: {
            id: {
                type: 'integer',
                primaryKey: true,
                autoIncrement: true,
                unique: true
            },
            title: {
                type: 'string'
            }, // varchar(255)
            description: {
                type: 'text'
            }, // text
            // A tag may have many assignments
            assignments: {
                collection: 'assignment',
                via: 'tag',
                through: 'assignmenttag'
            },
        }
    };
</code>```

AssignmentTag.js model is:

```<code>    module.exports = {
        connection: db_conection,
        tableName: 'assignment_tag',
        attributes: {
            id: {
                type: 'integer',
                primaryKey: true,
                autoIncrement: true,
                unique: true
            },
            assignment: {
                columnName: 'assignment_id',
                model: 'assignment'
            },
            tag: {
                columnName: 'tag_id',
                model: 'tag'
            },
        }
    };
</code>```

Any idea why tag associations aren't dropping on .update()?

UPDATE: I have created an Issue on the Waterline project to get some further help. I have isolated the issue in a Repository that is linked on the Waterline issue. https://github.com/balderdashy/waterline/issues/1453

RESOLVED: Waterline was responsive after about a week and updated the model associations to accommodate this request. See issue: https://github.com/balderdashy/waterline/issues/1453. They apparently are re-writing these associations in an upcoming release so this issue should be obsolete.

答: This was resolved via the following issue posted on the Waterline repo: https://github.com/balderdashy/waterline/issues/1453.</p>

Title: Waterline Update Through Association

Body:
I have a through association for two objects, Assignment and Tags. They are joined through the model AssignmentTag. I am able to read & write between these objects fine, but when I try to update, it doesn't drop the existing associations prior see notes for .update().

I believe I should be able to pass an array of Tag IDs to the Assignment model and it drop the current associations and update the new associations.

    Assignment.update({id: req.param("assignmentId")}, {tags: tags})
                .exec(function (err, updated) {
                    if (err) {
                        return res.serverError(err);
                    }

                    return res.json({
                        updated
                    }
                });

Assignment.js model is:

    module.exports = {
        connection: db_connection,
        tableName: 'assignments',
        attributes: {
            id: {
                type: 'integer',
                primaryKey: true,
                autoIncrement: true,
                unique: true
            },
            title: {
                type: 'string'
            }, // varchar(255)
            description: {
                type: 'text'
            }, // text
            // an assignment may have many tags
            tags: {
                collection: 'tag',
                via: 'assignment',
                through: 'assignmenttag'
            },
        }
    };

Tag.js model is:

    module.exports = {
        connection: db_connection,
        tableName: 'tags',
        attributes: {
            id: {
                type: 'integer',
                primaryKey: true,
                autoIncrement: true,
                unique: true
            },
            title: {
                type: 'string'
            }, // varchar(255)
            description: {
                type: 'text'
            }, // text
            // A tag may have many assignments
            assignments: {
                collection: 'assignment',
                via: 'tag',
                through: 'assignmenttag'
            },
        }
    };

AssignmentTag.js model is:

    module.exports = {
        connection: db_conection,
        tableName: 'assignment_tag',
        attributes: {
            id: {
                type: 'integer',
                primaryKey: true,
                autoIncrement: true,
                unique: true
            },
            assignment: {
                columnName: 'assignment_id',
                model: 'assignment'
            },
            tag: {
                columnName: 'tag_id',
                model: 'tag'
            },
        }
    };

Any idea why tag associations aren't dropping on .update()?

UPDATE: I have created an Issue on the Waterline project to get some further help. I have isolated the issue in a Repository that is linked on the Waterline issue. https://github.com/balderdashy/waterline/issues/1453

RESOLVED: Waterline was responsive after about a week and updated the model associations to accommodate this request. See issue: https://github.com/balderdashy/waterline/issues/1453. They apparently are re-writing these associations in an upcoming release so this issue should be obsolete.


问:
Why should I practice Test Driven Development and how should I start?
Lots of people talk about writing tests for their code before they start writing their code. This practice is generally known as Test Driven Development or TDD for short. What benefits do I gain from writing software this way? How do I get started with this practice?</p>

答: The benefits part has recently been covered, as for where to start....on a small enterprisey system where there aren't too many unknowns so the risks are low. If you don't already know a testing framework (like NUnit), start by learning that. Otherwise start by writing your first test :)</p>


问:
Which way do you prefer to create your forms in MVC?
Which way do you prefer to create your forms in MVC?

```<code><% Html.Form() { %>
<% } %>
</code>```

Or

```<code><form action="<%= Url.Action("ManageImage", "UserAccount") %>" method="post">
</form>
</code>```

I understand that Html.Form() as of PR5 now just uses the URL provided by the request.  However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included.

What is your take?

答:
The reason for using helpers is that they allow you to encapsulate common patterns in a consistent and DRY fashion. Think of them as a way of refactoring views to remove duplication just as you would with regular code.

For example, I blogged about some RESTful NHaml helpers that can build urls based on a model.

OwnerDisplayName: Nick Berardi

Body:
Which way do you prefer to create your forms in MVC?

<% Html.Form() { %>
<% } %>

Or

<form action="<%= Url.Action("ManageImage", "UserAccount") %>" method="post">
</form>

I understand that Html.Form() as of PR5 now just uses the URL provided by the request.  However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included.

What is your take?

LastEditorDisplayName: Graphain

OwnerDisplayName: Andrew Peters


问:
What's the simplest way to return the first line of a multi-line string in Perl?
When I say simple, I mean, within an expression, so that I can stick it in as a value in a hash without preparing it first. I'll post my solution but I'm looking for a better one that reminds me less of VB.  :)</p>

答:
```<code>($str =~ /\A(.*?)$/ms)[0];
</code>```

For large strings, this will be faster than

```<code>(split /\n/, $str)[0]
</code>```

as suggested by Manni.  [Edit: removed erroneous mention of split /\n/, $str, 1.]

If you want to include the terminal \n if it is present, add \n? just before the closing paren in the regex.

OwnerDisplayName: Kev

LastEditorDisplayName: brian d foy

Body:
($str =~ /\A(.*?)$/ms)[0];

For large strings, this will be faster than

(split /\n/, $str)[0]

as suggested by Manni.  [Edit: removed erroneous mention of split /\n/, $str, 1.]

If you want to include the terminal \n if it is present, add \n? just before the closing paren in the regex.


问:
How to select data top x data after y rows from SQL Server
For example I have a table which contains 10'000 rows. I want to select top 100 rows after top 500th row. How can I do this most efficiently.

Query needed for SQL Server 2008

For example i have this query already but i wonder are there any more effective solution

```<code>SELECT TOP 100 xx
FROM nn
WHERE cc NOT IN
   (SELECT TOP 500 cc
      FROM nn ORDER BY cc ASC)
</code>```

答:
Selecting TOP 500, then concatenating the TOP 100 to the result set.

Normally, in order to worth doing this, you need to have some criteria on which to base what your need 500 records for, and only 100 for another condition. I assume that these conditions are condition1 for the TOP 500, and condition2 for the TOP 100 you want. Because the conditions differ, that is the reason why the records might not be the same based on TOP 100.

```<code>select TOP 500 *
    from MyTable
    where -- condition1 -- Retrieving the first 500 rows meeting condition1
union
    select TOP 100 *
        from MyTable
        where -- condition2 -- Retrieving the first 100 rows meeting condition2
-- The complete result set of the two queries will be combined (UNIONed) into only one result set.
</code>```

EDIT #1

this is not what i meant. i want to select top 100 rows coming after top 500 th row. so selecting rows 501-600

After your comment, I better understood what you want to achieve. Try this:

```<code>WITH Results AS (
    select TOP 600 f.*, ROW_NUMBER() OVER (ORDER BY f.[type]) as RowNumber
        from MyTable f
) select *
    from Results
    where RowNumber between 501 and 600
</code>```

Does this help?

Body:
For example I have a table which contains 10'000 rows. I want to select top 100 rows after top 500th row. How can I do this most efficiently.

Query needed for SQL Server 2008

For example i have this query already but i wonder are there any more effective solution

SELECT TOP 100 xx
FROM nn
WHERE cc NOT IN
   (SELECT TOP 500 cc
      FROM nn ORDER BY cc ASC)

Body:
Selecting TOP 500, then concatenating the TOP 100 to the result set.

Normally, in order to worth doing this, you need to have some criteria on which to base what your need 500 records for, and only 100 for another condition. I assume that these conditions are condition1 for the TOP 500, and condition2 for the TOP 100 you want. Because the conditions differ, that is the reason why the records might not be the same based on TOP 100.

select TOP 500 *
    from MyTable
    where -- condition1 -- Retrieving the first 500 rows meeting condition1
union
    select TOP 100 *
        from MyTable
        where -- condition2 -- Retrieving the first 100 rows meeting condition2
-- The complete result set of the two queries will be combined (UNIONed) into only one result set.

EDIT #1

this is not what i meant. i want to select top 100 rows coming after top 500 th row. so selecting rows 501-600

After your comment, I better understood what you want to achieve. Try this:

WITH Results AS (
    select TOP 600 f.*, ROW_NUMBER() OVER (ORDER BY f.[type]) as RowNumber
        from MyTable f
) select *
    from Results
    where RowNumber between 501 and 600

Does this help?


问:
How to print the compiled instructions of V8 to Chromium console?
I modified the V8 engine by add '--print-opt-code' to flag arrays, and now it can print the compiled code to console.Just like this picture:
enter image description here

And now I want to print these codes to Chomium console window,
enter image description here

then what should I do?
Than you very much ~~

答:
I'm sorry, that's not supported. --print-opt-code always prints to stdout; there's no way to redirect its output to the DevTools console.

(Of course you could implement that, but I think it would be quite a bit of work.)


问:
Bootstrap dropdown won't work In Node app because of jQuery
I am currently creating a node app using handlebars. For the layout, I want a Bootstrap navbar with a dropdown inside of it. The dropdown will not work because I cannot get jquery to work.

Here is my directory structure only including relevant files:

```<code>root
  ├ models
  ├ node_modules
  | ├ jquery
  ├ public
  | ├ css
  | | ├ bootstrap.css
  | ├ fonts
  | ├ js
  | | ├ bootstrap.js
  | | ├ jquery-3.1.1.js
  ├ routes
  ├ views
  ├ app.js
  ├ package.json
</code>```

As you can see, I've downloaded jquery as a module and have also added it into my public folder using the downloaded version from the website.

I've linked it on my layout.handlebars file like so:

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

I've also required it in my app.js file like so:

```<code>var $ = require('jQuery');
</code>```

Even with two methods of implementation, jQuery is still not working and is causing my dropdown to not work.

If I inspect my page, I get this message:

If I check sources, we can see my bootstrap js file and the jquery file linked, though:

Any help is appreciated!

答: After actually using my brain and reading, the error message tell me my version of Bootstrap was incompatible with my version of jQuery. See the error message in my question above for clarification.</p>

Body:
I am currently creating a node app using handlebars. For the layout, I want a Bootstrap navbar with a dropdown inside of it. The dropdown will not work because I cannot get jquery to work.

Here is my directory structure only including relevant files:

root
  ├ models
  ├ node_modules
  | ├ jquery
  ├ public
  | ├ css
  | | ├ bootstrap.css
  | ├ fonts
  | ├ js
  | | ├ bootstrap.js
  | | ├ jquery-3.1.1.js
  ├ routes
  ├ views
  ├ app.js
  ├ package.json

As you can see, I've downloaded jquery as a module and have also added it into my public folder using the downloaded version from the website.

I've linked it on my layout.handlebars file like so:

I've also required it in my app.js file like so:

var $ = require('jQuery');

Even with two methods of implementation, jQuery is still not working and is causing my dropdown to not work.

If I inspect my page, I get this message:

If I check sources, we can see my bootstrap js file and the jquery file linked, though:

Any help is appreciated!


问:
Copy data from clipboard in postman
I use Postman a lot to test APIs. In addition, to authorize those tests I have to execute a program which generates a long signature which then, I copy and paste in Header. For one or two tests, it doesn't seem too much; but doing it for multiple APIs and like multiple times makes it really hectic and stupid.

Out of curiosity, I want to do this whole process automatically. I am able to copy that signature in clipboard(Using Toolkit and Clipboard in Java), but the issue is I don't know how to get from clipboard in Postman's pre-request script. I don't really know if it's possible or not. I apologize in advance if it's redundant or seems a bit stupid, because I haven't really found anything so far and it's purely my curiosity.
Thanks in advance!!!

答: I use swagger.io instead postman for this issues. It allows to create really useful query interface for code documentation, testing and API inspecting. http://editor.swagger.io/#!/</p>

Title: Copy data from clipboard in postman