问:
Why is Entity Framework generating the [Required] attribute on my computed column?
Simplified example: I have a computed column defined as a field in my Azure SQL server table.

```<code>CREATE TABLE [dbo].[MyTable]
(
  [Id] INT NOT NULL PRIMARY KEY IDENTITY,
  [CancelledOn] DATETIME NULL,
  [MyComputedColumn] AS CASE WHEN ([CancelledOn] IS NOT NULL) THEN 'Cancelled' ELSE 'Draft' END
)
</code>```

But when I generate a code-first ADO.NET Entity Data Model in Visual Studio 2017, the property gets generated with both [Required] and [DatabaseGenerated(DatabaseGeneratedOption.Computed)] attributes.

```<code>[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[Required]
[StringLength(19)]
public string MyComputedColumn { get; set; }
</code>```

Of course, this then causes entity validation errors and various other problems.

Why would EF mark this property as [Required] when it also knows that it's a computed field?

I understand I can just delete the attribute, but I'm looking for a cleaner solution than having to manually delete the [Required] attribute from all my computed columns every time I regenerate my entity model.  Can I declare the column differently in SQL, for example?

答: Even though we know the computed column can never be null by the logic you used, EF is not that smart, so you should make the computed column nullable even though it will never be null.</p>

Body:
Simplified example: I have a computed column defined as a field in my Azure SQL server table.

CREATE TABLE [dbo].[MyTable]
(
  [Id] INT NOT NULL PRIMARY KEY IDENTITY,
  [CancelledOn] DATETIME NULL,
  [MyComputedColumn] AS CASE WHEN ([CancelledOn] IS NOT NULL) THEN 'Cancelled' ELSE 'Draft' END
)

But when I generate a code-first ADO.NET Entity Data Model in Visual Studio 2017, the property gets generated with both [Required] and [DatabaseGenerated(DatabaseGeneratedOption.Computed)] attributes.

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[Required]
[StringLength(19)]
public string MyComputedColumn { get; set; }

Of course, this then causes entity validation errors and various other problems.

Why would EF mark this property as [Required] when it also knows that it's a computed field?

I understand I can just delete the attribute, but I'm looking for a cleaner solution than having to manually delete the [Required] attribute from all my computed columns every time I regenerate my entity model.  Can I declare the column differently in SQL, for example?


来源: stackexchange

问:
Kill process using Python /F flag
I'm wondering how to do this in python.

```<code>C:\>Taskkill /IM program.exe /F
</code>```

What I have so far is this. I just don't know how to add the  /F flag

```<code>comm = "taskkill /im " + myprogram
os.system(comm)
</code>```

答:
I think this code below works :</p>

```<code>comm = “{} {}“.format(comm, " /F")
</code>```

ContentLicense: CC BY-SA 4.0

Title: Kill process using Python /F flag

Body:
I'm wondering how to do this in python.

C:\>Taskkill /IM program.exe /F

What I have so far is this. I just don't know how to add the  /F flag

comm = "taskkill /im " + myprogram
os.system(comm)

Body:
I think this code below works :

comm = “{} {}“.format(comm, " /F")


问:
Keeping track of Navigation Controllers farther down the stack
I have an iPhone app that I'm building that has the following seutp.

AppDelegate creates a Navigation Controller and sets it's root controller to a MainController

MainController creates a TabBarController
and adds 5 TableViewControllers to it

When a user clicks a row in the Table I want to push it's view onto the Navigation controller. However, it's navigationController attribute is not set, I would need to access the MainController. I can get around this  by creating a property on the TableViewController and passing down the reference to the Navigation controller, but this feels dirty, especially if I would have to keep passing it down with more and more sub controllers. There has to be a better way.

I should note that I'm not using IB on the project.

Thanks!

答:
Why not access it from the app delegate?

This should work anywhere in your code.

```<code>-(id)mainController
{
     return [[[UIApplication sharedApplication] delegate] rootViewController];
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Why not access it from the app delegate?

This should work anywhere in your code.

-(id)mainController
{
     return [[[UIApplication sharedApplication] delegate] rootViewController];
}


问:
I need an example to understand Implicit Tagging in ASN.1
I have been going through the following tutorial

http://www.obj-sys.com/asn1tutorial/node12.html

Can you help me understand implicit tagging with an example?

答:
Using the accepted answer as an example of encoding:

```<code>Image ::= SEQUENCE {
    Width  INTEGER,
    Height INTEGER,
    Title  UTF8String
}
</code>```

An example of encoding would be:

The internal sequence breaks down into:

Explicit Optional

If you then have EXPLICIT OPTIONAL values:

```<code>Image ::= SEQUENCE {
    Width  [0] EXPLICIT INTEGER OPTIONAL,
    Height [1] EXPLICIT INTEGER OPTIONAL,
    Title  UTF8String
}
</code>```

The encoded sequence might be:

SEQUENCE 30 15 A1 02 02 02 EE 0C 0E 41 20 66 75 6E 6E 79 20 6B 69 74 74 65 6E (21-bytes)

And the internal sequence breaks down into:

CONTEXT[1] INTEGER: A1 02 02 02 EE 750 (2-bytes)

UTF8STRING: 0C 0E 41 20 66 75 6E 6E 79 20 6B 69 74 74 65 6E "A funny kitten" (14-bytes)

ContentLicense: CC BY-SA 2.5

Body:
Using the accepted answer as an example of encoding:

Image ::= SEQUENCE {
    Width  INTEGER,
    Height INTEGER,
    Title  UTF8String
}

An example of encoding would be:

The internal sequence breaks down into:

Explicit Optional

If you then have EXPLICIT OPTIONAL values:

Image ::= SEQUENCE {
    Width  [0] EXPLICIT INTEGER OPTIONAL,
    Height [1] EXPLICIT INTEGER OPTIONAL,
    Title  UTF8String
}

The encoded sequence might be:

SEQUENCE 30 15 A1 02 02 02 EE 0C 0E 41 20 66 75 6E 6E 79 20 6B 69 74 74 65 6E (21-bytes)

And the internal sequence breaks down into:

CONTEXT[1] INTEGER: A1 02 02 02 EE 750 (2-bytes)

UTF8STRING: 0C 0E 41 20 66 75 6E 6E 79 20 6B 69 74 74 65 6E "A funny kitten" (14-bytes)


问:
How to ensure the table get scanned daily as the table size growing
I have a DynamoDB table which stores metadata of items in S3 (i.e. images and files). Sometime the S3 items get deleted, but the metadata is not. So I run a process which scans the entire dynamoDB table to check if the S3 object still exists. If not, delete the dynamoDB row. But as the total number of objects increased, the scan took longer time to finish. I want to ensure that everything in DynamoDB get scanned everyday, no matter how big the table is. So looks for design suggestion to rewrite the scan tool, which need to be horizontal scalable with the table.

Currently, I'm using Parallel scan feature provided by dynamoDB to split the table into 1000 parts. And add more threads to scan each more part at same time. So that by increase parallelism, the entire scan finished in shorter time. And schedule the process to run at midnight. But I can see this method will fail when the table grow exceed some threshold when scanning one part takes longer than 1 day.

答: Instead of deleting first in S3, just mark the entry deleted in dynamo DB then later use the dynamo DB change feed to find and delete the object in S3. Beside making delete from S3 reliable it will also make the synchronous delete faster and provide strong consistency on the delete operation.</p>


问:
Heroku and Github integration (how to structure the project)
I'm creating a webservice and I want to store the source on github and run the app on heroku.  I haven't seen my exact scenario addressed anywhere on the 'net so far, so I'll ask it here:

I want to have the following directory structure:

```<code>/project
  .git
  README <-- project readme file
  TODO.otl <-- project outline
  ... <-- other project-related stuff
  /my_rails_app
     app
     config
     ...
     README <-- rails' readme file
</code>```

In the above, project corresponds to http://github.com/myuser/project, and my_rails_app is the code that should be pushed to heroku.  Do I need a separate branch for the rails app, or is there a simpler way that I'm missing?

I guess my project-related non-rails files could live in my_rails_app, but the rails README already lives there and it seems inconsistent to overwrite that.  However, if I leave it, my github page for the rails app will contain the rails readme, which makes no sense.

Also ... I tried just setting it up as described above and running

```<code>git push heroku
</code>```

from the main project folder.  Of course, heroku doesn't know I want to deploy the subfolder:

```<code>-----> Heroku receiving push
 !     Heroku push rejected, no Rails or Rack app detected.
</code>```

答: Just overwrite Rails' default README file. There's no reason to keep it around. Put your other project-management-related stuff in the doc directory. While you certainly have valid reasons for wanting to set it up the way you did, you're just creating a headache for yourself by  going against convention, and it's probably not worth the benefit.

Body:
I'm creating a webservice and I want to store the source on github and run the app on heroku.  I haven't seen my exact scenario addressed anywhere on the 'net so far, so I'll ask it here:

I want to have the following directory structure:

/project
  .git
  README <-- project readme file
  TODO.otl <-- project outline
  ... <-- other project-related stuff
  /my_rails_app
     app
     config
     ...
     README <-- rails' readme file

In the above, project corresponds to http://github.com/myuser/project, and my_rails_app is the code that should be pushed to heroku.  Do I need a separate branch for the rails app, or is there a simpler way that I'm missing?

I guess my project-related non-rails files could live in my_rails_app, but the rails README already lives there and it seems inconsistent to overwrite that.  However, if I leave it, my github page for the rails app will contain the rails readme, which makes no sense.

Also ... I tried just setting it up as described above and running

git push heroku

from the main project folder.  Of course, heroku doesn't know I want to deploy the subfolder:

-----> Heroku receiving push
 !     Heroku push rejected, no Rails or Rack app detected.


问:
Deep copy object that extends javafx Pane?
I'm trying to deep copy an array of my custom object "Space", which extends javafx Pane.

I've tried using Kryo libraries, and implementing clonable. I could use work arounds that don't actually deep copy, but that will make my code 100x more janky.

Currently I have the class Space:

```<code>public class Space extends Pane {
    private boolean available = true;
    private boolean light;
    private int x;
    private int y;
    private Peice peice;
    private Label peiceImage;
    private Rectangle border;

    public Space() {}

    public Space(int x, int y, boolean light) {
        border = new Rectangle(80,80);
        if (!light) {
            border.setFill(Color.DARKGREEN);
            border.setStroke(Color.DARKGREEN);
        } else {
            border.setFill(null);
            border.setStroke(null);
        }

        peiceImage = new Label();
        peiceImage.setTranslateX(16);
        peiceImage.setTranslateY(16);
        getChildren().addAll(border,peiceImage);

        this.x = x;
        this.y = y;
        this.peice = null;
        this.light = light;
    }
    //other unimportant methods.
}
</code>```

I then try to copy in another file:

```<code>   public Space[][] copyBoard(Space[][] thisBoard) {
        Kryo kryo = new Kryo();
        Space[][] copy = new Space[8][8];
        for (int x = 0; x < 8; x++) {
            for (int y = 0; y < 8; y++) {
                Space thisSpace = thisBoard[x][y];
                try {
                    kryo.setRegistrationRequired(false);
                    copy[x][y] = kryo.copy(thisSpace); //TODO This causes exception, dosent work
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
        return copy;
    }
</code>```

Trying to use the kryo library I get this error:

```<code>com.esotericsoftware.kryo.KryoException: Class cannot be created (missing no-arg constructor): javafx.scene.layout.Region$3
</code>```

But I'm not in any way commited to using kryo.

Thanks.

答:
You can do deep copy using serialization and afterward deserialization. There are nice utils to do so on the web. For example SerializationUtils from Apache.

You can do something like the following:

Space clonedSpace = SerializationUtils.clone(space);

Docs

Body:
I'm trying to deep copy an array of my custom object "Space", which extends javafx Pane.

I've tried using Kryo libraries, and implementing clonable. I could use work arounds that don't actually deep copy, but that will make my code 100x more janky.

Currently I have the class Space:

public class Space extends Pane {
    private boolean available = true;
    private boolean light;
    private int x;
    private int y;
    private Peice peice;
    private Label peiceImage;
    private Rectangle border;

    public Space() {}

    public Space(int x, int y, boolean light) {
        border = new Rectangle(80,80);
        if (!light) {
            border.setFill(Color.DARKGREEN);
            border.setStroke(Color.DARKGREEN);
        } else {
            border.setFill(null);
            border.setStroke(null);
        }

        peiceImage = new Label();
        peiceImage.setTranslateX(16);
        peiceImage.setTranslateY(16);
        getChildren().addAll(border,peiceImage);

        this.x = x;
        this.y = y;
        this.peice = null;
        this.light = light;
    }
    //other unimportant methods.
}

I then try to copy in another file:

   public Space[][] copyBoard(Space[][] thisBoard) {
        Kryo kryo = new Kryo();
        Space[][] copy = new Space[8][8];
        for (int x = 0; x < 8; x++) {
            for (int y = 0; y < 8; y++) {
                Space thisSpace = thisBoard[x][y];
                try {
                    kryo.setRegistrationRequired(false);
                    copy[x][y] = kryo.copy(thisSpace); //TODO This causes exception, dosent work
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
        return copy;
    }

Trying to use the kryo library I get this error:

com.esotericsoftware.kryo.KryoException: Class cannot be created (missing no-arg constructor): javafx.scene.layout.Region$3

But I'm not in any way commited to using kryo.

Thanks.


问:
compare count columns not recognized
I have some Columns whose values depend on sums for the row info.  However, when I get to the where statement, it won't let me compare those values so I can just display the ones with issues. See comment *** in query for issue.

This is what my query looks like:

```<code>SELECT
    DISTINCT
    p.ID
    ,p.Last
    ,p.First
    ,SUM(distinct CASE WHEN pf.facility in ('S','H','E') then 1 ELSE 0 END) as facility_count
    ,SUM(distinct CASE WHEN (fs.ques_id = 59 AND pf.facility in ('S','H','E') ) THEN 1 ELSE 0 END) AS sum_qst_59
    FROM person p
inner JOIN person_facilities pf ON p.ID = pf.ID
LEFT JOIN dbo.ADD_ANSW fs ON p.id = fs.id

WHERE
    pf.Facility in ('s', 'h', 'e')
    AND
    pf.status in ('Active')
    AND
    facility_count != sum_qst_59 ***--this doesn't work. Says no such columns***

group by p.id, Last, First
order by Last
</code>```

I saw compare counts, but I can't figure out how to get that to work for my query and output.  Any help would be appreciated.

In other words, there are people that belong in multiple facilities (which I'm counting their facilities for each person).  Plus I'm counting how many times they have answer 59 for those same facilities.  Then I'm comparing the counts because they should be the same if they answered it for all facilities.  Then I'm finding where the counts don't match so we can fix it.

*Update -
I'm trying what was suggested but it has the error

```<code>Incorrect syntax near keyword 'having'

SELECT
    DISTINCT
    p.ID
    ,p.Last
    ,p.First
   --change in having and sum line below
    ,having SUM(distinct CASE WHEN pf.facility in ('S','H','E') then 1 ELSE 0 END) as facility_count
<>
    SUM(distinct CASE WHEN (fs.ques_id = 59 AND pf.facility in ('S','H','E') ) THEN 1 ELSE 0 END) AS sum_qst_59
    FROM person p
inner JOIN person_facilities pf ON p.ID = pf.ID
LEFT JOIN dbo.ADD_ANSW fs ON p.id = fs.id

WHERE
    pf.Facility in ('s', 'h', 'e')
    AND
    pf.status in ('Active')

group by p.id, Last, First
order by Last
</code>```

Update 2: Also tried the following but still incorrect syntax near having -

```<code>   SELECT
        DISTINCT
        p.ID
        ,p.Last
        ,p.First
        ,SUM(distinct CASE WHEN pf.facility in ('S','H','E') then 1 ELSE 0 END) as facility_count
        ,SUM(distinct CASE WHEN (fs.ques_id = 59 AND pf.facility in ('S','H','E') ) THEN 1 ELSE 0 END) AS sum_qst_59
        FROM person p
    inner JOIN person_facilities pf ON p.ID = pf.ID
    LEFT JOIN dbo.ADD_ANSW fs ON p.id = fs.id

    WHERE
        pf.Facility in ('s', 'h', 'e')
        AND
        pf.status in ('Active')
       --change in having and sum line below
        AND --this has incorrect syntax near having
         having SUM(distinct CASE WHEN pf.facility in ('S','H','E') then 1 ELSE 0 END)
<>
        SUM(distinct CASE WHEN (fs.ques_id = 59 AND pf.facility in ('S','H','E') ) THEN 1 ELSE 0 END)

    group by p.id, Last, First
    order by Last
</code>```

答:
Column aliases cannot be used to reference expressions in a WHERE clause. But even if they could you'd be wrong as filters that should take place after aggregation have to be put in a HAVING clause.

Try:

```<code>...
HAVING sum(CASE
             WHEN pf.facility IN ('S','H','E') THEN
               1
             ELSE
               0
           END)
       <>
       sum(CASE
             WHEN fs.ques_id = 59
                  AND pf.facility IN ('S','H','E') THEN
               1
             ELSE
               0
           END)
...
</code>```

sum(DISTINCT ...) also doesn't seem to make sense. And the DISTINCT in the outer SELECT also could be useless.

Title: compare count columns not recognized

Body:
I have some Columns whose values depend on sums for the row info.  However, when I get to the where statement, it won't let me compare those values so I can just display the ones with issues. See comment *** in query for issue.

This is what my query looks like:

SELECT
    DISTINCT
    p.ID
    ,p.Last
    ,p.First
    ,SUM(distinct CASE WHEN pf.facility in ('S','H','E') then 1 ELSE 0 END) as facility_count
    ,SUM(distinct CASE WHEN (fs.ques_id = 59 AND pf.facility in ('S','H','E') ) THEN 1 ELSE 0 END) AS sum_qst_59
    FROM person p
inner JOIN person_facilities pf ON p.ID = pf.ID
LEFT JOIN dbo.ADD_ANSW fs ON p.id = fs.id

WHERE
    pf.Facility in ('s', 'h', 'e')
    AND
    pf.status in ('Active')
    AND
    facility_count != sum_qst_59 ***--this doesn't work. Says no such columns***

group by p.id, Last, First
order by Last

I saw compare counts, but I can't figure out how to get that to work for my query and output.  Any help would be appreciated.

In other words, there are people that belong in multiple facilities (which I'm counting their facilities for each person).  Plus I'm counting how many times they have answer 59 for those same facilities.  Then I'm comparing the counts because they should be the same if they answered it for all facilities.  Then I'm finding where the counts don't match so we can fix it.

*Update -
I'm trying what was suggested but it has the error

Incorrect syntax near keyword 'having'

SELECT
    DISTINCT
    p.ID
    ,p.Last
    ,p.First
   --change in having and sum line below
    ,having SUM(distinct CASE WHEN pf.facility in ('S','H','E') then 1 ELSE 0 END) as facility_count
<>
    SUM(distinct CASE WHEN (fs.ques_id = 59 AND pf.facility in ('S','H','E') ) THEN 1 ELSE 0 END) AS sum_qst_59
    FROM person p
inner JOIN person_facilities pf ON p.ID = pf.ID
LEFT JOIN dbo.ADD_ANSW fs ON p.id = fs.id

WHERE
    pf.Facility in ('s', 'h', 'e')
    AND
    pf.status in ('Active')

group by p.id, Last, First
order by Last

Update 2: Also tried the following but still incorrect syntax near having -

   SELECT
        DISTINCT
        p.ID
        ,p.Last
        ,p.First
        ,SUM(distinct CASE WHEN pf.facility in ('S','H','E') then 1 ELSE 0 END) as facility_count
        ,SUM(distinct CASE WHEN (fs.ques_id = 59 AND pf.facility in ('S','H','E') ) THEN 1 ELSE 0 END) AS sum_qst_59
        FROM person p
    inner JOIN person_facilities pf ON p.ID = pf.ID
    LEFT JOIN dbo.ADD_ANSW fs ON p.id = fs.id

    WHERE
        pf.Facility in ('s', 'h', 'e')
        AND
        pf.status in ('Active')
       --change in having and sum line below
        AND --this has incorrect syntax near having
         having SUM(distinct CASE WHEN pf.facility in ('S','H','E') then 1 ELSE 0 END)
<>
        SUM(distinct CASE WHEN (fs.ques_id = 59 AND pf.facility in ('S','H','E') ) THEN 1 ELSE 0 END)

    group by p.id, Last, First
    order by Last

Body:
Column aliases cannot be used to reference expressions in a WHERE clause. But even if they could you'd be wrong as filters that should take place after aggregation have to be put in a HAVING clause.

Try:

...
HAVING sum(CASE
             WHEN pf.facility IN ('S','H','E') THEN
               1
             ELSE
               0
           END)
       <>
       sum(CASE
             WHEN fs.ques_id = 59
                  AND pf.facility IN ('S','H','E') THEN
               1
             ELSE
               0
           END)
...

sum(DISTINCT ...) also doesn't seem to make sense. And the DISTINCT in the outer SELECT also could be useless.


问:
Simple find primes implementation
i have idea "find primes between 1 and n".
    Algorithms based on residual division.
    i use 2 array pr and nt.
    [pr is saved primes. nt is saved counter number.]
    ex.
    begin with 3
    3 is primes => pr0 = 3 and nt0 = 2.
    primes >3 is odd.
    when i = 5 nt0 = nt0-1 = 1  => 5 is prime.
    And pr1 = 5, nt1 =pr1 -1 = 4.
    when i = 7 :
    nt0 = nt0 -1 = 0, => 7 is prime.
    and pr2 = 7, nt2 = 6.
    when i = 9
    nt0 < 0 => 9 is not prime. nt0 = pr0 -1 = 2, nt1 = 3, nt2 = 5.
    ....

```<code>    using System;
    namespace primes
    { // program for find primes between 1 and n.
    class Program
    {    public  static void Main()
        {
            int[] pr = new int[100], ct = new int[100];
            ct[0] = 2;
            pr[0] = 3;// 3 is primes => n[0] is 3 .
            int n = 1; // n is number of primes.
            for (int i = 5; i < 111; i += 2)
            {
                for (int l = 0; l < n; l++)
                { if (ct[l] >= 0)
                    {
                       ct[l]--  ;
                        //Console.Write("{0} ", ct[l]);
                    }
                  else
                    {
                        ct[l] = pr[l] - 1  ;
                     //  Console.Write("{0} ", ct[l]);
                        for (int a = l + 1; a < n; a++)
                        {
                            ct[a]--;
                         //   Console.Write("{0} ", ct[a]);
                        }
                    //    Console.WriteLine();
                        goto resume; // when ct <0 jump to resume
                    }
                }
           //     Console.WriteLine();
                pr[n] = i;
                ct[n] = i ;
            //    Console.Write("{0} ", ct[n]);
                n++;
            resume : ;
            }
            for (int m = 0; m < n; m++)
            {
                Console.Write(" {0}", pr[m]);
            }
            Console.ReadKey();
        }
    }
    }
</code>```

i want to print primes 3,5,7,11, 13...
but i when i run:  3 5 7 9 13 15 17 23 29 37 39 63 65 71 89.
i dont understand.
Can you help me?

答:
i was wrong when used </p>

```<code> if (ct[l] >= 0)
                    {
                       ct[l]--  ;
                        //Console.Write("{0} ", ct[l]);
                    }
                  else {
.... goto resume ;
}
</code>```

<p>"when ct[l] < 0 and ct[k]<0(k>l) =>  ct[l] = pr[l] -1.
 But ct[k] = ct[k] -1."</p>

```<code> if(v != 0)
                { v = 0;// =>i is not prime and v = 0.
                }
               else  {
                pr[n] = i;// =>i is prime
                ct[n] = i-1 ;
                n++;
</code>```

Title: Simple find primes implementation

Body:
i have idea "find primes between 1 and n".
    Algorithms based on residual division.
    i use 2 array pr and nt.
    [pr is saved primes. nt is saved counter number.]
    ex.
    begin with 3
    3 is primes => pr0 = 3 and nt0 = 2.
    primes >3 is odd.
    when i = 5 nt0 = nt0-1 = 1  => 5 is prime.
    And pr1 = 5, nt1 =pr1 -1 = 4.
    when i = 7 :
    nt0 = nt0 -1 = 0, => 7 is prime.
    and pr2 = 7, nt2 = 6.
    when i = 9
    nt0 < 0 => 9 is not prime. nt0 = pr0 -1 = 2, nt1 = 3, nt2 = 5.
    ....

    using System;
    namespace primes
    { // program for find primes between 1 and n.
    class Program
    {    public  static void Main()
        {
            int[] pr = new int[100], ct = new int[100];
            ct[0] = 2;
            pr[0] = 3;// 3 is primes => n[0] is 3 .
            int n = 1; // n is number of primes.
            for (int i = 5; i < 111; i += 2)
            {
                for (int l = 0; l < n; l++)
                { if (ct[l] >= 0)
                    {
                       ct[l]--  ;
                        //Console.Write("{0} ", ct[l]);
                    }
                  else
                    {
                        ct[l] = pr[l] - 1  ;
                     //  Console.Write("{0} ", ct[l]);
                        for (int a = l + 1; a < n; a++)
                        {
                            ct[a]--;
                         //   Console.Write("{0} ", ct[a]);
                        }
                    //    Console.WriteLine();
                        goto resume; // when ct <0 jump to resume
                    }
                }
           //     Console.WriteLine();
                pr[n] = i;
                ct[n] = i ;
            //    Console.Write("{0} ", ct[n]);
                n++;
            resume : ;
            }
            for (int m = 0; m < n; m++)
            {
                Console.Write(" {0}", pr[m]);
            }
            Console.ReadKey();
        }
    }
    }

i want to print primes 3,5,7,11, 13...
but i when i run:  3 5 7 9 13 15 17 23 29 37 39 63 65 71 89.
i dont understand.
Can you help me?

Body:
i was wrong when used

 if (ct[l] >= 0)
                    {
                       ct[l]--  ;
                        //Console.Write("{0} ", ct[l]);
                    }
                  else {
.... goto resume ;
}

"when ct[l] < 0 and ct[k]<0(k>l) =>  ct[l] = pr[l] -1.
 But ct[k] = ct[k] -1."

 if(v != 0)
                { v = 0;// =>i is not prime and v = 0.
                }
               else  {
                pr[n] = i;// =>i is prime
                ct[n] = i-1 ;
                n++;


问:
Iterators in C++ (stl) vs Java, is there a conceptual difference?
I'm returning to c++ after being away for a bit and trying to dust off the old melon.

In Java Iterator is an interface to a container having methods: hasNext(), next() and remove(). The presence of hasNext() means it has the concept of a limit for the container being traversed.

```<code>//with an Iterator
Iterator<String> iter = trees.iterator();
while (iter.hasNext())
{
    System.out.println(iter.next());
}
</code>```

In the C++ standard template library, iterators seem to represent a datatype or class the supports the operator++ and operator== but has no concept of a limit built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end.

```<code>vector<int> vec;
vector<int>::iterator iter;

// Add some elements to vector
v.push_back(1);
v.push_back(4);
v.push_back(8);

for (iter= v.begin(); iter != v.end(); iter++)
{
    cout << *i << " "; //Should output 1 4 8
}
</code>```

The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it.

It there any further subtlety to this that I am missing?

答:
A pointer to an array element is indeed an iterator into the array.

As you say, in Java, an iterator has more knowledge of the underlying container than in C++. C++ iterators are general, and a pair of iterators can denote any range: this can be a sub-range of a container, a range over multiple containers (see http://www.justsoftwaresolutions.co.uk/articles/pair_iterators.pdf or http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/zip_iterator.html) or even a range of numbers (see http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/counting_iterator.html)

The iterator categories identify what you can and can't do with a given iterator.

OwnerDisplayName: Jeff V

Body:
I'm returning to c++ after being away for a bit and trying to dust off the old melon.

In Java Iterator is an interface to a container having methods: hasNext(), next() and remove(). The presence of hasNext() means it has the concept of a limit for the container being traversed.

//with an Iterator
Iterator<String> iter = trees.iterator();
while (iter.hasNext())
{
    System.out.println(iter.next());
}

In the C++ standard template library, iterators seem to represent a datatype or class the supports the operator++ and operator== but has no concept of a limit built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end.

vector<int> vec;
vector<int>::iterator iter;

// Add some elements to vector
v.push_back(1);
v.push_back(4);
v.push_back(8);

for (iter= v.begin(); iter != v.end(); iter++)
{
    cout << *i << " "; //Should output 1 4 8
}

The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it.

It there any further subtlety to this that I am missing?

OwnerDisplayName: Anthony Williams


问:
updating multiple blank fields in one table with data from another table
I am trying to find all fields in one table that are empty and populate them with data from another table.  Here is what I have:

```<code>UPDATE t1 SET col1 = (
   SELECT col99
     FROM t2
    WHERE t1.product_ID = t2.product_ID
) WHERE col1 IS NULL
</code>```

which works perfectly for updating all the blank fields in col1 of t1.  But I also need to check for blanks in other fields and update them.  I don't want the query to update all the fields each time any one of them is blank, just the blank field.  I could run multiple queries but I have to imagine there is a cleaner, better way.

Thanks,

Matthew

答:
Try:

```<code>UPDATE t1
SET
  col1 = COALESCE(col1, (SELECT col99 FROM t2 WHERE t1.product_ID = t2.product_ID)),
  col2 = COALESCE(col2, (SELECT ...)),
  -- etc.
</code>```

Should not perform better than your initial solution. It's just doing the job with only one UPDATE query instead of several.

Body:
I am trying to find all fields in one table that are empty and populate them with data from another table.  Here is what I have:

UPDATE t1 SET col1 = (
   SELECT col99
     FROM t2
    WHERE t1.product_ID = t2.product_ID
) WHERE col1 IS NULL

which works perfectly for updating all the blank fields in col1 of t1.  But I also need to check for blanks in other fields and update them.  I don't want the query to update all the fields each time any one of them is blank, just the blank field.  I could run multiple queries but I have to imagine there is a cleaner, better way.

Thanks,

Matthew

Body:
Try:

UPDATE t1
SET
  col1 = COALESCE(col1, (SELECT col99 FROM t2 WHERE t1.product_ID = t2.product_ID)),
  col2 = COALESCE(col2, (SELECT ...)),
  -- etc.

Should not perform better than your initial solution. It's just doing the job with only one UPDATE query instead of several.


问:
Use cookie-free domains - subdomain solution not working
I'm trying to optimize an html webpage, and one of the suggestions from yslow is:

Use cookie-free domains There are 11 components that are not
  cookie-free

So I followed one of the standard solutions I've seen and created a subdomain static.mysite.com and put the images there.

But I'm still getting the exact same problem -- a cookie is still being delivered with each image, and same yslow message.

So how do I get this subdomain to be cookie free?

答: I had the same problem. The subdomain simply didn't work, so I used a different domain name and it solved the problem. </p>


答:
Below is for BigQuery Standard SQL

```<code>#standardSQL
WITH search_events AS (
  SELECT ['firstevent', 'secondevent', 'thirdevent'] search
), temp AS (
  SELECT *, REGEXP_EXTRACT(events, CONCAT(search, r',(\w*)')) FinalEvent
  FROM (
    SELECT id, [time1, time2, time3, time4, time5] times,
      (SELECT STRING_AGG(event) FROM UNNEST([event1, event2, event3, event4, event5]) event) events,
      (SELECT STRING_AGG(search) FROM UNNEST(search) search) search
    FROM `project.dataset.table`, search_events
  )
)
SELECT FinalEvent,
  times[SAFE_OFFSET(ARRAY_LENGTH(REGEXP_EXTRACT_ALL(REGEXP_EXTRACT(events, CONCAT(r'(.*?)', search, ',', FinalEvent )), ',')) + 3)] time
FROM temp
WHERE IFNULL(FinalEvent, '') != ''
</code>```

If to apply to sample data from your question - result is

```<code>Row FinalEvent  time
1   fourthevent 10:03
2   fifthevent  10:25
</code>```

So, as you can see  - all final events are extracted along with their respective times

Now, you can do here whatever analytics you need  - I was not sure about logic behind AverageTimeBetweenFinalEvents, so I am leaving this to you - especially that I think that main focus of the question was extraction of those final events

would you be able to provide the logic behind this statement please?

   times[SAFE_OFFSET(ARRAY_LENGTH(REGEXP_EXTRACT_ALL(REGEXP_EXTRACT(events, CONCAT(r'(.*?)', search, ',', FinalEvent )), ',')) + 3)] time

Sure, hope below helps to get a logic behind that expression

assemble regular expression to extract list of events happened before matched events

extract those events

extract all commas into array

calculate position of final event by taking number of commas in above array + 3 (three is to reflect number of positions in search sequence)

extract respective time as an element of times array

Title: Retrieve unknown values based on non-schema specific sequence of column values

Body:
I want to return and operate on time values based on their related event values, but only if a specific sequence of events occurs. A simplified example table below:

+--------+------------+-------+-------------+-------+-------------+-------+-------------+-------+-------------+-------+
|   id   |   event1   | time1 |   event2    | time2 |   event3    | time3 |   event4    | time4 |   event5    | time5 |
+--------+------------+-------+-------------+-------+-------------+-------+-------------+-------+-------------+-------+
| abc123 | firstevent | 10:00 | secondevent | 10:01 | thirdevent  | 10:02 | fourthevent | 10:03 | fifthevent  | 10:04 |
| abc123 | thirdevent | 10:10 | secondevent | 10:11 | thirdevent  | 10:12 | firstevent  | 10:13 | secondevent | 10:14 |
| def456 | thirdevent | 10:20 | firstevent  | 10:21 | secondevent | 10:22 | thirdevent  | 10:24 | fifthevent  | 10:25 |
+--------+------------+-------+-------------+-------+-------------+-------+-------------+-------+-------------+-------+

For this table we want to retrieve the times whenever this particular sequence of events occurs: firstevent, secondevent, thirdevent, and a final event of any non-zero value. Meaning the relevant entries returned would be the following:

+--------+------------+-------+-------------+-------+-------------+-------+-------------+-------+------------+-------+
|   id   |   event1   | time1 |   event2    | time2 |   event3    | time3 |   event4    | time4 |   event5   | time5 |
+--------+------------+-------+-------------+-------+-------------+-------+-------------+-------+------------+-------+
| abc123 | firstevent | 10:00 | secondevent | 10:01 | thirdevent  | 10:02 | fourthevent | 10:03 | null       | null  |
| null   | null       | null  | null        | null  | null        | null  | null        | null  | null       | null  |
| def456 | null       | null  | firstevent  | 10:21 | secondevent | 10:22 | thirdevent  | 10:24 | fifthevent | 10:26 |
+--------+------------+-------+-------------+-------+-------------+-------+-------------+-------+------------+-------+

As shown above the columns are irrelevant to the occurrence of the sequence, with two results being returned starting in both the event1 and event2 columns, thus the solution should be independent and support n number of columns. These values can then be aggregated by the final non-zero event that occurs in the sequence after the 3 fixed variables to give something like the following:

+-------------+-------------------------------+
| FinalEvent  | AverageTimeBetweenFinalEvents |
+-------------+-------------------------------+
| fourthevent | 1:00                          |
| fifthevent  | 2:00                          |
+-------------+-------------------------------+

Body:
Below is for BigQuery Standard SQL

#standardSQL
WITH search_events AS (
  SELECT ['firstevent', 'secondevent', 'thirdevent'] search
), temp AS (
  SELECT *, REGEXP_EXTRACT(events, CONCAT(search, r',(\w*)')) FinalEvent
  FROM (
    SELECT id, [time1, time2, time3, time4, time5] times,
      (SELECT STRING_AGG(event) FROM UNNEST([event1, event2, event3, event4, event5]) event) events,
      (SELECT STRING_AGG(search) FROM UNNEST(search) search) search
    FROM `project.dataset.table`, search_events
  )
)
SELECT FinalEvent,
  times[SAFE_OFFSET(ARRAY_LENGTH(REGEXP_EXTRACT_ALL(REGEXP_EXTRACT(events, CONCAT(r'(.*?)', search, ',', FinalEvent )), ',')) + 3)] time
FROM temp
WHERE IFNULL(FinalEvent, '') != ''

If to apply to sample data from your question - result is

Row FinalEvent  time
1   fourthevent 10:03
2   fifthevent  10:25

So, as you can see  - all final events are extracted along with their respective times

Now, you can do here whatever analytics you need  - I was not sure about logic behind AverageTimeBetweenFinalEvents, so I am leaving this to you - especially that I think that main focus of the question was extraction of those final events

would you be able to provide the logic behind this statement please?

   times[SAFE_OFFSET(ARRAY_LENGTH(REGEXP_EXTRACT_ALL(REGEXP_EXTRACT(events, CONCAT(r'(.*?)', search, ',', FinalEvent )), ',')) + 3)] time

Sure, hope below helps to get a logic behind that expression

assemble regular expression to extract list of events happened before matched events

extract those events

extract all commas into array

calculate position of final event by taking number of commas in above array + 3 (three is to reflect number of positions in search sequence)

extract respective time as an element of times array


问:
Rewrite URL with parameter
I would like to rewrite this URL:

```<code>https://example.com/forms/cus_F8fylX6aITpJOR
</code>```

to

```<code>https://example.com/assets/forms/redirect.php?id=cus_F8fylX6aITpJOR
</code>```

Here what I tried:

```<code>RewriteCond %{QUERY_STRING} id=(\w+) [NC]
RewriteRule ^assets/forms/redirect.php?id=$1 [L]
</code>```

Where's my mistake ?

Thanks for any help.

答:
Here what you'll need:</p>

```<code>Options +FollowSymLinks
RewriteEngine On
RewriteRule ^forms/([^/]+) /assets/forms/redirect.php?id=$1 [QSA,L]
</code>```

Title: Rewrite URL with parameter

Body:
I would like to rewrite this URL:

https://example.com/forms/cus_F8fylX6aITpJOR

to

https://example.com/assets/forms/redirect.php?id=cus_F8fylX6aITpJOR

Here what I tried:

RewriteCond %{QUERY_STRING} id=(\w+) [NC]
RewriteRule ^assets/forms/redirect.php?id=$1 [L]

Where's my mistake ?

Thanks for any help.

Body:
Here what you'll need:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^forms/([^/]+) /assets/forms/redirect.php?id=$1 [QSA,L]


问:
Invalid Element Type upon import of custom React component
I'm trying to render a custom nav bar in my React application and I get an Invalid Type error.

I'm aware that there are default and named imports/exports in React, however I am exporting the CustomNavBar class as default and importing it as default in App.jsx. Other posters have mentioned that it might be an issue with package versions but I don't know where to start fixing that.

App.jsx:

```<code>import Button from 'react-bootstrap/Button';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Resume from './components/Resume';
import CustomNavBar from './components/CustomNavBar';
import './App.css';

function App() {
  return (
    <div className="App">
      <Router>
        <div>
          <CustomNavBar />
          <Route exact path = "/" component={Home} />
          <Route path = "/about" component={About} />
          <Route path = "/resume" component={Resume} />
        </div>
      </Router>

    </div>
  );
}

export default App;
</code>```

Code runs as normal when the CustomNavBar component is omitted.

CustomNavBar.jsx:

```<code>import React, { Component } from 'react'
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import { Link } from 'react-router-dom';

export default class CustomNavBar extends Component {
    render() {
        return (
            <Navbar default collapseOnSelect>
                <Navbar.Header>
                    <Navbar.Brand>
                        <Link to="/">Home</Link>
                    </Navbar.Brand>
                    <Navbar.Toggle />
                </Navbar.Header>
                <Navbar.Collapse>
                    <Nav pullRight>
                        <NavItem eventKey={1} componentClass={Link} to="/">
                            Home
                        </NavItem>
                        <NavItem eventKey={2} componentClass={Link} to="/about">
                            About
                        </NavItem>
                        <NavItem eventKey={3} componentClass={Link} to="/resume">
                            Resume
                        </NavItem>
                    </Nav>
                </Navbar.Collapse>
            </Navbar>
        );
    }
}
</code>```

package.json:

```<code>{
  "name": "my_site",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "^4.3.1",
    "react": "^16.8.6",
    "react-bootstrap": "^1.0.0-beta.8",
    "react-dom": "^16.8.6",
    "react-router": "^5.0.0",
    "react-router-dom": "^4.4.0-beta.8",
    "react-scripts": "3.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

The error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of CustomNavBar.

/****SOLVED****/
Header is no longer exported from bootstrap, brand and toggle should not be contained in a div in bootstrap 4.

答:
From looking at the docs of react-bootstrap, I don't think it exposes a Navbar.Header. Could that be the problem?
I have the same hunch for NavItem. It seems to me that it should say Nav.Item.

Body:
I'm trying to render a custom nav bar in my React application and I get an Invalid Type error.

I'm aware that there are default and named imports/exports in React, however I am exporting the CustomNavBar class as default and importing it as default in App.jsx. Other posters have mentioned that it might be an issue with package versions but I don't know where to start fixing that.

App.jsx:

import Button from 'react-bootstrap/Button';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Resume from './components/Resume';
import CustomNavBar from './components/CustomNavBar';
import './App.css';

function App() {
  return (

      <Router>

          <CustomNavBar />
          <Route exact path = "/" component={Home} />
          <Route path = "/about" component={About} />
          <Route path = "/resume" component={Resume} />

      </Router>

  );
}

export default App;

Code runs as normal when the CustomNavBar component is omitted.

CustomNavBar.jsx:

import React, { Component } from 'react'
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import { Link } from 'react-router-dom';

export default class CustomNavBar extends Component {
    render() {
        return (
            <Navbar default collapseOnSelect>
                <Navbar.Header>
                    <Navbar.Brand>
                        <Link to="/">Home</Link>
                    </Navbar.Brand>
                    <Navbar.Toggle />
                </Navbar.Header>
                <Navbar.Collapse>

                        <NavItem eventKey={1} componentClass={Link} to="/">
                            Home
                        </NavItem>
                        <NavItem eventKey={2} componentClass={Link} to="/about">
                            About
                        </NavItem>
                        <NavItem eventKey={3} componentClass={Link} to="/resume">
                            Resume
                        </NavItem>

                </Navbar.Collapse>
            </Navbar>
        );
    }
}

package.json:

{
  "name": "my_site",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "^4.3.1",
    "react": "^16.8.6",
    "react-bootstrap": "^1.0.0-beta.8",
    "react-dom": "^16.8.6",
    "react-router": "^5.0.0",
    "react-router-dom": "^4.4.0-beta.8",
    "react-scripts": "3.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

The error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of CustomNavBar.

/****SOLVED****/
Header is no longer exported from bootstrap, brand and toggle should not be contained in a div in bootstrap 4.


问:
Usefulness of GraphQL
I am relatively new to learning Graphql. I am working with another developer who is designing the front end in ReactJS and backend in Django. His opinion regarding Graphql is that it is not necessary and can use MySql and Django ORM instead. I am not sure what benefit then Graphql brings if entire development can be done using only ReactJS, DjangoORM and MySql.</p>

答:
By doing a standard API you can make a design like this to get a list of users:

```<code>[
  {
    name: '',
    email: '',
    age: '',
    address: {
      street: '',
      neighbourhood: '',
      number: ''
    }
  },
  .... more results with the same structure
]
</code>```

in this case if you want to show only the user name and email getting address and age is not worth it and is a waste of resources take in mind that this is just a simple example in some cases you are going to deal with many fields.

With GraphQL you can ask and get just the information you need so you can ask just for one field and that's all you are going to get.

Title: Usefulness of GraphQL

Body:
By doing a standard API you can make a design like this to get a list of users:

[
  {
    name: '',
    email: '',
    age: '',
    address: {
      street: '',
      neighbourhood: '',
      number: ''
    }
  },
  .... more results with the same structure
]

in this case if you want to show only the user name and email getting address and age is not worth it and is a waste of resources take in mind that this is just a simple example in some cases you are going to deal with many fields.

With GraphQL you can ask and get just the information you need so you can ask just for one field and that's all you are going to get.


问:
Just run a single R command from rpy2 (not a source file)
I am very new to rpy2 and I want to use it to just run a single R command. I know the source() function which takes a file path as the argument string, but I do not want to  write a single line to a file and call source() to run that line as this looks kinda indirect way to run a single line. I am wondering whether there is another function (named run_command() in below example) which just runs the line given as the argument.

Example: run_command("a=3+5")

答:
You can run r commands by using robjects.r from rpy2</p>

```<code>from rpy2 import robjects

robjects.r('a=3+5')

#To save the output
r_result=robjects.r('a=3+5')
print(r_result[0])

8.0
</code>```

Body:
You can run r commands by using robjects.r from rpy2

from rpy2 import robjects

robjects.r('a=3+5')

#To save the output
r_result=robjects.r('a=3+5')
print(r_result[0])

8.0


问:
jquery templating - import a file?
I'm working with backbone.js, but as far as I've seen, it doesn't care what templating system you use. Currently I'm trying out mustache.js, but I'm open to other ones. I'm a little annoyed though with the way I have to put a template into a string:

```<code>var context = {
    name: this.model.get('name'),
    email: this.model.get('email')
}

var template = "<form>Name<input name='name' type='text' value='{{name}}' />Email<input name='email' type='text' value='{{email}}' /></form>";

var html = Mustache.to_html(template, context);
    $(this.el).html(html);
    $('#app').html(this.el);
</code>```

I'd like if I could load it from a different file or something somehow. I want to be able to have template files in order to simplify things. For example, if I put it all in a string, I can't have breaks (well I can have html breaks, but that's not the point). After the line starts to get very long, it becomes unmanageable.

Tips?

答:
Edit

I just found this jQuery plugin - http://markdalgleish.com/projects/tmpload/ Does exactly what you want, and can be coupled with $.tmpl

I have built a lightweight template manager that loads templates via Ajax, which allows you to separate the templates into more manageable modules. It also performs simple, in-memory caching to prevent unnecessary HTTP requests. (I have used jQuery.ajax here for brevity)

```<code>var TEMPLATES = {};

var Template = {

  load: function(url, fn) {
    if(!TEMPLATES.hasOwnProperty(url)) {
      $.ajax({
        url: url,
        success: function(data) {
          TEMPLATES[url] = data;
          fn(data);
        }
      });
    } else {
      fn(TEMPLATES[url]);
    }
  },

  render: function(tmpl, context) {
    // Apply context to template string here
    // using library such as underscore.js or mustache.js
  }

};
</code>```

You would then use this code as follows, handling the template data via callback:

```<code>Template.load('/path/to/template/file', function(tmpl) {
  var output = Template.render(tmpl, { 'myVar': 'some value' });
});
</code>```

Title: jquery templating - import a file?

Body:
I'm working with backbone.js, but as far as I've seen, it doesn't care what templating system you use. Currently I'm trying out mustache.js, but I'm open to other ones. I'm a little annoyed though with the way I have to put a template into a string:

var context = {
    name: this.model.get('name'),
    email: this.model.get('email')
}

var template = "<form>Name<input name='name' type='text' value='{{name}}' />Email<input name='email' type='text' value='{{email}}' /></form>";

var html = Mustache.to_html(template, context);
    $(this.el).html(html);
    $('#app').html(this.el);

I'd like if I could load it from a different file or something somehow. I want to be able to have template files in order to simplify things. For example, if I put it all in a string, I can't have breaks (well I can have html breaks, but that's not the point). After the line starts to get very long, it becomes unmanageable.

Tips?

Body:
Edit

I just found this jQuery plugin - http://markdalgleish.com/projects/tmpload/ Does exactly what you want, and can be coupled with $.tmpl

I have built a lightweight template manager that loads templates via Ajax, which allows you to separate the templates into more manageable modules. It also performs simple, in-memory caching to prevent unnecessary HTTP requests. (I have used jQuery.ajax here for brevity)

var TEMPLATES = {};

var Template = {

  load: function(url, fn) {
    if(!TEMPLATES.hasOwnProperty(url)) {
      $.ajax({
        url: url,
        success: function(data) {
          TEMPLATES[url] = data;
          fn(data);
        }
      });
    } else {
      fn(TEMPLATES[url]);
    }
  },

  render: function(tmpl, context) {
    // Apply context to template string here
    // using library such as underscore.js or mustache.js
  }

};

You would then use this code as follows, handling the template data via callback:

Template.load('/path/to/template/file', function(tmpl) {
  var output = Template.render(tmpl, { 'myVar': 'some value' });
});


问:
bash looping through file to find beginning of string
I have a large textfile with ~ 10,000 lines of data, whereby each line may have a different number of columns. For example:

```<code>789 KKPP 2018 08 09 10 20 30 AUTO A2987 10SM 5-MIN 22/13
790 KGOX 2018 08 09 10 20 35 AUTO P0002 21/19
...
798 KLXZ 2018 08 09 10 20 40 AUTO 18013GT 7SM 21/16 RMK A02 T02060156
799 KMNO 2018 08 09 10 20 45 AUTO 10SM P0001
...
...
</code>```

I want to loop through every line and extract the 2nd column in which the prefix "P00*" appears. For example, in the above snippet of the file, I would want:

```<code>KGOX P0002
KMNO P0001
</code>```

Which correspond to the lines 790 and 799. The number of columns are completely random, and can change from one row to the next. The most important thing is that somewhere in the row, some column of text starts with "P00".

I have a simple while read loop:

```<code> while IFS='' read -r line || [[ -n "${line}" ]];
 do
 temp=$(echo ${line} | awk '{print $7}')
 if [[ ${temp:0:3} == "P00" ]];
 then
 data=${temp}
 fi
 done
</code>```

But this gets messy quickly, as the column numbers can exceed 30. Is there a simpler way to get this information and, perhaps, write to a text file? I know awk can do something that might work but can't get anything to work properly.

答:
In  you could use awk:

```<code>awk '{match($0,/.*(P000[^ ]+).*/,a)} a[1]{print $2,a[1] }' input
KGOX P0002
KMNO P0001
</code>```

This will search for the pattern "P00* till next white space and store it into an array called "a".

Note: GNU awk is require for this to work.

Body:
I have a large textfile with ~ 10,000 lines of data, whereby each line may have a different number of columns. For example:

789 KKPP 2018 08 09 10 20 30 AUTO A2987 10SM 5-MIN 22/13
790 KGOX 2018 08 09 10 20 35 AUTO P0002 21/19
...
798 KLXZ 2018 08 09 10 20 40 AUTO 18013GT 7SM 21/16 RMK A02 T02060156
799 KMNO 2018 08 09 10 20 45 AUTO 10SM P0001
...
...

I want to loop through every line and extract the 2nd column in which the prefix "P00*" appears. For example, in the above snippet of the file, I would want:

KGOX P0002
KMNO P0001

Which correspond to the lines 790 and 799. The number of columns are completely random, and can change from one row to the next. The most important thing is that somewhere in the row, some column of text starts with "P00".

I have a simple while read loop:

 while IFS='' read -r line || [[ -n "${line}" ]];
 do
 temp=$(echo ${line} | awk '{print $7}')
 if [[ ${temp:0:3} == "P00" ]];
 then
 data=${temp}
 fi
 done

But this gets messy quickly, as the column numbers can exceed 30. Is there a simpler way to get this information and, perhaps, write to a text file? I know awk can do something that might work but can't get anything to work properly.

Body:
In  you could use awk:

awk '{match($0,/.*(P000[^ ]+).*/,a)} a[1]{print $2,a[1] }' input
KGOX P0002
KMNO P0001

This will search for the pattern "P00* till next white space and store it into an array called "a".

Note: GNU awk is require for this to work.


问:
How to add multiple google cloud datasources using spring
I have two sql datasources already working locally, but I want to deploy it to two google cloud app-engines (I have it working with one right now). What do I need to change in my application-properties to define a second google instance/database?

I already have links set up in my pom for connections called sql.instance.second and sql.database.second. I don't know how to define spring.cloud.gcp.sql... for a second app-engine. Another option I have is to not run it locally at all but just define a cloud instance when I'm defining the datasources and then define a driver for each, but I'm not too sure how to do that either.

```<code>spring.cloud.gcp.sql.instance-connection-name=@sql.instance.first@
spring.cloud.gcp.sql.database-name=@sql.database.first@

primary.datasource.jdbc-url = @mysql.host.first@
primary.datasource.username = @mysql.user.first@
primary.datasource.password = @mysql.pass.first@

secondary.datasource.jdbc-url = @mysql.host.second@
secondary.datasource.username = @mysql.user.second@
secondary.datasource.password = @mysql.pass.second@
</code>```

答:
I was able to get it working by getting rid of this dependency first

```<code><dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-gcp-starter-sql-mysql</artifactId>
</dependency>
</code>```

Then changing my application.properties to this

```<code>primary.datasource.driverClassName=com.mysql.jdbc.GoogleDriver
primary.datasource.jdbc-url = @mysql.host.first@
primary.datasource.username = @mysql.user.first@
primary.datasource.password = @mysql.pass.first@

secondary.datasource.driverClassName=com.mysql.jdbc.GoogleDriver
secondary.datasource.jdbc-url = @mysql.host.second@
secondary.datasource.username = @mysql.user.second@
secondary.datasource.password = @mysql.pass.second@
</code>```

And deleting

```<code>spring.cloud.gcp.sql.instance-connection-name=@sql.instance.first@
spring.cloud.gcp.sql.database-name=@sql.database.first@
</code>```

Change the url of @mysql.host.first@ in my pom.xml to

```<code><mysql.host.first>jdbc:google:mysql:...</mysql.host.first>
</code>```

Body:
I have two sql datasources already working locally, but I want to deploy it to two google cloud app-engines (I have it working with one right now). What do I need to change in my application-properties to define a second google instance/database?

I already have links set up in my pom for connections called sql.instance.second and sql.database.second. I don't know how to define spring.cloud.gcp.sql... for a second app-engine. Another option I have is to not run it locally at all but just define a cloud instance when I'm defining the datasources and then define a driver for each, but I'm not too sure how to do that either.

spring.cloud.gcp.sql.instance-connection-name=@sql.instance.first@
spring.cloud.gcp.sql.database-name=@sql.database.first@

primary.datasource.jdbc-url = @mysql.host.first@
primary.datasource.username = @mysql.user.first@
primary.datasource.password = @mysql.pass.first@

secondary.datasource.jdbc-url = @mysql.host.second@
secondary.datasource.username = @mysql.user.second@
secondary.datasource.password = @mysql.pass.second@

Body:
I was able to get it working by getting rid of this dependency first

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-gcp-starter-sql-mysql</artifactId>
</dependency>

Then changing my application.properties to this

primary.datasource.driverClassName=com.mysql.jdbc.GoogleDriver
primary.datasource.jdbc-url = @mysql.host.first@
primary.datasource.username = @mysql.user.first@
primary.datasource.password = @mysql.pass.first@

secondary.datasource.driverClassName=com.mysql.jdbc.GoogleDriver
secondary.datasource.jdbc-url = @mysql.host.second@
secondary.datasource.username = @mysql.user.second@
secondary.datasource.password = @mysql.pass.second@

And deleting

spring.cloud.gcp.sql.instance-connection-name=@sql.instance.first@
spring.cloud.gcp.sql.database-name=@sql.database.first@

Change the url of @mysql.host.first@ in my pom.xml to

<mysql.host.first>jdbc:google:mysql:...</mysql.host.first>


问:
Most efficient way to determine if a Lua table is empty (contains no entries)?
What's the most efficient way to determine if a table is empty (that is, currently contains neither array-style values nor dict-style values)?

Currently, I'm using next():

```<code>if not next(myTable) then
    -- Table is empty
end
</code>```

Is there a more efficient way?

Note: The # operator does not suffice here, as it only operates on the array-style values in the table - thus #{test=2} is indistinguishable from #{} because both return 0. Also note that checking if the table variable is nil does not suffice as I am not looking for nil values, but rather tables with 0 entries (i.e. {}).

答:
How about this ?</p>

```<code>if endmyTable[1] == nil then
  -- myTable is empty
end
</code>```

Body:
What's the most efficient way to determine if a table is empty (that is, currently contains neither array-style values nor dict-style values)?

Currently, I'm using next():

if not next(myTable) then
    -- Table is empty
end

Is there a more efficient way?

Note: The # operator does not suffice here, as it only operates on the array-style values in the table - thus #{test=2} is indistinguishable from #{} because both return 0. Also note that checking if the table variable is nil does not suffice as I am not looking for nil values, but rather tables with 0 entries (i.e. {}).

Body:
How about this ?

if endmyTable[1] == nil then
  -- myTable is empty
end


问:
App Crashes When Something done in onCreate (That is not declarations or initialization)but not in onClick
I am creating a calculator.As you know it has many buttons I wanted to resize according to screen sizes.I put the code in my onCreate but it just crashed.I put it in OnClickListner, it worked.I want it to happen when we start the activity.How do I fix it?

I first did it in a separate class, then a separate function in MainActivity.java.Then in onCreate.Then in OnClickListner.

I accessed everything from onCreate in the first 3 attempts.

This is my code for resizing it in onClickListner--

findViewById(R.id.btnfix).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context context = getApplicationContext();
                Button btn1 = (Button)findViewById(R.id.b1);Button btn2 = (Button) findViewById(R.id.b2);Button btn3 = (Button) findViewById(R.id.b3);Button btn4 = (Button) findViewById(R.id.b4);Button btn5 = (Button) findViewById(R.id.b5);Button btn6 = (Button) findViewById(R.id.b6);Button btn7 = (Button) findViewById(R.id.b7);Button btn8 = (Button) findViewById(R.id.b8);Button btn9 = (Button) findViewById(R.id.b9);Button btn0 = (Button) findViewById(R.id.b0);Button btnsqrt = (Button) findViewById(R.id.sqrt);Button btnexpo = (Button) findViewById(R.id.expo);Button btncb = (Button) findViewById(R.id.cb);Button btnob = (Button) findViewById(R.id.ob);Button btnadd = (Button) findViewById(R.id.add);Button btnsub = (Button) findViewById(R.id.sub);Button btnmul = (Button) findViewById(R.id.mul);Button btndiv =  (Button) findViewById(R.id.div);Button btnclr = (Button) findViewById(R.id.clr);Button btnlog = (Button) findViewById(R.id.log);

                DisplayMetrics dm = new DisplayMetrics();
                WindowManager windowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
                windowManager.getDefaultDisplay().getMetrics(dm);
                int width = dm.widthPixels;
                int btnw = width/4;

                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) btn1.getLayoutParams();
                params.width = btnw;
                btn1.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn2.getLayoutParams();
                params.width = btnw;
                btn2.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn3.getLayoutParams();
                params.width = btnw;
                btn3.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn4.getLayoutParams();
                params.width = btnw;
                btn4.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn5.getLayoutParams();
                params.width = btnw;
                btn5.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn6.getLayoutParams();
                params.width = btnw;
                btn6.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn7.getLayoutParams();
                params.width = btnw;
                btn7.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn8.getLayoutParams();
                params.width = btnw;
                btn8.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn9.getLayoutParams();
                params.width = btnw;
                btn9.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn0.getLayoutParams();
                params.width = btnw;
                btn0.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnadd.getLayoutParams();
                params.width = btnw;
                btnadd.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnsub.getLayoutParams();
                params.width = btnw;
                btnsub.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnmul.getLayoutParams();
                params.width = btnw;
                btnmul.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btndiv.getLayoutParams();
                params.width = btnw;
                btndiv.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnsqrt.getLayoutParams();
                params.width = btnw;
                btnsqrt.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnexpo.getLayoutParams();
                params.width = btnw;
                btnexpo.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnob.getLayoutParams();
                params.width = btnw;
                btnob.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btncb.getLayoutParams();
                params.width = btnw;
                btncb.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnlog.getLayoutParams();
                params.width = btnw;
                btnlog.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnclr.getLayoutParams();
                params.width = btnw;
                btnclr.setLayoutParams(params);
            }
        });
```

<p>And this in onCreate only--</p>

<pre class="lang-java prettyprint-override"><code>@Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        textArea = (TextView) findViewById(R.id.edit_text);
        errorMessageText = (TextView) findViewById(R.id.error_message);
        errorMessageText.setVisibility(View.GONE);
        Context context = getApplicationContext();
        Button btn1 = (Button)findViewById(R.id.b1);Button btn2 = (Button) findViewById(R.id.b2);Button btn3 = (Button) findViewById(R.id.b3);Button btn4 = (Button) findViewById(R.id.b4);Button btn5 = (Button) findViewById(R.id.b5);Button btn6 = (Button) findViewById(R.id.b6);Button btn7 = (Button) findViewById(R.id.b7);Button btn8 = (Button) findViewById(R.id.b8);Button btn9 = (Button) findViewById(R.id.b9);Button btn0 = (Button) findViewById(R.id.b0);Button btnsqrt = (Button) findViewById(R.id.sqrt);Button btnexpo = (Button) findViewById(R.id.expo);Button btncb = (Button) findViewById(R.id.cb);Button btnob = (Button) findViewById(R.id.ob);Button btnadd = (Button) findViewById(R.id.add);Button btnsub = (Button) findViewById(R.id.sub);Button btnmul = (Button) findViewById(R.id.mul);Button btndiv =  (Button) findViewById(R.id.div);Button btnclr = (Button) findViewById(R.id.clr);Button btnlog = (Button) findViewById(R.id.log);

        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int btnw = width/4;

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) btn1.getLayoutParams();
        params.width = btnw;
        btn1.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn2.getLayoutParams();
        params.width = btnw;
        btn2.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn3.getLayoutParams();
        params.width = btnw;
        btn3.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn4.getLayoutParams();
        params.width = btnw;
        btn4.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn5.getLayoutParams();
        params.width = btnw;
        btn5.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn6.getLayoutParams();
        params.width = btnw;
        btn6.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn7.getLayoutParams();
        params.width = btnw;
        btn7.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn8.getLayoutParams();
        params.width = btnw;
        btn8.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn9.getLayoutParams();
        params.width = btnw;
        btn9.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn0.getLayoutParams();
        params.width = btnw;
        btn0.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnadd.getLayoutParams();
        params.width = btnw;
        btnadd.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnsub.getLayoutParams();
        params.width = btnw;
        btnsub.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnmul.getLayoutParams();
        params.width = btnw;
        btnmul.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btndiv.getLayoutParams();
        params.width = btnw;
        btndiv.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnsqrt.getLayoutParams();
        params.width = btnw;
        btnsqrt.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnexpo.getLayoutParams();
        params.width = btnw;
        btnexpo.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnob.getLayoutParams();
        params.width = btnw;
        btnob.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btncb.getLayoutParams();
        params.width = btnw;
        btncb.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnlog.getLayoutParams();
        params.width = btnw;
        btnlog.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnclr.getLayoutParams();
        params.width = btnw;
        btnclr.setLayoutParams(params);
</code>```

I tried n number of times, but only worked in onClickListner.It crashed elsetime

答:
It crashes because you are trying to get the LayoutParams when the layout has not been created yet. Try adding Post to your parent layout and do your logic in there.

For example

```<code>parentLayout.post(new Runnable() {
    @Override
    public void run() {
    //your code here
    }
   });
</code>```

Body:
I am creating a calculator.As you know it has many buttons I wanted to resize according to screen sizes.I put the code in my onCreate but it just crashed.I put it in OnClickListner, it worked.I want it to happen when we start the activity.How do I fix it?

I first did it in a separate class, then a separate function in MainActivity.java.Then in onCreate.Then in OnClickListner.

I accessed everything from onCreate in the first 3 attempts.

This is my code for resizing it in onClickListner--

findViewById(R.id.btnfix).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context context = getApplicationContext();
                Button btn1 = (Button)findViewById(R.id.b1);Button btn2 = (Button) findViewById(R.id.b2);Button btn3 = (Button) findViewById(R.id.b3);Button btn4 = (Button) findViewById(R.id.b4);Button btn5 = (Button) findViewById(R.id.b5);Button btn6 = (Button) findViewById(R.id.b6);Button btn7 = (Button) findViewById(R.id.b7);Button btn8 = (Button) findViewById(R.id.b8);Button btn9 = (Button) findViewById(R.id.b9);Button btn0 = (Button) findViewById(R.id.b0);Button btnsqrt = (Button) findViewById(R.id.sqrt);Button btnexpo = (Button) findViewById(R.id.expo);Button btncb = (Button) findViewById(R.id.cb);Button btnob = (Button) findViewById(R.id.ob);Button btnadd = (Button) findViewById(R.id.add);Button btnsub = (Button) findViewById(R.id.sub);Button btnmul = (Button) findViewById(R.id.mul);Button btndiv =  (Button) findViewById(R.id.div);Button btnclr = (Button) findViewById(R.id.clr);Button btnlog = (Button) findViewById(R.id.log);

                DisplayMetrics dm = new DisplayMetrics();
                WindowManager windowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
                windowManager.getDefaultDisplay().getMetrics(dm);
                int width = dm.widthPixels;
                int btnw = width/4;

                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) btn1.getLayoutParams();
                params.width = btnw;
                btn1.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn2.getLayoutParams();
                params.width = btnw;
                btn2.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn3.getLayoutParams();
                params.width = btnw;
                btn3.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn4.getLayoutParams();
                params.width = btnw;
                btn4.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn5.getLayoutParams();
                params.width = btnw;
                btn5.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn6.getLayoutParams();
                params.width = btnw;
                btn6.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn7.getLayoutParams();
                params.width = btnw;
                btn7.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn8.getLayoutParams();
                params.width = btnw;
                btn8.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn9.getLayoutParams();
                params.width = btnw;
                btn9.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btn0.getLayoutParams();
                params.width = btnw;
                btn0.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnadd.getLayoutParams();
                params.width = btnw;
                btnadd.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnsub.getLayoutParams();
                params.width = btnw;
                btnsub.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnmul.getLayoutParams();
                params.width = btnw;
                btnmul.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btndiv.getLayoutParams();
                params.width = btnw;
                btndiv.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnsqrt.getLayoutParams();
                params.width = btnw;
                btnsqrt.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnexpo.getLayoutParams();
                params.width = btnw;
                btnexpo.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnob.getLayoutParams();
                params.width = btnw;
                btnob.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btncb.getLayoutParams();
                params.width = btnw;
                btncb.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnlog.getLayoutParams();
                params.width = btnw;
                btnlog.setLayoutParams(params);

                params = (LinearLayout.LayoutParams) btnclr.getLayoutParams();
                params.width = btnw;
                btnclr.setLayoutParams(params);
            }
        });

And this in onCreate only--

@Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        textArea = (TextView) findViewById(R.id.edit_text);
        errorMessageText = (TextView) findViewById(R.id.error_message);
        errorMessageText.setVisibility(View.GONE);
        Context context = getApplicationContext();
        Button btn1 = (Button)findViewById(R.id.b1);Button btn2 = (Button) findViewById(R.id.b2);Button btn3 = (Button) findViewById(R.id.b3);Button btn4 = (Button) findViewById(R.id.b4);Button btn5 = (Button) findViewById(R.id.b5);Button btn6 = (Button) findViewById(R.id.b6);Button btn7 = (Button) findViewById(R.id.b7);Button btn8 = (Button) findViewById(R.id.b8);Button btn9 = (Button) findViewById(R.id.b9);Button btn0 = (Button) findViewById(R.id.b0);Button btnsqrt = (Button) findViewById(R.id.sqrt);Button btnexpo = (Button) findViewById(R.id.expo);Button btncb = (Button) findViewById(R.id.cb);Button btnob = (Button) findViewById(R.id.ob);Button btnadd = (Button) findViewById(R.id.add);Button btnsub = (Button) findViewById(R.id.sub);Button btnmul = (Button) findViewById(R.id.mul);Button btndiv =  (Button) findViewById(R.id.div);Button btnclr = (Button) findViewById(R.id.clr);Button btnlog = (Button) findViewById(R.id.log);

        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int btnw = width/4;

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) btn1.getLayoutParams();
        params.width = btnw;
        btn1.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn2.getLayoutParams();
        params.width = btnw;
        btn2.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn3.getLayoutParams();
        params.width = btnw;
        btn3.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn4.getLayoutParams();
        params.width = btnw;
        btn4.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn5.getLayoutParams();
        params.width = btnw;
        btn5.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn6.getLayoutParams();
        params.width = btnw;
        btn6.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn7.getLayoutParams();
        params.width = btnw;
        btn7.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn8.getLayoutParams();
        params.width = btnw;
        btn8.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn9.getLayoutParams();
        params.width = btnw;
        btn9.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btn0.getLayoutParams();
        params.width = btnw;
        btn0.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnadd.getLayoutParams();
        params.width = btnw;
        btnadd.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnsub.getLayoutParams();
        params.width = btnw;
        btnsub.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnmul.getLayoutParams();
        params.width = btnw;
        btnmul.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btndiv.getLayoutParams();
        params.width = btnw;
        btndiv.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnsqrt.getLayoutParams();
        params.width = btnw;
        btnsqrt.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnexpo.getLayoutParams();
        params.width = btnw;
        btnexpo.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnob.getLayoutParams();
        params.width = btnw;
        btnob.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btncb.getLayoutParams();
        params.width = btnw;
        btncb.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnlog.getLayoutParams();
        params.width = btnw;
        btnlog.setLayoutParams(params);

        params = (LinearLayout.LayoutParams) btnclr.getLayoutParams();
        params.width = btnw;
        btnclr.setLayoutParams(params);

I tried n number of times, but only worked in onClickListner.It crashed elsetime

Body:
It crashes because you are trying to get the LayoutParams when the layout has not been created yet. Try adding Post to your parent layout and do your logic in there.

For example

parentLayout.post(new Runnable() {
    @Override
    public void run() {
    //your code here
    }
   });


问:
Why *this* is not *this*?
I just wrote this piece of code to represent this error that is killing me (Grrr!)

I wonder why when I get error: method undefined I have checked in Safari and this variable inside parserDidStart() method is not of type EpisodeController it is of type EpisodeFeedParser why is this?

```<code><html>
<head>
<script type="text/javascript">
var EpisodeFeedParser = function(url){
    this.url = url;
    this.didStartCallback = null;
};
EpisodeFeedParser.prototype.parse = function(doc){
    this.didStartCallback(this);
};

var EpisodeController = function(){
    this.episodes = new Array();
    this.parser = null; //lazy
};
EpisodeController.prototype.parserDidStart = function(parser){
    console.log("here *this* is not of type EpisodeController but it is EpisodeFeedParser Why?");
    this.testEpi(); //**********ERROR HERE!***********
};
EpisodeController.prototype.fetchEpisodes = function(urlString){
    if(urlString !== undefined){
        if(parser === undefined){
            var parser = new EpisodeFeedParser(urlString);
            parser.didStartCallback = this.parserDidStart;
            this.parser = parser;
        }
        this.parser.parse();
    }
};
EpisodeController.prototype.testEpi = function(){
console.log("it worked!");
};

function testEpisode(){
    var controller = new EpisodeController();
    controller.fetchEpisodes("myurl");
}
</script>
</head>
<body>
<button type="button" onclick="testEpisode()">press me</button>
</body>
</html>
</code>```

答:
The problem is that "didStartCallBack" is being called on (and in the context of) "this", at a point in execution when "this" refers to the EpisodeFeedParser. I have fixed it using .call(), though I'm not sure why you'd need to write code this roundabout, I'm sure there must be a reason.

Important change:

```<code>parse: function(episodeController){
  this.didStartCallback.call(episodeController, this);
}//parse
</code>```

Full Code:

```<code><html>
<head>
<script type="text/javascript">
    //An interesting context problem...
    //Why is it of type EpisodeFeedParser?

    // ---- EpisodeFeedParser
    var EpisodeFeedParser = function(url){
        this.url = url;
    };
    EpisodeFeedParser.prototype = {
        url:null,
        didStartCallback:null,
        parse: function(episodeController){
            this.didStartCallback.call(episodeController, this);
        }//parse
    }//prototype

    // ---- EpisodeController
    var EpisodeController = function(){
        this.episodes = new Array();
        this.parser = null; //lazy
    };

    EpisodeController.prototype = {
        parserDidStart: function(parser){
            console.log("here *this* is not of type EpisodeController but it is EpisodeFeedParser Why?");
            debugger;
            this.testEpi(); //**********ERROR HERE!***********
        },

        fetchEpisodes: function(urlString){
            if(urlString !== undefined){
                if(this.parser === null){
                    this.parser = new EpisodeFeedParser(urlString);
                    this.parser.didStartCallback = this.parserDidStart;
                }//if
                this.parser.parse(this);
            }//if
        },//fetchEpisodes

        testEpi: function(){
            console.log("it worked!");
        }
    }//EpisodeController.prototype

    // ---- Global Stuff
    function testEpisode(){
        var controller = new EpisodeController();
        controller.fetchEpisodes("myurl");
    }
</script>
</head>

<body>
<button type="button" onclick="testEpisode()">press me</button>
</body>
</html>
</code>```

Title: Why *this* is not *this*?

Body:
I just wrote this piece of code to represent this error that is killing me (Grrr!)

I wonder why when I get error: method undefined I have checked in Safari and this variable inside parserDidStart() method is not of type EpisodeController it is of type EpisodeFeedParser why is this?

<button type="button" onclick="testEpisode()">press me</button>

Body:
The problem is that "didStartCallBack" is being called on (and in the context of) "this", at a point in execution when "this" refers to the EpisodeFeedParser. I have fixed it using .call(), though I'm not sure why you'd need to write code this roundabout, I'm sure there must be a reason.

Important change:

parse: function(episodeController){
  this.didStartCallback.call(episodeController, this);
}//parse

Full Code:

<html>
<head>
<script type="text/javascript">
    //An interesting context problem...
    //Why is it of type EpisodeFeedParser?

    // ---- EpisodeFeedParser
    var EpisodeFeedParser = function(url){
        this.url = url;
    };
    EpisodeFeedParser.prototype = {
        url:null,
        didStartCallback:null,
        parse: function(episodeController){
            this.didStartCallback.call(episodeController, this);
        }//parse
    }//prototype

    // ---- EpisodeController
    var EpisodeController = function(){
        this.episodes = new Array();
        this.parser = null; //lazy
    };

    EpisodeController.prototype = {
        parserDidStart: function(parser){
            console.log("here *this* is not of type EpisodeController but it is EpisodeFeedParser Why?");
            debugger;
            this.testEpi(); //**********ERROR HERE!***********
        },

        fetchEpisodes: function(urlString){
            if(urlString !== undefined){
                if(this.parser === null){
                    this.parser = new EpisodeFeedParser(urlString);
                    this.parser.didStartCallback = this.parserDidStart;
                }//if
                this.parser.parse(this);
            }//if
        },//fetchEpisodes

        testEpi: function(){
            console.log("it worked!");
        }
    }//EpisodeController.prototype

    // ---- Global Stuff
    function testEpisode(){
        var controller = new EpisodeController();
        controller.fetchEpisodes("myurl");
    }
</script>
</head>

<body>
<button type="button" onclick="testEpisode()">press me</button>
</body>
</html>


问:
add column denoting window with certain ending time (but various window lengths)
I have a data.frame:

```<code>       value time
1      1    3
2      2    6
3      3    9
4      4   12
5      5   15
6      6   18
7      7   21
8      8    0
9      9    3
10    10    6
11    11   18
12    12    6
</code>```

And I would like to add a column denotes a window from 6 to following value before 6. Ie:

```<code>   value time window
1      1    3      3
2      2    6      3
3      3    9      2
4      4   12      2
5      5   15      2
6      6   18      2
7      7   21      2
8      8    0      2
9      9    3      2
10    10    6      2
11    11   18      1
12    12    6      1
</code>```

The actual value of window doesn't matter as long as it can be used to make these groups.

(If anyone can think of a better title for this question by all means edit. This was the best I could come up with but don't think its particularly clear)

答:
An option would be create a logical vector on the reverse of 'time', do cumulative sum and reverse the output

```<code>library(dplyr)
df1 %>%
   mutate(window = rev(cumsum(rev(time) == 6)))
#    value time window
#1      1    3      3
#2      2    6      3
#3      3    9      2
#4      4   12      2
#5      5   15      2
#6      6   18      2
#7      7   21      2
#8      8    0      2
#9      9    3      2
#10    10    6      2
#11    11   18      1
#12    12    6      1
</code>```

Or in base R

```<code>df1$window <-  with(df1, rev(cumsum(rev(time) == 6)))
</code>```

data

```<code>df1 <- structure(list(value = 1:12, time = c(3L, 6L, 9L, 12L, 15L, 18L,
21L, 0L, 3L, 6L, 18L, 6L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))
</code>```

Body:
I have a data.frame:

       value time
1      1    3
2      2    6
3      3    9
4      4   12
5      5   15
6      6   18
7      7   21
8      8    0
9      9    3
10    10    6
11    11   18
12    12    6

And I would like to add a column denotes a window from 6 to following value before 6. Ie:

   value time window
1      1    3      3
2      2    6      3
3      3    9      2
4      4   12      2
5      5   15      2
6      6   18      2
7      7   21      2
8      8    0      2
9      9    3      2
10    10    6      2
11    11   18      1
12    12    6      1

The actual value of window doesn't matter as long as it can be used to make these groups.

(If anyone can think of a better title for this question by all means edit. This was the best I could come up with but don't think its particularly clear)

Body:
An option would be create a logical vector on the reverse of 'time', do cumulative sum and reverse the output

library(dplyr)
df1 %>%
   mutate(window = rev(cumsum(rev(time) == 6)))
#    value time window
#1      1    3      3
#2      2    6      3
#3      3    9      2
#4      4   12      2
#5      5   15      2
#6      6   18      2
#7      7   21      2
#8      8    0      2
#9      9    3      2
#10    10    6      2
#11    11   18      1
#12    12    6      1

Or in base R

df1$window <-  with(df1, rev(cumsum(rev(time) == 6)))

data

df1 <- structure(list(value = 1:12, time = c(3L, 6L, 9L, 12L, 15L, 18L,
21L, 0L, 3L, 6L, 18L, 6L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))


问:
git pull origin master does not update origin/master?
According to the documentation, git pull performs a git fetch then a git merge, however in that case performing git pull origin master should perform a git fetch origin master right?  However,  it does not appear to be doing so.  Here is an example.

Supposed my remote origin master (on GitHub in my case) has the following history:

```<code>commit 1111111 : my first commit
commit 2222222 : a commit from someone else
</code>```

and I only have my first commit locally as doing following shows

```<code>git checkout master
git log --pretty=format:'%h' -n 1
1111111

git checkout origin/master
git log --pretty=format:'%h' -n 1
1111111
</code>```

From here I do my pull and look at the results as follows:

```<code>git checkout master
git pull origin master

git log --pretty=format:'%h' -n 1
2222222

git checkout origin/master
git log --pretty=format:'%h' -n 1
1111111
</code>```

As can be seen, the pull did in fact update my master branch with the new commit(s) from the remote origin, but my local origin/master is still where it was.  Forcing me to do the following

```<code>git fetch origin master

git checkout origin/master
git log --pretty=format:'%h' -n 1
2222222
</code>```

Is this correct behavior for git pull or might I have something miss configured?  I looked through the git pull man page and didn't see anything that suggested this but I may have missed it.

答: it seems you have forked the repository and your forked branch is not updated with the latest code</p>

Body:
According to the documentation, git pull performs a git fetch then a git merge, however in that case performing git pull origin master should perform a git fetch origin master right?  However,  it does not appear to be doing so.  Here is an example.

Supposed my remote origin master (on GitHub in my case) has the following history:

commit 1111111 : my first commit
commit 2222222 : a commit from someone else

and I only have my first commit locally as doing following shows

git checkout master
git log --pretty=format:'%h' -n 1
1111111

git checkout origin/master
git log --pretty=format:'%h' -n 1
1111111

From here I do my pull and look at the results as follows:

git checkout master
git pull origin master

git log --pretty=format:'%h' -n 1
2222222

git checkout origin/master
git log --pretty=format:'%h' -n 1
1111111

As can be seen, the pull did in fact update my master branch with the new commit(s) from the remote origin, but my local origin/master is still where it was.  Forcing me to do the following

git fetch origin master

git checkout origin/master
git log --pretty=format:'%h' -n 1
2222222

Is this correct behavior for git pull or might I have something miss configured?  I looked through the git pull man page and didn't see anything that suggested this but I may have missed it.


问:
R: fuzzy merge two data frame
I have 2 data frames.

First,

```<code>abc <- data.frame(bin1 = c("0-25K", "25K-50K", "50K+"), group1 = c(1, 1, 2), bin2 = c("0-25", "25-50", "50+"), group2 = c(1, 2, 2))

pqr <- data.frame(bin1 = c("1_0-25K", "2_25K-50K", "3_50K+"),bin2 = c("0,25", "25,50", "50+"))

</code>```

I want to merge abc and pqr to get

```<code>pqr <- data.frame(bin1 = c("1_0-25K", "2_25K-50K", "3_50K+"), group1 = c(1, 1, 2), bin2 = c("0,25", "25,50", "50+"), group2 = c(1, 2, 2))
</code>```

I looked at a few older posted questions, but none of them have worked for me.

Merging two Data Frames using Fuzzy/Approximate String Matching in R

答:
This works:</p>

```<code>library(fuzzyjoin)
pqr <- pqr %>% stringdist_inner_join(abc, by = c(bin1 = "bin1"))
</code>```

Title: R: fuzzy merge two data frame

Body:
I have 2 data frames.

First,

abc <- data.frame(bin1 = c("0-25K", "25K-50K", "50K+"), group1 = c(1, 1, 2), bin2 = c("0-25", "25-50", "50+"), group2 = c(1, 2, 2))

pqr <- data.frame(bin1 = c("1_0-25K", "2_25K-50K", "3_50K+"),bin2 = c("0,25", "25,50", "50+"))

I want to merge abc and pqr to get

pqr <- data.frame(bin1 = c("1_0-25K", "2_25K-50K", "3_50K+"), group1 = c(1, 1, 2), bin2 = c("0,25", "25,50", "50+"), group2 = c(1, 2, 2))

I looked at a few older posted questions, but none of them have worked for me.

Merging two Data Frames using Fuzzy/Approximate String Matching in R

Body:
This works:

library(fuzzyjoin)
pqr <- pqr %>% stringdist_inner_join(abc, by = c(bin1 = "bin1"))