问:
How to add a line of best fit to scatter plot
I'm currently working with Pandas and matplotlib to perform some data visualization and I want to add a line of best fit to my scatter plot.

Here is my code:

```<code>import matplotlib
import matplotlib.pyplot as plt
import pandas as panda
import numpy as np

def PCA_scatter(filename):

   matplotlib.style.use('ggplot')

   data = panda.read_csv(filename)
   data_reduced = data[['2005', '2015']]

   data_reduced.plot(kind='scatter', x='2005', y='2015')
   plt.show()

PCA_scatter('file.csv')
</code>```

How do I go about this?

答:
You can do the whole fit and plot in one fell swoop with Seaborn.

```<code>import pandas as pd
import seaborn as sns
data_reduced= pd.read_csv('fake.txt',sep='\s+')
sns.regplot(data_reduced['2005'],data_reduced['2015'])
</code>```

Body:
I'm currently working with Pandas and matplotlib to perform some data visualization and I want to add a line of best fit to my scatter plot.

Here is my code:

import matplotlib
import matplotlib.pyplot as plt
import pandas as panda
import numpy as np

def PCA_scatter(filename):

   matplotlib.style.use('ggplot')

   data = panda.read_csv(filename)
   data_reduced = data[['2005', '2015']]

   data_reduced.plot(kind='scatter', x='2005', y='2015')
   plt.show()

PCA_scatter('file.csv')

How do I go about this?

Body:
You can do the whole fit and plot in one fell swoop with Seaborn.

import pandas as pd
import seaborn as sns
data_reduced= pd.read_csv('fake.txt',sep='\s+')
sns.regplot(data_reduced['2005'],data_reduced['2015'])


来源: stackexchange

问:
splice() inside a for loop, what is the solution?
I'm trying to remove repetitions from this array called "bigArray" while keeping the three first positions of the array intact (even if they repeat).

My issue is that the splice() inside the for loop is not working properly, since every time it splices, the for loop skips the next position of the array (since that position is then one position lower in the array).

How do I get my function to return [0,0,0,3,2] ?

Thank you

var bigArray = [0,0,0,3,2,2,3,3,2];

function call() {

  for (let i=3; i < (bigArray.length); i++) {
    if (bigArray.indexOf(bigArray[i]) !== i) {
          bigArray.splice(i,1);

    }

    }

    console.log(bigArray);
    return bigArray;
}

call();```

答:
You should subtract i.

var bigArray = [0,0,0,3,2,2,3,3,2];

function call() {

  for (let i=3; i < (bigArray.length); i++) {
    if (bigArray.indexOf(bigArray[i]) !== i) {
          bigArray.splice(i,1);
       i--;
    }

  }

    console.log(bigArray);
    return bigArray;
}

call();```

ContentLicense: CC BY-SA 3.0


答:
```<code>Select
tableA.SALES_TIME_PERIOD_ID
, tableA.Code
, tableA.ID
, tableA.floor_no
, tableA.Unit_no
, cast(tableB.PERIODICAMOUNT as decimal(13,2)) as ACTUAL
, tableB.PERIODICAMOUNT  as PRORATED

from tableA

inner join tableB
on tableA.Code = tableB.Code
and tableA.ID = tableB.ID
and tableA.floorno - tableB.floorno
and tableA.unitno = tableB.unitno
and tableA.SALES_TIME_PERIOD_ID between tableB.CHARGESTARTDATE and tableB.CHARGEENDDATE
</code>```

I have made a lot of assumptions here of course.. but this should get you going!

Title: Calculate prorated amount in sql server

Body:
I want to join table A with B & get the prorated sales amount.
How to achieve this . Can anyone help me?

Table A:
SALES_TIME_PERIOD_ID    CODE    ID  FLOOR_NO    UNIT_NO
31/07/2015               CN     K1A    L01        153
31/08/2015               CN     K1A    L01        153
30/09/2015               CN     K1A    L01        153
31/10/2015               CN     K1A    L01        153
30/11/2015               CN     K1A    L01        153
31/12/2015               CN     K1A    L01        153
31/01/2016               CN     K1A    L01        153
29/02/2016               CN     K1A    L01        153
31/03/2016               CN     K1A    L01        153
30/04/2016               CN     K1A    L01        153
31/05/2016               CN     K1A    L01        153
30/06/2016               CN     K1A    L01        153

Table B:

CODE    ID  FLOORNO UNITNO  CHARGESTARTDATE CHARGEENDDATE   PERIODICAMOUNT
CN      K1A  L01    153         24/08/2014  23/08/2015      13400.96
CN      K1A  L01    153         24/08/2015  23/08/2016      14071
CN      K1A  L01    153         24/08/2016  23/08/2017      14774.55

I Want output as:

SALES_TIME_PERIOD_ID    CODE    ID  FLOOR_NO    UNIT_NO ACTUAL      PRORATED
31/07/2015               CN     K1A   L01       153     13400.96    13400.96
31/08/2015               CN     K1A   L01       153     13400.96    13573.87355
30/09/2015               CN     K1A   L01       153     14071       14071
31/10/2015               CN     K1A   L01       153     14071       14071
30/11/2015               CN     K1A   L01       153     14071       14071
31/12/2015               CN     K1A   L01       153     14071       14071
31/01/2016               CN     K1A   L01       153     14071       14071
29/02/2016               CN     K1A   L01       153     14071       14071
31/03/2016               CN     K1A   L01       153     14071       14071
30/04/2016               CN     K1A   L01       153     14071       14071
31/05/2016               CN     K1A   L01       153     14071       14071
30/06/2016               CN     K1A   L01       153     14071       14071

Body:
Select
tableA.SALES_TIME_PERIOD_ID
, tableA.Code
, tableA.ID
, tableA.floor_no
, tableA.Unit_no
, cast(tableB.PERIODICAMOUNT as decimal(13,2)) as ACTUAL
, tableB.PERIODICAMOUNT  as PRORATED

from tableA

inner join tableB
on tableA.Code = tableB.Code
and tableA.ID = tableB.ID
and tableA.floorno - tableB.floorno
and tableA.unitno = tableB.unitno
and tableA.SALES_TIME_PERIOD_ID between tableB.CHARGESTARTDATE and tableB.CHARGEENDDATE

I have made a lot of assumptions here of course.. but this should get you going!


问:
Replacing N-level for loops with recursion in C++
I have been trying for some time now to come up with a way to compute all the various combinations of strings of words for some time now. Unlike most methods for combining on the web though, the algorithm must produce every combination, including those in which all the combined elements aren't in a single combination. ie, if I am combining 'Hello', 'New' and 'World', the combinations I am looking for are:

```<code>HelloNewWorld
HelloNew
HelloWorld
Hello
NewWorld
New
World
</code>```

A professor from my college did come up with a quick and dirty solution for doing just that, but it is using nested for loops.

```<code>#include <iostream>
#include <vector>
#include <array>
#include <string>

int main()
{
std::vector<std::array<std::string, 2>> vec(3);
vec[0] = {"Hello", ""};
vec[1] = {"New", ""};
vec[2] = {"World", ""};
for (int i = 0; i < 2; i++)
    for (int j = 0; j < 2; j++)
        for (int k = 0; k < 2; k++)
            std::cout << vec[0][i] + vec[1][j] + vec[2][k] << std::endl;
}
</code>```

As you might imagine, I desired a way to make this actually somewhat usable and portable. I know that this is possible with recursion, I just don't know how to implement it. Optimally, I would like to make this tail-recursive if at all possible, as the plan is to compute very large combinations. What would be the best way to do this recursively, and would it be easy to make tail-recursive?

答:
At each level it recurses both with and without the current word printing the result when it gets to the end of all the words:

```<code>#include <iostream>
#include <string>
#include <vector>

void recurse(std::vector<std::string> &values,size_t level,std::string str) {
  if (level<values.size()) {
    recurse(values,level+1,str+values[level]);
    recurse(values,level+1,str);
  } else {
    std::cout<<str<<"\n";
  }
}

int main(int argc, char*argv[]) {
  if (argc<2)
    std::cout<<argv[0]<<" <word> [<word> [...]]\n";
  else {
    std::vector<std::string> values;
    for(int i=1;i<argc;++i) {
      values.push_back(argv[i]);
    }
    recurse(values,0,"");
  }
  return 0;
}
</code>```

Which, when run with ./a.out Hello New World produces:

```<code>HelloNewWorld
HelloNew
HelloWorld
Hello
NewWorld
New
World
</code>```

Body:
I have been trying for some time now to come up with a way to compute all the various combinations of strings of words for some time now. Unlike most methods for combining on the web though, the algorithm must produce every combination, including those in which all the combined elements aren't in a single combination. ie, if I am combining 'Hello', 'New' and 'World', the combinations I am looking for are:

HelloNewWorld
HelloNew
HelloWorld
Hello
NewWorld
New
World

A professor from my college did come up with a quick and dirty solution for doing just that, but it is using nested for loops.

#include <iostream>
#include <vector>
#include <array>
#include <string>

int main()
{
std::vector<std::array<std::string, 2>> vec(3);
vec[0] = {"Hello", ""};
vec[1] = {"New", ""};
vec[2] = {"World", ""};
for (int i = 0; i < 2; i++)
    for (int j = 0; j < 2; j++)
        for (int k = 0; k < 2; k++)
            std::cout << vec[0][i] + vec[1][j] + vec[2][k] << std::endl;
}

As you might imagine, I desired a way to make this actually somewhat usable and portable. I know that this is possible with recursion, I just don't know how to implement it. Optimally, I would like to make this tail-recursive if at all possible, as the plan is to compute very large combinations. What would be the best way to do this recursively, and would it be easy to make tail-recursive?

Body:
At each level it recurses both with and without the current word printing the result when it gets to the end of all the words:

#include <iostream>
#include <string>
#include <vector>

void recurse(std::vector<std::string> &values,size_t level,std::string str) {
  if (level<values.size()) {
    recurse(values,level+1,str+values[level]);
    recurse(values,level+1,str);
  } else {
    std::cout<<str<<"\n";
  }
}

int main(int argc, char*argv[]) {
  if (argc<2)
    std::cout<<argv[0]<<" <word> [<word> [...]]\n";
  else {
    std::vector<std::string> values;
    for(int i=1;i<argc;++i) {
      values.push_back(argv[i]);
    }
    recurse(values,0,"");
  }
  return 0;
}

Which, when run with ./a.out Hello New World produces:

HelloNewWorld
HelloNew
HelloWorld
Hello
NewWorld
New
World


问:
using .reduce() on an a list of objects
I have this sample data set:

```<code>let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]
</code>```

I am trying to end up with this:

```<code>[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]
</code>```

I am using the .reduce() function to map over the list. However, I'm somewhat stuck.

I got this working:

```<code>let b = list.reduce((final_list, new_item) => {
  x = final_list.concat([[new_item.id, [new_item.first]]])
  return x
}, [])
</code>```

However, that flattens out the list into a list of lists of lists, but doesn't combine names that share a similar id.

I tried using .map() the code below does not work

I tried to map over the final_list (which is a list of [id, [names]] looking to see if the id of the new_item exists in the smaller_list and then add new_item.first to the smaller_list[1] (which should be the list of names).

Is this the right approach?

```<code>let b = list.reduce((final_list, new_item) => {
  final_list.map((smaller_list) => {
    if (smaller_list.indexOf((new_item.id)) >=0) {
      smaller_list[1].concat(new_item.first)
      // not sure what to do here...
    } else {
        // not sure what to do here either...
    }

  })
  x = final_list.concat([[item.id, [item.first]]])
  return x
}, [])
</code>```

答:
you want to do it with reduce, and doing it with a single reduce would be nice. here are 3 ways

verbose, more loops

```<code>const tuples1 = list.reduce( (tuples, obj) => {
  if( tuples.some( ( [id, _] ) => id === obj.id ) ){
    tuples.find( ( [id, _] ) => id === obj.id )[1].push(obj.first)
  }else{
    tuples.push([obj.id, [obj.first]])
  }
  return tuples
}, [])
</code>```

same as tuples1, terse

```<code>const tuples2 = list.reduce( (tuples, obj) =>
  ( tuples.some( ( [id, _] ) => id === obj.id ) ) ?
    ( tuples.find( ( [id, _] ) => id === obj.id )[1].push(obj.first), tuples ) :
    ( tuples.push([obj.id, [obj.first]]), tuples ), [])
</code>```

more verbose, less loops

```<code>const tuples3 = list.reduce( (tuples, obj) => {
  const existingId = tuples.find( ( [id, _] ) => id === obj.id )
  if( existingId ){
    existingId[1].push(obj.first)
  }else{
    tuples.push([obj.id, [obj.first]])
  }
  return tuples
}, [])
</code>```

each produce the same result

```<code>[ [ 1, [ 'morgan', 'eric' ] ],
  [ 2, [ 'brian', 'derek' ] ],
  [ 3, [ 'courtney' ] ],
  [ 4, [ 'eric', 'jon' ] ] ]
</code>```

Title: using .reduce() on an a list of objects

Body:
I have this sample data set:

let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]

I am trying to end up with this:

[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]

I am using the .reduce() function to map over the list. However, I'm somewhat stuck.

I got this working:

let b = list.reduce((final_list, new_item) => {
  x = final_list.concat([[new_item.id, [new_item.first]]])
  return x
}, [])

However, that flattens out the list into a list of lists of lists, but doesn't combine names that share a similar id.

I tried using .map() the code below does not work

I tried to map over the final_list (which is a list of [id, [names]] looking to see if the id of the new_item exists in the smaller_list and then add new_item.first to the smaller_list[1] (which should be the list of names).

Is this the right approach?

let b = list.reduce((final_list, new_item) => {
  final_list.map((smaller_list) => {
    if (smaller_list.indexOf((new_item.id)) >=0) {
      smaller_list[1].concat(new_item.first)
      // not sure what to do here...
    } else {
        // not sure what to do here either...
    }

  })
  x = final_list.concat([[item.id, [item.first]]])
  return x
}, [])

Body:
you want to do it with reduce, and doing it with a single reduce would be nice. here are 3 ways

verbose, more loops

const tuples1 = list.reduce( (tuples, obj) => {
  if( tuples.some( ( [id, _] ) => id === obj.id ) ){
    tuples.find( ( [id, _] ) => id === obj.id )[1].push(obj.first)
  }else{
    tuples.push([obj.id, [obj.first]])
  }
  return tuples
}, [])

same as tuples1, terse

const tuples2 = list.reduce( (tuples, obj) =>
  ( tuples.some( ( [id, _] ) => id === obj.id ) ) ?
    ( tuples.find( ( [id, _] ) => id === obj.id )[1].push(obj.first), tuples ) :
    ( tuples.push([obj.id, [obj.first]]), tuples ), [])

more verbose, less loops

const tuples3 = list.reduce( (tuples, obj) => {
  const existingId = tuples.find( ( [id, _] ) => id === obj.id )
  if( existingId ){
    existingId[1].push(obj.first)
  }else{
    tuples.push([obj.id, [obj.first]])
  }
  return tuples
}, [])

each produce the same result

[ [ 1, [ 'morgan', 'eric' ] ],
  [ 2, [ 'brian', 'derek' ] ],
  [ 3, [ 'courtney' ] ],
  [ 4, [ 'eric', 'jon' ] ] ]


问:
Going from a for loop to arrays in Python
```<code>for i in range(2,Nx-2):
    lyr1[i]=lyr0[i]-coef*(lyr0[i]*(lyr0[i+1]-lyr0[i-1])/2+(dsqr/(deltax)**2)*(lyr0[i+2]-2*lyr0[i+1]+2*lyr0[i-1]-lyr0[i-2]))

lyr1=lyr0[0:Nx]-coef*(lyr0[0:Nx]*(lyr0[2:Nx]-lyr0[0:Nx-2])/2+(dsqr/(deltax)**2)*(lyr0[1:Nx+1]-2*lyr0[0:Nx]+2*lyr0[2:Nx-2]-lyr0[3:Nx-3]))
</code>```

<p>I'm trying to change my for loop (above) into an operation on arrays. I am currently getting a broadcast error, but I need to be able to only select portions of the array to match my numerical integration scheme. Any help is greatly appreciated. </p>

答:
The problem is that you use vectors of different dimensions (due to your slicing), e.g., len(lyr0[0:Nx]) == 2 + len(lyr0[2:Nx]). Numpy tries to broadcast these operations to match the vector sizes, but they have incompatible dimensions (not being 1, not being multiples of each other etc.).

However, broadcasting is not what you want to do in the first place (judging from your loop implementation). It seems you rather want to do a look-ahead / look-back. Try shifting the values in lyr0 explicitly by using numpy's roll function instead.

Body:
for i in range(2,Nx-2):
    lyr1[i]=lyr0[i]-coef*(lyr0[i]*(lyr0[i+1]-lyr0[i-1])/2+(dsqr/(deltax)**2)*(lyr0[i+2]-2*lyr0[i+1]+2*lyr0[i-1]-lyr0[i-2]))

lyr1=lyr0[0:Nx]-coef*(lyr0[0:Nx]*(lyr0[2:Nx]-lyr0[0:Nx-2])/2+(dsqr/(deltax)**2)*(lyr0[1:Nx+1]-2*lyr0[0:Nx]+2*lyr0[2:Nx-2]-lyr0[3:Nx-3]))

I'm trying to change my for loop (above) into an operation on arrays. I am currently getting a broadcast error, but I need to be able to only select portions of the array to match my numerical integration scheme. Any help is greatly appreciated.


答:
One other way to do it.

```<code>    function finddup(arr){
      var tmp = [];
      for(var i = 0; i < arr.length; i++){
         if(i<3)
         {
          tmp.push(arr[i]);
         }
        else
        if(tmp.indexOf(arr[i]) == -1)
         {
         tmp.push(arr[i]);
         }
     }
    return tmp;
     }
</code>```

Hope this help you !

Title: splice() inside a for loop, what is the solution?

Body:
I'm trying to remove repetitions from this array called "bigArray" while keeping the three first positions of the array intact (even if they repeat).

My issue is that the splice() inside the for loop is not working properly, since every time it splices, the for loop skips the next position of the array (since that position is then one position lower in the array).

How do I get my function to return [0,0,0,3,2] ?

Thank you

var bigArray = [0,0,0,3,2,2,3,3,2];

function call() {

  for (let i=3; i < (bigArray.length); i++) {
    if (bigArray.indexOf(bigArray[i]) !== i) {
          bigArray.splice(i,1);

    }

    }

    console.log(bigArray);
    return bigArray;
}

call();

Body:
One other way to do it.

    function finddup(arr){
      var tmp = [];
      for(var i = 0; i < arr.length; i++){
         if(i<3)
         {
          tmp.push(arr[i]);
         }
        else
        if(tmp.indexOf(arr[i]) == -1)
         {
         tmp.push(arr[i]);
         }
     }
    return tmp;
     }

Hope this help you !


问:
A good web hosting service that allows more then 1GB MySQL databases
I was looking for a good mysql and php hosting service that allows more then 1GB MySQL databases for a cheap price and great service. can some one give some suggestions</p>

答:
Go for a VPS. They don't limit on MySQL. You can have the database as large as your assigned disk space. Following are awesome and cheap VPS providers:

Virpus

VPSLatch

Try finding coupon codes and you will save around 30% in this holiday season :). Both accept PayPal.

ContentLicense: CC BY-SA 2.5


问:
Django Model self referencing M2M field
I'm trying to get a Django model to automatically construct a typical __str__(self) value for itself (in the model definition), but based on 3 ManyToMany Fields. Unlike when using basic field types (as in the first two models), this doesn't appear to work for M2M fields (see the third model).
The model migrates fine, but causes errors when being referenced in the admin.

Any help much appreciated, thanks!

```<code>class Party(models.Model):
    name=models.CharField("Party", max_length=150)
    def __str__(self):              # __unicode__ on Python 2
        return self.name

    class Meta:
         ordering = ('name',)

class ValCharBehav(models.Model):
    name=models.CharField("Value / Character / Behaviour", max_length=150, unique=True)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class ValCharBehavWithPeople(models.Model):
    vcb=models.ManyToManyField(ValCharBehav, verbose_name="Value / Character / Behvaiour")
    bywhom=models.ManyToManyField(Party, verbose_name="By Whom", blank=True, related_name="valCharByWhomReverseAccessor")
    towhom=models.ManyToManyField(Party, verbose_name="To Whom", blank=True, related_name="valCharToWhomReverseAccessor")

    def __str__(self):              # __unicode__ on Python 2
         return self.vcb.name+": by: "+self.bywhom.name+", to: "+self.towhom.name
</code>```

答:
Or if you prefer a slightly more terse version of @ykh’s answer:</p>

```<code>def __str__(self):
    return '%s, by %s, to %s' % [
        ' | '.join(x.values_list('name', flat=True))
        for x in (self.vcb, self.bywhom, self.towhom) ]
</code>```

Title: Django Model self referencing M2M field

Body:
I'm trying to get a Django model to automatically construct a typical __str__(self) value for itself (in the model definition), but based on 3 ManyToMany Fields. Unlike when using basic field types (as in the first two models), this doesn't appear to work for M2M fields (see the third model).
The model migrates fine, but causes errors when being referenced in the admin.

Any help much appreciated, thanks!

class Party(models.Model):
    name=models.CharField("Party", max_length=150)
    def __str__(self):              # __unicode__ on Python 2
        return self.name

    class Meta:
         ordering = ('name',)

class ValCharBehav(models.Model):
    name=models.CharField("Value / Character / Behaviour", max_length=150, unique=True)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class ValCharBehavWithPeople(models.Model):
    vcb=models.ManyToManyField(ValCharBehav, verbose_name="Value / Character / Behvaiour")
    bywhom=models.ManyToManyField(Party, verbose_name="By Whom", blank=True, related_name="valCharByWhomReverseAccessor")
    towhom=models.ManyToManyField(Party, verbose_name="To Whom", blank=True, related_name="valCharToWhomReverseAccessor")

    def __str__(self):              # __unicode__ on Python 2
         return self.vcb.name+": by: "+self.bywhom.name+", to: "+self.towhom.name

Body:
Or if you prefer a slightly more terse version of @ykh’s answer:

def __str__(self):
    return '%s, by %s, to %s' % [
        ' | '.join(x.values_list('name', flat=True))
        for x in (self.vcb, self.bywhom, self.towhom) ]


问:
Bundle loses its values between activities
I use the following codes to start activity with bundle extras data, and I can see the data has saved in Intent extras:

```<code>public static Intent newIntent(Context packageContext, AccountItem account, TransactionItem transaction) {
    Bundle args = new Bundle();
    args.putParcelable("arg_key_account", account);
    args.putParcelable("arg_key_transaction", transaction);
    args.putInt("test_key", 18);

    Intent intent = new Intent(packageContext, TransactionConnectActivity.class);
    intent.putExtra("arg_key", args);
    intent.putExtra("test_key", 21);
    return intent;
}
</code>```

However, when I try to get bundle extras data from intent, the bundle has no data:

```<code>protected void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    Intent intent = getIntent();
    if (intent != null) {
        int test = intent.getIntExtra("test_key", -1);
        Bundle args = intent.getExtras().getBundle("arg_key");
    }
    ...
}
</code>```

The custom object have implement Parcelable, and all members have been written to parcel. and I have read these questions and answers, but still cannot figure out where i am wrong?

Pendingintent getbroadcast lost parcelable data

Parcelable object that receives passed data coming up null

Parcelable custom object losing instance values when passed with intent

Bundle loses values between activities

答:
To make sure Parcelable works, should use correct method to writeToParcel and createFromParcel, otherwise Android cannot retrieve data correctly which will cause createFromParcel returns a null object.

As for this issue here, I use writeValue to parcel a String member, which must use writeString.

Body:
I use the following codes to start activity with bundle extras data, and I can see the data has saved in Intent extras:

public static Intent newIntent(Context packageContext, AccountItem account, TransactionItem transaction) {
    Bundle args = new Bundle();
    args.putParcelable("arg_key_account", account);
    args.putParcelable("arg_key_transaction", transaction);
    args.putInt("test_key", 18);

    Intent intent = new Intent(packageContext, TransactionConnectActivity.class);
    intent.putExtra("arg_key", args);
    intent.putExtra("test_key", 21);
    return intent;
}

However, when I try to get bundle extras data from intent, the bundle has no data:

protected void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    Intent intent = getIntent();
    if (intent != null) {
        int test = intent.getIntExtra("test_key", -1);
        Bundle args = intent.getExtras().getBundle("arg_key");
    }
    ...
}

The custom object have implement Parcelable, and all members have been written to parcel. and I have read these questions and answers, but still cannot figure out where i am wrong?

Pendingintent getbroadcast lost parcelable data

Parcelable object that receives passed data coming up null

Parcelable custom object losing instance values when passed with intent

Bundle loses values between activities


问:
Cloning an array in Javascript/Typescript
I have array of two objects:

```<code>genericItems: Item[] = [];
backupData: Item[] = [];
</code>```

I am populating my HTML table with genericItemsdata. The table is modifiable. There is a reset button to undo all changes done with backUpData. This array is populated by a service:

```<code>getGenericItems(selected: Item) {
this.itemService.getGenericItems(selected).subscribe(
  result => {
     this.genericItems = result;
  });
     this.backupData = this.genericItems.slice();
  }
</code>```

My idea was that, the user changes will get reflected in first array and second array can be used as backup for reset operation. The issue I am facing here is when the user modifies the table (genericItems[]) the second array backupData also gets modified.

How is this happening and how to prevent this?

答:
I have the same issue with primeNg DataTable. After trying and crying, I've fixed the issue by using this code.

```<code>private deepArrayCopy(arr: SelectItem[]): SelectItem[] {
    const result: SelectItem[] = [];
    if (!arr) {
      return result;
    }
    const arrayLength = arr.length;
    for (let i = 0; i <= arrayLength; i++) {
      const item = arr[i];
      if (item) {
        result.push({ label: item.label, value: item.value });
      }
    }
    return result;
  }
</code>```

For initializing backup value

```<code>backupData = this.deepArrayCopy(genericItems);
</code>```

For resetting changes

```<code>genericItems = this.deepArrayCopy(backupData);
</code>```

The magic bullet is to recreate items by using {} instead of calling constructor.
I've tried new SelectItem(item.label, item.value) which doesn't work.

ContentLicense: CC BY-SA 4.0

Body:
I have array of two objects:

genericItems: Item[] = [];
backupData: Item[] = [];

I am populating my HTML table with genericItemsdata. The table is modifiable. There is a reset button to undo all changes done with backUpData. This array is populated by a service:

getGenericItems(selected: Item) {
this.itemService.getGenericItems(selected).subscribe(
  result => {
     this.genericItems = result;
  });
     this.backupData = this.genericItems.slice();
  }

My idea was that, the user changes will get reflected in first array and second array can be used as backup for reset operation. The issue I am facing here is when the user modifies the table (genericItems[]) the second array backupData also gets modified.

How is this happening and how to prevent this?

Body:
I have the same issue with primeNg DataTable. After trying and crying, I've fixed the issue by using this code.

private deepArrayCopy(arr: SelectItem[]): SelectItem[] {
    const result: SelectItem[] = [];
    if (!arr) {
      return result;
    }
    const arrayLength = arr.length;
    for (let i = 0; i <= arrayLength; i++) {
      const item = arr[i];
      if (item) {
        result.push({ label: item.label, value: item.value });
      }
    }
    return result;
  }

For initializing backup value

backupData = this.deepArrayCopy(genericItems);

For resetting changes

genericItems = this.deepArrayCopy(backupData);

The magic bullet is to recreate items by using {} instead of calling constructor.
I've tried new SelectItem(item.label, item.value) which doesn't work.


问:
decode java google oauth2.0 JWT
Im trying to decode the google oauth token_id using the below stmts..For some reason, the claims are decoded partially...

```<code>String token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjdkZGQwOGEwM2IyNWQwZjVhMDllMjNiMmJlMTBkZDIyODQyYTg1NjkifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTAxOTI0MjQ2MzYwNDM0OTY2NzMzIiwiYXpwIjoiNTk0OTU1MjgxODg2LWJxcjBkYm1kcmFicWFvbm1oZWlxazBza2RkZjVhbGs1LmxCLTO3GHRBn0";

        //String[] jwtParts = token.split("\\.");
        String[] base64EncodedSegments = token.split("\\.");
        System.out.println(Arrays.toString(base64EncodedSegments));
        String base64EncodedHeader = base64EncodedSegments[0];
        String base64EncodedClaims = base64EncodedSegments[1];
        byte[] claims = new byte[1000000];
        claims = DatatypeConverter.parseBase64Binary(base64EncodedClaims);
        String s = new String(claims);
        System.out.println(s);
        System.out.println(s.getClass().getName());

        JSONObject emailobject = new JSONObject(s);
        String emailid = emailobject.getString("email");
        System.out.println(emailid);
</code>```

Decoded claims below:

It starts with a "{" braces but does not close with "}" and because of that I'm  unable to convert to a JSON object and get the actual email id

```<code>{"iss":"accounts.google.com","sub":"101924246360434966733","azp":"594955281886-bqr0d0skddf5alk5.apps.googleusercontent.com","email":"test@gmail.com","at_hash":"dVrka2339w4Cezz32ssrY_w","email_verified":true,"aud":"594955281-bqr0dbmdrak5.apps.googleusercontent.com","iat":1423238546,"exp":1413223244
</code>```

***********Update************

This piece of code works for to connect to google oauth and retrieve the email id...

```<code>ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource(UriBuilder.fromUri("https://accounts.google.com/o/oauth2/token").build());
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("code", request.getParameter("code"));
formData.add("client_id", Global.GOOGLE_CLIENT_ID);
formData.add("redirect_uri", Global.GOOGLE_REDIRECT_URL);
formData.add("client_secret", Global.GOOGLE_SECRET);
formData.add("grant_type", "authorization_code");
ClientResponse response1 = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData);
JSONObject jobject = new JSONObject(response1.getEntity(String.class));
String token_id = jobject.getString("id_token");
String[] base64EncodedSegments = token_id.split("\\.");

String base64EncodedHeader = base64EncodedSegments[0];
String base64EncodedClaims = base64EncodedSegments[1];
JsonParser parser = new JsonParser();
JsonElement payload = parser.parse(StringUtils.newStringUtf8(Base64.decodeBase64(base64EncodedClaims)));
JSONObject emailobject = new JSONObject(payload.toString());
String emailid = emailobject.getString("email");
</code>```

Jars needed -

```<code><dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.3</version>
        </dependency>

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3</version>
</dependency>
</code>```

答:
The oauth2 tokens are encoded with Base64URL, however DatatypeConverter.parseBase64Binary() decodes standard Base64.

To convert them into standard Base64 you'll have to turn - into +, _ into / and appending padding chars = until each of the separate Base64URL-Strings (base64EncodedSegments[]) String.length() is a multiple of 4.

This should fix your problem with the missing } char which was lost due to the non-existent = padding chars in Base64URL Strings.

Title: decode java google oauth2.0 JWT

Body:
Im trying to decode the google oauth token_id using the below stmts..For some reason, the claims are decoded partially...

String token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjdkZGQwOGEwM2IyNWQwZjVhMDllMjNiMmJlMTBkZDIyODQyYTg1NjkifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTAxOTI0MjQ2MzYwNDM0OTY2NzMzIiwiYXpwIjoiNTk0OTU1MjgxODg2LWJxcjBkYm1kcmFicWFvbm1oZWlxazBza2RkZjVhbGs1LmxCLTO3GHRBn0";

        //String[] jwtParts = token.split("\\.");
        String[] base64EncodedSegments = token.split("\\.");
        System.out.println(Arrays.toString(base64EncodedSegments));
        String base64EncodedHeader = base64EncodedSegments[0];
        String base64EncodedClaims = base64EncodedSegments[1];
        byte[] claims = new byte[1000000];
        claims = DatatypeConverter.parseBase64Binary(base64EncodedClaims);
        String s = new String(claims);
        System.out.println(s);
        System.out.println(s.getClass().getName());

        JSONObject emailobject = new JSONObject(s);
        String emailid = emailobject.getString("email");
        System.out.println(emailid);

Decoded claims below:

It starts with a "{" braces but does not close with "}" and because of that I'm  unable to convert to a JSON object and get the actual email id

{"iss":"accounts.google.com","sub":"101924246360434966733","azp":"594955281886-bqr0d0skddf5alk5.apps.googleusercontent.com","email":"test@gmail.com","at_hash":"dVrka2339w4Cezz32ssrY_w","email_verified":true,"aud":"594955281-bqr0dbmdrak5.apps.googleusercontent.com","iat":1423238546,"exp":1413223244

***********Update************

This piece of code works for to connect to google oauth and retrieve the email id...

ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource(UriBuilder.fromUri("https://accounts.google.com/o/oauth2/token").build());
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("code", request.getParameter("code"));
formData.add("client_id", Global.GOOGLE_CLIENT_ID);
formData.add("redirect_uri", Global.GOOGLE_REDIRECT_URL);
formData.add("client_secret", Global.GOOGLE_SECRET);
formData.add("grant_type", "authorization_code");
ClientResponse response1 = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData);
JSONObject jobject = new JSONObject(response1.getEntity(String.class));
String token_id = jobject.getString("id_token");
String[] base64EncodedSegments = token_id.split("\\.");

String base64EncodedHeader = base64EncodedSegments[0];
String base64EncodedClaims = base64EncodedSegments[1];
JsonParser parser = new JsonParser();
JsonElement payload = parser.parse(StringUtils.newStringUtf8(Base64.decodeBase64(base64EncodedClaims)));
JSONObject emailobject = new JSONObject(payload.toString());
String emailid = emailobject.getString("email");

Jars needed -

<dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.3</version>
        </dependency>

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3</version>
</dependency>


问:
Inner join in SQLite3
I'm trying to execute an inner join in SQLite3 and it's not working. I keep getting error messages indicating that the field name in table2 is ambiguous.

Would appreciate any input as to why.

```<code>SELECT
table1.id, table1.cd1, table1.cd2, table1.cd3, table1.cd4, table2.ab

FROM
table1

INNER JOIN table2 ON table2.dx = table1.cd1
INNER JOIN table2 ON table2.dx = table1.cd2
INNER JOIN table2 ON table2.dx = table1.cd3
INNER JOIN table2 ON table2.dx = table1.cd4

GROUP BY 1, 2, 3, 4, 5, 6
</code>```

The field "dx" in table2 corresponds to four different fields in table1: "cd1", "cd2", "cd3", "cd4."

答:
You need table aliases:

```<code>SELECT t1.id, t1.cd1, t1.cd2, t1.cd3, t1.cd4, ?.ab
FROM table1 t1 JOIN
     table2 t21
     ON t21.dx = t1.cd1 JOIN
     table2 t22
     ON t22.dx = t1.cd2 JOIN
     table2 t23
     ON t23.dx = t1.cd3 JOIN
     table2 t24
     ON t24.dx = t1.cd4
GROUP BY 1, 2, 3, 4, 5, 6;
</code>```

I don't know which table ab is supposed to come from, so you need to fill that in.

Title: Inner join in SQLite3

Body:
I'm trying to execute an inner join in SQLite3 and it's not working. I keep getting error messages indicating that the field name in table2 is ambiguous.

Would appreciate any input as to why.

SELECT
table1.id, table1.cd1, table1.cd2, table1.cd3, table1.cd4, table2.ab

FROM
table1

INNER JOIN table2 ON table2.dx = table1.cd1
INNER JOIN table2 ON table2.dx = table1.cd2
INNER JOIN table2 ON table2.dx = table1.cd3
INNER JOIN table2 ON table2.dx = table1.cd4

GROUP BY 1, 2, 3, 4, 5, 6

The field "dx" in table2 corresponds to four different fields in table1: "cd1", "cd2", "cd3", "cd4."

Body:
You need table aliases:

SELECT t1.id, t1.cd1, t1.cd2, t1.cd3, t1.cd4, ?.ab
FROM table1 t1 JOIN
     table2 t21
     ON t21.dx = t1.cd1 JOIN
     table2 t22
     ON t22.dx = t1.cd2 JOIN
     table2 t23
     ON t23.dx = t1.cd3 JOIN
     table2 t24
     ON t24.dx = t1.cd4
GROUP BY 1, 2, 3, 4, 5, 6;

I don't know which table ab is supposed to come from, so you need to fill that in.


问:
Call SConstruct from R
How can I call a sconstruct script from R (e.g. in Rstudio)? I'd like to call SCons and, ideally, also read the output. So that I can get the print from e.g. scons --tree=all as a string.

If I run > system("scons")
I get: sh: scons: command not found

Setting the path Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/path/to/my/sconstruct", sep=":")) doesn't help.

However, any other command works. E.g. if I have a Python script (in the same directory), I can call it as: > system('python test.py')
and get the expected: Hello Rld! back. >system('ls') lists the SConstruct, so I'm in the right work directory.

Calling from a Python script also works, eg: from subprocess import call call('scons') evokes the SConstruct as expected. However, calling that Python script from R -- doesn't work.

It appears as there is something in the R environment setting that I got wrong.

I'm on OS, but a portable solution would be fantastic!

答:
You'll need to either be in the directory where the SConstruct is, specify it's file or use -C to change directory to it.
I don't know R or what the syntax is.

```<code>Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/path/to/my/sconstruct", sep=":"))
</code>```

Should likely be:

```<code>Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/path/to/scons", sep=":"))
</code>```

Title: Call SConstruct from R

Body:
You'll need to either be in the directory where the SConstruct is, specify it's file or use -C to change directory to it.
I don't know R or what the syntax is.

Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/path/to/my/sconstruct", sep=":"))

Should likely be:

Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/path/to/scons", sep=":"))


问:
Binary Tree sorting while enter elements
i am newbie learning java .
i want to make Binary tree that sort the elements

i used this code

```<code>private void setNode (Node Value, Node head){

    if (head == null || Value.Value == head.Value)
        return;

        if (Value.Value > head.Value) {
            if (head.Right == null) {
                head.Right = Value;
                return;
            } else
                setNode(Value, head.Right);
        }

    if (Value.Value < head.Value){
        if(head.Left == null){
            head.Left = Value;
            return;}
        else
            setNode(Value, head.Left);
    }

}
</code>```

but if i used it like this

```<code>for (int i=0 ; i < array.length ; i++)
        link.addNode(new Node(i));

BinaryLinkList a = new BinaryLinkList(link);
    a.Search(700);
</code>```

it will find it after 700 try
because every time the number entered this larger than the previous
it will be like this

0

.1

..2

...3

....4

.....5

.......

........

.........700 <<

...........

............1000

i want it to sort while enter the elements one by one not array
any help ?

答:
The worst case for the general concept of a Binary Tree is to insert elements in sorted order. You will then exactly experience what you just told us, all elements will be put to one side and you do not gain any advantage from the tree concept (the depth is the amount of elements).

For sorting input that may already be sorted you should use other data structures than a Binary Tree, there are many concepts with different advantages and disadvantages.

There is also an optimization where you balance a tree after some time. As @Kevin Anderson mentioned you may take a look at self balancing binary trees. Also the implementation coming with the standard Java library is self balancing too (TreeSet at JavaAPI). Maybe you are also looking for a PriorityQueue (PriorityQueue at JavaAPI). There are also multiple concepts of how to implement such a queue (for example as BucketQueue), again with advantages and disadvantages.

What is your user case? We can help you find a suitable data-structure if you tell us what you want to implement with it.

Body:
i am newbie learning java .
i want to make Binary tree that sort the elements

i used this code

private void setNode (Node Value, Node head){

    if (head == null || Value.Value == head.Value)
        return;

        if (Value.Value > head.Value) {
            if (head.Right == null) {
                head.Right = Value;
                return;
            } else
                setNode(Value, head.Right);
        }

    if (Value.Value < head.Value){
        if(head.Left == null){
            head.Left = Value;
            return;}
        else
            setNode(Value, head.Left);
    }

}

but if i used it like this

for (int i=0 ; i < array.length ; i++)
        link.addNode(new Node(i));

BinaryLinkList a = new BinaryLinkList(link);
    a.Search(700);

it will find it after 700 try
because every time the number entered this larger than the previous
it will be like this

0

.1

..2

...3

....4

.....5

.......

........

.........700 <<

...........

............1000

i want it to sort while enter the elements one by one not array
any help ?


问:
How to enable HTML content on top of Flash content without the frame rate dropping?
I'm developing a Flash application which is communicating with Javascript to allow more features such as custom HTML input etc., by placing an absolute positioned div on top of the Flash application and controlling its position etc. with Flash & Javascript.

Because these html elements have to appear above  the Flash content, I figured the following basic CSS would be enough to do the trick:

```<code>#flashContent {
                position: absolute;
                left: 0px;
                top: 0px;
                z-index: 0;
            }
            #htmlContent {
                position: absolute;
                left: 200px;
                top: 200px;
                z-index: 1;
                width: 200px;
                height: 200px;
                background-color: yellow;
            }
</code>```

So, the htmlContent has a higher z-index than the flash content and thus it should be shown above it. Unfortunately, this only seems to work when you set the Flash object's "wmode" parameter to "transparent".

The problem with this setting is that it's seriously decreasing the application's frame rate to an unacceptable amount.

For static content this does not seem to be a problem, however for my application there's all kinds of elements that you can drag around which have to be moved real-time (while moving the mouse).

So, how do I enable html content on top of flash content without using the "transparent" wmode parameter or how do I optimize frame rate when using the "transparent" wmode parameter?

答: don't use absolute positioning. float it. </p>

Body:
I'm developing a Flash application which is communicating with Javascript to allow more features such as custom HTML input etc., by placing an absolute positioned div on top of the Flash application and controlling its position etc. with Flash & Javascript.

Because these html elements have to appear above  the Flash content, I figured the following basic CSS would be enough to do the trick:

#flashContent {
                position: absolute;
                left: 0px;
                top: 0px;
                z-index: 0;
            }
            #htmlContent {
                position: absolute;
                left: 200px;
                top: 200px;
                z-index: 1;
                width: 200px;
                height: 200px;
                background-color: yellow;
            }

So, the htmlContent has a higher z-index than the flash content and thus it should be shown above it. Unfortunately, this only seems to work when you set the Flash object's "wmode" parameter to "transparent".

The problem with this setting is that it's seriously decreasing the application's frame rate to an unacceptable amount.

For static content this does not seem to be a problem, however for my application there's all kinds of elements that you can drag around which have to be moved real-time (while moving the mouse).

So, how do I enable html content on top of flash content without using the "transparent" wmode parameter or how do I optimize frame rate when using the "transparent" wmode parameter?


问:
Change background image opacity
I have a div element with text blocks and a parent div in which I have set a background image. Now I want to reduce the opacity of the background image. How can I do that?

EDIT:

I am looking to change the way my blog post looks at blogger.com by editing the html content. The html code looks as follows:

```<code><div>
 //my blog post
</div>
</code>```

I tried to surround the whole code above with a div element and set opacity of each div separately as below:

```<code><div style="background-image:url("image.jpg"); opacity:0.5;">
<div style="opacity:1;">
 //my blog post
</div>
</div>
</code>```

But it is not working.

答:
What I did is: </p>

```<code><div id="bg-image"></div>
<div class="container">
    <h1>Hello World!</h1>
</div>
</code>```

<p>CSS: </p>

```<code>html {
    height: 100%;
    width: 100%;
}
body {
    height: 100%;
    width: 100%;
}
#bg-image {
    height: 100%;
    width: 100%;
    position: absolute;
    background-image: url(images/background.jpg);
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    opacity: 0.3;
}
</code>```

Title: Change background image opacity

Body:
I have a div element with text blocks and a parent div in which I have set a background image. Now I want to reduce the opacity of the background image. How can I do that?

EDIT:

I am looking to change the way my blog post looks at blogger.com by editing the html content. The html code looks as follows:

 //my blog post

I tried to surround the whole code above with a div element and set opacity of each div separately as below:

 //my blog post

But it is not working.

Body:
What I did is:

<div id="bg-image"></div>
<div class="container">
    <h1>Hello World!</h1>
</div>

CSS:

html {
    height: 100%;
    width: 100%;
}
body {
    height: 100%;
    width: 100%;
}
#bg-image {
    height: 100%;
    width: 100%;
    position: absolute;
    background-image: url(images/background.jpg);
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    opacity: 0.3;
}


问:
Adding to an array in main via function argument
I'm not sure if I even worded the title correctly, but basically. I want to know if there is a way to add to the buff array from the hey function using the pointers in the arguments and why does it work if it does?

buf[100].
example:

```<code>int main(){
  char buf[100];
  hey("320244",buf);
  printf("%s", buf);
}
  void hey(char* s, char* result){
  /*
  some code that appends to result using pointers
  do some stuff with s and get the result back in buf without using return.
  */
}
</code>```

答:
Let's do the right thing, and use a structure to describe a dynamically allocated, grow-as-needed string:

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

struct mystring {
    char   *ptr;  /* The actual string */
    size_t  len;  /* The length of the string */
    size_t  max;  /* Maximum number of chars allocated for */
};
#define MYSTRING_INIT { NULL, 0, 0 }
</code>```

If we want to append something to a struct mystring, we define a function that takes a pointer to the structure the function can modify. (If it only needed a char pointer instead of a structure, it'd take a char **; a pointer to a char pointer.)

```<code>void mystring_append(struct mystring *ms, const char *s)
{
    const size_t slen = (s) ? strlen(s) : 0;

    /* Make sure ms points to a struct mystring; is not NULL */
    if (!ms) {
        fprintf(stderr, "mystring_append(): No struct mystring specified; ms == NULL!\n");
        exit(EXIT_FAILURE);
    }

    /* Make sure we have enough memory allocated for the data */
    if (ms->len + slen >= ms->max) {
        const size_t  max = ms->len + slen + 1;
        char         *ptr;

        ptr = realloc(ms->ptr, max);
        if (!ptr) {
            fprintf(stderr, "mystring_append(): Out of memory!\n");
            exit(EXIT_FAILURE);
        }

        ms->max = max;
        ms->ptr = ptr;
    }

    /* Append. */
    if (slen > 0) {
        memmove(ms->ptr + ms->len, s, slen);
        ms->len += slen;
    }

    /* We allocated one char extra for the
       string-terminating nul byte, '\0'. */
    ms->ptr[ms->len] = '\0';

    /* Done! */
}
</code>```

The (s) ? strlen(s) : 0; expression uses the ?: conditional operator. Essentially, if s is non-NULL, the expression evaluates to strlen(s), otherwise it evaluates to 0. You could use

```<code>size_t slen;

if (s != NULL)
    slen = strlen(s);
else
    slen = 0;
</code>```

instead; I just like the concise const size_t  slen = (s) ? strlen(s) : 0 form better. (The const tells the compiler that the slen variable is not going to be modified. While it might help the compiler generate better code, it is mostly a hint to other programmers that slen will have this particular value all through this function, so they do not need to check if it might be modified somewhere. It helps code maintenance in the long term, so it is a very good habit to get into.)

Normally, functions return success or error. For ease of use, mystring_append() does not return anything. If there is an error, it prints an error message to standard output, and stops the program.

It is a good practice to create a function that releases any dynamic memory used by such a structure. For example,

```<code>void mystring_free(struct mystring *ms)
{
    if (ms) {
        free(ms->ptr);
        ms->ptr = NULL;
        ms->len  = 0;
        ms->max  = 0;
    }
}
</code>```

Often, you see initialization functions as well, like

```<code>void mystring_init(struct mystring *ms)
{
    ms->ptr = NULL;
    ms->len = 0;
    ms->max = 0;
}
</code>```

but I prefer initialization macros like MYSTRING_INIT, defined earlier.

You can use the above in a program like this:

```<code>int main(void)
{
    struct mystring  message = MYSTRING_INIT;

    mystring_append(&message, "Hello, ");
    mystring_append(&message, "world!");

    printf("message = '%s'.\n", message.ptr);

    mystring_free(&message);

    return EXIT_SUCCESS;
}
</code>```

Notes:

When we declare a variable of the structure type (and not as a pointer to the structure, i.e. no *), we use . between the variable name and the field name. In main(), we have struct mystring  message;, so we use message.ptr to refer to the char pointer in the message structure.

When we declare a variable as a pointer to a structure type (as in the functions, with * before the variable name), we use -> between the variable name and the field name. For example, in mystring_append() we have struct mystring *ms, so we use ms->ptr to refer to the char pointer in the structure pointed to by the ms variable.

Dynamic memory management is not difficult. realloc(NULL, size) is equivalent to malloc(size), and free(NULL) is safe (does nothing).

In the above function, we just need to keep track of both current length, and the number of chars allocated for the dynamic buffer pointed to by field ptr, and remember that a string needs that terminating nul byte, '\0', which is not counted in its length.

The above function reallocates only just enough memory for the additional string. In practice, extra memory is often allocated, so that the number of reallocations needed is kept to a minimum. (This is because memory allocation/reallocation functions are considered expensive, or slow, compared to other operations.) That is a topic for another occasion, though.

If we want a function to be able to modify a variable (be that any type, even a structure) in the callers scope -- struct mystring message; in main() in the above example --, the function needs to take a pointer to variable of that type, and modify the value via the pointer.

The address-of operator, &, takes the address of some variable. In particular, &message in the above example evaluates to a pointer to a struct mystring.

If we write struct mystring *ref = &message;, with struct mystring message;, then message is a variable of struct mystring type, and ref is a pointer to message; ref being of struct mystring * type.

Body:
I'm not sure if I even worded the title correctly, but basically. I want to know if there is a way to add to the buff array from the hey function using the pointers in the arguments and why does it work if it does?

buf[100].
example:

int main(){
  char buf[100];
  hey("320244",buf);
  printf("%s", buf);
}
  void hey(char* s, char* result){
  /*
  some code that appends to result using pointers
  do some stuff with s and get the result back in buf without using return.
  */
}

Body:
Let's do the right thing, and use a structure to describe a dynamically allocated, grow-as-needed string:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

struct mystring {
    char   *ptr;  /* The actual string */
    size_t  len;  /* The length of the string */
    size_t  max;  /* Maximum number of chars allocated for */
};
#define MYSTRING_INIT { NULL, 0, 0 }

If we want to append something to a struct mystring, we define a function that takes a pointer to the structure the function can modify. (If it only needed a char pointer instead of a structure, it'd take a char **; a pointer to a char pointer.)

void mystring_append(struct mystring *ms, const char *s)
{
    const size_t slen = (s) ? strlen(s) : 0;

    /* Make sure ms points to a struct mystring; is not NULL */
    if (!ms) {
        fprintf(stderr, "mystring_append(): No struct mystring specified; ms == NULL!\n");
        exit(EXIT_FAILURE);
    }

    /* Make sure we have enough memory allocated for the data */
    if (ms->len + slen >= ms->max) {
        const size_t  max = ms->len + slen + 1;
        char         *ptr;

        ptr = realloc(ms->ptr, max);
        if (!ptr) {
            fprintf(stderr, "mystring_append(): Out of memory!\n");
            exit(EXIT_FAILURE);
        }

        ms->max = max;
        ms->ptr = ptr;
    }

    /* Append. */
    if (slen > 0) {
        memmove(ms->ptr + ms->len, s, slen);
        ms->len += slen;
    }

    /* We allocated one char extra for the
       string-terminating nul byte, '\0'. */
    ms->ptr[ms->len] = '\0';

    /* Done! */
}

The (s) ? strlen(s) : 0; expression uses the ?: conditional operator. Essentially, if s is non-NULL, the expression evaluates to strlen(s), otherwise it evaluates to 0. You could use

size_t slen;

if (s != NULL)
    slen = strlen(s);
else
    slen = 0;

instead; I just like the concise const size_t  slen = (s) ? strlen(s) : 0 form better. (The const tells the compiler that the slen variable is not going to be modified. While it might help the compiler generate better code, it is mostly a hint to other programmers that slen will have this particular value all through this function, so they do not need to check if it might be modified somewhere. It helps code maintenance in the long term, so it is a very good habit to get into.)

Normally, functions return success or error. For ease of use, mystring_append() does not return anything. If there is an error, it prints an error message to standard output, and stops the program.

It is a good practice to create a function that releases any dynamic memory used by such a structure. For example,

void mystring_free(struct mystring *ms)
{
    if (ms) {
        free(ms->ptr);
        ms->ptr = NULL;
        ms->len  = 0;
        ms->max  = 0;
    }
}

Often, you see initialization functions as well, like

void mystring_init(struct mystring *ms)
{
    ms->ptr = NULL;
    ms->len = 0;
    ms->max = 0;
}

but I prefer initialization macros like MYSTRING_INIT, defined earlier.

You can use the above in a program like this:

int main(void)
{
    struct mystring  message = MYSTRING_INIT;

    mystring_append(&message, "Hello, ");
    mystring_append(&message, "world!");

    printf("message = '%s'.\n", message.ptr);

    mystring_free(&message);

    return EXIT_SUCCESS;
}

Notes:

When we declare a variable of the structure type (and not as a pointer to the structure, i.e. no *), we use . between the variable name and the field name. In main(), we have struct mystring  message;, so we use message.ptr to refer to the char pointer in the message structure.

When we declare a variable as a pointer to a structure type (as in the functions, with * before the variable name), we use -> between the variable name and the field name. For example, in mystring_append() we have struct mystring *ms, so we use ms->ptr to refer to the char pointer in the structure pointed to by the ms variable.

Dynamic memory management is not difficult. realloc(NULL, size) is equivalent to malloc(size), and free(NULL) is safe (does nothing).

In the above function, we just need to keep track of both current length, and the number of chars allocated for the dynamic buffer pointed to by field ptr, and remember that a string needs that terminating nul byte, '\0', which is not counted in its length.

The above function reallocates only just enough memory for the additional string. In practice, extra memory is often allocated, so that the number of reallocations needed is kept to a minimum. (This is because memory allocation/reallocation functions are considered expensive, or slow, compared to other operations.) That is a topic for another occasion, though.

If we want a function to be able to modify a variable (be that any type, even a structure) in the callers scope -- struct mystring message; in main() in the above example --, the function needs to take a pointer to variable of that type, and modify the value via the pointer.

The address-of operator, &, takes the address of some variable. In particular, &message in the above example evaluates to a pointer to a struct mystring.

If we write struct mystring *ref = &message;, with struct mystring message;, then message is a variable of struct mystring type, and ref is a pointer to message; ref being of struct mystring * type.


问:
How to set text to go over an image strictly in HTML?
I am writing an emailed newsletter, and need to set an image as the footer, with a few clickable links over it. I have figured it out using both HTML and CSS, but no matter where I searched I could not find a way to do this strictly using HTML. Can anyone help me out?

```<code><!--Footer-->
                        <tr id="footer">
                        <td id="footer" style="font-family: 'Titillium Web', sans-serif;;-webkit-text-size-adjust:none;background-image: url" img url"" templates\uuaemail-foot.jpg";padding-left:="" 20px;padding-right:="" 20px;padding-top:="" 10px;padding-bottom:="" 20px;"="">
                        <table height="101" width="602">
                        <tbody>
                            <tr>
                                <td id="footer" style="font-size: 10px;color:white;" height="95" valign="top" width="600" align="center"><p><br></p><p class="style3"><strong><span style="font-size: 12px;">admissions.rutgers.edu<br></span></strong></p><p class="style3"><span class="style7"><span style="font-size: 8px;"><strong> University Undergraduate Admissions</strong>, Operations Center<br>©2017 , an equal opportunity, affirmative action institution.</span></span></p></td>
                            </tr>
                        </tbody>
                    </table>
                </td>
</code>```

Is what I currently have (with CSS styling)

update: My issue is that the email is widely sent to Ms Outlook 2016, which I have both heard and seen through testing that it does not process CSS styles very well. When I opened this code in Outlook, it showed the CSS styling commands at the top of the message, and did not apply it at all.

答:
You want to use background image in your email and you want it rendered in outlook. Use this site http://backgrounds.cm/ to generate code for background image that will work in all outlook desktop versions. Then you can add links etc. over the image.

Also, please don't use same id more than once in your code. You can assign an ID to one element only. To cover multiple elements, use class attribute.

Body:
I am writing an emailed newsletter, and need to set an image as the footer, with a few clickable links over it. I have figured it out using both HTML and CSS, but no matter where I searched I could not find a way to do this strictly using HTML. Can anyone help me out?

admissions.rutgers.edu

 University Undergraduate Admissions, Operations Center
©2017 , an equal opportunity, affirmative action institution.

Is what I currently have (with CSS styling)

update: My issue is that the email is widely sent to Ms Outlook 2016, which I have both heard and seen through testing that it does not process CSS styles very well. When I opened this code in Outlook, it showed the CSS styling commands at the top of the message, and did not apply it at all.


问:
Detecting the opening or closing of a details element
How can I detect when a details element is opened or closed in Javascript? Other than attaching a listener to the click function and checking if the open attribute is set or not. </p>

答:
In jQuery you can catch the event using .on('toggle') like this:

```<code>$('#detail-id').on('toggle', function() {
   //code
});
</code>```

Body:
In jQuery you can catch the event using .on('toggle') like this:

$('#detail-id').on('toggle', function() {
   //code
});


问:
Using R in Sublime text 3: independent help page
In R (just default mac R) on my mac machine, when I see the help page with

```<code>> ?read.csv
</code>```

it appears on a new window with a beautiful format.

Now I'm using the Sublime text 3 for R (with SublimeREPL:R, R-Box, R-Extended etc.) on the mac machine, many things work fine.

My question is:
when I type the help page (?read.csv), the contents appear on the same ST3 window with a plain format.
Is there any way to make it appear on a new window such as a HTML page (in Safari)?

答:
Set the help_type option to "html":

```<code>options(help_type = 'html')
</code>```

and it will open help files in the default browser. If you put that in your .Rprofile, you won't need to set it for each session.

Body:
In R (just default mac R) on my mac machine, when I see the help page with

> ?read.csv

it appears on a new window with a beautiful format.

Now I'm using the Sublime text 3 for R (with SublimeREPL:R, R-Box, R-Extended etc.) on the mac machine, many things work fine.

My question is:
when I type the help page (?read.csv), the contents appear on the same ST3 window with a plain format.
Is there any way to make it appear on a new window such as a HTML page (in Safari)?

Body:
Set the help_type option to "html":

options(help_type = 'html')

and it will open help files in the default browser. If you put that in your .Rprofile, you won't need to set it for each session.


问:
SQL statement to convert date-time format in some columns
I have an SQLite database in which some columns are date-time strings with the format 1/2/2000 3:45:56 am.

Is there an SQL statement which can convert these values to strings with an ISO-8601-like format (2000-01-02 03:45:56)?

(One possible non-SQL way to do this would be to export the database as a CSV file, and use Python, with its csv and datetime modules, to parse the columns.)

答: SQL As Understood By SQLite - Date And Time Functions.</p>


问:
splice() inside a for loop, what is the solution?
I'm trying to remove repetitions from this array called "bigArray" while keeping the three first positions of the array intact (even if they repeat).

My issue is that the splice() inside the for loop is not working properly, since every time it splices, the for loop skips the next position of the array (since that position is then one position lower in the array).

How do I get my function to return [0,0,0,3,2] ?

Thank you

var bigArray = [0,0,0,3,2,2,3,3,2];

function call() {

  for (let i=3; i < (bigArray.length); i++) {
    if (bigArray.indexOf(bigArray[i]) !== i) {
          bigArray.splice(i,1);

    }

    }

    console.log(bigArray);
    return bigArray;
}

call();```

答:
if you are looking for a functional approach:</p>

```<code>var arr = [0,0,0,3,2,2,3,3,2];
arr.filter((e,i,self) => i<3 ? true : self.findIndex(x=>x === e) === i)
</code>```

Body:
if you are looking for a functional approach:

var arr = [0,0,0,3,2,2,3,3,2];
arr.filter((e,i,self) => i<3 ? true : self.findIndex(x=>x === e) === i)


问:
Concat arabic and english string with string.Format()
Have some trouble with concat two string.

```<code>return string.Format("{0}{1}{2}",
            IdWithSubType,

            ExtraInfo.Any(info => info.InfoType == UniExtraInfoType.Alias)
            ? string.Format(" ({0})", string.Join(",", ExtraInfo.First(info => info.InfoType == UniExtraInfoType.Alias).Info))
            : "",

            Context != null
            ? string.Format(" ({0})", Context.IdWithSubType)
            : "");
</code>```

it's ok when IdWithSubType, extrainfo and context has latin or kirillic symbols, but IdWithSubType can be arabic, and concat with that is wrong.
e.g.100252575)طائرات هليكوبت@vk.com)
arabic and other symbols mixed, but i need something like "here arabic string"                    (100252575@vk.com. it would be great if this problem have solve with String.Format. Hope for your help. Thank you

答:
It's likely no encoding issues appear there, just how RTL (right-to-left) string follows arrangement as part of LTR (left-to-right) string.

There's 2 characters which commonly used in bidirectional formatting to mark either LTR & RTL part, assigned as 0x200e (LTR) & 0x200f (RTL). In this case, use 0x200e to mark end of RTL part (in Arabic) and starting LTR part:

```<code>string leftToRight = ((char)0x200E).ToString();

// using string.Format
return string.Format("{0}{1}{2}{3}",
            IdWithSubType,
            leftToRight,

            ExtraInfo.Any(info => info.InfoType == UniExtraInfoType.Alias)
            ? string.Format(" ({0})", string.Join(",", ExtraInfo.First(info => info.InfoType == UniExtraInfoType.Alias).Info))
            : "",

            Context != null
            ? string.Format(" ({0})", Context.IdWithSubType)
            : "");,

// alternative: using string.Join
return string.Join(leftToRight, IdWithSubType,
            ExtraInfo.Any(info => info.InfoType == UniExtraInfoType.Alias)
            ? string.Format(" ({0})", string.Join(",", ExtraInfo.First(info => info.InfoType == UniExtraInfoType.Alias).Info))
            : "",

            Context != null
            ? string.Format(" ({0})", Context.IdWithSubType)
            : "");,
</code>```

Demo: .NET Fiddle Example

Similar issues:

incorrect right to left concatenation english and Arabic

Problem creating correct path concatenating left to right with right to left sections

Body:
Have some trouble with concat two string.

return string.Format("{0}{1}{2}",
            IdWithSubType,

            ExtraInfo.Any(info => info.InfoType == UniExtraInfoType.Alias)
            ? string.Format(" ({0})", string.Join(",", ExtraInfo.First(info => info.InfoType == UniExtraInfoType.Alias).Info))
            : "",

            Context != null
            ? string.Format(" ({0})", Context.IdWithSubType)
            : "");

it's ok when IdWithSubType, extrainfo and context has latin or kirillic symbols, but IdWithSubType can be arabic, and concat with that is wrong.
e.g.100252575)طائرات هليكوبت@vk.com)
arabic and other symbols mixed, but i need something like "here arabic string"                    (100252575@vk.com. it would be great if this problem have solve with String.Format. Hope for your help. Thank you

Body:
It's likely no encoding issues appear there, just how RTL (right-to-left) string follows arrangement as part of LTR (left-to-right) string.

There's 2 characters which commonly used in bidirectional formatting to mark either LTR & RTL part, assigned as 0x200e (LTR) & 0x200f (RTL). In this case, use 0x200e to mark end of RTL part (in Arabic) and starting LTR part:

string leftToRight = ((char)0x200E).ToString();

// using string.Format
return string.Format("{0}{1}{2}{3}",
            IdWithSubType,
            leftToRight,

            ExtraInfo.Any(info => info.InfoType == UniExtraInfoType.Alias)
            ? string.Format(" ({0})", string.Join(",", ExtraInfo.First(info => info.InfoType == UniExtraInfoType.Alias).Info))
            : "",

            Context != null
            ? string.Format(" ({0})", Context.IdWithSubType)
            : "");,

// alternative: using string.Join
return string.Join(leftToRight, IdWithSubType,
            ExtraInfo.Any(info => info.InfoType == UniExtraInfoType.Alias)
            ? string.Format(" ({0})", string.Join(",", ExtraInfo.First(info => info.InfoType == UniExtraInfoType.Alias).Info))
            : "",

            Context != null
            ? string.Format(" ({0})", Context.IdWithSubType)
            : "");,

Demo: .NET Fiddle Example

Similar issues:

incorrect right to left concatenation english and Arabic

Problem creating correct path concatenating left to right with right to left sections


问:
PHP Class on Class, get Parent
Let's say I have three classes. One being the parent and two being "childs". However, I'm not using  class - extends -:

```<code>class root
{
   function root(){
      $this->son = new son();
      $this->daughter = new daughter();
   }
}
class son
{
 ...
}
class daughter
{
  ...
}
</code>```

How could I call a function of son from a function of daughter? In other words, how could I reference the class root from son/daughter so that I could call functions of each other, from each other?

答:
Example, hopefully speaking for itself, with the important lines being:

a) $this->son = new Son($this); – where a reference to the Root object is passed to a new Son class (or Daughter respectively).

b) echo $son->root->daughter->aboutme(); – where the reference is used to access other objects, root might have access to.

One can consider this a kind of Mediator pattern.

```<code><?php
    class Root
    {
        function __construct(){
            $this->son = new Son($this);
            $this->daughter = new Daughter($this);
        }
        function aboutme() { print "I'm root.\n"; }

    }
    class Son
    {
        function __construct($root) {
            $this->root = $root;
        }
        function aboutme() { print "I'm a son.\n"; }
    }
    class Daughter
    {
        function __construct($root) {
            $this->root = $root;
        }
        function aboutme() { print "I'm a daughter.\n"; }
    }

    $root = new Root();
    echo $root->aboutme();
    $son = $root->son;
    echo $son->aboutme();
    echo $son->root->daughter->aboutme();
?>
</code>```

This will yield:

```<code>I'm root.
I'm a son.
I'm a daughter.
</code>```

Title: PHP Class on Class, get Parent

Body:
Let's say I have three classes. One being the parent and two being "childs". However, I'm not using  class - extends -:

class root
{
   function root(){
      $this->son = new son();
      $this->daughter = new daughter();
   }
}
class son
{
 ...
}
class daughter
{
  ...
}

How could I call a function of son from a function of daughter? In other words, how could I reference the class root from son/daughter so that I could call functions of each other, from each other?

Body:
Example, hopefully speaking for itself, with the important lines being:

a) $this->son = new Son($this); – where a reference to the Root object is passed to a new Son class (or Daughter respectively).

b) echo $son->root->daughter->aboutme(); – where the reference is used to access other objects, root might have access to.

One can consider this a kind of Mediator pattern.

<?php
    class Root
    {
        function __construct(){
            $this->son = new Son($this);
            $this->daughter = new Daughter($this);
        }
        function aboutme() { print "I'm root.\n"; }

    }
    class Son
    {
        function __construct($root) {
            $this->root = $root;
        }
        function aboutme() { print "I'm a son.\n"; }
    }
    class Daughter
    {
        function __construct($root) {
            $this->root = $root;
        }
        function aboutme() { print "I'm a daughter.\n"; }
    }

    $root = new Root();
    echo $root->aboutme();
    $son = $root->son;
    echo $son->aboutme();
    echo $son->root->daughter->aboutme();
?>

This will yield:

I'm root.
I'm a son.
I'm a daughter.


问:
Find multiple files open write new line save
In Linux I need to write a new line in the same file saved in multiple different directories.

They are saved for example in:

```<code>Home/user1/settings/settings.ini
Home/user2/settings/settings.ini
...
Home/user500/settings/settings.ini
</code>```

How can I do it?

答:
That will do:</p>

```<code>for file in /home/*/settings/settings.ini; do
    echo >> "${file}"
done
</code>```

Body:
In Linux I need to write a new line in the same file saved in multiple different directories.

They are saved for example in:

Home/user1/settings/settings.ini
Home/user2/settings/settings.ini
...
Home/user500/settings/settings.ini

How can I do it?

Body:
That will do:

for file in /home/*/settings/settings.ini; do
    echo >> "${file}"
done


问:
Filling a react form using JQuery
So I am in the process of attempting to use some simple code injection to populate a form and submit it, in most cases, I am able to have the textbox revalidate by firing the blur event, but in the case of a react form build on redux, it does not validate in the same manner.

I tried using the following code, but it does not work:

top.jQuery('input#last-name-\\[0\\]').val('Smith').attr('value','Smith').trigger('blur');

Is there an event that I should be firing instead of the input event?

The values are not detected as firing the click event on the submit fails validation, as though no data has been entered in the form.

I tried a number of triggers including keyup, keydown, keypress, focus, blur, and changed.

Please note that using default values are not an option, because I am injecting the form data into a website that is not my own.

This is the code that react is using to build the component:

```<code>function LastNameComponent(_ref) {
    var index = _ref.index,
        isFirstField = _ref.isFirstField,
        formatValue = _ref.formatValue;

    var minLength = 2;
    var maxLength = 80;
    return _react2.default.createElement(
        'div',
        { className: 'form--item span3' },
        _react2.default.createElement(
            'label',
            { className: 'search-label small field__icon_group' },
            _react2.default.createElement(
                'span',
                null,
                '*'
            ),
            'Last Name',
            _react2.default.createElement(_TextInput2.default, {
                id: "last-name-[" + index + "]",
                model: "searchParams.searches[" + index + "].fields.lastName",
                validators: { required: function required(value) {
                        return !value || value.length < minLength || value.length > maxLength;
                    } },
                formatValue: formatValue
            }),
            _react2.default.createElement(_ErrorMessage2.default, {
                model: "searchParams.searches[" + index + "].fields.lastName",
                messages: { required: "Please enter the member's Last Name" }
            })
        )
    );
}
</code>```

答:
This does the trick

```<code>var target = $('input')[0]
var event = document.createEvent("HTMLEvents");
$('input').val('Smith')
event.initEvent("input", true, true);
target.dispatchEvent(event);
</code>```

Working example with same code here: https://codesandbox.io/s/W66Z4RA3E

Refer to https://github.com/facebook/react/issues/3249

Seems like event triggering is non trivial because dom and react events are not one to one.

Title: Filling a react form using JQuery

Body:
So I am in the process of attempting to use some simple code injection to populate a form and submit it, in most cases, I am able to have the textbox revalidate by firing the blur event, but in the case of a react form build on redux, it does not validate in the same manner.

I tried using the following code, but it does not work:

top.jQuery('input#last-name-\\[0\\]').val('Smith').attr('value','Smith').trigger('blur');

Is there an event that I should be firing instead of the input event?

The values are not detected as firing the click event on the submit fails validation, as though no data has been entered in the form.

I tried a number of triggers including keyup, keydown, keypress, focus, blur, and changed.

Please note that using default values are not an option, because I am injecting the form data into a website that is not my own.

This is the code that react is using to build the component:

function LastNameComponent(_ref) {
    var index = _ref.index,
        isFirstField = _ref.isFirstField,
        formatValue = _ref.formatValue;

    var minLength = 2;
    var maxLength = 80;
    return _react2.default.createElement(
        'div',
        { className: 'form--item span3' },
        _react2.default.createElement(
            'label',
            { className: 'search-label small field__icon_group' },
            _react2.default.createElement(
                'span',
                null,
                '*'
            ),
            'Last Name',
            _react2.default.createElement(_TextInput2.default, {
                id: "last-name-[" + index + "]",
                model: "searchParams.searches[" + index + "].fields.lastName",
                validators: { required: function required(value) {
                        return !value || value.length < minLength || value.length > maxLength;
                    } },
                formatValue: formatValue
            }),
            _react2.default.createElement(_ErrorMessage2.default, {
                model: "searchParams.searches[" + index + "].fields.lastName",
                messages: { required: "Please enter the member's Last Name" }
            })
        )
    );
}

Body:
This does the trick

var target = $('input')[0]
var event = document.createEvent("HTMLEvents");
$('input').val('Smith')
event.initEvent("input", true, true);
target.dispatchEvent(event);

Working example with same code here: https://codesandbox.io/s/W66Z4RA3E

Refer to https://github.com/facebook/react/issues/3249

Seems like event triggering is non trivial because dom and react events are not one to one.


问:
Read many SPSS files at once in R
I am trying to read all SPSS files in a folder in R to different data.frames. I only need that, all of those files read into R dataframes.

I believe I need a for loop or maybe some solution with lapply or sapply. I have tried many options with loops or lapply, but the best I got was to create all the data.

The best I got so far was with the following code (adapted from a solution to open multiple CSV files):

```<code>library(foreign)

filenames <- list.files()

filelist <- lapply(filenames, read.spss, to.data.frame = TRUE)

names(filelist) <- c("nic", "hon", "chi", "cr", "repdom", "ecu", "col",
"sal", "par", "mex", "arg", "gua", "pan", "uru", "bra")

invisible(lapply(names(filelist), function(x)
assign(x,filelist[[x]],envir=.GlobalEnv)))
</code>```

With this code, I got all the files read, but as lists, not as data.frames. I don't know where I could put a "as.data.frame" or something like this to get what I want.

Maybe a solution would be to loop for all the files in the folder, so that the first element in the list (the first file), would be read as df.1, then df.2, etc. It doesn't matter what the names of the dataframes will be, I just need a simple code to read all of them into dataframes.

答:
At present, your object file_list is probably a character vector, not a list. If you prefer the resulting object to be a list, try:

```<code>library(foreign)

file_list <- as.list(list.files())
res <- lapply(file_list, read.spss, to.data.frame = TRUE)
</code>```

This generates a vector of file names and coerces that vector to a list class object. Then, we apply read.spss to the list of file names using lapply, and assign the results to the object res.

Alternatively, you can apply read.spss straight to the character vector object (without coercing the vector to a list) using sapply:

```<code>file_vector <- list.files()
res <- sapply(file_vector, read.spss, to.data.frame = TRUE)
</code>```

See also: Read multiple CSV files into separate data frames

Title: Read many SPSS files at once in R

Body:
I am trying to read all SPSS files in a folder in R to different data.frames. I only need that, all of those files read into R dataframes.

I believe I need a for loop or maybe some solution with lapply or sapply. I have tried many options with loops or lapply, but the best I got was to create all the data.

The best I got so far was with the following code (adapted from a solution to open multiple CSV files):

library(foreign)

filenames <- list.files()

filelist <- lapply(filenames, read.spss, to.data.frame = TRUE)

names(filelist) <- c("nic", "hon", "chi", "cr", "repdom", "ecu", "col",
"sal", "par", "mex", "arg", "gua", "pan", "uru", "bra")

invisible(lapply(names(filelist), function(x)
assign(x,filelist[[x]],envir=.GlobalEnv)))

With this code, I got all the files read, but as lists, not as data.frames. I don't know where I could put a "as.data.frame" or something like this to get what I want.

Maybe a solution would be to loop for all the files in the folder, so that the first element in the list (the first file), would be read as df.1, then df.2, etc. It doesn't matter what the names of the dataframes will be, I just need a simple code to read all of them into dataframes.

Body:
At present, your object file_list is probably a character vector, not a list. If you prefer the resulting object to be a list, try:

library(foreign)

file_list <- as.list(list.files())
res <- lapply(file_list, read.spss, to.data.frame = TRUE)

This generates a vector of file names and coerces that vector to a list class object. Then, we apply read.spss to the list of file names using lapply, and assign the results to the object res.

Alternatively, you can apply read.spss straight to the character vector object (without coercing the vector to a list) using sapply:

file_vector <- list.files()
res <- sapply(file_vector, read.spss, to.data.frame = TRUE)

See also: Read multiple CSV files into separate data frames


问:
Celery best way manage/get eta of task
I want to get eta of task in celery each time with get request. There is no direct api in celery to get task scheduled time (except inspect() - but it's seems very costly to me)

How can i manage eta of particular task? The downside of storing eta time in Django model is not consistent ( either i couldnt store taks_id because i can't -  dont know how get eta from task_id)

I see on one question that there is no api, cause it somehow depends on brokers and etc. But i hope that there is some solution

So what's the best way manage task_id to get eta?

Backend and broker is redis

答:
I don't think there is a magic way to do this.

What I do in my app is just log the execution time for each task and return that as an ETA. If you wanted to get a little more accurate you could also factor in the redis queue size and the task consumption rate.

Title: Celery best way manage/get eta of task


问:
How to Delete DataRow from DataTable quickly
I input data in DataTable in column direction.

```<code>for(int i=0 ; i<mTable.Count ; i++){
  Table.Columns.Add(i);
  foreach(DataRow row in Table.Rows){
    if(result == 1)
      row[i] = result;
    else
      row[i] = null;
  }
}
</code>```

From here, If All data of column is null, I want to delete row.

For example,

1 2 3 4 5

6 7 8 9 10

11 12 13 14 15

16 17 18 19 20

11, 12, 13, 14, 15 are null, I want to delete Table.Rows[2].

So, I use next way.

```<code>for(int i = Table.Rows.Count-1;i >= 0;i--)
{
                for (int j = 0; j < mTable.Count; j++)
                {
                    if (Table.Rows[i][j] != null)
                        break;
                    if(j == mTable.Count-1)
                        Table.Rows.Remove(Table.Rows[i]);
                }
}
</code>```

But, If There's a lot of data, It will slow down considerably.

Is there another fast way?

答:
You algorithm is probably the quickest method.  But you can can a little bit better performance with a few improvements</p>

```<code>            int numberOfCols = Table.Columns.Count;
            for (int i = Table.Rows.Count - 1; i >= 0; i--)
            {
                Boolean delete = true;
                for (int j = 0; j < numberOfCols; j++)
                {
                    if (Table.Rows[i][j] != null)
                    {
                        delete = false;
                        break;
                    }
                }
                if (delete)
                {
                    Table.Rows.Remove(Table.Rows[i]);
                }
            }
</code>```

Body:
I input data in DataTable in column direction.

for(int i=0 ; i<mTable.Count ; i++){
  Table.Columns.Add(i);
  foreach(DataRow row in Table.Rows){
    if(result == 1)
      row[i] = result;
    else
      row[i] = null;
  }
}

From here, If All data of column is null, I want to delete row.

For example,

1 2 3 4 5

6 7 8 9 10

11 12 13 14 15

16 17 18 19 20

11, 12, 13, 14, 15 are null, I want to delete Table.Rows[2].

So, I use next way.

for(int i = Table.Rows.Count-1;i >= 0;i--)
{
                for (int j = 0; j < mTable.Count; j++)
                {
                    if (Table.Rows[i][j] != null)
                        break;
                    if(j == mTable.Count-1)
                        Table.Rows.Remove(Table.Rows[i]);
                }
}

But, If There's a lot of data, It will slow down considerably.

Is there another fast way?

Body:
You algorithm is probably the quickest method.  But you can can a little bit better performance with a few improvements

            int numberOfCols = Table.Columns.Count;
            for (int i = Table.Rows.Count - 1; i >= 0; i--)
            {
                Boolean delete = true;
                for (int j = 0; j < numberOfCols; j++)
                {
                    if (Table.Rows[i][j] != null)
                    {
                        delete = false;
                        break;
                    }
                }
                if (delete)
                {
                    Table.Rows.Remove(Table.Rows[i]);
                }
            }


问:
How can I make a static homepage while still using React?
From my understanding, React.js isn't SEO friendly. I want to make my homepage static and not have React involved with rendering it so that I can optimize it to be as SEO friendly as possible. What's the best way to do this?</p>

答:
You need to use server side rendering, which leverages the React renderToString method, requires a dynamic web server.  Here's a tutorial.

renderToString()

Render a React element to its initial HTML. This should only be used
  on the server. React will return an HTML string. You can use this
  method to generate HTML on the server and send the markup down on the
  initial request for faster page loads and to allow search engines to
  crawl your pages for SEO purposes.

If you call ReactDOM.render() on a node that already has this
  server-rendered markup, React will preserve it and only attach event
  handlers, allowing you to have a very performant first-load
  experience.


问:
Editing django database on same page without moving to other view function
I have a details page that displays the details of the parts and has option for adding stock of that part and list of stock that has already been added

```<code>def part_details(request,pk):
    temp =check_session_exist(request)
    if temp != True:
        return HttpResponseRedirect(temp)

    my_list=populate_nav_bar() //displaying navigation bar
    temp_list = models.part_list.objects.get(part_id=pk) // get stock information

    if request.method  == 'POST': //adding stock of the current part
        form_entered=forms.part_stock_form(request.POST)
        if form_entered.is_valid():
            temp = models.part_stock()
            temp.part_id = models.part_list.objects.get(pk=pk)
            temp.entry_date = form_entered.cleaned_data['entry_date']
            temp.supplier = form_entered.cleaned_data['supplier']
            temp.amount = form_entered.cleaned_data['amount']
            temp.save()
            return HttpResponseRedirect(reverse('parts:part_details',args=[pk]))
        else:
            print("invalid field")
            return render(request, 'part_details.html',
                      {'part_temp': temp, 'my_list': my_list, 'part_stock_form': form_entered})

    return render(request,'part_details.html', {'part_temp':temp_list,'my_list':my_list,'part_stock_form': forms.part_stock_form})
</code>```

now I want o to edit the stock from the same page where do I put the function for this. can't I just call the function for it without redirecting it to other view and redirecting back to the same view. does javascript provide a function for adding/editing database?

答: Do you want to edit the db whithout reload the page? If this is the case, you can use ajax for that, or in the form put the same url and it will return to the same view</p>

Body:
I have a details page that displays the details of the parts and has option for adding stock of that part and list of stock that has already been added

def part_details(request,pk):
    temp =check_session_exist(request)
    if temp != True:
        return HttpResponseRedirect(temp)

    my_list=populate_nav_bar() //displaying navigation bar
    temp_list = models.part_list.objects.get(part_id=pk) // get stock information

    if request.method  == 'POST': //adding stock of the current part
        form_entered=forms.part_stock_form(request.POST)
        if form_entered.is_valid():
            temp = models.part_stock()
            temp.part_id = models.part_list.objects.get(pk=pk)
            temp.entry_date = form_entered.cleaned_data['entry_date']
            temp.supplier = form_entered.cleaned_data['supplier']
            temp.amount = form_entered.cleaned_data['amount']
            temp.save()
            return HttpResponseRedirect(reverse('parts:part_details',args=[pk]))
        else:
            print("invalid field")
            return render(request, 'part_details.html',
                      {'part_temp': temp, 'my_list': my_list, 'part_stock_form': form_entered})

    return render(request,'part_details.html', {'part_temp':temp_list,'my_list':my_list,'part_stock_form': forms.part_stock_form})

now I want o to edit the stock from the same page where do I put the function for this. can't I just call the function for it without redirecting it to other view and redirecting back to the same view. does javascript provide a function for adding/editing database?


问:
Python extend and pop on list if condition met
I want to filter the list moving all 0 to the end of the list leaving everything else in order.

So I have enumerated the list and on an item being equal to 0 I want to extend the list then remove the item from its index. How should I do this?

This is my code.

```<code>def move_zeros(array):
    for index, item in enumerate(array):
        if item == 0:
            array.extend(item, array.pop(index))
    return array
</code>```

答:
you can make two lists and append them

```<code>def move_zeros(array):
    l1 = [v for v in array if v != 0]
    l2 = [v for v in array if v == 0]
    return l1 + l2
</code>```

this way, you keep the order and also, by creating new lists, you dont modify the list in place, which is usually not a good idea

What should also work instead if creating l2 with a list comprehension, just generate a zero array of length equal to the number of 0s you get from taking the difference in length of the original array and l1

```<code>l2 = [0] * (len(array) - len(l1))
</code>```

Body:
I want to filter the list moving all 0 to the end of the list leaving everything else in order.

So I have enumerated the list and on an item being equal to 0 I want to extend the list then remove the item from its index. How should I do this?

This is my code.

def move_zeros(array):
    for index, item in enumerate(array):
        if item == 0:
            array.extend(item, array.pop(index))
    return array

Body:
you can make two lists and append them

def move_zeros(array):
    l1 = [v for v in array if v != 0]
    l2 = [v for v in array if v == 0]
    return l1 + l2

this way, you keep the order and also, by creating new lists, you dont modify the list in place, which is usually not a good idea

What should also work instead if creating l2 with a list comprehension, just generate a zero array of length equal to the number of 0s you get from taking the difference in length of the original array and l1

l2 = [0] * (len(array) - len(l1))


问:
String Interpolation In Codesmith Generator
Is there a way to use some of the newer c# features like string interpolation, ie:
var string = $"Hello {worldVar}"</p>

答: I work at CodeSmith Tools, the latest version (8.0) added support for .NET 4.7 and string interpolation. </p>


问:
jquery remove table row
I'm having a problem removing a table row, I can highlight the row red but when I try to remove it the slideup function messes up. I have wrapped them in a div but I don't no how to access the children of the tr and then the children of that?

```<code>$('#test tr:not(:first)').click(function()
        {
            $(this).css("background-color","red");

            $(this).children("td div").slideUp(function()
            {
                $(this).parent().remove();
            });
        });
</code>```

The problem is this line:

```<code>$(this).children("td div").slideUp(function()
</code>```

I also tried

```<code>$(this).children("td").children("div").slideUp(function()
</code>```

The slide up only removes the first column.

```<code><table border="1" width="600" cellspacing="0" cellpadding="0" id="test">
    <tr>
        <td><b>First Name</b></td>
        <td><b>Last Name</b></td>
        <td><b>Address</b></td>
        <td><b>Town</b></td>

    </tr>

    <tr>
        <td><div>First Name</td>
        <td>Last Name</td>
        <td>Address</td>
        <td>Town</div></td>

    </tr>

</table>
</code>```

Do I need to wrap the content of each  with a div tag?

Thanks

答:
Calling children("td div") will find all direct children that match the selector. (all children which are
s that happen to be inside of s)

Since all of the direct children are s, it won't match anything.

Calling children("td").children("div") will find all
s inside of all s.

It will thus find the only
 you have there.

EDIT: You can use jQuery to create wrapper elements; see my blog post:

```<code>$('#test tr:not(:first)').click(function() {
    $(this).css("background-color","red");

    $(this).children().wrapInner('<div>').children().slideUp(function() {
        $(this).closest('tr').remove();
    });
});
</code>```

Demo

Title: jquery remove table row

Body:
I'm having a problem removing a table row, I can highlight the row red but when I try to remove it the slideup function messes up. I have wrapped them in a div but I don't no how to access the children of the tr and then the children of that?

$('#test tr:not(:first)').click(function()
        {
            $(this).css("background-color","red");

            $(this).children("td div").slideUp(function()
            {
                $(this).parent().remove();
            });
        });

The problem is this line:

$(this).children("td div").slideUp(function()

I also tried

$(this).children("td").children("div").slideUp(function()

The slide up only removes the first column.

        First Name
        Last Name
        Address
        Town

First Name
        Last Name
        Address
        Town

Do I need to wrap the content of each  with a div tag?

Thanks

Body:
Calling children("td div") will find all direct children that match the selector. (all children which are <div>s that happen to be inside of <td>s)

Since all of the direct children are <td>s, it won't match anything.

Calling children("td").children("div") will find all <div>s inside of all <td>s.

It will thus find the only <div> you have there.

EDIT: You can use jQuery to create wrapper elements; see my blog post:

$('#test tr:not(:first)').click(function() {
    $(this).css("background-color","red");

    $(this).children().wrapInner('<div>').children().slideUp(function() {
        $(this).closest('tr').remove();
    });
});

Demo