问:
How do I calculate a for loop to display in a listbox where the first loop is user input but the remaining iterations are calculated?
I am trying to create a loop that will calculate inside a listbox but run the actual calculation after the first statement and compound the remaining...

Here is my code:

```<code> // Count Loop
 int numdays;
 numdays = 1;

 // Declare and Assign Variables
 double organism, daysmultiply, dailyincrease;
 organism = double.Parse(OrganismTextBox.Text);
 dailyincrease = double.Parse(DailyIncreaseTextBox.Text);
 daysmultiply = double.Parse(DaysMultiplyTextBox.Text);
 ResultsListBox.Items.Clear();

 // Need to have daily increase texbox formatted as a percentage - unsure how
 for (numdays = 0;  numdays <= daysmultiply; numdays++)
 {
     ResultsListBox.Items.Add(" Day " + numdays + " Popualtion is " + (organism * dailyincrease));
     numdays = numdays++;
 }
</code>```

The result of the calculation is a loop that calculates .6 each time it iterates. I am trying to figure out how to compound the loop each time.
Can someone please help?

答:
Your values don't "compound", because you do nothing in the loop that would cause that to happen, i.e. to change the values of the variables involved in calculating your values.

Your loop has other issues as well: you increment the loop index twice for each iteration; and you unnecessarily reassign the result of the post-increment operator back to the variable (the whole point of the operator is to do that assignment implicitly).

You probably want a loop that looks more like this:

```<code>for (numdays = 0;  numdays <= daysmultiply; numdays++)
{
     ResultsListBox.Items.Add(" Day " + numdays + " Population is " + organism);
     organism = organism * dailyincrease;
}
</code>```

or possibly:

```<code>for (numdays = 0;  numdays <= daysmultiply; numdays++)
{
     ResultsListBox.Items.Add(" Day " + numdays + " Population is " + organism);
     organism += organism * dailyincrease;
}
</code>```

The first example simply multiplies the organism value by the dailyincrease value. The second example does that multiplication and then adds the result to the current organism value. It's not clear from your question which is appropriate; it would depend on what the actual meaning of dailyincrease is. That is, if it's strictly the scale applied each day, then the first example is correct. If it's a representation of the percentage change (e.g. the 0.6 to which you refer means that the population increases 60% each day), then the second example is correct.

Body:
I am trying to create a loop that will calculate inside a listbox but run the actual calculation after the first statement and compound the remaining...

Here is my code:

 // Count Loop
 int numdays;
 numdays = 1;

 // Declare and Assign Variables
 double organism, daysmultiply, dailyincrease;
 organism = double.Parse(OrganismTextBox.Text);
 dailyincrease = double.Parse(DailyIncreaseTextBox.Text);
 daysmultiply = double.Parse(DaysMultiplyTextBox.Text);
 ResultsListBox.Items.Clear();

 // Need to have daily increase texbox formatted as a percentage - unsure how
 for (numdays = 0;  numdays <= daysmultiply; numdays++)
 {
     ResultsListBox.Items.Add(" Day " + numdays + " Popualtion is " + (organism * dailyincrease));
     numdays = numdays++;
 }

The result of the calculation is a loop that calculates .6 each time it iterates. I am trying to figure out how to compound the loop each time.
Can someone please help?

Body:
Your values don't "compound", because you do nothing in the loop that would cause that to happen, i.e. to change the values of the variables involved in calculating your values.

Your loop has other issues as well: you increment the loop index twice for each iteration; and you unnecessarily reassign the result of the post-increment operator back to the variable (the whole point of the operator is to do that assignment implicitly).

You probably want a loop that looks more like this:

for (numdays = 0;  numdays <= daysmultiply; numdays++)
{
     ResultsListBox.Items.Add(" Day " + numdays + " Population is " + organism);
     organism = organism * dailyincrease;
}

or possibly:

for (numdays = 0;  numdays <= daysmultiply; numdays++)
{
     ResultsListBox.Items.Add(" Day " + numdays + " Population is " + organism);
     organism += organism * dailyincrease;
}

The first example simply multiplies the organism value by the dailyincrease value. The second example does that multiplication and then adds the result to the current organism value. It's not clear from your question which is appropriate; it would depend on what the actual meaning of dailyincrease is. That is, if it's strictly the scale applied each day, then the first example is correct. If it's a representation of the percentage change (e.g. the 0.6 to which you refer means that the population increases 60% each day), then the second example is correct.


来源: stackexchange

问:
MS Word hindi chart
I work with Microsoft Office Word 2010, and I want to type numbers with Hindi language.
So I go to "Options" and set Numeral to Hindi.
Now I can write hindi numbers ...
But in charts, my numbers don't change to Hindi, and they are still Latin. (I set MS Excel numeral to Hindi too.)

How can I change these??? This is a bad problem!!

答: A workaround would be to download a Hindi font, say from here: Hindi Fonts. Paste them in the fonts folder in Control Panel. Restart word. Now, in your chart, select the numbers that you wish to show in Hindi, and select the Hindi font you just downloaded. Use Font2 or Font3 from the given link, and it should do the trick.</p>

ContentLicense: CC BY-SA 2.5

Title: MS Word hindi chart


问:
Understanding visuals in VEINS and Omnet++
I was able to create routing config files for sumo, link them with Omnet++ and VEINS. When I ran the VEINS simulation, I see the movement of the vehicles and exchange of information between them as seen here :

Questions:

Where can I find more exact information about the color of nodes : when the node circle is green, red, etc.?

What do these blue connecting lines in the debug mode mean? Where can I find more information?

答:
When the node receives a message named "data" it calls onData() which, among others, does the animations you are asking for

```<code>else if (std::string(wsm->getName()) == "data") {
    onData(wsm);
</code>```

Where can I find more exact information about the color of nodes :
  when the node circle is green, red, etc.?

```<code>void TraCIDemo11p::onData(WaveShortMessage* wsm) {
    // Here is the green color for the nodes
    findHost()->getDisplayString().updateWith("r=16,green");
    // Here the blue lines are drawn
    annotations->scheduleErase(1, annotations->drawLine(wsm->getSenderPos(), mobility->getPositionAt(simTime()), "blue"));

    if (mobility->getRoadId()[0] != ':') traciVehicle->changeRoute(wsm->getWsmData(), 9999);
    if (!sentMessage) sendMessage(wsm->getWsmData());
}
</code>```

What do these blue connecting lines in the debug mode mean? Where can
  I find more information?

When a node receives a data message, a blue line is drawn by the receiving node, from itself to the node that sent the message.

ContentLicense: CC BY-SA 3.0

Body:
When the node receives a message named "data" it calls onData() which, among others, does the animations you are asking for

else if (std::string(wsm->getName()) == "data") {
    onData(wsm);

Where can I find more exact information about the color of nodes :
  when the node circle is green, red, etc.?

void TraCIDemo11p::onData(WaveShortMessage* wsm) {
    // Here is the green color for the nodes
    findHost()->getDisplayString().updateWith("r=16,green");
    // Here the blue lines are drawn
    annotations->scheduleErase(1, annotations->drawLine(wsm->getSenderPos(), mobility->getPositionAt(simTime()), "blue"));

    if (mobility->getRoadId()[0] != ':') traciVehicle->changeRoute(wsm->getWsmData(), 9999);
    if (!sentMessage) sendMessage(wsm->getWsmData());
}

What do these blue connecting lines in the debug mode mean? Where can
  I find more information?

When a node receives a data message, a blue line is drawn by the receiving node, from itself to the node that sent the message.


问:
Making a new column in pandas based on conditions of other columns
I would like to make a new column based on an if statement that has conditionals of two or more other columns in a dataframe.

For example, column3 = True if (column1 < 10.0) and (column2 > 0.0).

I have looked around and it seems that other have used the apply method with a lambda function, but i am a bit of a novice on these.

I suppose i could make two additional columns that makes that row a 1 if the condition is met for each column, then sum the columns to check if all conditions are met, but this seems a bit inelegant.

If you provide an answer with apply/lambda, let's suppose the dataframe is called sample_df and the columns are col1, col2, and col3.

Thanks so much!

答:
You can use eval here for short:

```<code># create some dummy data
df = pd.DataFrame(np.random.randint(0, 10, size=(5, 2)),
                  columns=["col1", "col2"])
print(df)

    col1    col2
0   1       7
1   2       3
2   4       6
3   2       5
4   5       4

df["col3"] = df.eval("col1 < 5 and col2 > 5")
print(df)

    col1    col2    col3
0   1       7       True
1   2       3       False
2   4       6       True
3   2       5       False
4   5       4       False
</code>```

You can also write it without eval via (df["col1"] < 5) & (df["col2"] > 5).

You may also enhance the example with np.where to explicitly set the values for the positive and negative cases right away:

```<code>df["col4"] = np.where(df.eval("col1 < 5 and col2 > 5"), "Positive Value", "Negative Value")
print(df)

    col1    col2    col3    col4
0   1       7       True    Positive Value
1   2       3       False   Negative Value
2   4       6       True    Positive Value
3   2       5       False   Negative Value
4   5       4       False   Negative Value
</code>```

Body:
You can use eval here for short:

# create some dummy data
df = pd.DataFrame(np.random.randint(0, 10, size=(5, 2)),
                  columns=["col1", "col2"])
print(df)

    col1    col2
0   1       7
1   2       3
2   4       6
3   2       5
4   5       4

df["col3"] = df.eval("col1 < 5 and col2 > 5")
print(df)

    col1    col2    col3
0   1       7       True
1   2       3       False
2   4       6       True
3   2       5       False
4   5       4       False

You can also write it without eval via (df["col1"] < 5) & (df["col2"] > 5).

You may also enhance the example with np.where to explicitly set the values for the positive and negative cases right away:

df["col4"] = np.where(df.eval("col1 < 5 and col2 > 5"), "Positive Value", "Negative Value")
print(df)

    col1    col2    col3    col4
0   1       7       True    Positive Value
1   2       3       False   Negative Value
2   4       6       True    Positive Value
3   2       5       False   Negative Value
4   5       4       False   Negative Value


问:
Copy Value of Local into Pointer
Trying to find the correct way to do this, but can't seem to find the correct syntax anywhere..

all I want to do is copy the the value of a local variable into a pointer, so I may use that pointer anywhere. Otherwise when the method returns the value of the that pointer will be unpredictable.. Heres what I have but it seems to still just reference the address of the local variable

```<code>void method(){

 unsigned int localValue = 0x00FF00AA;
 unsigned int *point = (unsigned int *) 0x00000000;
 *point = localValue;
}
</code>```

but this code just seg faults. Is there a way to do this?

答:
Program received signal SIGSEGV, Segmentation fault.

In C code, segmentation faults most often occur because of errors in
  pointer use. Dereferencing a null pointer will always result in a segmentation fault, but wild pointers and dangling pointers point to memory that may or may not exist, and may or may not be readable or writable, and thus can result in transient bugs.

```<code>line 8        *point = localValue;
</code>```

Here your assigning local value to the pointer that causing the SIGSEGV.

Try this.

```<code>#include <stdio.h>

void method(){
    unsigned int localValue = 0x00FF00AA;
    unsigned int *point = &localValue;
    printf("%p\n", *point); //this just debug code
}

int main(void) {
    method();

    return 0;
}
</code>```

Title: Copy Value of Local into Pointer

Body:
Trying to find the correct way to do this, but can't seem to find the correct syntax anywhere..

all I want to do is copy the the value of a local variable into a pointer, so I may use that pointer anywhere. Otherwise when the method returns the value of the that pointer will be unpredictable.. Heres what I have but it seems to still just reference the address of the local variable

void method(){

 unsigned int localValue = 0x00FF00AA;
 unsigned int *point = (unsigned int *) 0x00000000;
 *point = localValue;
}

but this code just seg faults. Is there a way to do this?

Body:
Program received signal SIGSEGV, Segmentation fault.

In C code, segmentation faults most often occur because of errors in
  pointer use. Dereferencing a null pointer will always result in a segmentation fault, but wild pointers and dangling pointers point to memory that may or may not exist, and may or may not be readable or writable, and thus can result in transient bugs.

line 8        *point = localValue;

Here your assigning local value to the pointer that causing the SIGSEGV.

Try this.

#include <stdio.h>

void method(){
    unsigned int localValue = 0x00FF00AA;
    unsigned int *point = &localValue;
    printf("%p\n", *point); //this just debug code
}

int main(void) {
    method();

    return 0;
}


问:
Rails - How to add values in seperate objects together
You have an array of objects which contain a key-value reference.

```<code>[{booking_ref: 'w578383', foo: 'bar', price1: 500, price2: 30],
{booking_ref: 'w578383', foo: 'bar', price1: 600, price2: 40},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]
</code>```

I want to:

group objects by key-value reference (booking_ref)

go through those groupings and to each object add the financial values only together (price1 and price2 to the other booking's price1 and price2)

collapse out of groupings back to an array of objects which contain a key-value reference. That would now be:

```<code>[{booking_ref: 'w578383', foo: 'bar', price1: 1100, price2: 70},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]
</code>```

I am thinking:

```<code>objects.group_by(&:booking_ref).each {|group|
  group.merge {|key, value1, value2| value1 + value2 if key == price1 || price2}
}
</code>```

Does that work and if so how do I then return them back out of the group_by state?

答:
With hash objects, you could calculate the sums and merge them back to the first hash in each group :</p>

```<code>bookings = [
{booking_ref: 'w578383', foo: 'bar', price1: 500, price2: 30},
{booking_ref: 'w578383', foo: 'bar', price1: 600, price2: 40},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}
]

grouped_bookings = bookings.group_by{ |h| h[:booking_ref] }.map do |ref, hs|
  sums = hs.each_with_object(Hash.new(0)) do |h, sum|
    %i(price1 price2).each do |price|
      sum[price] += h[price].to_i
    end
  end
  hs.first.merge(sums)
end

p grouped_bookings
# [{:booking_ref=>"w578383", :foo=>"bar", :price1=>1100, :price2=>70},
# {:booking_ref=>"r123523", :foo=>"bar", :price1=>699, :price2=>4}]
</code>```

Body:
You have an array of objects which contain a key-value reference.

[{booking_ref: 'w578383', foo: 'bar', price1: 500, price2: 30],
{booking_ref: 'w578383', foo: 'bar', price1: 600, price2: 40},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]

I want to:

group objects by key-value reference (booking_ref)

go through those groupings and to each object add the financial values only together (price1 and price2 to the other booking's price1 and price2)

collapse out of groupings back to an array of objects which contain a key-value reference. That would now be:

[{booking_ref: 'w578383', foo: 'bar', price1: 1100, price2: 70},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]

I am thinking:

objects.group_by(&:booking_ref).each {|group|
  group.merge {|key, value1, value2| value1 + value2 if key == price1 || price2}
}

Does that work and if so how do I then return them back out of the group_by state?

Body:
With hash objects, you could calculate the sums and merge them back to the first hash in each group :

bookings = [
{booking_ref: 'w578383', foo: 'bar', price1: 500, price2: 30},
{booking_ref: 'w578383', foo: 'bar', price1: 600, price2: 40},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}
]

grouped_bookings = bookings.group_by{ |h| h[:booking_ref] }.map do |ref, hs|
  sums = hs.each_with_object(Hash.new(0)) do |h, sum|
    %i(price1 price2).each do |price|
      sum[price] += h[price].to_i
    end
  end
  hs.first.merge(sums)
end

p grouped_bookings
# [{:booking_ref=>"w578383", :foo=>"bar", :price1=>1100, :price2=>70},
# {:booking_ref=>"r123523", :foo=>"bar", :price1=>699, :price2=>4}]


问:
C# Generating new id from database on windows forms application
I have to make automatic generate new AccountID  on my load windows form app.

So for example when users start windows form "Add new Account" in textbox for "Account id" I have to show latest value from database. If i have two accounts in database on windows form in textbox value will be three.

My code perfectly work if i have at least one account in database, but when my database is empty i got exception.

This is my code:

```<code>public int GetLatestAccountID()
{
    try
    {
        command.CommandText = "select Max(AccountID)as maxID from Account";
        command.CommandType = CommandType.Text;

        connection.Open();

        OleDbDataReader reader= command.ExecuteReader();

        if (reader.Read())
        {
            int valueID = Convert.ToInt32(reader["maxID"]);
            return valueID + 1;
        }

        return 1;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (connection!= null)
        {
            connection.Close();
        }
    }
}
</code>```

Also I find answer on stackoverflow:

```<code>object aa = DBNull.Value;
int valueID = (aa as int?).GetValueOrDefault();
</code>```

But this line of code works if my database is empty, but when I have one account in the database, it will always show on my windows form in account id textbox value one. I use Microsoft Access 2007 database.

I appreciate any help.

答:
I'm guessing you want:

```<code>public int GetLatestAccountID(string connectionString)
{
    using(var dbConn = new OleDbConnection(connectionString))
    {
        dbConn.Open();

        string query = "select Max(AccountID) from Account";
        using(var dbCommand = new OleDbCommand(query, dbConn))
        {
            var value = dbCommand.ExecuteScalar();
            if ((value != null) && (value != DBNull.Value))
                return Convert.ToInt32(value) + 1;

            return 1;
        }
    }
}
</code>```

It looks like you're opening your database connection once and leaving it open during your entire program. Don't do that; that leads to race conditions and data corruption. .NET implements database connection pooling so you're not improving performance at all by leaving connections open.

You're also not telling us what you're using GetLatestAccountID for. If you're trying to use that as a primary key you are also going to run into problems with race conditions. If you want a primary key you should let the database create it and return the value after you've created the record.

Body:
I have to make automatic generate new AccountID  on my load windows form app.

So for example when users start windows form "Add new Account" in textbox for "Account id" I have to show latest value from database. If i have two accounts in database on windows form in textbox value will be three.

My code perfectly work if i have at least one account in database, but when my database is empty i got exception.

This is my code:

public int GetLatestAccountID()
{
    try
    {
        command.CommandText = "select Max(AccountID)as maxID from Account";
        command.CommandType = CommandType.Text;

        connection.Open();

        OleDbDataReader reader= command.ExecuteReader();

        if (reader.Read())
        {
            int valueID = Convert.ToInt32(reader["maxID"]);
            return valueID + 1;
        }

        return 1;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (connection!= null)
        {
            connection.Close();
        }
    }
}

Also I find answer on stackoverflow:

object aa = DBNull.Value;
int valueID = (aa as int?).GetValueOrDefault();

But this line of code works if my database is empty, but when I have one account in the database, it will always show on my windows form in account id textbox value one. I use Microsoft Access 2007 database.

I appreciate any help.

Body:
I'm guessing you want:

public int GetLatestAccountID(string connectionString)
{
    using(var dbConn = new OleDbConnection(connectionString))
    {
        dbConn.Open();

        string query = "select Max(AccountID) from Account";
        using(var dbCommand = new OleDbCommand(query, dbConn))
        {
            var value = dbCommand.ExecuteScalar();
            if ((value != null) && (value != DBNull.Value))
                return Convert.ToInt32(value) + 1;

            return 1;
        }
    }
}

It looks like you're opening your database connection once and leaving it open during your entire program. Don't do that; that leads to race conditions and data corruption. .NET implements database connection pooling so you're not improving performance at all by leaving connections open.

You're also not telling us what you're using GetLatestAccountID for. If you're trying to use that as a primary key you are also going to run into problems with race conditions. If you want a primary key you should let the database create it and return the value after you've created the record.


问:
Compiling PipelineDB on RaspberryPi 2
I'm trying to compile PipelineDB on a RasberryPi 2 running Raspbian.
I followed the instructions and installed ZeroMQ. I get this error:

```<code>In file included from ../../../../src/include/pgstat.h:18:0,
                 from brin.c:29:
../../../../src/include/pipeline/scheduler.h:53:2: error: unknown type name ‘pg_atomic_uint64’
  pg_atomic_uint64 generation;
</code>```

Can anyone help?

答: Your architecture likely does not support 64-bit atomic operations, which PipelineDB requires. See https://github.com/pipelinedb/pipelinedb/blob/master/src/include/port/atomics.h#L61</p>

Title: Compiling PipelineDB on RaspberryPi 2

Body:
I'm trying to compile PipelineDB on a RasberryPi 2 running Raspbian.
I followed the instructions and installed ZeroMQ. I get this error:

In file included from ../../../../src/include/pgstat.h:18:0,
                 from brin.c:29:
../../../../src/include/pipeline/scheduler.h:53:2: error: unknown type name ‘pg_atomic_uint64’
  pg_atomic_uint64 generation;

Can anyone help?


问:
Graceful handing over resources from initramfs to userspace
There are hardware devices which need userspace suppport, like daemon running and handling parts of interaction not suitable (too complex or policy-related) for kernel space.

Running such daemons is easy once you reach userspace -- you can run'em as a result of hotplug event and don't worry much.

Once initramfs comes to the picture, everything suddenly breaks apart: if the daemon is run from initramfs then it needs to either keep running when execution is switched to regular rootfs, which is particularily hard, given initramfs is freed during switch_root or hand out resources and state to another copy of itself, run from rootfs. Both solutions seem inelegant and hacky.

Is there obvious way to manage such devices and their supporting daemons I overlooked?

答:
Do you have a specific case? How have the other distributions handled this?

Looking at how Fedora does udev, it starts it up from the initramfs, gets it to do its stuff so the really root fs can be mounted, then shuts it down again before switching.


问:
how to do the concurrent version of List.map in ocaml?
I am trying to implement the concurrent version of List.map function in Ocaml. I know there is a similar function in module Async.Std.Deferred.List, but here I am just trying to attack this myself.

Here is what I have:

```<code>let deferred_listmap (f : 'a -> 'b Deferred.t) (l : 'a list) =
let f' acc elem =
    (f elem) >>= fun s ->
    return (acc@[s]) in
List.fold_left f' [] l
</code>```

And obviously there is a type matching error here, since fold_left requires a function f with type ('b list -> 'a -> 'b list), while the f' I have here is of type ('b list -> 'a -> 'b list Deferred.t). But for this I cannot help since I am using a bind(>>=) here which expects the return type of its function argument to be a deferred type. So I am getting kind of a contradiction here, and I cannot think of other uses on bind or folds or other functions in List module to solve this. Any suggestions?

答:
I guess you could try with the Thread and Event Modules .

```<code>open Thread
open Event

let tapply f ls =
    let res =
        List.map (fun e ->
        let c = new_channel () in
        let _ = create (fun c -> send c (f e) |> sync) c in
        receive c) ls in
        List.map sync res
</code>```

example :

```<code># tapply (fun e -> delay 3.0; e*e) [17;573;2;6;3];;
- : int list = [289; 328329; 4; 36; 9] (*waiting time only 3 sec, not 15*)
</code>```

Body:
I am trying to implement the concurrent version of List.map function in Ocaml. I know there is a similar function in module Async.Std.Deferred.List, but here I am just trying to attack this myself.

Here is what I have:

let deferred_listmap (f : 'a -> 'b Deferred.t) (l : 'a list) =
let f' acc elem =
    (f elem) >>= fun s ->
    return (acc@[s]) in
List.fold_left f' [] l

And obviously there is a type matching error here, since fold_left requires a function f with type ('b list -> 'a -> 'b list), while the f' I have here is of type ('b list -> 'a -> 'b list Deferred.t). But for this I cannot help since I am using a bind(>>=) here which expects the return type of its function argument to be a deferred type. So I am getting kind of a contradiction here, and I cannot think of other uses on bind or folds or other functions in List module to solve this. Any suggestions?

Body:
I guess you could try with the Thread and Event Modules .

open Thread
open Event

let tapply f ls =
    let res =
        List.map (fun e ->
        let c = new_channel () in
        let _ = create (fun c -> send c (f e) |> sync) c in
        receive c) ls in
        List.map sync res

example :

# tapply (fun e -> delay 3.0; e*e) [17;573;2;6;3];;
- : int list = [289; 328329; 4; 36; 9] (*waiting time only 3 sec, not 15*)


问:
Trying to update a dataframe
I have a dataframe (df) which looks like:

```<code>0   1                   2                       3
0   BBG.apples.S        BBG.XNGS.bananas.S      0
1   BBG.apples.S        BBG.XNGS.oranges.S      0
2   BBG.apples.S        BBG.XNGS.pairs.S        0
3   BBG.apples.S        BBG.XNGS.mango.S        0
4   BBG.apples.S        BBG.XNYS.mango.S        0
5   BBG.XNGS.bananas.S  BBG.XNGS.oranges.S      0
6   BBG.XNGS.bananas.S  BBG.XNGS.pairs.S        0
7   BBG.XNGS.bananas.S  BBG.XNGS.kiwi.S         0
8   BBG.XNGS.oranges.S  BBG.XNGS.pairs.S        0
9   BBG.XNGS.oranges.S  BBG.XNGS.kiwi.S         0
10  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
11  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
12  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
13  BBG.XNGS.peaches.S  BBG.XNGS.kiwi.S         0
</code>```

I am trying to update a value (first row, third column) in the dataframe using:

```<code>for index, row in df.iterrows():

        status = row[3]

        if int(status) == 0:

            df[index]['3'] = 1
</code>```

but when I print the dataframe out it remains unchanged.

What am I doing wrong?

答:
You can't modify a data frame by iterating like that. See here.

If you only want to modify the element at [1, 3], you can access it directly:

```<code>df[1, 3] = 1
</code>```

If you're trying to turn every 0 in column 3 to a 1, try this:

```<code>df[df['3'] == 0] = 1
</code>```

EDIT: In addition, the docs for iterrows say that you'll often get a copy back, which is why the operation fails.

ContentLicense: CC BY-SA 4.0

Title: Trying to update a dataframe

Body:
I have a dataframe (df) which looks like:

0   1                   2                       3
0   BBG.apples.S        BBG.XNGS.bananas.S      0
1   BBG.apples.S        BBG.XNGS.oranges.S      0
2   BBG.apples.S        BBG.XNGS.pairs.S        0
3   BBG.apples.S        BBG.XNGS.mango.S        0
4   BBG.apples.S        BBG.XNYS.mango.S        0
5   BBG.XNGS.bananas.S  BBG.XNGS.oranges.S      0
6   BBG.XNGS.bananas.S  BBG.XNGS.pairs.S        0
7   BBG.XNGS.bananas.S  BBG.XNGS.kiwi.S         0
8   BBG.XNGS.oranges.S  BBG.XNGS.pairs.S        0
9   BBG.XNGS.oranges.S  BBG.XNGS.kiwi.S         0
10  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
11  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
12  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
13  BBG.XNGS.peaches.S  BBG.XNGS.kiwi.S         0

I am trying to update a value (first row, third column) in the dataframe using:

for index, row in df.iterrows():

        status = row[3]

        if int(status) == 0:

            df[index]['3'] = 1

but when I print the dataframe out it remains unchanged.

What am I doing wrong?

Body:
You can't modify a data frame by iterating like that. See here.

If you only want to modify the element at [1, 3], you can access it directly:

df[1, 3] = 1

If you're trying to turn every 0 in column 3 to a 1, try this:

df[df['3'] == 0] = 1

EDIT: In addition, the docs for iterrows say that you'll often get a copy back, which is why the operation fails.


问:
Have two elements side by side fill all space vertically
I have two elements in my page's body that I want to live side by side and fill all vertical space.

My code is super simple:

```<code><!-- index.html minus all the usual junk-->
<!-- also ignore the lack of a url-tag and the like, it's intentionally left out -->
<body>
  <textarea id="text-field">
  <iframe id="render-field">
</body>
</code>```

and

```<code>// index.css
body {
  font: caption;
  display: flex;
  height: 100%;
}

#text-field {
  font-family: Courier;
  width: 50%;
  flex: 1 0 auto;
}

#render-field {
  width: 50%;
  flex: 1 0 auto;
}
</code>```

It doesn't matter what I try, the two elements will not fill all the sapce available in the body.

Any help?

答:
Here's a plunker example using vh

vh    Relative to 1% of the height of the viewport*

Plunker example

Reference

Body:
I have two elements in my page's body that I want to live side by side and fill all vertical space.

My code is super simple:

  <textarea id="text-field">

and

// index.css
body {
  font: caption;
  display: flex;
  height: 100%;
}

#text-field {
  font-family: Courier;
  width: 50%;
  flex: 1 0 auto;
}

#render-field {
  width: 50%;
  flex: 1 0 auto;
}

It doesn't matter what I try, the two elements will not fill all the sapce available in the body.

Any help?


问:
SyntaxError: invalid syntax when opening a file
```<code>import re

fhand = open('sum.txt','r')
number = re.findall('[0-9]'+, fhand)
print number
</code>```

I am getting syntax error as

```<code> number = re.findall('[0-9]'+, fhand)
                              ^
     SyntaxError: invalid syntax
</code>```

Not sure what's going on. Can anybody help?

答:
Read the file contents and declare the entire pattern inside a string literal.

Here is an example:

```<code>>>> import re
>>> fhand = open(r'D:\2\_1.txt','r')
>>> fhand
<open file 'D:\\2\\_1.txt', mode 'r' at 0x0282B230>
>>> number = re.findall('[0-9]+', fhand.read())
>>> print number
['1', '2', '3', '1', '0', '2', '0', '7', '0', '2', '2', '0', '3', '0', '5', '0', '3']
>>>
</code>```

Body:
import re

fhand = open('sum.txt','r')
number = re.findall('[0-9]'+, fhand)
print number

I am getting syntax error as

 number = re.findall('[0-9]'+, fhand)
                              ^
     SyntaxError: invalid syntax

Not sure what's going on. Can anybody help?

Body:
Read the file contents and declare the entire pattern inside a string literal.

Here is an example:

>>> import re
>>> fhand = open(r'D:\2\_1.txt','r')
>>> fhand
<open file 'D:\\2\\_1.txt', mode 'r' at 0x0282B230>
>>> number = re.findall('[0-9]+', fhand.read())
>>> print number
['1', '2', '3', '1', '0', '2', '0', '7', '0', '2', '2', '0', '3', '0', '5', '0', '3']
>>>


问:
How to merge two excel sheets by patient ID without excluding duplicate data
I want to merge two data sheets by patient ID including all data. Is there an easy way to combine two excel sheets and create one data file in excel.
Sheet 1 is in the left side and sheet 2 is in the right side.

答:
You can use Manthan Patel's Vlookup method if you create a unique ID on both sheets.  You can create a dummy ID by inserting a column to the left of your ID and then use

```<code>=B2 & "-" & countif($B$2:B2,B2)
</code>```

in cell A2 and then auto-fill down.  You will then have a unique ID for each row that you can use a vlookup on to get the data onto sheet2.  The ID will be 1-1, 1-2, 2-1,

The limitation will be if Sheet2 has less rows for a particular patient ID than Sheet1 so you need to also think about the output that you are trying to acheive when you merge the sheets.

Body:
You can use Manthan Patel's Vlookup method if you create a unique ID on both sheets.  You can create a dummy ID by inserting a column to the left of your ID and then use

=B2 & "-" & countif($B$2:B2,B2)

in cell A2 and then auto-fill down.  You will then have a unique ID for each row that you can use a vlookup on to get the data onto sheet2.  The ID will be 1-1, 1-2, 2-1,

The limitation will be if Sheet2 has less rows for a particular patient ID than Sheet1 so you need to also think about the output that you are trying to acheive when you merge the sheets.


问:
ASP NET SQL - select * from where author
I'm having a problem showing equal results from SQL database

```<code>"select * from Log where Author=" + User.Identity.Name
</code>```

That's the current command I've tried, but can't get it working.

while this works:

```<code>"select * from Log where Author='markus'"
</code>```

Thanks for any help.

答:
You can wrap the string in single quotes like this:

```<code>"select * from Log where Author='" + User.Identity.Name + "'"
</code>```

However the standard way of doing this is using parameterized statements:

```<code>"select * from Log where Author = @Author";
</code>```

Then apply the value to param @Author using SqlParameter.

For more info, see:

Why do we always prefer using parameters in SQL statements?

Body:
I'm having a problem showing equal results from SQL database

"select * from Log where Author=" + User.Identity.Name

That's the current command I've tried, but can't get it working.

while this works:

"select * from Log where Author='markus'"

Thanks for any help.

Body:
You can wrap the string in single quotes like this:

"select * from Log where Author='" + User.Identity.Name + "'"

However the standard way of doing this is using parameterized statements:

"select * from Log where Author = @Author";

Then apply the value to param @Author using SqlParameter.

For more info, see:

Why do we always prefer using parameters in SQL statements?


问:
2 classes in 2 header files
I am trying to compile a program that has 2 .h and 3.cpp . I keep getting the same error message: "error: ‘Patrons’ does not name a type   Patrons match;"

when I put the whole code in one single .cpp file, I have no errors and it compiles, but for my assignment I need to do it in separate files.

I think I wrote the code right so I dont know why I get the error message.

```<code>// class patrons.h

using namespace std;

class Patrons //named it patrons because this is where i have a list of all    the patrons
{

    int patronscnt;
    public:
    std::list<string>::iterator PL;
    std::list<string> patslist;
    string name;
    void patronslist();
    void addpatron();
    void removepatron();
    void editpatron();

};
</code>```

-

```<code>// class patron.h

using namespace std;

class Patron //class decleration. Named it patron because it has the information of one patron
{
    string x;
    string input;//class members
    Patrons match;
    public:

    void ID();
    void email();
    void phone();
    void address();
    void borrowstatus();
    void finestatus();
    void check(string);
    //update
 };
</code>```

答: You need to include Patrons.h in Patrons: #include "Patrons.h"

Title: 2 classes in 2 header files

Body:
I am trying to compile a program that has 2 .h and 3.cpp . I keep getting the same error message: "error: ‘Patrons’ does not name a type   Patrons match;"

when I put the whole code in one single .cpp file, I have no errors and it compiles, but for my assignment I need to do it in separate files.

I think I wrote the code right so I dont know why I get the error message.

// class patrons.h

using namespace std;

class Patrons //named it patrons because this is where i have a list of all    the patrons
{

    int patronscnt;
    public:
    std::list<string>::iterator PL;
    std::list<string> patslist;
    string name;
    void patronslist();
    void addpatron();
    void removepatron();
    void editpatron();

};

-

// class patron.h

using namespace std;

class Patron //class decleration. Named it patron because it has the information of one patron
{
    string x;
    string input;//class members
    Patrons match;
    public:

    void ID();
    void email();
    void phone();
    void address();
    void borrowstatus();
    void finestatus();
    void check(string);
    //update
 };


问:
SimpleCursorAdapter within a ScrollView
I'm having  abit of an issue and i'm not too sure how to go about solving it.

Essentially i have an activity which has a base xml layout of ScrollView and i want this activity to list some results from a Cursor. So i thought i'd use SimpleCursorAdapter... however when i got it all set up it appears that the ListView that the SimpleCursorAdapter goes into doesn't play nice being within another scrollable layout element.

I've sorta got it working programmically but i'd much rather use a ListAdapter as it will make each list entry look like a button and keep it inline with the design of the rest of the application and can handle the ids of each item and where to send the user upon clicking.

So my question is this: is there anyway to either make ListView show all the items such that it never needs to scroll, or can i change the ListView to something like a LinearLayout?

I hope that makes sense!
Any help / insight / ideas are welcome!
Cheers!

答:
You can NEVER use a scroll view and a ListView together. Its a mess! and illogical as well.

Here are some of the approaches you can use:

Theres no screen big enough to show all the content of you listView you can try wrapping up your content but as I said it won't help as scroll view and list view don't work together. So you can either remove your or

If your list items are simple you can dynamically add your views to LinearLayout with specified location

Another tip I can give you is you can always use an relative layout and place your listView alignParentBottom="true" and emit the scrollView approach this will make you listview alwyas scrollable.

Title: SimpleCursorAdapter within a ScrollView


问:
Scrape all matching contents using XPath function
How do I make sure that my selenium code scrapes all matching contents of my XPath?

Please help me with your ideas.

For example, these are my HTML Tags:

```<code><tr class="1" role="r1">
    <td class="c1">
        <a href="www.google.com">
        </a>
    </td>
</tr>
<tr class="2" role="r2">
    <td class="c2">
        <a href="www.youtube.com">
        </a>
    </td>
</tr>
<tr class="3" role="c3">
    <td class="c3">
        <a href="www.facebook.com">
        </a>
    </td>
</tr>
</code>```

I want my selenium code to fetch all links from href tag.

So, below is my XPath:

```<code>String links = driver.findElement(By.xpath("//tr[@role='cad']//td[@class='c1']//a")).getAttribute("href");
System.out.println(links);
</code>```

but it fetches only the first href output, i.e. www.google.com.

The desired output is:

```<code>www.google.com
www.youtube.com
www.facebook.com
</code>```

How can I achieve this?

Any array implementation would be better options?

答:
Try below code.</p>

```<code>List<WebElement> links = driver.findElements(By.xpath("//tr/td/a"));

    for(int i=0;i<links.size();i++){
        System.out.println(links.get(i).getAttribute("href"));
    }
</code>```

Body:
How do I make sure that my selenium code scrapes all matching contents of my XPath?

Please help me with your ideas.

For example, these are my HTML Tags:

I want my selenium code to fetch all links from href tag.

So, below is my XPath:

String links = driver.findElement(By.xpath("//tr[@role='cad']//td[@class='c1']//a")).getAttribute("href");
System.out.println(links);

but it fetches only the first href output, i.e. www.google.com.

The desired output is:

www.google.com
www.youtube.com
www.facebook.com

How can I achieve this?

Any array implementation would be better options?

Body:
Try below code.

List<WebElement> links = driver.findElements(By.xpath("//tr/td/a"));

    for(int i=0;i<links.size();i++){
        System.out.println(links.get(i).getAttribute("href"));
    }


问:
How to prevent a value from being multiplied due to user inputs?
I'm making a fitness tracking website. Users can add weight loss goals and use a calorie calculator to calculate how many calories they've lost from certain exercises. I've implemented a progress bar which shows the users calorie loss progress. It also shows two values, one for the total number of calories the user has lost, and a value for the target number of calories the user is aiming to lose.

When I add more than one goal, the target number of calories value is correct, however, the value showing how many calories the user has lost seems to get multiplied by how many goals have been entered by that user.

I'm struggling on how to prevent this from happening and for the value to show how many calories the user has lost regardless of how many goals have been set.

For example, a user has burned 1310 calories in total. When a second weight loss goal is added by the user, this calorie loss value doubles to 2620 without the user inputting any weight loss activities.

This is the query I've used...

```<code>$sql = "SELECT
      SUM(calories) as calories
      , CASE g.weightunit
          WHEN 'lbs' THEN 3500
          ELSE 7700
        END * weightlost  as target_calories
    FROM (SELECT * FROM goal ORDER BY weightlost DESC) g
        INNER JOIN tracklog t USING (userid)
    WHERE userid = ? ";
$stmt = $con->prepare($sql);
$stmt->bind_param('i', $_SESSION['userid']);
$stmt->execute();
$stmt->bind_result($calories, $target);
$res = $stmt->fetch();
</code>```

答:
Consider joining the unit level, goal, to aggregate level, tracklog, then join by userid. Right now, you join both at unit level then aggregate, summing multiple times for multiple matches along joins.

SELECT t.SumCalories,
       CASE WHEN g.weightunit = 'lbs' THEN 3500 ELSE 7700 END *
           g.weightlost As Target_calories
FROM goal g
INNER JOIN
  (SELECT sub.userid, SUM(sub.calories) as SumCalories
   FROM tracklog sub
   GROUP BY sub.userid) t
USING (userid)
WHERE g.userid = ?
ORDER BY g.weightlost DESC
```

By the way, likely you are using MySQL with ONLY_FULL_GROUP_ON setting to off as the engine does not through a syntax error for having no specified non-aggregated columns in GROUP BY clause.

Every other RDBMS would thrown an error for this. As best practice, always use GROUP BY to specify groupings in aggregate queries to avoid unreliable results.

Body:
I'm making a fitness tracking website. Users can add weight loss goals and use a calorie calculator to calculate how many calories they've lost from certain exercises. I've implemented a progress bar which shows the users calorie loss progress. It also shows two values, one for the total number of calories the user has lost, and a value for the target number of calories the user is aiming to lose.

When I add more than one goal, the target number of calories value is correct, however, the value showing how many calories the user has lost seems to get multiplied by how many goals have been entered by that user.

I'm struggling on how to prevent this from happening and for the value to show how many calories the user has lost regardless of how many goals have been set.

For example, a user has burned 1310 calories in total. When a second weight loss goal is added by the user, this calorie loss value doubles to 2620 without the user inputting any weight loss activities.

This is the query I've used...

$sql = "SELECT
      SUM(calories) as calories
      , CASE g.weightunit
          WHEN 'lbs' THEN 3500
          ELSE 7700
        END * weightlost  as target_calories
    FROM (SELECT * FROM goal ORDER BY weightlost DESC) g
        INNER JOIN tracklog t USING (userid)
    WHERE userid = ? ";
$stmt = $con->prepare($sql);
$stmt->bind_param('i', $_SESSION['userid']);
$stmt->execute();
$stmt->bind_result($calories, $target);
$res = $stmt->fetch();

Body:
Consider joining the unit level, goal, to aggregate level, tracklog, then join by userid. Right now, you join both at unit level then aggregate, summing multiple times for multiple matches along joins.

SELECT t.SumCalories,
       CASE WHEN g.weightunit = 'lbs' THEN 3500 ELSE 7700 END *
           g.weightlost As Target_calories
FROM goal g
INNER JOIN
  (SELECT sub.userid, SUM(sub.calories) as SumCalories
   FROM tracklog sub
   GROUP BY sub.userid) t
USING (userid)
WHERE g.userid = ?
ORDER BY g.weightlost DESC

By the way, likely you are using MySQL with ONLY_FULL_GROUP_ON setting to off as the engine does not through a syntax error for having no specified non-aggregated columns in GROUP BY clause.

Every other RDBMS would thrown an error for this. As best practice, always use GROUP BY to specify groupings in aggregate queries to avoid unreliable results.


问:
php - PHPExcel setReadDataOnly(true) is not working with ODS
Enter 12:00 in an ODS cell and get default Time format, setReadDataOnly(true) then getValue(), the value is 25569.5, if format the cell as number then getValue(), the value is 0.5. How can I see 12:00 in ODS and getValue()= 0.5?

答:
You can't see the date/time in ODS (or xlsx or xls, etc) using PHPExcel if you've used setReadDataOnly(true)....

The whole point of setReadDataOnly(true) is that it reads only the raw content of a cell, without any of the formatting information, such as that which identifies the cell as containing a date/time value.

Excel stores date/time values as a serialized timestamp, the number of days since a base start date (1st January 1900 or 1st January 1904, depending on the calendar setting), as a floating point value.
What identifies this as a date/time value is the number format mask, which specifies how that float should be displayed.

PHPExcel replicates this behaviour, and if you load the spreadsheet with setReadDataOnly(false), then getValue() will return the serialized timestamp, while getFormattedValue() will apply the number format mask and return a formatted date/time string.
Conversely, if you load the file with setReadDataOnly(true), there is no way that the code can identify this float as a date/time value, or know how it should be formatted other than as a float, because you elected not to load the formatting information that woul allow this identification too be made.

TL/DR Don't use setReadDataOnly(true) if you want PHPExcel to be able to identify date/time values as dates/times


问:
Animated Word Web in Javascript
I am trying to design an animated word web similar to the one found here. The goal is to have a center word bubble that is fixed in one location and to have other word bubbles around it that are moving around.

I was hoping to use the bubble chart from chartjs as a base and remove the legend, gridlines, axies, etc. to get the bubbles. However except for the tooltips included in the documentation, I have not been able to find a way to add text to one of the bubbles. Is there a way to add the text inside the bubble so that it is always visible? Or can anyone point me in the direction of a better library to accomplish this?

答:
I am crazy but i coded that in Canvas. Was bored haha. Test it by pasting to a new html file :D You can play with parametrs, colors, shapes and new bubbles with new texts. Have fun!</p>

```<code>    <!DOCTYPE html>
    <html>

    <head>
      <title></title>

    </head>

<body>
    <canvas id="canvas"></canvas>

  <script>
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      canvas.width = 400;
      canvas.height = 400;
      var r = 0;

      var bubbles = [];

      bubbles.push(new Bubble(canvas.width/2, canvas.height/2, "Apple", "rgb(0,0,120)", 30, 20));
        bubbles.push(new Bubble(canvas.width/2 + 100, canvas.height/2, "Store", "rgb(0,0,200)", 30, 20));
         bubbles.push(new Bubble(canvas.width/2 - 100, canvas.height/2, "Ipad", "rgb(0,0,200)", 30, 20));
          bubbles.push(new Bubble(canvas.width/2, canvas.height/2 + 100, "iMac", "rgb(120,0,0)", 30, 20));

      setInterval(function(){update();}, 20);

      function update()
      {
          ctx.clearRect(0,0,canvas.width, canvas.height);
          for (var i=bubbles.length-1; i>=0; i--)
          {
              bubbles[i].update();

          }
      }

    function Vector(x,y)
    {
        this.x = x;
        this.y = y;

        this.startX = x;
        this.startY = y;

        this.add = function (v)
        {
            this.x += v.x;
            this.y += v.y;
        }

        this.mult = function(p)
        {
            this.x *= p;
            this.y *= p;
        }

         this.rotate = function(ang)
         {
        this.x = (this.startX - bubbles[0].position.x) * Math.cos(ang)
                        - (this.startY - bubbles[0].position.y) * Math.sin(ang)
                        + bubbles[0].position.x;

        this.y = (this.startX - bubbles[0].position.x) * Math.sin(ang)
                        + (this.startY - bubbles[0].position.y) * Math.cos(ang)
                        + bubbles[0].position.y;
         }

    }

    function Bubble(x,y,text, color, width, height)
    {
        this.position = new Vector(x,y);
        this.velocity = new Vector(0,0);
        this.acceleration = new Vector(0,0);

        this.text = text;
        this.color = color;

        this.width = width;
        this.height = height;

        this.draw = function()
        {   ctx.beginPath();

                if(this.text != "Apple")
                {
                    ctx.lineTo(bubbles[0].position.x, bubbles[0].position.y);
                }
             ctx.font = "bold 13pt Arial";
            ctx.fillStyle = this.color;
            ctx.strokeStyle = this.color;
              ctx.arc(this.position.x,this.position.y, this.width, 0, 2 * Math.PI, false);
               ctx.fill();
                ctx.fillStyle = "black";

              ctx.stroke();
                ctx.fillText(this.text, this.position.x - this.width / 2 - 6, this.position.y + this.height / 4);
        }

        this.update = function()
        {
              if(this.text != "Apple")
             {
                 r--;
                 if (r < -1440)
                 r = 1;

                this.position.rotate( Math.PI / 720 * r);

             }
              this.draw();
        }
    }

  </script>
</body>

</html>
</code>```

Title: Animated Word Web in Javascript

Body:
I am crazy but i coded that in Canvas. Was bored haha. Test it by pasting to a new html file :D You can play with parametrs, colors, shapes and new bubbles with new texts. Have fun!

    <!DOCTYPE html>
    <html>

    <head>
      <title></title>

    </head>

<body>
    <canvas id="canvas"></canvas>

  <script>
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      canvas.width = 400;
      canvas.height = 400;
      var r = 0;

      var bubbles = [];

      bubbles.push(new Bubble(canvas.width/2, canvas.height/2, "Apple", "rgb(0,0,120)", 30, 20));
        bubbles.push(new Bubble(canvas.width/2 + 100, canvas.height/2, "Store", "rgb(0,0,200)", 30, 20));
         bubbles.push(new Bubble(canvas.width/2 - 100, canvas.height/2, "Ipad", "rgb(0,0,200)", 30, 20));
          bubbles.push(new Bubble(canvas.width/2, canvas.height/2 + 100, "iMac", "rgb(120,0,0)", 30, 20));

      setInterval(function(){update();}, 20);

      function update()
      {
          ctx.clearRect(0,0,canvas.width, canvas.height);
          for (var i=bubbles.length-1; i>=0; i--)
          {
              bubbles[i].update();

          }
      }

    function Vector(x,y)
    {
        this.x = x;
        this.y = y;

        this.startX = x;
        this.startY = y;

        this.add = function (v)
        {
            this.x += v.x;
            this.y += v.y;
        }

        this.mult = function(p)
        {
            this.x *= p;
            this.y *= p;
        }

         this.rotate = function(ang)
         {
        this.x = (this.startX - bubbles[0].position.x) * Math.cos(ang)
                        - (this.startY - bubbles[0].position.y) * Math.sin(ang)
                        + bubbles[0].position.x;

        this.y = (this.startX - bubbles[0].position.x) * Math.sin(ang)
                        + (this.startY - bubbles[0].position.y) * Math.cos(ang)
                        + bubbles[0].position.y;
         }

    }

    function Bubble(x,y,text, color, width, height)
    {
        this.position = new Vector(x,y);
        this.velocity = new Vector(0,0);
        this.acceleration = new Vector(0,0);

        this.text = text;
        this.color = color;

        this.width = width;
        this.height = height;

        this.draw = function()
        {   ctx.beginPath();

                if(this.text != "Apple")
                {
                    ctx.lineTo(bubbles[0].position.x, bubbles[0].position.y);
                }
             ctx.font = "bold 13pt Arial";
            ctx.fillStyle = this.color;
            ctx.strokeStyle = this.color;
              ctx.arc(this.position.x,this.position.y, this.width, 0, 2 * Math.PI, false);
               ctx.fill();
                ctx.fillStyle = "black";

              ctx.stroke();
                ctx.fillText(this.text, this.position.x - this.width / 2 - 6, this.position.y + this.height / 4);
        }

        this.update = function()
        {
              if(this.text != "Apple")
             {
                 r--;
                 if (r < -1440)
                 r = 1;

                this.position.rotate( Math.PI / 720 * r);

             }
              this.draw();
        }
    }

  </script>
</body>

</html>


问:
jquery change css click
I've created a menu which is one made by jquery for dropdown. It works fine. But I wanna rotate fa-bars. I wroten codes. CSS codes doesn't work. What I missed?</p>

```<code>$(function(){
    var a = 0;
    $('.topnavmenuOpen').click(function(){
        if ( a == 0 ){
            $(this).html('<i class="fa fa-bars" aria-hidden="true"></i>');
            a++;
        } else {
            $(this).html('<i class="fa fa-bars" aria-hidden="true"></i>');
            a = 0;
        }
        $(this).next('ul').slideToggle(500);

    });

$('.topnavmenuOpen').click(function(){
                          $('i .fa').css({
    'transform' : 'rotate(180deg)',
    'transition' : 'width 2s, height 2s, transform 2s'
});
                          });

});
</code>```

答:
```<code>$('.topnavmenuOpen').click(function(){
                      $('i .fa').css({
'transform' : 'rotate(180deg)',
'transition' : 'width 2s, height 2s, transform 2s'
});
                          });
</code>```

change

```<code>$(".topnavmenuOpen").on('click', function(){
    $("i.fa").addClass("rotate");
});
</code>```

and add your css page

```<code>.rotate {
    transform: rotate(180deg);
    transition: all 2s;
}
</code>```

Title: jquery change css click

Body:
I've created a menu which is one made by jquery for dropdown. It works fine. But I wanna rotate fa-bars. I wroten codes. CSS codes doesn't work. What I missed?

$(function(){
    var a = 0;
    $('.topnavmenuOpen').click(function(){
        if ( a == 0 ){
            $(this).html('');
            a++;
        } else {
            $(this).html('');
            a = 0;
        }
        $(this).next('ul').slideToggle(500);

    });

$('.topnavmenuOpen').click(function(){
                          $('i .fa').css({
    'transform' : 'rotate(180deg)',
    'transition' : 'width 2s, height 2s, transform 2s'
});
                          });

});

Body:
$('.topnavmenuOpen').click(function(){
                      $('i .fa').css({
'transform' : 'rotate(180deg)',
'transition' : 'width 2s, height 2s, transform 2s'
});
                          });

change

$(".topnavmenuOpen").on('click', function(){
    $("i.fa").addClass("rotate");
});

and add your css page

.rotate {
    transform: rotate(180deg);
    transition: all 2s;
}


问:
Mocking platform detection in Jest and React Native
Some of the code I am trying to test detects the platform, using, e.g.:

import { Platform } from 'react-native';
...

if (Platform.OS === 'android') {
  ...
} else {
  ...
}
```

Is there a sensible way to mock this with Jest and/or something else, so I can test both branches in one test run?

Or is the smart way to decouple it and put the platform into, e.g., a context variable? Although it always feels restructuring code to make it easier to test is something of a cheat.

答:
You have to mock the module and import it into your test. Then you can use mockImplementation to set the it to either android or ios

import reactNative from 'react-native';
jest.mock('react-native', () = > jest.fn();

it('is android', () => {
  reactNative.mockImplementation(()=>({Platform:{OS: 'android'}}))
  //test the android case
})

it('is android', ()=>{
  reactNative.mockImplementation(()=>({Platform: { OS: 'io' }}))
  //test the ios case
})
```

Body:
Some of the code I am trying to test detects the platform, using, e.g.:

import { Platform } from 'react-native';
...

if (Platform.OS === 'android') {
  ...
} else {
  ...
}

Is there a sensible way to mock this with Jest and/or something else, so I can test both branches in one test run?

Or is the smart way to decouple it and put the platform into, e.g., a context variable? Although it always feels restructuring code to make it easier to test is something of a cheat.


问:
Using Xamarin, why would my application setting default to false?
I am running into a really strange problem.  I have created an application setting for an iPad application, and for some reason the setting is defaulting to false- but only until the user opens the settings and observes the actual setting.  After being observed at least once, the setting will always return the correct value, whether it is true or false (if the setting were a quantum particle it would make more sense to me).  This behavior only occurs on device, not in simulator.  Also, it is consistent when I launch in debug mode on device or when I release through TestFlight.

My setting is defined in Root.plist, which is located in my client solution in the Settings.bundle folder. All of the other settings defined in this file work fine.

Since I can't really show the Xamarin designer, here's my XML from Root.plist:

```<code><dict>
    <key>Title</key>
    <string>Camera Settings</string>
    <key>Type</key>
    <string>PSGroupSpecifier</string>
</dict>
<dict>
    <key>DefaultValue</key>
    <true/>
    <key>Key</key>
    <string>useCameraForScanning</string>
    <key>Title</key>
    <string>Use Camera for Scanning</string>
    <key>Type</key>
    <string>PSToggleSwitchSpecifier</string>
</dict>
</code>```

And here's my accessor code:

```<code>private const string useCameraForScanningKey = "useCameraForScanning";
private static bool useCameraForScanning = true;
public static bool UseCameraForScanning
{
    get
    {
        bool useCamera = NSUserDefaults.StandardUserDefaults.BoolForKey(useCameraForScanningKey);
        useCameraForScanning = useCamera;
        return useCameraForScanning;
    }
    set { NSUserDefaults.StandardUserDefaults.SetBool(value, useCameraForScanningKey); }
}
</code>```

Breakpoints throughout the accessor prove that the setting is being retrieved as false.  I am very new to this Root.plist business, so I am guessing I am missing something obvious here.

Thanks in advance for any help offered!

答:
The link https://makeapppie.com/tag/root-plist/ clarifies a little more.

Many controls will have a  poorly named attribute Default Value. This is the value shown in  the settings app, not a true value of the default. It will show the values after the first use, but it is for display purposes not value purposes.

Here the solution

```<code>public static bool? NullableBoolForKey(this NSUserDefaults defaults, string key)
{
    var value = defaults.ValueForKey(new NSString(key));
    return value == null ? (bool?)null : ((NSNumber)value).UInt32Value == 1;
}
</code>```

Body:
I am running into a really strange problem.  I have created an application setting for an iPad application, and for some reason the setting is defaulting to false- but only until the user opens the settings and observes the actual setting.  After being observed at least once, the setting will always return the correct value, whether it is true or false (if the setting were a quantum particle it would make more sense to me).  This behavior only occurs on device, not in simulator.  Also, it is consistent when I launch in debug mode on device or when I release through TestFlight.

My setting is defined in Root.plist, which is located in my client solution in the Settings.bundle folder. All of the other settings defined in this file work fine.

Since I can't really show the Xamarin designer, here's my XML from Root.plist:

<dict>
    <key>Title</key>
    <string>Camera Settings</string>
    <key>Type</key>
    <string>PSGroupSpecifier</string>
</dict>
<dict>
    <key>DefaultValue</key>
    <true/>
    <key>Key</key>
    <string>useCameraForScanning</string>
    <key>Title</key>
    <string>Use Camera for Scanning</string>
    <key>Type</key>
    <string>PSToggleSwitchSpecifier</string>
</dict>

And here's my accessor code:

private const string useCameraForScanningKey = "useCameraForScanning";
private static bool useCameraForScanning = true;
public static bool UseCameraForScanning
{
    get
    {
        bool useCamera = NSUserDefaults.StandardUserDefaults.BoolForKey(useCameraForScanningKey);
        useCameraForScanning = useCamera;
        return useCameraForScanning;
    }
    set { NSUserDefaults.StandardUserDefaults.SetBool(value, useCameraForScanningKey); }
}

Breakpoints throughout the accessor prove that the setting is being retrieved as false.  I am very new to this Root.plist business, so I am guessing I am missing something obvious here.

Thanks in advance for any help offered!

Body:
The link https://makeapppie.com/tag/root-plist/ clarifies a little more.

Many controls will have a  poorly named attribute Default Value. This is the value shown in  the settings app, not a true value of the default. It will show the values after the first use, but it is for display purposes not value purposes.

Here the solution

public static bool? NullableBoolForKey(this NSUserDefaults defaults, string key)
{
    var value = defaults.ValueForKey(new NSString(key));
    return value == null ? (bool?)null : ((NSNumber)value).UInt32Value == 1;
}


问:
How to check if C++ abstract method is defined at runtime
How to check if C++ abstract method is defined at runtime

```<code>class ABase{
public:
 virtual void do1() = 0;
};

class BBase: public ABase{
public:
 virtual void do1(){}
};

class CBase: public ABase{
public:
};

ABase * base = rand() % 2 ? new BBase() : new CBase();
if(&(base->do1) != 0)
  base->do1();
</code>```

This gives error.

Thanks,
Max

答:
You cannot instantiate the CBase since it's ... abstract, i.e. does not implement all pure virtual functions of its parents.

The easiest would probably be to define a stub implementation in the ABase:

```<code>class ABase {
public:
 void do1() { /* do nothing */ }
};

class BBase: public ABase {
public:
 void do1() { /* do something */ }
};

class CBase: public ABase {};

ABase * base = rand() % 2 ? new BBase() : new CBase();
base->do1();
</code>```

Body:
How to check if C++ abstract method is defined at runtime

class ABase{
public:
 virtual void do1() = 0;
};

class BBase: public ABase{
public:
 virtual void do1(){}
};

class CBase: public ABase{
public:
};

ABase * base = rand() % 2 ? new BBase() : new CBase();
if(&(base->do1) != 0)
  base->do1();

This gives error.

Thanks,
Max

Body:
You cannot instantiate the CBase since it's ... abstract, i.e. does not implement all pure virtual functions of its parents.

The easiest would probably be to define a stub implementation in the ABase:

class ABase {
public:
 void do1() { /* do nothing */ }
};

class BBase: public ABase {
public:
 void do1() { /* do something */ }
};

class CBase: public ABase {};

ABase * base = rand() % 2 ? new BBase() : new CBase();
base->do1();


问:
PHP code to download CSV file not working
I have the below code, where I generate random numbers and try to download them as a CSV file.

If I try the CSV code snippet alone on a different file it works, but in this code, it just does not work. I do see the random numbers echoed, but it does not download the CSV file.

```<code><?php

$dataarray=array();

function convert_to_csv($input_array, $output_file_name, $delimiter)
{
$temp_memory = fopen('php://memory', 'w');
foreach ($input_array as $line)
{
fputcsv($temp_memory, $line, $delimiter);
}

fseek($temp_memory, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
fpassthru($temp_memory);
}

for ($i = 0; $i <= 25000; $i++)
{
  $num = (rand(50,110));

  array_push($dataarray,"$num");

  echo "Hearbeat #" .$i . "\t\t ------   " . $num;
  echo "<br>";
}

convert_to_csv($dataarray, 'data_as_csv.csv', ',');

?>
</code>```

答:
Actually, the problem is in your convert_to_csv function.
fputcsv expects the second parameter to be an array, and in you case is a string. You have 2 options depending on what you want:

1) Each number in a separate line: just change the fputcsv function call to: fputcsv($temp_memory, [$line], $delimiter);

2) All numbers in the same line separated by $delimiter:

```<code>function convert_to_csv($input_array, $output_file_name, $delimiter)
        {
            $temp_memory = fopen('php://memory', 'w');

            fputcsv($temp_memory, $fields, $delimiter);
            fseek($temp_memory, 0);
            header('Content-Type: application/csv');
            header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
            fpassthru($temp_memory);
        }
</code>```

And (I'm sure you already know), for the file to be downloaded automatically you must not echo anything.

Body:
I have the below code, where I generate random numbers and try to download them as a CSV file.

If I try the CSV code snippet alone on a different file it works, but in this code, it just does not work. I do see the random numbers echoed, but it does not download the CSV file.

<?php

$dataarray=array();

function convert_to_csv($input_array, $output_file_name, $delimiter)
{
$temp_memory = fopen('php://memory', 'w');
foreach ($input_array as $line)
{
fputcsv($temp_memory, $line, $delimiter);
}

fseek($temp_memory, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
fpassthru($temp_memory);
}

for ($i = 0; $i <= 25000; $i++)
{
  $num = (rand(50,110));

  array_push($dataarray,"$num");

  echo "Hearbeat #" .$i . "\t\t ------   " . $num;
  echo "
";
}

convert_to_csv($dataarray, 'data_as_csv.csv', ',');

?>

Body:
Actually, the problem is in your convert_to_csv function.
fputcsv expects the second parameter to be an array, and in you case is a string. You have 2 options depending on what you want:

1) Each number in a separate line: just change the fputcsv function call to: fputcsv($temp_memory, [$line], $delimiter);

2) All numbers in the same line separated by $delimiter:

function convert_to_csv($input_array, $output_file_name, $delimiter)
        {
            $temp_memory = fopen('php://memory', 'w');

            fputcsv($temp_memory, $fields, $delimiter);
            fseek($temp_memory, 0);
            header('Content-Type: application/csv');
            header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
            fpassthru($temp_memory);
        }

And (I'm sure you already know), for the file to be downloaded automatically you must not echo anything.


问:
Always same culture: en-US
I have an asp.net core project where I want to set the default language to nl-BE. For some reason it always take the language en-US

See code below (ps: I created my own ApplicationLocalizer who fetched the resources from a database => works fine).

Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
            //Add MVC
            services.AddMvc()
                .AddViewLocalization();

            //Localization factory
            services.AddSingleton<IStringLocalizerFactory, ApplicationLocalizerFactory>();

            ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context)
{
            ...

            //Localization
            var supportedCultures = new[]
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("nl-BE")
                };
            var options = new RequestLocalizationOptions {
                DefaultRequestCulture = new RequestCulture("nl-BE"),
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures
            };
            app.UseRequestLocalization(options);

            ...
}
</code>```

A controller

```<code>public string Index()
{
    return CultureInfo.CurrentCulture.Name;
}
</code>```

This snippet of code always returns en-US

Can someone help me solve this problem?

答:
After hours of searching for solution with no result, I went for heavy debugging and realized that the middleware services are executed in an order as declared in the Configure(IApplicationBuilder app...). Therefore the localization middleware was invoked after the controller action was executed.

When I moved the app.UseRequestLocalization(options) invocation at the very beginning I got properly localized Thread/CultureInfo in controller actions.

```<code>    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
        IApplicationLifetime appLifetime)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // THIS HAS TO BE A VERY FIRST MIDDLEWARE REGISTRATION
        SetUpLocalization(app);

        app.UseCors("AllowAllOrigins");

        app.UseMvc();

        appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());
    }

    private static void SetUpLocalization(IApplicationBuilder app)
    {
        var supportedCultures = new[]
        {
            new CultureInfo("en-US"),
            new CultureInfo("pl-PL"),
            new CultureInfo("pl")
        };

        var options = new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("en-US", "en-US"),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        };
        // Configure the Localization middleware
        app.UseRequestLocalization(options);
    }
</code>```

Title: Always same culture: en-US

Body:
I have an asp.net core project where I want to set the default language to nl-BE. For some reason it always take the language en-US

See code below (ps: I created my own ApplicationLocalizer who fetched the resources from a database => works fine).

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
            //Add MVC
            services.AddMvc()
                .AddViewLocalization();

            //Localization factory
            services.AddSingleton<IStringLocalizerFactory, ApplicationLocalizerFactory>();

            ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context)
{
            ...

            //Localization
            var supportedCultures = new[]
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("nl-BE")
                };
            var options = new RequestLocalizationOptions {
                DefaultRequestCulture = new RequestCulture("nl-BE"),
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures
            };
            app.UseRequestLocalization(options);

            ...
}

A controller

public string Index()
{
    return CultureInfo.CurrentCulture.Name;
}

This snippet of code always returns en-US

Can someone help me solve this problem?

Body:
After hours of searching for solution with no result, I went for heavy debugging and realized that the middleware services are executed in an order as declared in the Configure(IApplicationBuilder app...). Therefore the localization middleware was invoked after the controller action was executed.

When I moved the app.UseRequestLocalization(options) invocation at the very beginning I got properly localized Thread/CultureInfo in controller actions.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
        IApplicationLifetime appLifetime)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // THIS HAS TO BE A VERY FIRST MIDDLEWARE REGISTRATION
        SetUpLocalization(app);

        app.UseCors("AllowAllOrigins");

        app.UseMvc();

        appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());
    }

    private static void SetUpLocalization(IApplicationBuilder app)
    {
        var supportedCultures = new[]
        {
            new CultureInfo("en-US"),
            new CultureInfo("pl-PL"),
            new CultureInfo("pl")
        };

        var options = new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("en-US", "en-US"),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        };
        // Configure the Localization middleware
        app.UseRequestLocalization(options);
    }


问:
Restrict a input to only specific character and 6 digit of numbers
I want to restrict an input to only One Character (R) and 6 numbers only...
E.g: R123896

If Input length increase 7 it will remove that digit and if First word is not R , it should replace that character to "R"

I have written this script, but don't know how to move forward and shape it to what i want...

```<code>$("#consultationident").keyup(function(key){
var txtVal = $(this).val();
 if(isNumber(txtVal) && txtVal.length>6)
 {
     $(this).val(txtVal.substring(0,6) )
 }
});
</code>```

Please help!

答:
here is the code for validating input using regex</p>

```<code> $("#consultationident").keyup(function(key){
    var txtVal = $(this).val();
    if(txtVal.length>6)
     {
       str =  $(this).val().substring(0,7);

       pattern = /^[a-zA-Z]{1}(\d{6})$/

       if(pattern.test(str)) {
         str = str.replace(/^[a-zA-Z]/,"R")   // Replace any character with "R"
         console.log(str);
    }
      else {
         console.log("invalid input");
      }
   }
});
</code>```

Body:
I want to restrict an input to only One Character (R) and 6 numbers only...
E.g: R123896

If Input length increase 7 it will remove that digit and if First word is not R , it should replace that character to "R"

I have written this script, but don't know how to move forward and shape it to what i want...

$("#consultationident").keyup(function(key){
var txtVal = $(this).val();
 if(isNumber(txtVal) && txtVal.length>6)
 {
     $(this).val(txtVal.substring(0,6) )
 }
});

Please help!

Body:
here is the code for validating input using regex

 $("#consultationident").keyup(function(key){
    var txtVal = $(this).val();
    if(txtVal.length>6)
     {
       str =  $(this).val().substring(0,7);

       pattern = /^[a-zA-Z]{1}(\d{6})$/

       if(pattern.test(str)) {
         str = str.replace(/^[a-zA-Z]/,"R")   // Replace any character with "R"
         console.log(str);
    }
      else {
         console.log("invalid input");
      }
   }
});


问:
Django Model field needs to be unique over multiple models with shared abstract base class
Suppose I want to have multiple kinds of articles, all reachable on site.com/news/article-slug
(so depending on article-slug, it can be a video article, a text article, an image slider article, ...)

I have these models:

class Article(models.Model):
    class Meta:
        abstract = True
    slug = models.SlugField(max_length=60, unique=True)

class TextArticle(Article):
    content = models.TextField()

class VideoArticle(Article):
    video = models.ForeignKey(Video)
```

But the problem is that I can create a TextArticle and a VideoArticle with the same slug.

Is there an easy way to fix it so that if there's already a VideoArticle with a specific slug, no TextArticle can be added with the same slug (and vice versa)?

If there's no easy fix:

should I go for custom form validation with database querying?

should I not make the base class abstract?

any other ideas?

Thanks in advance!

答:
It sounds like you don't actually want an abstract class, but rather for the Article class to be the table for which all subclasses reference:

https://docs.djangoproject.com/en/1.10/topics/db/models/#multi-table-inheritance

Body:
Suppose I want to have multiple kinds of articles, all reachable on site.com/news/article-slug
(so depending on article-slug, it can be a video article, a text article, an image slider article, ...)

I have these models:

class Article(models.Model):
    class Meta:
        abstract = True
    slug = models.SlugField(max_length=60, unique=True)

class TextArticle(Article):
    content = models.TextField()

class VideoArticle(Article):
    video = models.ForeignKey(Video)

But the problem is that I can create a TextArticle and a VideoArticle with the same slug.

Is there an easy way to fix it so that if there's already a VideoArticle with a specific slug, no TextArticle can be added with the same slug (and vice versa)?

If there's no easy fix:

should I go for custom form validation with database querying?

should I not make the base class abstract?

any other ideas?

Thanks in advance!


问:
splice in javascript change values of my other objects
NOTE! this is for an extra credit assignment, so I am not looking for code re-write but rather guidance in what I am doing wrong. I have gone through my code several times and I feel like I am just missing something very minor. I have completed it fully with the exception of the following error:

I created an array of objects.
Everything starts off fine. I can create objects and they are added to the array and successfully displayed on my screen with correct values.
The trouble arises when I delete an object from the array. It does delete this object and removes it from my displayed list, but suddenly all the remaining objects get new values. These new values match those of the LAST object I added to the array. I need them to retain their original values!

```<code>var tableContent = document.getElementById("tableContent");
var tableString = " ";
var counter = 0;
var courseArray = [];
tableContent.innerHTML = tableString;

function Course(number, title, hours, prereq) {
    this.number = number;
    this.title = title;
    this.hours = hours;
    this.prereq = prereq;
}

function createCourse() {
    var number = document.getElementById("number-field");
    var title = document.getElementById("title-field");
    var hours = document.getElementById("hours-field");
    var prereq = document.getElementById("prereq-field");
    courseArray.push(new Course(number, title, hours, prereq));
    buildCourseTableBody();
}
function buildCourseTableBody() {

    tableString += "<tr>" +
        "<td>" + counter + "</td>" +
        "<td>" + courseArray[counter].number.value + "</td>" +
        "<td>" + courseArray[counter].title.value + "</td>" +
        "<td>" + courseArray[counter].hours.value + "</td>" +
        "<td>" + courseArray[counter].prereq.value + "</td>" +
        "<td><button id='delete' onClick='deleteCourse(" + counter + ")'><img id=counter src='../image/delete.png' alt='delete course'></button></td>" +
        "</tr>";
    counter++;
    tableContent.innerHTML = tableString;

}
function deleteCourse(counterIndex) {
    courseArray.splice(counterIndex, 1);
    counter--;
    tableString = "";
    for (var i = 0; i < courseArray.length; i++) {
        tableString += "<tr>" +
            "<td>" + i + "</td>" +
            "<td>" + courseArray[i].number.value + "</td>" +
            "<td>" + courseArray[i].title.value + "</td>" +
            "<td>" + courseArray[i].hours.value + "</td>" +
            "<td>" + courseArray[i].prereq.value + "</td>" +
            "<td><button id='delete' onClick='deleteCourse(" + i + ")'><img id=counter src='../image/delete.png' alt='delete course'></button></td>" +
            "</tr>";
    }
</code>```

and HTML code(everything in main, which is wrapped in body. js file is included):

```<code><main id="main-index">
    <h1 id="page-caption">CS Department Course Catalog</h1>

    <div id="course-list">
        <p id="course-list-caption">Course List</p>

        <table>
            <thead>
            <tr>
                <th>Count</th>
                <th>Number</th>
                <th>Title</th>
                <th>Hours</th>
                <th>Prereq</th>
                <th>Action</th>
            </tr>
            </thead>

            <tbody id="tableContent">

            </tbody>
        </table>
    </div>

    <div id="course-edit">
        <p><input id="number-field" placeholder="Course #, e.g. CS234"></p>
        <p><input id="title-field" placeholder="Course title, e.g. Database and Wed Systems Development"></p>
        <p><input id="hours-field" placeholder="Credit hours, e.g. 3.0"></p>
        <p><input id="prereq-field" placeholder="Course prereqs, e.g. CS150, CS111"></p>

        <p><button id="add" onClick="createCourse()">+</button></p>
    </div>

</main>
</code>```

答:
Your error is in createCourse. You are assigning the HTML-Elements instead of their value.

```<code>function createCourse() {
  var number = document.getElementById("number-field").value;
  var title = document.getElementById("title-field").value;
  var hours = document.getElementById("hours-field").value;
  var prereq = document.getElementById("prereq-field").value;
  courseArray.push(new Course(number, title, hours, prereq));
  buildCourseTableBody();
}
</code>```

The class course will hold a reference to the element itself. Like that your functions which generate the table itself, will always get the most current value of the input boxes.

Notice:
Don't forget to adapt buildCourseTableBody and deleteCourse.

Body:
NOTE! this is for an extra credit assignment, so I am not looking for code re-write but rather guidance in what I am doing wrong. I have gone through my code several times and I feel like I am just missing something very minor. I have completed it fully with the exception of the following error:

I created an array of objects.
Everything starts off fine. I can create objects and they are added to the array and successfully displayed on my screen with correct values.
The trouble arises when I delete an object from the array. It does delete this object and removes it from my displayed list, but suddenly all the remaining objects get new values. These new values match those of the LAST object I added to the array. I need them to retain their original values!

var tableContent = document.getElementById("tableContent");
var tableString = " ";
var counter = 0;
var courseArray = [];
tableContent.innerHTML = tableString;

function Course(number, title, hours, prereq) {
    this.number = number;
    this.title = title;
    this.hours = hours;
    this.prereq = prereq;
}

function createCourse() {
    var number = document.getElementById("number-field");
    var title = document.getElementById("title-field");
    var hours = document.getElementById("hours-field");
    var prereq = document.getElementById("prereq-field");
    courseArray.push(new Course(number, title, hours, prereq));
    buildCourseTableBody();
}
function buildCourseTableBody() {

    tableString += "
" +
        "" + counter + "	" +
        "" + courseArray[counter].number.value + "	" +
        "" + courseArray[counter].title.value + "	" +
        "" + courseArray[counter].hours.value + "	" +
        "" + courseArray[counter].prereq.value + "	" +
        "<button id='delete' onClick='deleteCourse(" + counter + ")'></button>	" +
        "
";
    counter++;
    tableContent.innerHTML = tableString;

}
function deleteCourse(counterIndex) {
    courseArray.splice(counterIndex, 1);
    counter--;
    tableString = "";
    for (var i = 0; i < courseArray.length; i++) {
        tableString += "
" +
            "" + i + "	" +
            "" + courseArray[i].number.value + "	" +
            "" + courseArray[i].title.value + "	" +
            "" + courseArray[i].hours.value + "	" +
            "" + courseArray[i].prereq.value + "	" +
            "<button id='delete' onClick='deleteCourse(" + i + ")'></button>	" +
            "
";
    }

and HTML code(everything in main, which is wrapped in body. js file is included):

CS Department Course Catalog

Course List

                Count
                Number
                Title
                Hours
                Prereq
                Action

<input id="number-field" placeholder="Course #, e.g. CS234">

<input id="title-field" placeholder="Course title, e.g. Database and Wed Systems Development">

<input id="hours-field" placeholder="Credit hours, e.g. 3.0">

<input id="prereq-field" placeholder="Course prereqs, e.g. CS150, CS111">

<button id="add" onClick="createCourse()">+</button>

Body:
Your error is in createCourse. You are assigning the HTML-Elements instead of their value.

function createCourse() {
  var number = document.getElementById("number-field").value;
  var title = document.getElementById("title-field").value;
  var hours = document.getElementById("hours-field").value;
  var prereq = document.getElementById("prereq-field").value;
  courseArray.push(new Course(number, title, hours, prereq));
  buildCourseTableBody();
}

The class course will hold a reference to the element itself. Like that your functions which generate the table itself, will always get the most current value of the input boxes.

Notice:
Don't forget to adapt buildCourseTableBody and deleteCourse.


问:
Downgrade in-app level return an error
I have an app with inapp purchases. I move to auto renew inapp purchase using StoreKit. Everything is working find.

But when I downgrade from a level 3 to a level 1 (or from level 3 to level 2, or from a level 2 to level 1), purchase doesn't working an return : "SKErrorDomain Code=0 “Cannot connect to iTunes Store”. No problem with upgrades.

But sometimes, waiting 10-15 minutes after the first purchase before downgrade is working. But not always.

What I did :

Use device and not simulator (!)

Sandbox tester is new and never used on a production env

Logout every production account from the device

Change order of products and save

Any idea of what's going on ?

答: In addition to the comment above that I left for you, there was an issue with sandbox server at the time of this question being asked so that could have been an issue. See See "refer"'s response as well as this question also asked on stackoverflow let me know if you are still experiencing issues.</p>

Title: Downgrade in-app level return an error


问:
Rails - How to add values in seperate objects together
You have an array of objects which contain a key-value reference.

```<code>[{booking_ref: 'w578383', foo: 'bar', price1: 500, price2: 30],
{booking_ref: 'w578383', foo: 'bar', price1: 600, price2: 40},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]
</code>```

I want to:

group objects by key-value reference (booking_ref)

go through those groupings and to each object add the financial values only together (price1 and price2 to the other booking's price1 and price2)

collapse out of groupings back to an array of objects which contain a key-value reference. That would now be:

```<code>[{booking_ref: 'w578383', foo: 'bar', price1: 1100, price2: 70},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]
</code>```

I am thinking:

```<code>objects.group_by(&:booking_ref).each {|group|
  group.merge {|key, value1, value2| value1 + value2 if key == price1 || price2}
}
</code>```

Does that work and if so how do I then return them back out of the group_by state?

答:
First, group_by is fine, then use a map to iterate the hash and then reduce the value from a list to a sum using inject

```<code>objects.group_by(&:booking_ref)
       .map{|ref, list| {booking_ref: ref,
                        price1:  => list.inject(0){|sum,h| sum + h.price1},
                        price2: => list.inject(0){|sum,h| sum + h.price2}
                        }
           }
</code>```

Body:
You have an array of objects which contain a key-value reference.

[{booking_ref: 'w578383', foo: 'bar', price1: 500, price2: 30],
{booking_ref: 'w578383', foo: 'bar', price1: 600, price2: 40},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]

I want to:

group objects by key-value reference (booking_ref)

go through those groupings and to each object add the financial values only together (price1 and price2 to the other booking's price1 and price2)

collapse out of groupings back to an array of objects which contain a key-value reference. That would now be:

[{booking_ref: 'w578383', foo: 'bar', price1: 1100, price2: 70},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]

I am thinking:

objects.group_by(&:booking_ref).each {|group|
  group.merge {|key, value1, value2| value1 + value2 if key == price1 || price2}
}

Does that work and if so how do I then return them back out of the group_by state?

Body:
First, group_by is fine, then use a map to iterate the hash and then reduce the value from a list to a sum using inject

objects.group_by(&:booking_ref)
       .map{|ref, list| {booking_ref: ref,
                        price1:  => list.inject(0){|sum,h| sum + h.price1},
                        price2: => list.inject(0){|sum,h| sum + h.price2}
                        }
           }


问:
Can't XClass eventnews Location and Organizer
I like to extend (own extension) eventnews (https://github.com/georgringer/eventnews) to use tt_address (https://github.com/TYPO3-extensions/tt_address) records for locations and organizers. The TCA is no problem, but XClass'ing does not work:

```<code>$GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects']['GeorgRinger\\Eventnews\\Domain\\Model\\Location'] = array(
    'className' => 'TYPO3\\TtAddress\\Domain\\Model\\Address',
);

$GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects']['GeorgRinger\\Eventnews\\Domain\\Model\\Organizer'] = array(
    'className' => 'TYPO3\\TtAddress\\Domain\\Model\\Address',
);
</code>```

Has it something to do with the PHPDoc annotations in Classes/Domain/Model/News.php ?

XClass'ing the News Model will help maybe, but i want to understand why it's not possible to use the code above

答:
This is most likely because of the proxy class generator in the news extension. It changes the way classes are loaded in order to allow overriding and extending the news model.

https://docs.typo3.org/typo3cms/extensions/news/DeveloperManual/ExtendNews/ProxyClassGenerator/Index.html

Body:
I like to extend (own extension) eventnews (https://github.com/georgringer/eventnews) to use tt_address (https://github.com/TYPO3-extensions/tt_address) records for locations and organizers. The TCA is no problem, but XClass'ing does not work:

$GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects']['GeorgRinger\\Eventnews\\Domain\\Model\\Location'] = array(
    'className' => 'TYPO3\\TtAddress\\Domain\\Model\\Address',
);

$GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects']['GeorgRinger\\Eventnews\\Domain\\Model\\Organizer'] = array(
    'className' => 'TYPO3\\TtAddress\\Domain\\Model\\Address',
);

Has it something to do with the PHPDoc annotations in Classes/Domain/Model/News.php ?

XClass'ing the News Model will help maybe, but i want to understand why it's not possible to use the code above