问:
In a while loop, how do you add a variable from the past loop to the same variable in the current loop
So i am really new to Java, only started programming a couple of months ago for a class. I am completely and utterly stuck on this project. This is the project.

And this is my code so far.

```<code>double mile;
double gas;
int week;
double mpg;
double totalMile;
double totalGas;

week = 0;
gas = 0;
mile = 0;
totalMile = 0;
totalGas = 0;

Scanner reply = new Scanner(System.in);

System.out.println("Please enter the amount of miles.");
mile = reply.nextDouble();

while(mile != -99)
{
    week++;

    System.out.println("Please enter the amount of gas (in gallons) purchased for this week.");
    gas = reply.nextDouble();
    mpg = mile / gas;

    System.out.println("Week: "+week+"");
    System.out.println("Miles: "+mile+" Vacation Miles Traveled: "+totalMile+"");
    System.out.println("Gallons: "+gas+" Vacation Gallons Purchased: "+totalGas+"");
    System.out.println("MPG: "+mpg+"");

    System.out.println("Please enter the amount of miles.");
    mile = reply.nextDouble();

}
</code>```

The only part I am REALLY stuck on is how to get the "Vacation Miles/Gas" values, I don't know how to add up a total of the same variable while in a while loop.

答:
Assuming you are trying to keep a running total, try totalmile += reply.nextDouble();

What this does is totalmile = totalmile + reply.nextDouble();

Body:
So i am really new to Java, only started programming a couple of months ago for a class. I am completely and utterly stuck on this project. This is the project.

And this is my code so far.

double mile;
double gas;
int week;
double mpg;
double totalMile;
double totalGas;

week = 0;
gas = 0;
mile = 0;
totalMile = 0;
totalGas = 0;

Scanner reply = new Scanner(System.in);

System.out.println("Please enter the amount of miles.");
mile = reply.nextDouble();

while(mile != -99)
{
    week++;

    System.out.println("Please enter the amount of gas (in gallons) purchased for this week.");
    gas = reply.nextDouble();
    mpg = mile / gas;

    System.out.println("Week: "+week+"");
    System.out.println("Miles: "+mile+" Vacation Miles Traveled: "+totalMile+"");
    System.out.println("Gallons: "+gas+" Vacation Gallons Purchased: "+totalGas+"");
    System.out.println("MPG: "+mpg+"");

    System.out.println("Please enter the amount of miles.");
    mile = reply.nextDouble();

}

The only part I am REALLY stuck on is how to get the "Vacation Miles/Gas" values, I don't know how to add up a total of the same variable while in a while loop.


来源: stackexchange

问:
Change text in HTML that I'm grabbing from a text file
What I'm doing is grabbing the HTML code for my header from a text file.

But once a User logs in I want it to say Welcome "Username" at the top, which is a dropdown to account settings, cart, etc...

So since I'm inserting the HTML into a DIV on page load, I don't actually have access to any of the elements inside in C#.

How would I go about doing this? Is there any way to access something like a (p id="name")'s inner text, after its loaded in from the text file?

Would like to do this with C# not JS please.

Edit: I have a work around for now, but I am still interested in better answers.

 headerText = headerText.Replace("::Username::", Session["Username"] as string);
```

<p>Here is my code for grabbing the HTML and pasting it in.</p>

```string headerText = File.ReadAllText(Server.MapPath("~/global/header.html"));
        string footerText = File.ReadAllText(Server.MapPath("~/global/footer.html"));

        headerText = headerText.Replace("::Username::", Session["Username"] as string);

        divHeader.InnerHtml = headerText;
        divFooter.InnerHtml = footerText;
```

<p>To be more clear, is there anyway to access something like</p>

``` <asp:Panel ID="panelAccount" runat="server">
```

which is stored in another HTML file.

答:
As much as I liked Adrians response, I found out a better way to do what I needed to do, I could do with a MasterPage. I definitely be using Adrians answer for a load of other things though so it still holds valid.

Then in the C# file associated with the master page you create a property like this.

```<code> public Panel PanelAccount
    {
        get { return panelAccount; }
        set { panelAccount = value; }
    }
</code>```

Then from the regular WebForm, you can call "PanelAccount" to access that property.

Here is a tutorial for how to do that.

Thanks for everyones downvotes with no inputs, you guys are stars!

ContentLicense: CC BY-SA 4.0

Body:
What I'm doing is grabbing the HTML code for my header from a text file.

But once a User logs in I want it to say Welcome "Username" at the top, which is a dropdown to account settings, cart, etc...

So since I'm inserting the HTML into a DIV on page load, I don't actually have access to any of the elements inside in C#.

How would I go about doing this? Is there any way to access something like a (p id="name")'s inner text, after its loaded in from the text file?

Would like to do this with C# not JS please.

Edit: I have a work around for now, but I am still interested in better answers.

 headerText = headerText.Replace("::Username::", Session["Username"] as string);

Here is my code for grabbing the HTML and pasting it in.

string headerText = File.ReadAllText(Server.MapPath("~/global/header.html"));
        string footerText = File.ReadAllText(Server.MapPath("~/global/footer.html"));

        headerText = headerText.Replace("::Username::", Session["Username"] as string);

        divHeader.InnerHtml = headerText;
        divFooter.InnerHtml = footerText;

To be more clear, is there anyway to access something like

 <asp:Panel ID="panelAccount" runat="server">

which is stored in another HTML file.

Body:
As much as I liked Adrians response, I found out a better way to do what I needed to do, I could do with a MasterPage. I definitely be using Adrians answer for a load of other things though so it still holds valid.

Then in the C# file associated with the master page you create a property like this.

 public Panel PanelAccount
    {
        get { return panelAccount; }
        set { panelAccount = value; }
    }

Then from the regular WebForm, you can call "PanelAccount" to access that property.

Here is a tutorial for how to do that.

Thanks for everyones downvotes with no inputs, you guys are stars!

ContentLicense: CC BY-SA 3.0


问:
Count all entries of child tables in single query
I have a parent table which holds a primary key (IdMain) that two separate tables use as a foreign key.

e.g.

```<code>MainTable
  |--Child1
  |--Child2
</code>```

Is there a simple way to count the number of entries in Child1 and Child2 with a specific IdMain?

I can do it with two queries, both inner joins, then add the result - and I've tried by having MainTable mt1  and MainTable mt2 in the same FROM but not got the results I expected.

答:
You can use full outer join on the two sub query joins like below

See Working demo

```<code>create table MainTable (idMain int);
insert into MainTable values (1),(2),(3),(4)
create table Child1 (idChild int);
insert into Child1 values (1),(1),(2),(3),(3),(3)
create table Child2 (idChild int);
insert into Child2 values (2),(2),(2),(3)

select
A.idMain,
ISNULL(countA,0) +ISNULL(countB,0) as count
from
(
    select
    M.idMain,count(1) countA
    from MainTable M
    join Child1 A
    on A.idChild=M.idMain
    group by M.idMain
)A
full outer join
(
    select
        M.idMain,count(1) countB
    from MainTable M
    join Child2 B
    on B.idChild=M.idMain
    group by M.idMain
 )B
 on A.idMain=B.idMain
 --- your where clause goes here
</code>```

Body:
I have a parent table which holds a primary key (IdMain) that two separate tables use as a foreign key.

e.g.

MainTable
  |--Child1
  |--Child2

Is there a simple way to count the number of entries in Child1 and Child2 with a specific IdMain?

I can do it with two queries, both inner joins, then add the result - and I've tried by having MainTable mt1  and MainTable mt2 in the same FROM but not got the results I expected.

Body:
You can use full outer join on the two sub query joins like below

See Working demo

create table MainTable (idMain int);
insert into MainTable values (1),(2),(3),(4)
create table Child1 (idChild int);
insert into Child1 values (1),(1),(2),(3),(3),(3)
create table Child2 (idChild int);
insert into Child2 values (2),(2),(2),(3)

select
A.idMain,
ISNULL(countA,0) +ISNULL(countB,0) as count
from
(
    select
    M.idMain,count(1) countA
    from MainTable M
    join Child1 A
    on A.idChild=M.idMain
    group by M.idMain
)A
full outer join
(
    select
        M.idMain,count(1) countB
    from MainTable M
    join Child2 B
    on B.idChild=M.idMain
    group by M.idMain
 )B
 on A.idMain=B.idMain
 --- your where clause goes here


问:
VTK dyld: Library not loaded: libvtkDomainsChemistryOpenGL2-7.1.1.dylib
I try to learn VTK and when I execute the tutorials code it give me this error:

dyld: Library not loaded: libvtkDomainsChemistryOpenGL2-7.1.1.dylib

Where is this library?

I use macOS Sierra and I install the vtk by this:
enter link description here

Can you help me?

答:
The proper choice of cmake flags certainly will help solving your problem. Reading question and answer of this SO post may be helpful.

I am not fully convinced if you followed the referenced instructions exactly, because in the excerpt of the CMakeCache (see here, point 5), BUILD_SHARED_LIBS was disabled. However, your problem indicates that your binary was linked dynamically. Here I'm missing further details about your setup.

Let me maybe share the cmake command that I used to build vtk (with python wrapper and shared libraries). This worked for vtk 7.x.

```<code>mkdir build
cd build
INSTALL_DIR="/opt/dev/versions/vtk/vtk-7.1.0-shared"
cmake .. -DCMAKE_BUILD_TYPE=Release \
         -DVTK_WRAP_PYTHON=ON \
         -DBUILD_EXAMPLES=OFF \
         -DBUILD_SHARED_LIBS=ON \
         -DBUILD_TESTING=OFF \
         -DCMAKE_INSTALL_PREFIX="$INSTALL_DIR" \
         -DCMAKE_MACOSX_RPATH=ON \
         -DCMAKE_INSTALL_RPATH="$INSTALL_DIR/lib" \
         -DPYTHON_INCLUDE_DIR="/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/" \
         -DPYTHON_LIBRARY="/Library/Frameworks/Python.framework/Versions/2.7/lib/libpython2.7.dylib"
make -j8
make install
</code>```

Note that I had to set the python related flags to ensure that the correct python environment is used. (Often, there are multiple python environments available on a Mac: The python distributed by MacOS itself, a user python that was installed via homebrew or macports, or the framework that was acquired via www.python.org. For me the third option applied.)

Body:
The proper choice of cmake flags certainly will help solving your problem. Reading question and answer of this SO post may be helpful.

I am not fully convinced if you followed the referenced instructions exactly, because in the excerpt of the CMakeCache (see here, point 5), BUILD_SHARED_LIBS was disabled. However, your problem indicates that your binary was linked dynamically. Here I'm missing further details about your setup.

Let me maybe share the cmake command that I used to build vtk (with python wrapper and shared libraries). This worked for vtk 7.x.

mkdir build
cd build
INSTALL_DIR="/opt/dev/versions/vtk/vtk-7.1.0-shared"
cmake .. -DCMAKE_BUILD_TYPE=Release \
         -DVTK_WRAP_PYTHON=ON \
         -DBUILD_EXAMPLES=OFF \
         -DBUILD_SHARED_LIBS=ON \
         -DBUILD_TESTING=OFF \
         -DCMAKE_INSTALL_PREFIX="$INSTALL_DIR" \
         -DCMAKE_MACOSX_RPATH=ON \
         -DCMAKE_INSTALL_RPATH="$INSTALL_DIR/lib" \
         -DPYTHON_INCLUDE_DIR="/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/" \
         -DPYTHON_LIBRARY="/Library/Frameworks/Python.framework/Versions/2.7/lib/libpython2.7.dylib"
make -j8
make install

Note that I had to set the python related flags to ensure that the correct python environment is used. (Often, there are multiple python environments available on a Mac: The python distributed by MacOS itself, a user python that was installed via homebrew or macports, or the framework that was acquired via www.python.org. For me the third option applied.)


问:
Is there a webhook for settlements?
Does authorize.net provide any web hooks for settlements? The documentation doesn't have it listed.

We'd like to update our database once an order has settled (for the purpose of providing void or refund options).  If you have done this before and didn't use webhooks, how did you do it?

答: There is no webhook for settlements. However, since they occur daily, and at the same time each day, you can have a regularly scheduled script (e.g. cron job) use the Transaction Details API to get settlement information.</p>

Title: Is there a webhook for settlements?


问:
aggregate a column in a data frame
```<code>df1 <- read.table(text = "V1    V2
    21140 -2
    21140  0
    21140  2
    21140 -1
     3878  0
     3878  1
     3878  2
   20434  -1
   20434   2
   20434   1", header = TRUE)
</code>```

for getting the mean i used the following command

```<code>sample.test.final <- df1[,list(V2 = mean(V2)), by = c("V1")]
</code>```

Now i want the following results

condition : if the value of V2 for corresponding V1 is negative select that value or else use the max positive value

```<code>df2 <-      "V1    V2
            21140  -2
             3878   2
            20434  -1"
</code>```

答:
Simply use if/else condition check to summarize the column:

```<code>df1[, .(V2 = if(all(V2 >= 0)) max(V2) else V2[V2 < 0]), V1]

#      V1 V2
#1: 21140 -2
#2: 21140 -1
#3:  3878  2
#4: 20434 -1
</code>```

 Note this keeps all negative values in V2 if there's any.

Title: aggregate a column in a data frame

Body:
df1 <- read.table(text = "V1    V2
    21140 -2
    21140  0
    21140  2
    21140 -1
     3878  0
     3878  1
     3878  2
   20434  -1
   20434   2
   20434   1", header = TRUE)

for getting the mean i used the following command

sample.test.final <- df1[,list(V2 = mean(V2)), by = c("V1")]

Now i want the following results

condition : if the value of V2 for corresponding V1 is negative select that value or else use the max positive value

df2 <-      "V1    V2
            21140  -2
             3878   2
            20434  -1"

Body:
Simply use if/else condition check to summarize the column:

df1[, .(V2 = if(all(V2 >= 0)) max(V2) else V2[V2 < 0]), V1]

#      V1 V2
#1: 21140 -2
#2: 21140 -1
#3:  3878  2
#4: 20434 -1

 Note this keeps all negative values in V2 if there's any.


问:
Angular 2: Conditional Output Property Binding
Is it possible to conditionally bind to an output property?  Something like this: <my-Component (myOutputProp)="funcThatReturnsTrueOrFalse()? func1() : func2()"></my-component>

I've tried the above example, as well as <my-Component (myOutputProp)="funcThatReturnsFunc1OrFunc2()></my-component>.

I've looked around and come to the realization that you can't dynamically change bindings after the fact, can't access EventListeners from nativeElement, and seen some indications that you could do this with regular event bindings, although I couldn't get those to work either.

Thanks.

UPDATE

My output property is defined like this:

@Output() myOutputProp: EventEmitter<any> = new EventEmitter<any>();

UPDATE 2

For reasons beyond my control, I can't just fire one event and branch within that based on true/false.  Primarily because in one situation, a false value from my ternary expression evaluation will not bind anything to the output property, and I need to be able to detect that within my child component (via myOutputProp.observers.length)

答:
You can use the EventEmitter to emit based on your boolean value. Just push the appropriate value via the emit(...) method.

Here's a simple example including two components. One component is a button, which emits a String value that changes when you click the button. The other component is consuming that event and displaying it. You can find a demo here: https://stackblitz.com/edit/angular-4natth

Here's the first component, which is a simple button. Note that clicking the button sets a boolean flag. This flag then determines which string is emitted by the event emitter.

```<code>@Component({
  selector: 'my-example',
  template: '<button mat-raised-button (click)="doThings()">Click me!</button>'
})
export class ExampleComponent {

  @Output()
  status: EventEmitter<string> = new EventEmitter();

  flag = false;

  doThings() {
    this.flag = !this.flag; // toggle the boolean flag
    this.status.emit(this.getValue()); // push the value
  }

  private getValue() {
    if(this.flag) {
      return "Truthy!";
    }
    return "Falsy!";
  }
}
</code>```

The second component is consuming and the values being emitted from (status):

```<code>@Component({
  selector: 'my-container',
  template: '<my-example (status)="updateStatus($event)">loading...</my-example><p>Current status: {{status}}</p>'
})
export class ContainerComponent {
  status: string = "Not set yet - click the button!";

  updateStatus(value: string) {
    this.status = value;
  }
}
</code>```

Whenever you click the button, the EventEmitter.emit(...) method is called, pushing the appropriate value. On the other end, the event is consumed using (status)="updateStatus($event)", where in this case $event is of type string because I've declared the EventEmitter to be emitting a string. I could easily have also been emitting a boolean value and have the updateStatus method instead do different things based on the emitted value.

So, say for example you have this in your Component:

```<code>@Output()
myOutputProp: EventEmitter<boolean> = new EventEmitter();
</code>```

You could then do something like this:

```<code><my-Component (myOutputProp)="someFunc($event)"></my-component>
</code>```

And define your someFunc like this:

```<code>someFunc(emittedValue: boolean) {
  emittedValue ? func1() : func2();
}
</code>```

Or, let's say you need the output of your event emitter to be some sort of value that you need preserved rather than a boolean. You could still declare your component the same:

```<code><my-Component (myOutputProp)="someFunc($event)"></my-component>
</code>```

And define your someFunc like this:

```<code>someFunc(emittedValue: any) {
  funcThatReturnsTrueOrFalse() ? func1(emittedValue) : func2(emittedValue);
}
</code>```

So while you can't directly bind the ternary to the event emitter, you can instead bind something static which turns around and invokes the ternary itself.

Body:
You can use the EventEmitter to emit based on your boolean value. Just push the appropriate value via the emit(...) method.

Here's a simple example including two components. One component is a button, which emits a String value that changes when you click the button. The other component is consuming that event and displaying it. You can find a demo here: https://stackblitz.com/edit/angular-4natth

Here's the first component, which is a simple button. Note that clicking the button sets a boolean flag. This flag then determines which string is emitted by the event emitter.

@Component({
  selector: 'my-example',
  template: '<button mat-raised-button (click)="doThings()">Click me!</button>'
})
export class ExampleComponent {

  @Output()
  status: EventEmitter<string> = new EventEmitter();

  flag = false;

  doThings() {
    this.flag = !this.flag; // toggle the boolean flag
    this.status.emit(this.getValue()); // push the value
  }

  private getValue() {
    if(this.flag) {
      return "Truthy!";
    }
    return "Falsy!";
  }
}

The second component is consuming and the values being emitted from (status):

@Component({
  selector: 'my-container',
  template: '<my-example (status)="updateStatus($event)">loading...</my-example><p>Current status: {{status}}</p>'
})
export class ContainerComponent {
  status: string = "Not set yet - click the button!";

  updateStatus(value: string) {
    this.status = value;
  }
}

Whenever you click the button, the EventEmitter.emit(...) method is called, pushing the appropriate value. On the other end, the event is consumed using (status)="updateStatus($event)", where in this case $event is of type string because I've declared the EventEmitter to be emitting a string. I could easily have also been emitting a boolean value and have the updateStatus method instead do different things based on the emitted value.

So, say for example you have this in your Component:

@Output()
myOutputProp: EventEmitter<boolean> = new EventEmitter();

You could then do something like this:

<my-Component (myOutputProp)="someFunc($event)"></my-component>

And define your someFunc like this:

someFunc(emittedValue: boolean) {
  emittedValue ? func1() : func2();
}

Or, let's say you need the output of your event emitter to be some sort of value that you need preserved rather than a boolean. You could still declare your component the same:

<my-Component (myOutputProp)="someFunc($event)"></my-component>

And define your someFunc like this:

someFunc(emittedValue: any) {
  funcThatReturnsTrueOrFalse() ? func1(emittedValue) : func2(emittedValue);
}

So while you can't directly bind the ternary to the event emitter, you can instead bind something static which turns around and invokes the ternary itself.


问:
Postgres pg_dump cache lookup failed for index
I am trying to create a back-up of a postgres database using the following command (omitting details):

```<code>$ pg_dump -h $host -p 5432 -U $user $db > db.sql
</code>```

After some time, I get an error (formatted)

```<code>pg_dump: [archiver (db)] query failed: ERROR:  cache lookup failed for index 1184605879
pg_dump: [archiver (db)] query was:
SELECT  t.tableoid,
        t.oid,
        t.relname AS indexname,
        pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef,
        t.relnatts AS indnkeys,
        i.indkey,
        i.indisclustered,
        false AS indisreplident,
        t.relpages,
        c.contype,
        c.conname,
        c.condeferrable,
        c.condeferred,
        c.tableoid AS contableoid,
        c.oid AS conoid,
        pg_catalog.pg_get_constraintdef(c.oid, false) AS condef,
        (SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace,
        t.reloptions AS indreloptions
FROM pg_catalog.pg_index i
JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid)
LEFT JOIN pg_catalog.pg_constraint c ON (i.indrelid = c.conrelid AND i.indexrelid = c.conindid AND c.contype IN ('p','u','x'))
WHERE i.indrelid = '1184605870'::pg_catalog.oid AND i.indisvalid AND i.indisready
ORDER BY indexname
</code>```

I then verified the index ID in pg_index does not exist. Is there some way to fix this, or some way to ignore this error and continue so I can continue exporting non-pg_catalog data?

答:
It's possible that a system index get corrupted. I'd try the following:

Stop database server

Start database in single-user mode, ignoring system and user-defined indexes:

postgres --single -D /path/to/data --ignore_system_indexes=on --enable_indexscan=off --enable_bitmapscan=off <database>

Reindex entire database (including catalog): REINDEX DATABASE
<database>;

Restart database and try dumping again...

More: ignore_system_indexes, REINDEX, enable_bitmapscan/enable_indexscan, single-user mode;

Body:
I am trying to create a back-up of a postgres database using the following command (omitting details):

$ pg_dump -h $host -p 5432 -U $user $db > db.sql

After some time, I get an error (formatted)

pg_dump: [archiver (db)] query failed: ERROR:  cache lookup failed for index 1184605879
pg_dump: [archiver (db)] query was:
SELECT  t.tableoid,
        t.oid,
        t.relname AS indexname,
        pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef,
        t.relnatts AS indnkeys,
        i.indkey,
        i.indisclustered,
        false AS indisreplident,
        t.relpages,
        c.contype,
        c.conname,
        c.condeferrable,
        c.condeferred,
        c.tableoid AS contableoid,
        c.oid AS conoid,
        pg_catalog.pg_get_constraintdef(c.oid, false) AS condef,
        (SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace,
        t.reloptions AS indreloptions
FROM pg_catalog.pg_index i
JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid)
LEFT JOIN pg_catalog.pg_constraint c ON (i.indrelid = c.conrelid AND i.indexrelid = c.conindid AND c.contype IN ('p','u','x'))
WHERE i.indrelid = '1184605870'::pg_catalog.oid AND i.indisvalid AND i.indisready
ORDER BY indexname

I then verified the index ID in pg_index does not exist. Is there some way to fix this, or some way to ignore this error and continue so I can continue exporting non-pg_catalog data?


问:
How to move/rename file from internal app storage to external storage on Android?
I am downloading files from the internet and saving the streaming data to a temp file in my app's internal storage given by getFilesDir().

Once the download is complete, I need to move the temp file to my download directory on External Memory (usually an SD Card).  For some reason though, File.renameTo() isn't working for this.  I'm guessing there's a problem because it's two separate file systems, but I can still download directly to the SD Card and the file URIs are correct.

Is there another simple and quick way to transfer that file from internal memory to external or do I have to do a byte stream copy and delete the original?

答:
To copy files from internal memory to SD card and vice-versa using following piece of code:

```<code>public static void copyFile(File src, File dst) throws IOException
{
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();
    try
    {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    }
    finally
    {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
}
</code>```

And - it works...

ContentLicense: CC BY-SA 2.5

Body:
To copy files from internal memory to SD card and vice-versa using following piece of code:

public static void copyFile(File src, File dst) throws IOException
{
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();
    try
    {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    }
    finally
    {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
}

And - it works...


问:
R ggbiplot aesthetics
is it possible to change the thickness of the ellipses (incl circle) in ggbiplot? The arguments don't seem to have that option. Is there another way around it? So far I've dealt with this issue by making my data points more transparent.</p>

答: Copying the ggbiplot code into a  new function and changing it works, but the change in line 87 only works if var.axes = TRUE, which is the default. If you set var.axes = FALSE then you need to add a size parameter to the call in line 124. Something like g <- g + geom_path(data = ell, aes(color = groups, group = groups),size=2).

Title: R ggbiplot aesthetics


问:
How to know the amount of memory available for broadcast variables in pyspark?
I have a broadcast variable that I am using in pyspark, and I want to know how much space I have available.

I know that a broadcasted variable stays within spark.executor.memory, but does it have to fit within the confines of the storage?  Or the confines of the processing?

I know that the spark.memory.fraction is what is used for determining the fraction of spark.executor.memory used for storage, versus the amount used for processing.  but, say my spark.executor.memory is 10GB and spark.memory.fraction is 0.75.

Does the broadcasted variable have to be less than 2.5GB or less than 5GB?

this is pyspark 1.6.1.

Also, here is a resource that would be useful as a reference point:  https://0x0fff.com/spark-memory-management/

I do not understand what is "user memory" in that article.

EDIT :  As an extension to this question, it would be great to know where the cached tables are stored.  Are those in the same place as broadcast variables?  or somewhere different?  It seems to me like those are inside of the spark.memory.storageFraction.

答:
Broadcasted variable is stored in the memory of Python process (there is also serialized copy on the JVM). So the part of the memory which is used is the execution memory.

Please remember that PySpark keeps a copy of the variable for each Spark core. So the actual memory limit is closer to

```<code>(`spark.executor.memory` * `spark.memory.fraction`) / `spark.executor.cores`
</code>```

Body:
Broadcasted variable is stored in the memory of Python process (there is also serialized copy on the JVM). So the part of the memory which is used is the execution memory.

Please remember that PySpark keeps a copy of the variable for each Spark core. So the actual memory limit is closer to

(`spark.executor.memory` * `spark.memory.fraction`) / `spark.executor.cores`


问:
How to do predict() for linearmodels
Below is Fixed Effect Estimation python code by linearmodels module from here.

from linearmodels import PanelOLS
mod = PanelOLS(y_train, x_train, entity_effects=True)
res = mod.fit(cov_type='clustered', cluster_entity=True)

How can we do predict(x_test) operation as sklearn after mod.fit() ?

答: Conformed with the author that linearmodels still not support the function predict(), the development of this feature is in progress. Refer to here for more details.

Title: How to do predict() for linearmodels


问:
Rails JSON Parameter not parsed
I have a registration form in ReactJS and want to to send the user data (name, email, password) in JSON format to my rails API. Rails then does not parse my JSON data into parameters.

Routes

```<code>Rails.application.routes.draw do
    get '/list_users' => 'users#index'
    post '/register_user' => 'users#register'
end
</code>```

User Controller

```<code>class UsersController < ApplicationController
    def index
        @users = User.all
        render json: @users
    end

    def register
        puts params.inspect
        @user = User.new(name: 'TEST', :email => params[:email], :password => params[:password])
        #@user = User.new(name: 'User', email: 'controller@user.com', password: 'password') (this works)
        @user.save
    end
end
</code>```

puts params.inspect outputs:

```<code><ActionController::Parameters {"controller"=>"users", "action"=>"register"} permitted: false>
</code>```

Registration form

```<code>postData(){
    var myHeaders = new Headers();
    myHeaders.append('Accept', 'application/json')
    myHeaders.append('Content-Type', 'application/json');

    var data = JSON.stringify({
        name: "Test",
        email: "test@post.com",
        password: "password"
    })

    fetch("http://127.0.0.1:3000/register_user",{
        method: 'POST',
        headers: myHeaders,
        mode: 'no-cors',
        body: data
    })
    .then(function(res){ return res.json(); })
    .then(function(data){ alert( JSON.stringify( data ) ) })
    .catch( (ex) => {
        console.log("Fetch failed" + ex);
    });
}
</code>```

parameter wrapping for JSON is enabled in the config.
Thanks for the help!

答:
JSON parameters in this case will not have symbolic keys, but string ones. Try this instead:</p>

```<code>@user = User.new(name: 'TEST', :email => params['email'], :password => params['password'])
</code>```

Title: Rails JSON Parameter not parsed

Body:
I have a registration form in ReactJS and want to to send the user data (name, email, password) in JSON format to my rails API. Rails then does not parse my JSON data into parameters.

Routes

Rails.application.routes.draw do
    get '/list_users' => 'users#index'
    post '/register_user' => 'users#register'
end

User Controller

class UsersController < ApplicationController
    def index
        @users = User.all
        render json: @users
    end

    def register
        puts params.inspect
        @user = User.new(name: 'TEST', :email => params[:email], :password => params[:password])
        #@user = User.new(name: 'User', email: 'controller@user.com', password: 'password') (this works)
        @user.save
    end
end

puts params.inspect outputs:

<ActionController::Parameters {"controller"=>"users", "action"=>"register"} permitted: false>

Registration form

postData(){
    var myHeaders = new Headers();
    myHeaders.append('Accept', 'application/json')
    myHeaders.append('Content-Type', 'application/json');

    var data = JSON.stringify({
        name: "Test",
        email: "test@post.com",
        password: "password"
    })

    fetch("http://127.0.0.1:3000/register_user",{
        method: 'POST',
        headers: myHeaders,
        mode: 'no-cors',
        body: data
    })
    .then(function(res){ return res.json(); })
    .then(function(data){ alert( JSON.stringify( data ) ) })
    .catch( (ex) => {
        console.log("Fetch failed" + ex);
    });
}

parameter wrapping for JSON is enabled in the config.
Thanks for the help!

Body:
JSON parameters in this case will not have symbolic keys, but string ones. Try this instead:

@user = User.new(name: 'TEST', :email => params['email'], :password => params['password'])


问:
Angular: Correct way to use calc in style binding
What is the correct way to bind calc() to style.height, style.width in angular?

I have:

[style.height]="calc(100% - 57px)"```
</div>
</div>
</p>

<p>and getting back:</p>

```Error: Missing expected ) at column 14 in [calc(100% - 4px)]
```

seems like the '(' is not being escaped.

答:
It needs to be a string, use ''

```<code>[style.height]="'calc(100vh - ' + (checkedTaskTracker.checkedTasks.length > 0 ? '240px': '171px') + ')'"
</code>```

Body:
What is the correct way to bind calc() to style.height, style.width in angular?

I have:

[style.height]="calc(100% - 57px)"

and getting back:

Error: Missing expected ) at column 14 in [calc(100% - 4px)]

seems like the '(' is not being escaped.

Body:
It needs to be a string, use ''

[style.height]="'calc(100vh - ' + (checkedTaskTracker.checkedTasks.length > 0 ? '240px': '171px') + ')'"


问:
select Query to convert datetime column to UTC
I have a table in MYSQL with 10 columns. The table has a datetime column in local time zone.

Now I want to do select * from table but want the     datetime to display in UTC timezone format

How can I get the desired result

答:
You need to use MySQL's function CONVERT_TZ

```<code>CONVERT_TZ(datetime_column,'[local time zone]','UTC')
</code>```

https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_convert-tz

Body:
You need to use MySQL's function CONVERT_TZ

CONVERT_TZ(datetime_column,'[local time zone]','UTC')

https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_convert-tz


问:
Best method to Merge two Datasets (Maybe if function?)
I have two data sets I am working with. Datasets TestA and Test B (Below is how to make them in R)

```<code>Instructor <- c('Mr.A','Mr.A','Mr.B', 'Mr.C', 'Mr.D')
Class <- c('French','French','English', 'Math', 'Geometry')
Section <- c('1','2','3','5','5')
Time <- c('9:00-10:00','10:00-11:00','9:00-10:00','9:00-10:00','10:00-11:00')
Date <- c('MWF','MWF','TR','TR','MWF')
Enrollment <- c('30','40','24','29','40')

TestA <- data.frame(Instructor,Class,Section,Time,Date,Enrollment)

rm(Instructor,Class,Section,Time,Date,Enrollment)

Student <- c("Frances","Cass","Fern","Pat","Peter","Kory","Cole")
ID <- c('123','121','101','151','456','789','314')
Instructor <- c('','','','','','','')
Time <- c('','','','','','','')
Date <- c('','','','','','','')
Enrollment <- c('','','','','','','')
Class <- c('French','French','French','French','English', 'Math', 'Geometry')
Section <- c('1','1','2','2','3','5','5')

TestB <- data.frame(Student, ID, Instructor, Class, Section, Time, Date, Enrollment)

rm(Instructor,Class,Section,Time,Date,Enrollment,ID,Student)
</code>```

I would like to merge both datasets (If possible, without using merge() ) So that All the columns of Test A are filled with the information provided by TestB and it should be added depending on the Class and Section.

I tried using merge(TestA, TestB, by=c('Class','Section'), all.x=TRUE) but it adds observations to the original TestA. This is just a test but in the datasets I am using there are hundreds of observations. It worked when I did it with these smaller frames but something is happening to the bigger set. That's why I'd like to know if there is a merge alternative.

Any ideas on how to do this?

The output should look like this

```<code>Class   Section Instructor  Time          Date   Enrollment Student ID
English  3      Mr.B    9:00-10:00  TR      24      Peter   456
French   1      Mr.A    9:00-10:00  MWF     30      Frances 123
French   1      Mr.A    9:00-10:00  MWF 30  Cass    121
French   2      Mr.A    10:00-11:00 MWF 40  Fern    101
French   2      Mr.A    10:00-11:00 MWF 40  Pat 151
Geometry 5      Mr.D    10:00-11:00 MWF 40  Cole    314
Math     5      Mr.C    9:00-10:00  TR  29  Kory    789
</code>```

答:
The key is to drop the empty but duplicate columns from TestB before merging / joining as shown by SymbolixAU.

Here is an implementation in data.table syntax:

```<code>library(data.table)
setDT(TestB)[, .(Student, ID, Class, Section)][setDT(TestA), on = .(Class, Section)]

   Student  ID    Class Section Instructor        Time Date Enrollment
1: Frances 123   French       1       Mr.A  9:00-10:00  MWF         30
2:    Cass 121   French       1       Mr.A  9:00-10:00  MWF         30
3:    Fern 101   French       2       Mr.A 10:00-11:00  MWF         40
4:     Pat 151   French       2       Mr.A 10:00-11:00  MWF         40
5:   Peter 456  English       3       Mr.B  9:00-10:00   TR         24
6:    Kory 789     Math       5       Mr.C  9:00-10:00   TR         29
7:    Cole 314 Geometry       5       Mr.D 10:00-11:00  MWF         40
</code>```

Body:
I have two data sets I am working with. Datasets TestA and Test B (Below is how to make them in R)

Instructor <- c('Mr.A','Mr.A','Mr.B', 'Mr.C', 'Mr.D')
Class <- c('French','French','English', 'Math', 'Geometry')
Section <- c('1','2','3','5','5')
Time <- c('9:00-10:00','10:00-11:00','9:00-10:00','9:00-10:00','10:00-11:00')
Date <- c('MWF','MWF','TR','TR','MWF')
Enrollment <- c('30','40','24','29','40')

TestA <- data.frame(Instructor,Class,Section,Time,Date,Enrollment)

rm(Instructor,Class,Section,Time,Date,Enrollment)

Student <- c("Frances","Cass","Fern","Pat","Peter","Kory","Cole")
ID <- c('123','121','101','151','456','789','314')
Instructor <- c('','','','','','','')
Time <- c('','','','','','','')
Date <- c('','','','','','','')
Enrollment <- c('','','','','','','')
Class <- c('French','French','French','French','English', 'Math', 'Geometry')
Section <- c('1','1','2','2','3','5','5')

TestB <- data.frame(Student, ID, Instructor, Class, Section, Time, Date, Enrollment)

rm(Instructor,Class,Section,Time,Date,Enrollment,ID,Student)

I would like to merge both datasets (If possible, without using merge() ) So that All the columns of Test A are filled with the information provided by TestB and it should be added depending on the Class and Section.

I tried using merge(TestA, TestB, by=c('Class','Section'), all.x=TRUE) but it adds observations to the original TestA. This is just a test but in the datasets I am using there are hundreds of observations. It worked when I did it with these smaller frames but something is happening to the bigger set. That's why I'd like to know if there is a merge alternative.

Any ideas on how to do this?

The output should look like this

Class   Section Instructor  Time          Date   Enrollment Student ID
English  3      Mr.B    9:00-10:00  TR      24      Peter   456
French   1      Mr.A    9:00-10:00  MWF     30      Frances 123
French   1      Mr.A    9:00-10:00  MWF 30  Cass    121
French   2      Mr.A    10:00-11:00 MWF 40  Fern    101
French   2      Mr.A    10:00-11:00 MWF 40  Pat 151
Geometry 5      Mr.D    10:00-11:00 MWF 40  Cole    314
Math     5      Mr.C    9:00-10:00  TR  29  Kory    789

Body:
The key is to drop the empty but duplicate columns from TestB before merging / joining as shown by SymbolixAU.

Here is an implementation in data.table syntax:

library(data.table)
setDT(TestB)[, .(Student, ID, Class, Section)][setDT(TestA), on = .(Class, Section)]

   Student  ID    Class Section Instructor        Time Date Enrollment
1: Frances 123   French       1       Mr.A  9:00-10:00  MWF         30
2:    Cass 121   French       1       Mr.A  9:00-10:00  MWF         30
3:    Fern 101   French       2       Mr.A 10:00-11:00  MWF         40
4:     Pat 151   French       2       Mr.A 10:00-11:00  MWF         40
5:   Peter 456  English       3       Mr.B  9:00-10:00   TR         24
6:    Kory 789     Math       5       Mr.C  9:00-10:00   TR         29
7:    Cole 314 Geometry       5       Mr.D 10:00-11:00  MWF         40


问:
brain type internal not showing unity3d
I have trained a model with Python(PPO). I got the byte file for brain but when I try to select brain type, it doesn't show any Internal option. I'm using ML-AgentsNoPlugin.unitypackage for this project. Please let me know what's wrong

答:
Ok, I got the same issue.

The solution is:

put ENABLE_TENSORFLOW in Player Settings -> Other Settings -> Scripting Define Symbols (type it, click return and tab...in this way it keeps it after restart)

set Scripting Runtime Version to Experimental (.Net 4.6 Equivalent)

Restart Unity and it should work.

Title: brain type internal not showing unity3d


问:
Passing parameters to .js file
I am developing a widget.
the code for it is :

```<code><script src="../test/js.js"></script>
</code>```

I want to pass paramters to a .js file like this, as we pass parameters like a query string.

```<code><script src="../test/js.js?place=us&list=10"></script>.
</code>```

These are my contents in my .js file.

```<code>var _html = '<div id="FJ_TF_Cont" style="position: relative; padding: 0; margin: 0; border-width: 0px; width: 200px;">'
+ '<iframe width="210" height="640" src="../test/content.aspx" name="FJIframe" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" style="width: 210px; border-width: 0px; z-index: 1;">'
+ '</iframe>'
+ '</div>';

document.write(_html);
</code>```

Please note the content of src in Iframe it contains:

```<code>src="../test/content.aspx"
</code>```

now i want to pass these parameters that in js string to this src as querystring.

the final src should look like :

```<code> src="../test/content.aspx?place=us&list=0"
</code>```

I need help as i am a newbie to js.

答:
I second @goleztrol's answer.
Here's a smaller (single script tag) version

```<code><script type="text/javascript">
  var place="us";
  var list=0;
  var script_tag = document.createElement('script');
  script_tag.setAttribute("type","text/javascript");
  script_tag.setAttribute("src", "<your-js-src>");
  document.getElementsByTagName('body')[0].appendChild(script_tag);
</script>
</code>```

Hope that helps :)

Title: Passing parameters to .js file

Body:
I am developing a widget.
the code for it is :

I want to pass paramters to a .js file like this, as we pass parameters like a query string.

.

These are my contents in my .js file.

var _html = '
'
+ ''
+ ''
+ '
';

document.write(_html);

Please note the content of src in Iframe it contains:

src="../test/content.aspx"

now i want to pass these parameters that in js string to this src as querystring.

the final src should look like :

 src="../test/content.aspx?place=us&list=0"

I need help as i am a newbie to js.

Body:
I second @goleztrol's answer.
Here's a smaller (single script tag) version

<script type="text/javascript">
  var place="us";
  var list=0;
  var script_tag = document.createElement('script');
  script_tag.setAttribute("type","text/javascript");
  script_tag.setAttribute("src", "<your-js-src>");
  document.getElementsByTagName('body')[0].appendChild(script_tag);
</script>

Hope that helps :)


问:
MySQL query not outputting result only heading
I am currently practicing PHP and AJAX and I am trying to create an application that allows a user to search a database for product stock in real time. When the user types in a letter within one of the entries the headings show up but not the data. I'm not sure if I am doing it wrong but I'll let you guys be the judge of that. Code below:

Results.php - Below

```<code> <!DOCTYPE html>
<html>
<head>
<title>Results</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect("localhost", "username", "password", "databaseName");
//edited out for safety

if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"jakeholc_ajaxtest");

$sql="SELECT * FROM stock WHERE name LIKE '%{$q}%'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Product name</th>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
</tr>";

if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['descr'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "</tr>";
}
}

echo "</table>";
mysqli_close($con);
?>
</code>```

答: $q = intval($_GET['q']); attempts to turn your input into an integer. Remove this line.

Body:
I am currently practicing PHP and AJAX and I am trying to create an application that allows a user to search a database for product stock in real time. When the user types in a letter within one of the entries the headings show up but not the data. I'm not sure if I am doing it wrong but I'll let you guys be the judge of that. Code below:

Results.php - Below

 <!DOCTYPE html>

<title>Results</title>
<link rel="stylesheet" type="text/css" href="style.css">

<?php
$q = intval($_GET['q']);

$con = mysqli_connect("localhost", "username", "password", "databaseName");
//edited out for safety

if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"jakeholc_ajaxtest");

$sql="SELECT * FROM stock WHERE name LIKE '%{$q}%'";
$result = mysqli_query($con,$sql);

echo "

Product name
Description
Price
Quantity

";

if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "
";
echo "" . $row['name'] . "	";
echo "" . $row['descr'] . "	";
echo "" . $row['price'] . "	";
echo "" . $row['quantity'] . "	";
echo "
";
}
}

echo "
";
mysqli_close($con);
?>


问:
How to connect the App Maker to Google Cloud apis
I am new to the App Maker, just curious, can the App Maker connect to Google Cloud apis, such as Google Speech api? and where should I start with? Thanks! </p>

答:
G Suite Services

Some APIs are available out of the box. You can find docs for all of them in Apps Script reference:
https://developers.google.com/apps-script/reference/

Advanced Google Services

Even more, you can easily plug-in Advanced Google Services:
https://developers.google.com/appmaker/settings#advanced_google_services

Other Services

If you need something special... Then you can try to enable that specific API for your Cloud Project and talk to it using oAuth(I'm not 100% sure, never tried it myself). You can access your Cloud Project by viewing you deployment logs: Settings -> Deployments -> Deployment Logs

This will redirect you to Google Cloud Console. There you'll be enable services you need.

You can find further steps by following the link:

https://developers.google.com/apps-script/guides/services/external


问:
Mockito.eq matcher seems to match against list reference, not value
I have a method addToClonedList(List) in class App that calls method add(List) in class Dependency.  I want to unit test addToClonedList(List), and I want to create a mock Dependency object (called mockDependency) and verify that the method mockDependency.add(List) is called with the correct argument.  However, since the List instance referenced by clonedList gets a new element (100) added to if after the call in question, Mockito thinks that the 2-element List was passed to the mockDependency, and the test fails.  In reality, the List passed to mockDependency.add(List) only contained one element when it was called.  Is this expected Mockito behavior?  Is there a more standard way to test that I've passed the correct List to mockDependency.add(List)?

See my code structure and test output below:

main/java/App.java:

```<code>import java.util.*;

public class App {
  Dependency dataLayer = new Dependency();

  void addToClonedList(List<Integer> integerList) {
    List<Integer> clonedList = new ArrayList<Integer>(integerList);
    dataLayer.add(clonedList);
    clonedList.add(100);
  }
}
</code>```

main/java/Dependency.java:

```<code>import java.util.List;

public class Dependency {
  void add(List<Integer> integerList) {
    //
  }
}
</code>```

test/java/AppTest.java:

```<code>import java.util.*;
import org.junit.*;
import org.mockito.*;

public class AppTest {

  @InjectMocks
  App app;

  @Mock
  Dependency mockDependency;

  @Before
  public void beforeEachTest() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testWithVerify() {
    List<Integer> originalList = new ArrayList<>();
    originalList.add(1);

    app.addToClonedList(originalList);

    Mockito.verify(mockDependency).add(Mockito.eq(originalList));
  }
}
</code>```

pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.athenahealth</groupId>
  <artifactId>mockitotest</artifactId>
  <version>1.0-SNAPSHOT</version>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.testifyproject.mock</groupId>
      <artifactId>mockito</artifactId>
      <version>0.9.8</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>

</project>
</code>```

Test output:

```<code>Argument(s) are different! Wanted:
mockDependency.add([1]);
-> at AppTest.testWithVerify(AppTest.java:25)
Actual invocation has different arguments:
mockDependency.add([1, 100]);
-> at App.addToClonedList(App.java:8)

Comparison Failure:
Expected :mockDependency.add([1]);
Actual   :mockDependency.add([1, 100]);
</code>```

答:
Mockito isn't magical.

When the add method is called on the mock, the mock simply holds onto a reference to the value of the parameter. The eq matcher then compares to see whether the parameter you pass into verify equals that value, using equals. It can't do any better than this because, in general, it doesn't know how to take a copy of the parameter.

If you modify the value passed into the mock afterwards, Mockito doesn't know that you've done this, and still just compares the two references using equals.

You call the method on the mock with clonedList, and then add a value into clonedList, but not integerList. As such, when you compare clonedList to originalList using eq, they are different, and hence the check doesn't pass.

As suggested, if you don't add to clonedList, the test passes; and you can then see that it's not comparing using == by replacing eq with same (the test will then fail).

Body:
I have a method addToClonedList(List) in class App that calls method add(List) in class Dependency.  I want to unit test addToClonedList(List), and I want to create a mock Dependency object (called mockDependency) and verify that the method mockDependency.add(List) is called with the correct argument.  However, since the List instance referenced by clonedList gets a new element (100) added to if after the call in question, Mockito thinks that the 2-element List was passed to the mockDependency, and the test fails.  In reality, the List passed to mockDependency.add(List) only contained one element when it was called.  Is this expected Mockito behavior?  Is there a more standard way to test that I've passed the correct List to mockDependency.add(List)?

See my code structure and test output below:

main/java/App.java:

import java.util.*;

public class App {
  Dependency dataLayer = new Dependency();

  void addToClonedList(List<Integer> integerList) {
    List<Integer> clonedList = new ArrayList<Integer>(integerList);
    dataLayer.add(clonedList);
    clonedList.add(100);
  }
}

main/java/Dependency.java:

import java.util.List;

public class Dependency {
  void add(List<Integer> integerList) {
    //
  }
}

test/java/AppTest.java:

import java.util.*;
import org.junit.*;
import org.mockito.*;

public class AppTest {

  @InjectMocks
  App app;

  @Mock
  Dependency mockDependency;

  @Before
  public void beforeEachTest() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testWithVerify() {
    List<Integer> originalList = new ArrayList<>();
    originalList.add(1);

    app.addToClonedList(originalList);

    Mockito.verify(mockDependency).add(Mockito.eq(originalList));
  }
}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.athenahealth</groupId>
  <artifactId>mockitotest</artifactId>
  <version>1.0-SNAPSHOT</version>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.testifyproject.mock</groupId>
      <artifactId>mockito</artifactId>
      <version>0.9.8</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>

</project>

Test output:

Argument(s) are different! Wanted:
mockDependency.add([1]);
-> at AppTest.testWithVerify(AppTest.java:25)
Actual invocation has different arguments:
mockDependency.add([1, 100]);
-> at App.addToClonedList(App.java:8)

Comparison Failure:
Expected :mockDependency.add([1]);
Actual   :mockDependency.add([1, 100]);


问:
How does Apache Spark handle non-Spark code?
Let's say I create a Spark job (in Java) which includes Spark code (using the Dataset API) and non-Spark code. It seems like the Spark code will be automatically parallelized and run on multiple machines. Does Spark know to run the the regular-Java/non-Spark on only one machine?</p>

答:
Spark programs are standard Scala / Java programs. Unless you explicitly use distribution / parallelization primitives, codes run exactly as is.  So to answer:

Does Spark know to run the the regular-Java/non-Spark on only one machine?

it just doesn't care. For the JVM it is plain code.


问:
Nested Foreach List NetLogo

Hi,

In Netlogo v.6, I'm trying to calculate a time-weighted measure of a peer's cooperative behavior. The point is, I can't figure out exactly how to do a nested foreach in NetLogo.

My current approach:

setup a list: reputation_peer

setup a list: reputation_peer_list, of variable 1 (behavior) and variable 2 (time tick)

Each encounter, add reputation_list to reputation_peer, making the reputation_peer a list of lists

calculate the weighted reputation:

taking item 2 of each list in reputation_peer, which is the time tick of that encounter

and dividing it by the current time tick.

This gives a fraction: tick of that encounter/total time ticks

setup a list reputation_weighted

To weigh the reputations, multiply the time fraction with the first item of reputation_peer, which is the behavior variable

Then, I want to know the reputation_current, by taking all values from reputation_weighted and adding them up.

I'm messing around with the foreach function but I can't seem to figure it out.
How would such an approach be coded in Netlogo?

My current code is (setting reputation_peer myself to test it):

```<code>to calculate_reputation
    set reputation_peer [[8 4][9 2][10 3][11 2][14 1]]
    if ticks > 0 [
      foreach reputation_peer [x -> set reputation_peer_list list (item 0 x) ((item 1 x) / ticks )
      set reputation_peer_list_2 lput reputation_peer_list reputation_peer_list_2]
      foreach reputation_peer_list_2 [x -> set reputation_peer_list_list (list (item 0 x * item 1 x))]
      foreach reputation_peer_list_list [x -> set reputation_peer_current reputation_peer_current + x]
    ]
end
</code>```

I don't really know whether I'm doing it right, but mainly, this code seems a very bulky with all the list_list things going on. I'm guessing it could be a lot simpler.

Would greatly help me out if you guys have some tips.

答:
I'm not 100% sure of what you're expecting as final output, but maybe this does what you need?</p>

```<code>to calc-rep-2
  set reputation_peer [[8 4][9 2][10 3][11 2][14 1]]
  let weighted_rep_list []

  if ticks > 0 [
    foreach reputation_peer [ x ->
      ; Pull out the values from reputation_peer for ease of use
      let encounter_behavior item 0 x
      let encounter_time item 1 x

      ; Calculate the time fraction for the current item
      let time_fraction encounter_time / ticks

      ; Calculate the weighted reputations
      let weighted_rep encounter_behavior * time_fraction

      ; Add the weighted rep to the list of weighted reps
      set weighted_rep_list lput weighted_rep weighted_rep_list
    ]

    ; Now, weighted_rep_list is a list of weighted reputations
    print weighted_rep_list

    ; Get the sum of the list
    print sum weighted_rep_list
  ]

  tick
end
</code>```

Title: Nested Foreach List NetLogo

Body:
Hi,

In Netlogo v.6, I'm trying to calculate a time-weighted measure of a peer's cooperative behavior. The point is, I can't figure out exactly how to do a nested foreach in NetLogo.

My current approach:

setup a list: reputation_peer

setup a list: reputation_peer_list, of variable 1 (behavior) and variable 2 (time tick)

Each encounter, add reputation_list to reputation_peer, making the reputation_peer a list of lists

calculate the weighted reputation:

taking item 2 of each list in reputation_peer, which is the time tick of that encounter

and dividing it by the current time tick.

This gives a fraction: tick of that encounter/total time ticks

setup a list reputation_weighted

To weigh the reputations, multiply the time fraction with the first item of reputation_peer, which is the behavior variable

Then, I want to know the reputation_current, by taking all values from reputation_weighted and adding them up.

I'm messing around with the foreach function but I can't seem to figure it out.
How would such an approach be coded in Netlogo?

My current code is (setting reputation_peer myself to test it):

to calculate_reputation
    set reputation_peer [[8 4][9 2][10 3][11 2][14 1]]
    if ticks > 0 [
      foreach reputation_peer [x -> set reputation_peer_list list (item 0 x) ((item 1 x) / ticks )
      set reputation_peer_list_2 lput reputation_peer_list reputation_peer_list_2]
      foreach reputation_peer_list_2 [x -> set reputation_peer_list_list (list (item 0 x * item 1 x))]
      foreach reputation_peer_list_list [x -> set reputation_peer_current reputation_peer_current + x]
    ]
end

I don't really know whether I'm doing it right, but mainly, this code seems a very bulky with all the list_list things going on. I'm guessing it could be a lot simpler.

Would greatly help me out if you guys have some tips.

Body:
I'm not 100% sure of what you're expecting as final output, but maybe this does what you need?

to calc-rep-2
  set reputation_peer [[8 4][9 2][10 3][11 2][14 1]]
  let weighted_rep_list []

  if ticks > 0 [
    foreach reputation_peer [ x ->
      ; Pull out the values from reputation_peer for ease of use
      let encounter_behavior item 0 x
      let encounter_time item 1 x

      ; Calculate the time fraction for the current item
      let time_fraction encounter_time / ticks

      ; Calculate the weighted reputations
      let weighted_rep encounter_behavior * time_fraction

      ; Add the weighted rep to the list of weighted reps
      set weighted_rep_list lput weighted_rep weighted_rep_list
    ]

    ; Now, weighted_rep_list is a list of weighted reputations
    print weighted_rep_list

    ; Get the sum of the list
    print sum weighted_rep_list
  ]

  tick
end


问:
find input field where type=text in the table row
I have a delete image that that is triggered by a 'click' handler.  I'm passing the element parameter into the function that triggered the event, which is the delete image.

Is there a way I can find the input where type="text" for the table row that of the delete image that was clicked?

Here is the code I'm working with:

```<code>        A4J.AJAX.AddListener({
            onafterajax: function(req,evt,data) {

                j$('[id$=deleteImage]').on('click', function(elem) {
                    console.log('the delete button was clicked');
                    console.log('************** before ' + localStorage.activeButtons);
                    var activeArray  = localStorage.activeButtons.split(',');
                    var idx = activeArray.indexOf('account');
                    if (idx > -1) activeArray.splice(idx, 1);
                    localStorage.activeButtons = activeArray.join(',');
                    console.log('************** after ' + localStorage.activeButtons);
                });

                var lastRow = j$('table[id$=participantTable] tbody tr:last');
                var active = localStorage.activeButtons.split(',');

                var dataRows = j$('tr.dataRow');
                dataRows.each(function(index, elem) {
                    updateImages(elem, active[index]);
                });
            }
        });
</code>```

I need to find the input[type="text"] in the table row that the delete image was clicked and get the id of that input field and check if the id contains one of the following values: contact, user or account.  I need to pass the value contained in the input id into the indexOf() method.

Thanks for any help.

答:
Answer for the question: </p>

```<code> $("#TblName tbody tr input[type=text]").each(function(){
        console.log($(this).val());
    });

    $("#TblName tr input[type=text]").each(function(){
        console.log($(this).val());
    });

       $(".TblClass tr .InputClass").each(function(){
            console.log($(this).val());
        });
</code>```

Body:
I have a delete image that that is triggered by a 'click' handler.  I'm passing the element parameter into the function that triggered the event, which is the delete image.

Is there a way I can find the input where type="text" for the table row that of the delete image that was clicked?

Here is the code I'm working with:

        A4J.AJAX.AddListener({
            onafterajax: function(req,evt,data) {

                j$('[id$=deleteImage]').on('click', function(elem) {
                    console.log('the delete button was clicked');
                    console.log('************** before ' + localStorage.activeButtons);
                    var activeArray  = localStorage.activeButtons.split(',');
                    var idx = activeArray.indexOf('account');
                    if (idx > -1) activeArray.splice(idx, 1);
                    localStorage.activeButtons = activeArray.join(',');
                    console.log('************** after ' + localStorage.activeButtons);
                });

                var lastRow = j$('table[id$=participantTable] tbody tr:last');
                var active = localStorage.activeButtons.split(',');

                var dataRows = j$('tr.dataRow');
                dataRows.each(function(index, elem) {
                    updateImages(elem, active[index]);
                });
            }
        });

I need to find the input[type="text"] in the table row that the delete image was clicked and get the id of that input field and check if the id contains one of the following values: contact, user or account.  I need to pass the value contained in the input id into the indexOf() method.

Thanks for any help.

Body:
Answer for the question:

 $("#TblName tbody tr input[type=text]").each(function(){
        console.log($(this).val());
    });

    $("#TblName tr input[type=text]").each(function(){
        console.log($(this).val());
    });

       $(".TblClass tr .InputClass").each(function(){
            console.log($(this).val());
        });


问:
How do I invoke a private static method using reflection (Java)?
I would like to invoke a private static method. I have its name. I've heard it can be done using Java reflection mechanism. How can I do it?

EDIT: One problem I encountered when trying to invoke the method is how to specify the type of its argument. My method receives one argument and its type is Map. Therefore I cannot do Map<User, String>.TYPE (In run time there's no such a thing as Map because of Java Type erasure). Is there another way to get the method?

答:
No, you can't say Map<K,V>.class. This is because of type erasure. At runtime, there's no such thing.

Luckily, you can say just plain old Map.class. It's all the same at runtime.

If the warnings bother you, search for other questions related to generics and type erasure, there's a wealth of information on the subject here.


问:
NVDA Screen Reader not reading Javascript Alert() Popup in Chrome
I've written a javascript alert() message on a Salesforce page which appears on page load. The code simply goes along the lines of:

```<code><script type="text/javascript">
   window.onready = function() {
   alert('message for user goes here.');
}
<script>
</code>```

The message appears on page load, however, it isn't being picked up by the NVDA screen reader. It just reads "Unknown" (I can't even tab into it), which isn't very helpful.

How can you get the screen reader to focus/read a javascript alert message? Is this a bug with NVDA/Chrome?

I'm using the latest version of Chrome: 62.0.3202.94. And NVDA: 2017.4

答:
This is a Chrome bug, and a known one. As Monorail has very poor search functions (at least, in my experience), I couldn't find the bug by number, but believe me, it does exist. Per this issue, alert(), confirm() and onBeforeUnload() dialogs are not read in Chrome. JAWS copes with it better than NVDA though: if you Alt+Tab and then Alt+Tab back to Chrome, you'll be getting the ability to tab around the dialog.

I confirmed this issue fixed in Chrome Canary versions 64, so try this or just wait a bit. Yesterday or today I got Chrome updated, now it is Google Chrome Version 63.0.3239.84.


问:
In a while loop, how do you add a variable from the past loop to the same variable in the current loop
So i am really new to Java, only started programming a couple of months ago for a class. I am completely and utterly stuck on this project. This is the project.

And this is my code so far.

```<code>double mile;
double gas;
int week;
double mpg;
double totalMile;
double totalGas;

week = 0;
gas = 0;
mile = 0;
totalMile = 0;
totalGas = 0;

Scanner reply = new Scanner(System.in);

System.out.println("Please enter the amount of miles.");
mile = reply.nextDouble();

while(mile != -99)
{
    week++;

    System.out.println("Please enter the amount of gas (in gallons) purchased for this week.");
    gas = reply.nextDouble();
    mpg = mile / gas;

    System.out.println("Week: "+week+"");
    System.out.println("Miles: "+mile+" Vacation Miles Traveled: "+totalMile+"");
    System.out.println("Gallons: "+gas+" Vacation Gallons Purchased: "+totalGas+"");
    System.out.println("MPG: "+mpg+"");

    System.out.println("Please enter the amount of miles.");
    mile = reply.nextDouble();

}
</code>```

The only part I am REALLY stuck on is how to get the "Vacation Miles/Gas" values, I don't know how to add up a total of the same variable while in a while loop.

答:
I'm assuming you want to keep track of all the miles you've driven since the very beginning?

Why not just use your total miles or total gallons variables in the while loop?

```<code>totalmile += mile
totalgas += gas
</code>```

You might also want to move your

```<code>System.out.println("Please enter the amount of miles.");
mile = reply.nextDouble();
</code>```

So your code looks like:

```<code>week++;

System.out.println("Please enter the amount of gas (in gallons) purchased for this week.");
gas = reply.nextDouble();
mpg = mile / gas;

System.out.println("Please enter the amount of miles.");
mile = reply.nextDouble();

totalgas += gas
totalmiles += mile

System.out.println("Week: "+week+"");
System.out.println("Miles: "+mile+" Vacation Miles Traveled: "+totalmile+"");
System.out.println("Gallons: "+gas+" Vacation Gallons Purchased: "+totalgas+"");
System.out.println("MPG: "+mpg+"");
</code>```

So yeah.
Good luck with your programming assignment!

Body:
So i am really new to Java, only started programming a couple of months ago for a class. I am completely and utterly stuck on this project. This is the project.

And this is my code so far.

double mile;
double gas;
int week;
double mpg;
double totalMile;
double totalGas;

week = 0;
gas = 0;
mile = 0;
totalMile = 0;
totalGas = 0;

Scanner reply = new Scanner(System.in);

System.out.println("Please enter the amount of miles.");
mile = reply.nextDouble();

while(mile != -99)
{
    week++;

    System.out.println("Please enter the amount of gas (in gallons) purchased for this week.");
    gas = reply.nextDouble();
    mpg = mile / gas;

    System.out.println("Week: "+week+"");
    System.out.println("Miles: "+mile+" Vacation Miles Traveled: "+totalMile+"");
    System.out.println("Gallons: "+gas+" Vacation Gallons Purchased: "+totalGas+"");
    System.out.println("MPG: "+mpg+"");

    System.out.println("Please enter the amount of miles.");
    mile = reply.nextDouble();

}

The only part I am REALLY stuck on is how to get the "Vacation Miles/Gas" values, I don't know how to add up a total of the same variable while in a while loop.

Body:
I'm assuming you want to keep track of all the miles you've driven since the very beginning?

Why not just use your total miles or total gallons variables in the while loop?

totalmile += mile
totalgas += gas

You might also want to move your

System.out.println("Please enter the amount of miles.");
mile = reply.nextDouble();

So your code looks like:

week++;

System.out.println("Please enter the amount of gas (in gallons) purchased for this week.");
gas = reply.nextDouble();
mpg = mile / gas;

System.out.println("Please enter the amount of miles.");
mile = reply.nextDouble();

totalgas += gas
totalmiles += mile

System.out.println("Week: "+week+"");
System.out.println("Miles: "+mile+" Vacation Miles Traveled: "+totalmile+"");
System.out.println("Gallons: "+gas+" Vacation Gallons Purchased: "+totalgas+"");
System.out.println("MPG: "+mpg+"");

So yeah.
Good luck with your programming assignment!


问:
Compare two version strings in Swift
I have two different app version Strings (i.e. "3.0.1" and "3.0.2").

How can compare these using Swift?

答:
Wrote a small Swift 3 class to do this:</p>

```<code>class VersionString: NSObject {

    // MARK: - Properties
    var string = ""
    override var description: String {
        return string
    }

    // MARK: - Initialization
    private override init() {
        super.init()
    }
    convenience init(_ string: String) {
        self.init()
        self.string = string
    }

    func compare(_ rhs: VersionString) -> ComparisonResult {
        return string.compare(rhs.string, options: .numeric)
    }

    static func ==(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedSame
    }

    static func <(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedAscending
    }

    static func <=(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedAscending || lhs.compare(rhs) == .orderedSame
    }

    static func >(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedDescending
    }

    static func >=(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedDescending || lhs.compare(rhs) == .orderedSame
    }
}

let v1 = VersionString("1.2.3")
let v2 = VersionString("1.2.3")

print("\(v1) == \(v2): \(v1 == v2)") // 1.2.3 == 1.2.3: true
print("\(v1) >  \(v2): \(v1 > v2)")  // 1.2.3 >  1.2.3: false
print("\(v1) >= \(v2): \(v1 >= v2)") // 1.2.3 >= 1.2.3: true
print("\(v1) <  \(v2): \(v1 < v2)")  // 1.2.3 <  1.2.3: false
print("\(v1) <= \(v2): \(v1 <= v2)") // 1.2.3 <= 1.2.3: true
</code>```

Title: Compare two version strings in Swift

Body:
Wrote a small Swift 3 class to do this:

class VersionString: NSObject {

    // MARK: - Properties
    var string = ""
    override var description: String {
        return string
    }

    // MARK: - Initialization
    private override init() {
        super.init()
    }
    convenience init(_ string: String) {
        self.init()
        self.string = string
    }

    func compare(_ rhs: VersionString) -> ComparisonResult {
        return string.compare(rhs.string, options: .numeric)
    }

    static func ==(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedSame
    }

    static func <(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedAscending
    }

    static func <=(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedAscending || lhs.compare(rhs) == .orderedSame
    }

    static func >(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedDescending
    }

    static func >=(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedDescending || lhs.compare(rhs) == .orderedSame
    }
}

let v1 = VersionString("1.2.3")
let v2 = VersionString("1.2.3")

print("\(v1) == \(v2): \(v1 == v2)") // 1.2.3 == 1.2.3: true
print("\(v1) >  \(v2): \(v1 > v2)")  // 1.2.3 >  1.2.3: false
print("\(v1) >= \(v2): \(v1 >= v2)") // 1.2.3 >= 1.2.3: true
print("\(v1) <  \(v2): \(v1 < v2)")  // 1.2.3 <  1.2.3: false
print("\(v1) <= \(v2): \(v1 <= v2)") // 1.2.3 <= 1.2.3: true


问:
Shorter way to check for null with parseDouble?
amountStr is a value that occasionally contains a double value represented as a string.

I want to use Double.parseDouble to read it into a double variable: amountDbl.

```<code>this.amountDbl = Double.parseDouble(amountStr);
</code>```

It seems to throw a NullPointerException if amountStr doesn't have a value.

Does this mean I have to write a check like this every time?

```<code>if(amountStr!=null)
    this.amountDbl = Double.parseDouble(amountStr);
</code>```

Because I have so many statements like this in my code, I'm hoping for a more concise way of doing this check (or avoiding it).

答: Might be a couple of years late to answer this question. The NumberUtils Class in org.apache.commons.lang3.math package has a method createDouble that does what you are asking for(https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#createDouble-java.lang.String-)</p>

Body:
amountStr is a value that occasionally contains a double value represented as a string.

I want to use Double.parseDouble to read it into a double variable: amountDbl.

this.amountDbl = Double.parseDouble(amountStr);

It seems to throw a NullPointerException if amountStr doesn't have a value.

Does this mean I have to write a check like this every time?

if(amountStr!=null)
    this.amountDbl = Double.parseDouble(amountStr);

Because I have so many statements like this in my code, I'm hoping for a more concise way of doing this check (or avoiding it).


问:
How do I create as assoc record with SQLAlchemy in Pylons?
I've got a User model and a Ledger model with a many-to-many relationship.  SQLAlchemy has created my database tables correctly, so I'm pretty sure it's got the right mappings.  I can create a new record in each table, but I can't figure out how to associate them.  How do I do it?

My table definitions:

```<code>user_table = sa.Table('user', meta.metadata,
    sa.Column('id', types.Integer,
        sa.Sequence('user_seq_id', optional=True), primary_key=True),
    sa.Column('username', types.Unicode(255), nullable=False, unique=True),
    sa.Column('password', types.Unicode(255), nullable=False),
    sa.Column('salt', types.Unicode(255), nullable=False)
    )
userledger_table = sa.Table('userledger', meta.metadata,
    sa.Column('id', types.Integer,
        sa.Sequence('user_seq_id', optional=True), primary_key=True),
    sa.Column('user_id', types.Integer(), sa.ForeignKey('user.id')),
    sa.Column('ledger_id', types.Integer(), sa.ForeignKey('ledger.id')),
    )
ledger_table = sa.Table('ledger', meta.metadata,
    sa.Column('id', types.Integer,
        sa.Sequence('ledger_seq_id', optional=True), primary_key=True),
    sa.Column('name', types.Unicode(255), nullable=False),
    )
</code>```

Mappings:

```<code>orm.mapper(User, user_table);
orm.mapper(Ledger, ledger_table, properties={
    'users':orm.relation(User, secondary=userledger_table)
    })
</code>```

答:
I found my answer in this tutorial.</p>

```<code>ledger = model.Ledger()
ledger.name = name
ledger.users.append(user)
meta.Session.add(ledger)
meta.Session.commit()
</code>```

Body:
I've got a User model and a Ledger model with a many-to-many relationship.  SQLAlchemy has created my database tables correctly, so I'm pretty sure it's got the right mappings.  I can create a new record in each table, but I can't figure out how to associate them.  How do I do it?

My table definitions:

user_table = sa.Table('user', meta.metadata,
    sa.Column('id', types.Integer,
        sa.Sequence('user_seq_id', optional=True), primary_key=True),
    sa.Column('username', types.Unicode(255), nullable=False, unique=True),
    sa.Column('password', types.Unicode(255), nullable=False),
    sa.Column('salt', types.Unicode(255), nullable=False)
    )
userledger_table = sa.Table('userledger', meta.metadata,
    sa.Column('id', types.Integer,
        sa.Sequence('user_seq_id', optional=True), primary_key=True),
    sa.Column('user_id', types.Integer(), sa.ForeignKey('user.id')),
    sa.Column('ledger_id', types.Integer(), sa.ForeignKey('ledger.id')),
    )
ledger_table = sa.Table('ledger', meta.metadata,
    sa.Column('id', types.Integer,
        sa.Sequence('ledger_seq_id', optional=True), primary_key=True),
    sa.Column('name', types.Unicode(255), nullable=False),
    )

Mappings:

orm.mapper(User, user_table);
orm.mapper(Ledger, ledger_table, properties={
    'users':orm.relation(User, secondary=userledger_table)
    })

Body:
I found my answer in this tutorial.

ledger = model.Ledger()
ledger.name = name
ledger.users.append(user)
meta.Session.add(ledger)
meta.Session.commit()


问:
Error takes exactly 2 arguments (3 given)
Hi i am trying to plot points in a google map by indexing the dictionary with a foor loop, have this dictionary of lat:long

```<code> latlon = {32.1243973: -101.8856125, 32.666694: -104.233502, 32.222012:
 -101.819122, 32.53151: -103.353018, 32.668496: -104.235722, 32.1041336: -101.8818588}
</code>```

And i have this code:

```<code>if __name__ == "__main__":
        map = Map()
        for latitude, longitude in latlon.iteritems():
            map.add_point(latitude, longitude)
</code>```

I get the error TypeError: add_point() takes exactly 2 arguments (3 given)

I am giving only latitude and longitude why it says i am giving 3 arguments?

Thanks in advance!

Edit: addint the class map:

```<code>class Map(object):
    def __init__(self):
        self._points = []
    def add_point(self, coordinates):
        self._points.append(coordinates)
    def __str__(self):
        centerLat = sum(( x[0] for x in self._points )) / len(self._points)
        centerLon = sum(( x[1] for x in self._points )) / len(self._points)
        markersCode = "\n".join(
            [ """new google.maps.Marker({{
                position: new google.maps.LatLng({lat}, {lon}),
                map: map
                }});""".format(lat=x[0], lon=x[1]) for x in self._points
            ])
        return """
            <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
            <div id="map-canvas" style="height: 100%; width: 100%"></div>
            <script type="text/javascript">
                var map;
                function show_map() {{
                    map = new google.maps.Map(document.getElementById("map-canvas"), {{
                        zoom: 8,
                        center: new google.maps.LatLng({centerLat}, {centerLon})
                    }});
                    {markersCode}
                }}
                google.maps.event.addDomListener(window, 'load', show_map);
            </script>
        """.format(centerLat=centerLat, centerLon=centerLon,
                   markersCode=markersCode)
</code>```

答:
add_point seems to want the latitude & longitude as a single object; something like this:

```<code>for ll in latlon.iteritems():
    map.add_point(ll)
</code>```

Body:
Hi i am trying to plot points in a google map by indexing the dictionary with a foor loop, have this dictionary of lat:long

 latlon = {32.1243973: -101.8856125, 32.666694: -104.233502, 32.222012:
 -101.819122, 32.53151: -103.353018, 32.668496: -104.235722, 32.1041336: -101.8818588}

And i have this code:

if __name__ == "__main__":
        map = Map()
        for latitude, longitude in latlon.iteritems():
            map.add_point(latitude, longitude)

I get the error TypeError: add_point() takes exactly 2 arguments (3 given)

I am giving only latitude and longitude why it says i am giving 3 arguments?

Thanks in advance!

Edit: addint the class map:

class Map(object):
    def __init__(self):
        self._points = []
    def add_point(self, coordinates):
        self._points.append(coordinates)
    def __str__(self):
        centerLat = sum(( x[0] for x in self._points )) / len(self._points)
        centerLon = sum(( x[1] for x in self._points )) / len(self._points)
        markersCode = "\n".join(
            [ """new google.maps.Marker({{
                position: new google.maps.LatLng({lat}, {lon}),
                map: map
                }});""".format(lat=x[0], lon=x[1]) for x in self._points
            ])
        return """

        """.format(centerLat=centerLat, centerLon=centerLon,
                   markersCode=markersCode)

Body:
add_point seems to want the latitude & longitude as a single object; something like this:

for ll in latlon.iteritems():
    map.add_point(ll)


问:
Assigned(TStopWatch) gives E2008
```<code>if assigned(S3) then Log('TChunkManager.UpdateVertices Create VAO ms: ' +
  S3.ElapsedMilliseconds.ToString);
</code>```

The problem is the assigned part, I tried with Log('aaa') and also Log works fine elsewhere. Why is S3 (TStopwatch) is uncompatible with assigned?

```<code>**[dcc64 Error] thChunkManager.pas(529): E2008 Incompatible types**
</code>```

How can I check if S3 is created or not?

答:
TStopWatch is a record type, not a class type.  An instance of a record can be created in stack memory of the calling thread.  An instance of a class type must be allocated dynamically in heap memory instead.   Only pointers can be passed to Assigned().  A record instance on the stack doesn't count.

For what you are attempting, you probably want to use the TStopWatch.IsRunning property instead:

```<code>if S3.IsRunning then
  Log('TChunkManager.UpdateVertices Create VAO ms: ' + S3.ElapsedMilliseconds.ToString);
</code>```

Title: Assigned(TStopWatch) gives E2008

Body:
if assigned(S3) then Log('TChunkManager.UpdateVertices Create VAO ms: ' +
  S3.ElapsedMilliseconds.ToString);

The problem is the assigned part, I tried with Log('aaa') and also Log works fine elsewhere. Why is S3 (TStopwatch) is uncompatible with assigned?

**[dcc64 Error] thChunkManager.pas(529): E2008 Incompatible types**

How can I check if S3 is created or not?

Body:
TStopWatch is a record type, not a class type.  An instance of a record can be created in stack memory of the calling thread.  An instance of a class type must be allocated dynamically in heap memory instead.   Only pointers can be passed to Assigned().  A record instance on the stack doesn't count.

For what you are attempting, you probably want to use the TStopWatch.IsRunning property instead:

if S3.IsRunning then
  Log('TChunkManager.UpdateVertices Create VAO ms: ' + S3.ElapsedMilliseconds.ToString);


问:
How does load balancing work for very high traffic domains?
Take Google.com for example. If it ultimately resolves to a single IP at any point of time, the packets will land on a single server. Even if all it does is send a redirect response (for transferring load other servers), it still has to be capable of handling hundreds of thousands of requests per second.

I can think of a number of non standard ways to handle this. For example the router may be programmed to load balance the packet across multiple servers. But it still means that google.com is dependent on a single physical facility as IP addresses are not portable to another location.

I was hoping internet fabric itself has some mechanism to handle such things.Multiple A records per domain is one such mechanism. But while researching this I found that google.com's DNS entry has only one A record and the IP value is different depending on which site you query it from.

How is it done? In what ways is it better and why has Google chosen to do it this way instead of having multiple A records?

Trying to lookup A record of google.com yields different results from different sites:
https://www.misk.com/tools/#dns/google.com  Resolves to 216.58.217.142
https://www.ultratools.com/tools/dnsLookupResult resolves to 172.217.9.206

答:
This is generally done using dynamic DNS/round robin DNS/ DNS load balancing.

Say your have 3 web servers at 3 different locations. When the lookup is done the DNS server will respond with a different IP for each request. Some DNS servers also allow a policy based config... wherein it can return a certain IP 70% of time and some other IP 30% of the time.

This document provides reference on how to do this with Windows 2016.


问:
Web Service Security Username Token
Is there any good tutorial on how to implement the Web Service security username token in a C# web service header?

Can some body point me to one.

Thanks

答:
Here is an article that, I believe, can be of help to you : http://www.primaryobjects.com/2015/05/08/token-based-authentication-for-web-service-apis-in-c-mvc-net/

If you prefer video tutorial, here’s the good one :  https://youtu.be/7E6wNd_9FJ0

I would recommend you to go through article, read it carefully and try to implement it side by side.

Hope it helps! :)

Title: Web Service Security Username Token


问:
Fixing Laravel form array validation recursion limits
Laravel Form Validation is great, except that it doesn't filter out extraneous keys when array notation is used.

I am type hinting the form request in my controller.

```<code>public function saveEdit(Post\EditRequest $request)
{
    $valid = $request->validated();
}
</code>```

If my form has address_1 and address_2, and the user spoofs address_3, the spoofed value will not turn up in $valid.

However, if my form uses array notation, such as venue[address_1], and venue[address_2], then the user can spoof venue[address_3], and it will turn up in $valid.

Has anyone else come across this? How did you deal with it?

It seems like the validated() method on the form request class needs to operate recursively.

答:
Unfortunately, Laravel doesn't include built-in support for validating array keys yet, only array values. To do so, we need to add custom validation rules.

However, with alternative protection like $fillable model attributes and the array_only() helper function, creating these rules is a lot of extra work for a very unlikely edge case. We provide validation feedback for expected user error and sanitize to protect our data from unexpected input.

If the user spoofs a key, as long as we don't save it, or we filter it out, they won't be too concerned if they don't see a pretty validation message—it doesn't make sense to validate a field that shouldn't exist in the first place.

To illustrate how sanitization works, here's a Venue model that declares its fillable attributes:

class Venue extends Model
{
    protected $fillable = [ 'address_1', 'address_2' ];
    ...
}
```

<p>Now, if a malicious user attempts to spoof another attribute in the array: </p>

<pre class="lang-php prettyprint-override"><code><input name="venue[address_1]" value="...">
<input name="venue[address_2]" value="...">
<input name="venue[address_3]" value="spoof!">
</code>```

...and we use the input array directly to update a model:

public function update(Request $request, $venueId)
{
    $venue = Venue::find($venueId);
    $venue->update($request->venue);
    ...
}
```

<p>...the model will strip out the additional <code>address_3</code> element from the input array because we never declared it as a fillable field. In other words, the model sanitized the input. </p>

<p>In some cases, we may need to simply sanitize array elements without using Eloquent models. We can use the <code>array_only()</code> function (or <code>Arr:only()</code>) to do this:</p>

<pre class="lang-php prettyprint-override"><code>$venueAddress = array_only($request->venue, [ 'address_1', 'address_2' ]);
</code>```

Body:
Laravel Form Validation is great, except that it doesn't filter out extraneous keys when array notation is used.

I am type hinting the form request in my controller.

public function saveEdit(Post\EditRequest $request)
{
    $valid = $request->validated();
}

If my form has address_1 and address_2, and the user spoofs address_3, the spoofed value will not turn up in $valid.

However, if my form uses array notation, such as venue[address_1], and venue[address_2], then the user can spoof venue[address_3], and it will turn up in $valid.

Has anyone else come across this? How did you deal with it?

It seems like the validated() method on the form request class needs to operate recursively.

Body:
Unfortunately, Laravel doesn't include built-in support for validating array keys yet, only array values. To do so, we need to add custom validation rules.

However, with alternative protection like $fillable model attributes and the array_only() helper function, creating these rules is a lot of extra work for a very unlikely edge case. We provide validation feedback for expected user error and sanitize to protect our data from unexpected input.

If the user spoofs a key, as long as we don't save it, or we filter it out, they won't be too concerned if they don't see a pretty validation message—it doesn't make sense to validate a field that shouldn't exist in the first place.

To illustrate how sanitization works, here's a Venue model that declares its fillable attributes:

class Venue extends Model
{
    protected $fillable = [ 'address_1', 'address_2' ];
    ...
}

Now, if a malicious user attempts to spoof another attribute in the array:

<input name="venue[address_1]" value="...">
<input name="venue[address_2]" value="...">
<input name="venue[address_3]" value="spoof!">

...and we use the input array directly to update a model:

public function update(Request $request, $venueId)
{
    $venue = Venue::find($venueId);
    $venue->update($request->venue);
    ...
}

...the model will strip out the additional address_3 element from the input array because we never declared it as a fillable field. In other words, the model sanitized the input.

In some cases, we may need to simply sanitize array elements without using Eloquent models. We can use the array_only() function (or Arr:only()) to do this:

$venueAddress = array_only($request->venue, [ 'address_1', 'address_2' ]);