问:
how create 2d array in javascript with row and cel [[2,4,6], [4,16,32],[8,64,128]];?
How do I create a 2d array in JavaScript with row and cel?

Example output [[2,4,6], [4,16,32],[8,64,128]];

var matrix = [],
    row = [],

for(var i = 0; i < 3; i++) {
  row = [];
  for(var j = 2; j <= 6; j++) {
    row.push(j++);

  }
  matrix.push(row);

}
console.log('matrix', matrix[0],matrix[1],matrix[2]);

for(var i = 0; i < 3; i++) {
  for(var j = 0; j < 3; j++) {
 console.log(matrix[i][j]);
  }
}```

答:
```<code>/*If you notice it nothing but Array of arrays simple.
Example take 3 arrays*/
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [8,9,0];`
//The combined array
var totalArr = [];
totalArr.push(arr1);
totalArr.push(arr2);
totalArr.push(arr3);`
/*Array.push() accepts the value that
needs to be inserted into the array in question here that is totalArr
Printing the array values*/
for(var i=0;i<totalArr.length;i++){
   for(var j=0;j<arr1.length;j++){
      console.log(totalArr[i][j]);
   }
}

/*on similar ground your code also works fine for me */
var matrix = [];
var row = [];

for(var i = 0; i < 3; i++) {
  row = [];
  for(var j = 2; j <= 6; j++) {
    row.push(j);
  }
  matrix.push(row);
}
console.log('matrix', matrix[0],matrix[1],matrix[2]);

for(var i = 0; i < 3; i++) {
  for(var j = 0; j < 3; j++) {
    console.log(matrix[i][j]);
  }
}
console.log(matrix[0][1]); // gives 3 as o/p as expected
hope this helps!!!
</code>```


来源: stackexchange

问:
pyFirmata's write() function
I'm working along the book "Python Programming for Arduino" written by Pratik Desai (annoyingly smart guy).

I got stuck in exercise where student is learning to implement a slider that changes intensity of LED that is connected to a pin. I marked where the code isn't working as it should.

Code is:

```<code>import tkinter
from pyfirmata import ArduinoMega
from time import sleep

port = '/dev/ttyACM0'
board = ArduinoMega(port)
sleep(5)
lenPin = board.get_pin('d:11:o')

top = tkinter.Tk()
top.title('Specify time using Entry')
top.minsize(300, 30)
timePeriodEntry = tkinter.Entry(top, bd=5, width=25)
brightnessScale = tkinter.Scale(top, from_=0, to=100,
orient=tkinter.HORIZONTAL)
brightnessScale.grid(column=2, row=2)
tkinter.Label(top, text='Time (seconds)').grid(column=1, row=1)
tkinter.Label(top, text='Brightness (%)').grid(column=1, row=2)

def onStartPress():
    time_period = timePeriodEntry.get()
    time_period = float(time_period)
    ledBrightness = brightnessScale.get()
    ledBrightness = float(ledBrightness)
    startButton.config(state=tkinter.DISABLED)
    lenPin.write(ledBrightness / 100.0) # this part of code ain't working
    sleep(time_period)
    lenPin.write(0)
    startButton.config(state=tkinter.ACTIVE)

timePeriodEntry.grid(column=2, row=1)
timePeriodEntry.focus_set()
startButton = tkinter.Button(top, text='Lit Up', command=onStartPress)
startButton.grid(column=1, row=3)
exitButton = tkinter.Button(top, text='Exit', command=top.quit)
exitButton.grid(column=2, row=3)

top.mainloop()
</code>```

According to the book this code should work. I did some basic checks such as printing out the variable ledBrightness to see if it gets the correct value and it is getting the correct value. Problem is when I run the program it isn't working. The LED won't come on at all. It works only when I replace the variable with 1 (True) which turns the LED on or 0 (False) which turns it back off, however without any option to adjust intensity.

What I'm doing wrong here? If the write() function can accept only 1 or 0 how come that this book says you can customize the input?

答:
From the documentation:

write(value)

Output a voltage from the pin

Parameters: value – Uses value as a boolean if the pin is in output mode, or expects a float from 0 to 1 if the pin is in PWM mode. If the pin is in SERVO the value should be in degrees.

get_pin(pin_def)

Returns the activated pin given by the pin definition. May raise an InvalidPinDefError or a PinAlreadyTakenError.

Parameters: pin_def – Pin definition as described below, but without the arduino name. So for example a:1:i.

‘a’ analog pin Pin number ‘i’ for input ‘d’ digital pin Pin number ‘o’ for output ‘p’ for pwm (Pulse-width modulation)

All seperated by :.

You need to define the pin as PWM not output.

```<code>lenPin = board.get_pin('d:11:p')
</code>```

Then lenPin.write(value) doesn't just accept 0 and 1, but any float number between 0 and 1.

ContentLicense: CC BY-SA 3.0

Title: pyFirmata's write() function

Body:
I'm working along the book "Python Programming for Arduino" written by Pratik Desai (annoyingly smart guy).

I got stuck in exercise where student is learning to implement a slider that changes intensity of LED that is connected to a pin. I marked where the code isn't working as it should.

Code is:

import tkinter
from pyfirmata import ArduinoMega
from time import sleep

port = '/dev/ttyACM0'
board = ArduinoMega(port)
sleep(5)
lenPin = board.get_pin('d:11:o')

top = tkinter.Tk()
top.title('Specify time using Entry')
top.minsize(300, 30)
timePeriodEntry = tkinter.Entry(top, bd=5, width=25)
brightnessScale = tkinter.Scale(top, from_=0, to=100,
orient=tkinter.HORIZONTAL)
brightnessScale.grid(column=2, row=2)
tkinter.Label(top, text='Time (seconds)').grid(column=1, row=1)
tkinter.Label(top, text='Brightness (%)').grid(column=1, row=2)

def onStartPress():
    time_period = timePeriodEntry.get()
    time_period = float(time_period)
    ledBrightness = brightnessScale.get()
    ledBrightness = float(ledBrightness)
    startButton.config(state=tkinter.DISABLED)
    lenPin.write(ledBrightness / 100.0) # this part of code ain't working
    sleep(time_period)
    lenPin.write(0)
    startButton.config(state=tkinter.ACTIVE)

timePeriodEntry.grid(column=2, row=1)
timePeriodEntry.focus_set()
startButton = tkinter.Button(top, text='Lit Up', command=onStartPress)
startButton.grid(column=1, row=3)
exitButton = tkinter.Button(top, text='Exit', command=top.quit)
exitButton.grid(column=2, row=3)

top.mainloop()

According to the book this code should work. I did some basic checks such as printing out the variable ledBrightness to see if it gets the correct value and it is getting the correct value. Problem is when I run the program it isn't working. The LED won't come on at all. It works only when I replace the variable with 1 (True) which turns the LED on or 0 (False) which turns it back off, however without any option to adjust intensity.

What I'm doing wrong here? If the write() function can accept only 1 or 0 how come that this book says you can customize the input?

Body:
From the documentation:

write(value)

Output a voltage from the pin

Parameters: value – Uses value as a boolean if the pin is in output mode, or expects a float from 0 to 1 if the pin is in PWM mode. If the pin is in SERVO the value should be in degrees.

get_pin(pin_def)

Returns the activated pin given by the pin definition. May raise an InvalidPinDefError or a PinAlreadyTakenError.

Parameters: pin_def – Pin definition as described below, but without the arduino name. So for example a:1:i.

‘a’ analog pin Pin number ‘i’ for input ‘d’ digital pin Pin number ‘o’ for output ‘p’ for pwm (Pulse-width modulation)

All seperated by :.

You need to define the pin as PWM not output.

lenPin = board.get_pin('d:11:p')

Then lenPin.write(value) doesn't just accept 0 and 1, but any float number between 0 and 1.


问:
C# ExecuteNonQuery Error (Connecting My.ASP Web Form to an Access DB)
I'm trying to connect my ASP.NET online registration form to  MS Access backend database. The connection code I'm using is

```<code>String connString;
connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\Comp\MyWebsite\WorkDatabase.mdb";
OleDbConnection myConnection = new  OleDbConnection(connString);
myConnection.Open();
string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();

try
{
    using (myConnection)
    {
        myConnection.Open();
        myCommand.ExecuteNonQuery();
        SuccReglbl.Text = "successful registration";
    }
}
catch (Exception ex)
{
    SuccReglbl.Text = "Exception in DBHandler" + ex;
}
finally
{

}

myCommand.ExecuteNonQuery();
OleDbDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{

}
myConnection.Close();
</code>```

I keep getting an error when I click on the "Register" button. The error is

"ExecuteNonQuery requires an open and available Connection. The connection's current state is closed."

I'm unsure how to fix this.

答:
You closed the database connection twice.
try to remove first myConnection.Close();</p>

Body:
I'm trying to connect my ASP.NET online registration form to  MS Access backend database. The connection code I'm using is

String connString;
connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\Comp\MyWebsite\WorkDatabase.mdb";
OleDbConnection myConnection = new  OleDbConnection(connString);
myConnection.Open();
string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();

try
{
    using (myConnection)
    {
        myConnection.Open();
        myCommand.ExecuteNonQuery();
        SuccReglbl.Text = "successful registration";
    }
}
catch (Exception ex)
{
    SuccReglbl.Text = "Exception in DBHandler" + ex;
}
finally
{

}

myCommand.ExecuteNonQuery();
OleDbDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{

}
myConnection.Close();

I keep getting an error when I click on the "Register" button. The error is

"ExecuteNonQuery requires an open and available Connection. The connection's current state is closed."

I'm unsure how to fix this.


问:
How to check if template argument is a callable with a given signature
Basically, what I want to achieve is compile-time verification (with possibly nice error message) that registered callable (either a function, a lambda, a struct with call operator) has correct signature. Example (contents of the static_assert are to be filled):

```<code>struct A {
  using Signature = void(int, double);

  template <typename Callable>
  void Register(Callable &&callable) {
    static_assert(/* ... */);
    callback = callable;
  }

  std::function<Signature> callback;
};
</code>```

答:
If you accept to transform A in a variadic template class, you can use decltype(), to activare Register only if callable is compatible, as follows

```<code>template <typename R, typename ... Args>
struct A
 {
   using Signature = R(Args...);

   template <typename Callable>
   auto Register (Callable && callable)
      -> decltype( callable(std::declval<Args>()...), void() )
    { callback = callable; }

   std::function<Signature> callback;
 };
</code>```

This way, if you prefer, calling Register() with a incompatible function, you can obtain a soft error and activate another Register() function

```<code>void Register (...)
 { /* do something else */ };
</code>```

Body:
Basically, what I want to achieve is compile-time verification (with possibly nice error message) that registered callable (either a function, a lambda, a struct with call operator) has correct signature. Example (contents of the static_assert are to be filled):

struct A {
  using Signature = void(int, double);

  template <typename Callable>
  void Register(Callable &&callable) {
    static_assert(/* ... */);
    callback = callable;
  }

  std::function<Signature> callback;
};

Body:
If you accept to transform A in a variadic template class, you can use decltype(), to activare Register only if callable is compatible, as follows

template <typename R, typename ... Args>
struct A
 {
   using Signature = R(Args...);

   template <typename Callable>
   auto Register (Callable && callable)
      -> decltype( callable(std::declval<Args>()...), void() )
    { callback = callable; }

   std::function<Signature> callback;
 };

This way, if you prefer, calling Register() with a incompatible function, you can obtain a soft error and activate another Register() function

void Register (...)
 { /* do something else */ };


问:
Assign random letter to each variable
How can I cycle through variables and assign a random letter to each?

Without having to do:

```<code>var1 = RandomLetter();
var2 = RandomLetter();
var3 = RandomLetter();
var4 = RandomLetter();
var5 = RandomLetter();
</code>```

This will produce all having the same letter:

```<code>var1 = var2 = var3 = RandomLetter();
</code>```

I'm looking for a way to shorten the process, I need to do this to 50+ variables.

At first I though a foreach loop, but they are null and don't start out in a collection to loop through.

```<code>// Variables
public static char var1, var2, var3, var4, var5;

// Generate Random Letter
public static Random random = new Random();
public static char RandomLetter()
{
    const string text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int index = random.Next(text.Length);
    return text[index];
}
</code>```

答:
You can create an array of (irrelevant) numbers, and then convert every (irrelevant) number into a random character.

```<code>var randomLetterList = Enumerable.Range(0, 50)
                            .Select(x => RandomLetter())
                            .ToArray();
</code>```

```<code>Enumerable.Range(0, 50)
</code>```

This returns a list of 50 numbers, starting at 0: [ 0 , 1 , 2 , ... , 49 ]

```<code>.Select(x => RandomLetter())
</code>```

This turns every element of the list into a random letter (notice that the actual value of the number is never used): e.g. [ 'b' , 'h' , 'm' , ... , 'o' ].

The important thing to note here is that the resulting list will contain exactly as many letters, as the initial list had numbers.

```<code>.ToArray();
</code>```

This just converts the IEnumerable<char> into a char[]. This allows you to access the letters by using their index.

Instead of using

var1

var2

var3

...

var50

you instead use:

randomLetterList[0]

randomLetterList[1]

randomLetterList[2]

...

randomLetterList[49]

Title: Assign random letter to each variable

Body:
How can I cycle through variables and assign a random letter to each?

Without having to do:

var1 = RandomLetter();
var2 = RandomLetter();
var3 = RandomLetter();
var4 = RandomLetter();
var5 = RandomLetter();

This will produce all having the same letter:

var1 = var2 = var3 = RandomLetter();

I'm looking for a way to shorten the process, I need to do this to 50+ variables.

At first I though a foreach loop, but they are null and don't start out in a collection to loop through.

// Variables
public static char var1, var2, var3, var4, var5;

// Generate Random Letter
public static Random random = new Random();
public static char RandomLetter()
{
    const string text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int index = random.Next(text.Length);
    return text[index];
}

Body:
You can create an array of (irrelevant) numbers, and then convert every (irrelevant) number into a random character.

var randomLetterList = Enumerable.Range(0, 50)
                            .Select(x => RandomLetter())
                            .ToArray();

Enumerable.Range(0, 50)

This returns a list of 50 numbers, starting at 0: [ 0 , 1 , 2 , ... , 49 ]

.Select(x => RandomLetter())

This turns every element of the list into a random letter (notice that the actual value of the number is never used): e.g. [ 'b' , 'h' , 'm' , ... , 'o' ].

The important thing to note here is that the resulting list will contain exactly as many letters, as the initial list had numbers.

.ToArray();

This just converts the IEnumerable<char> into a char[]. This allows you to access the letters by using their index.

Instead of using

var1

var2

var3

...

var50

you instead use:

randomLetterList[0]

randomLetterList[1]

randomLetterList[2]

...

randomLetterList[49]


问:
Hibernate miss existing field
I have such entity structure

```<code>@MappedSuperclass
public abstract class Base {
    UUID id;
}

@MappedSuperclass
public abstract class Parent<C extends Child> extends Base {
    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<C> children;
}

@MappedSuperclass
public abstract class Child<P extends Parent> extends Base {
    @JoinColumn(name = "parent_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private P parent;
}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "ap")
public class AP extends Parent<AC> {}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "ac")
public class AC extends Child<AP> {}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "bp")
public class BP extends Parent<BC> {}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "bc")
public class BC extends Child<BP> {}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "cp")
public class CP extends Parent<CC> {}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "cc")
public class CC extends Child<CP> {
     String value;
}
</code>```

I do criteria query

```<code>    CriteriaQuery<Long> cq = getEntityManager().getCriteriaBuilder().createQuery(Long.class);
    Root<CP> rt = cq.from(CP.class);
    Path child = rt.join("children");
    final CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    cq.select(criteriaBuilder.count(rt));
    cq.where(criteriaBuilder.equal(child.get("value"), "exists"));
    TypedQuery<Long> q = getEntityManager().createQuery(cq);
    Long res = q.getSingleResult()
</code>```

and get error on line with where clause:

```<code>java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [value] on this ManagedType [Base]
</code>```

After debugging a while I've found out that Parent meta class in entity manager's meta model keeps property children as List of AC. AC obviously doesn't contains field "value".

Any idea how to fix this error?

答:
I think there is no easy fix. Unless you are willing to move value to AC and make CC to extend AC<CP>. Or something alike.

This behavior is because of type erasure.

The actual generic type of children is not available at runtime because compiler casts list to generic type List<AC> based on the upper bound AC.

See also this great answer that explained this thing to me quite well.

After query it is possible to check and cast the list / items to actual type but not at all sure if it is possible within CriteriaQuery.

Title: Hibernate miss existing field

Body:
I have such entity structure

@MappedSuperclass
public abstract class Base {
    UUID id;
}

@MappedSuperclass
public abstract class Parent<C extends Child> extends Base {
    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<C> children;
}

@MappedSuperclass
public abstract class Child
 extends Base {
    @JoinColumn(name = "parent_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private P parent;
}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "ap")
public class AP extends Parent<AC> {}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "ac")
public class AC extends Child<AP> {}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "bp")
public class BP extends Parent<BC> {}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "bc")
public class BC extends Child<BP> {}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "cp")
public class CP extends Parent<CC> {}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "cc")
public class CC extends Child<CP> {
     String value;
}

I do criteria query

    CriteriaQuery<Long> cq = getEntityManager().getCriteriaBuilder().createQuery(Long.class);
    Root<CP> rt = cq.from(CP.class);
    Path child = rt.join("children");
    final CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    cq.select(criteriaBuilder.count(rt));
    cq.where(criteriaBuilder.equal(child.get("value"), "exists"));
    TypedQuery<Long> q = getEntityManager().createQuery(cq);
    Long res = q.getSingleResult()

and get error on line with where clause:

java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [value] on this ManagedType [Base]

After debugging a while I've found out that Parent meta class in entity manager's meta model keeps property children as List of AC. AC obviously doesn't contains field "value".

Any idea how to fix this error?


问:
Entity Framework Many to many data not persisting
I have strange problem with entity framework. I'm trying to update my entity User which has many-to-many relation with Team. When I try to add some team (which exists in database) to the user nothing changes in the database. However when I remove all teams from the user it is persiting to database and the user is free of any team. Why adding is not persisting? Any ideas?

```<code>  public int Save(User entity)
    {
        using (var context = new UsersContext())
        {
                var teamIds = entity.Teams.Select(t => t.Id).ToArray();
                context.Entry(entity).State = EntityState.Modified;
                context.Entry(entity).Collection(u => u.Teams).Load();
                entity.Teams.Clear();
                foreach (var teamId in teamIds)
                {
                    entity.Teams.Add(context.Teams.Find(teamId));
                }

            return context.SaveChanges();
        }
    }
</code>```

答:
The problem is, the moment you call context.Entry(entity).State = EntityState.Modified;, the referenced Team entries will be set to State = EntityState.Unchanged, the collection will not be recognized as modified, EF will ignore the attempt to get the actual database values via context.Entry(entity).Collection(u => u.Teams).Load(); and it will also not recognize the changes with clear and re-add, because context.Teams.Find(teamId) will return the local entries that where already marked unchanged and the collection at the end will contain the same data as it did initially.

Possible Solution: clear collection before setting State Modified, then load the collection from database and clear again before re-adding your items:

```<code>using (var context = new DbC())
{
    var teamIds = entity.Teams.Select(t => t.Id).ToArray();
    entity.Teams.Clear();
    context.Entry(entity).State = EntityState.Modified;
    context.Entry(entity).Collection(u => u.Teams).Load();
    entity.Teams.Clear();
    foreach (var teamId in teamIds)
    {
        entity.Teams.Add(context.Teams.Find(teamId));
    }
    return context.SaveChanges();
}
</code>```

See here for a somewhat similar topic: Updating a reference to a child object in Entity framework 4.1 (CodeFirst) even though it is about a single reference rather than a collection, the basic problem is the same.

A quote from documentation regarding the Collection(..).Load():

Loads the collection of entities from the database.  Note that entities that
  already exist in the context are not overwritten with values from the database.

This is part of why loading is not effective to get the actual database state, when the collection is initially filled.

Body:
I have strange problem with entity framework. I'm trying to update my entity User which has many-to-many relation with Team. When I try to add some team (which exists in database) to the user nothing changes in the database. However when I remove all teams from the user it is persiting to database and the user is free of any team. Why adding is not persisting? Any ideas?

  public int Save(User entity)
    {
        using (var context = new UsersContext())
        {
                var teamIds = entity.Teams.Select(t => t.Id).ToArray();
                context.Entry(entity).State = EntityState.Modified;
                context.Entry(entity).Collection(u => u.Teams).Load();
                entity.Teams.Clear();
                foreach (var teamId in teamIds)
                {
                    entity.Teams.Add(context.Teams.Find(teamId));
                }

            return context.SaveChanges();
        }
    }

Body:
The problem is, the moment you call context.Entry(entity).State = EntityState.Modified;, the referenced Team entries will be set to State = EntityState.Unchanged, the collection will not be recognized as modified, EF will ignore the attempt to get the actual database values via context.Entry(entity).Collection(u => u.Teams).Load(); and it will also not recognize the changes with clear and re-add, because context.Teams.Find(teamId) will return the local entries that where already marked unchanged and the collection at the end will contain the same data as it did initially.

Possible Solution: clear collection before setting State Modified, then load the collection from database and clear again before re-adding your items:

using (var context = new DbC())
{
    var teamIds = entity.Teams.Select(t => t.Id).ToArray();
    entity.Teams.Clear();
    context.Entry(entity).State = EntityState.Modified;
    context.Entry(entity).Collection(u => u.Teams).Load();
    entity.Teams.Clear();
    foreach (var teamId in teamIds)
    {
        entity.Teams.Add(context.Teams.Find(teamId));
    }
    return context.SaveChanges();
}

See here for a somewhat similar topic: Updating a reference to a child object in Entity framework 4.1 (CodeFirst) even though it is about a single reference rather than a collection, the basic problem is the same.

A quote from documentation regarding the Collection(..).Load():

Loads the collection of entities from the database.  Note that entities that
  already exist in the context are not overwritten with values from the database.

This is part of why loading is not effective to get the actual database state, when the collection is initially filled.


问:
what is the main differences between web service and wcf?
i know that web service can be host only in IIS but wcf can be host in IIS and both in win service too. but where is the actual main power lies in wcf for which developer choose wcf rather web service. please explain in detail. thanks</p>

答: Basically WCF is a lot more poweful way of building distributed apps. As opposed to the asmx which was really only SOAP over http, WCF provides with many other communication providers (such as TCP/IP). WCF lets you configure its behaviours via configuration (how to process data - async vs sync, only one instance of the wcf service for any client request and etc). So wcf, in the nutshell is the successession of the remoting classes of .net 2.0 plus the asmx together. With that being said, you can host your WCF outside the IIS in your own process - Win Service, Win Form or whatever exe. You just need to implement the service host. </p>

ContentLicense: CC BY-SA 2.5


问:
Difference between Server-side and Backend
What is the difference between Server-side and Backend?

I am new to all of this coding and I want to create a website. I'm going to use Node.js for the backend, but what is server-side? Can someone explain in simple words to me how this works? Also, what is a backend anyway?

答:
Backend defines a component in a logical separation of an application.
This component is running server-side. The backend is responsible for handling data, authentication, database access etc.

The Frontend is another component which is running client-side. Its what the user sees and interacts with. It sends data to the backend where it is stored in databases.


问:
How to prevent users from going back to the previous page?
I am using ASP.NET MVC (latest version).

Imagine having 2 pages:

Page-1: "Enter data" >> Page-2: "Thank you"

After submitting Page-1 you are being redirected to Page-2.

My goal: I want to make sure that you can't go back to Page-1 when you hit the browser's back button once you made it to Page-2. Instead I want you rather to stay on Page-2 (or being pushed forward to Page-2 every time you hit the back button).

I have tried all different kind of things. The following is just some simplified pseudo code ...

```<code>[NoBrowserCache]
public ActionResult Page1(int userId)
{
   var user = GetUserFromDb(userId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
      // forward to page 2
      return RedirectToAction("Page2", routeValues: new { userId = userId });
   }

   var model = new Page1Model();

   return View("Page1", model);
}

[NoBrowserCache]
[HttpPost]
public ActionResult Page1(Page1Model model)
{
   var user = GetUserFromDb(model.UserId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
       // forward to page 2
       return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
   }

   // Save posted data to the db
   // ...

   return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
}

public class NoBrowserCache : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Haha ... tried everything I found on the web here:
        // Make sure the requested page is not put in the browser cache.
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-cache");
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);
        filterContext.HttpContext.Response.Expires = 0;
    }
}
</code>```

If only I could make sure that a request is being sent to the server every time I hit the back button. But right now, clicking the back button just pulls Page-1 from my browser's cache without sending a request to the server. So currently, I have no chance to redirect you forward to Page-2 by server means.

Any ideas or suggestions?

Thanks, guys!

Btw: There is no login/authentication involved. So, I can't use Session.Abandon() or stuff like this. And I would rather use some server based code than javascript if possible.

EDIT 2017-5-12
Following @grek40, I made sure that the anti-chaching statements end up in the browser. I therefor completely removed the [NoBrowserCache]-ActionFilterAttribute from my C# code above. Instead I added the following statements in the  section of my _Layout.cshtml:

```<code><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
</code>```

I confirm that these three lines are being rendered to my browser (used my browser's developer tools to inspect). However, caching still works. I can still move backward without any server requests. Tested this with Google Chrome v62, Firefox Quantum v57 and Microsoft Edge v41 (all on Win10). #

EDIT 2017-6-12
Again following @grek40's suggestions: tried Expires: 0 as well as Expires: -1. No difference. I still didn't manage, to turn off my browser's cache.

答:
Finally I found a solution. It's javascript based, but very simple.

I just had to add the following snippet to my Page-2 (the page I don't want users to leave anymore once they got there):

```<code><script type="text/javascript">

$(document).ready(function () {
    history.pushState({ page: 1 }, "title 1", "#nbb");
    window.onhashchange = function (event) {
        window.location.hash = "nbb";
    };
});
</code>```

I found this here: how to stop browser back button using javascript

Thanks to all your support guys. But "my own" solution was the only one that worked.

Body:
I am using ASP.NET MVC (latest version).

Imagine having 2 pages:

Page-1: "Enter data" >> Page-2: "Thank you"

After submitting Page-1 you are being redirected to Page-2.

My goal: I want to make sure that you can't go back to Page-1 when you hit the browser's back button once you made it to Page-2. Instead I want you rather to stay on Page-2 (or being pushed forward to Page-2 every time you hit the back button).

I have tried all different kind of things. The following is just some simplified pseudo code ...

[NoBrowserCache]
public ActionResult Page1(int userId)
{
   var user = GetUserFromDb(userId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
      // forward to page 2
      return RedirectToAction("Page2", routeValues: new { userId = userId });
   }

   var model = new Page1Model();

   return View("Page1", model);
}

[NoBrowserCache]
[HttpPost]
public ActionResult Page1(Page1Model model)
{
   var user = GetUserFromDb(model.UserId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
       // forward to page 2
       return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
   }

   // Save posted data to the db
   // ...

   return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
}

public class NoBrowserCache : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Haha ... tried everything I found on the web here:
        // Make sure the requested page is not put in the browser cache.
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-cache");
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);
        filterContext.HttpContext.Response.Expires = 0;
    }
}

If only I could make sure that a request is being sent to the server every time I hit the back button. But right now, clicking the back button just pulls Page-1 from my browser's cache without sending a request to the server. So currently, I have no chance to redirect you forward to Page-2 by server means.

Any ideas or suggestions?

Thanks, guys!

Btw: There is no login/authentication involved. So, I can't use Session.Abandon() or stuff like this. And I would rather use some server based code than javascript if possible.

EDIT 2017-5-12
Following @grek40, I made sure that the anti-chaching statements end up in the browser. I therefor completely removed the [NoBrowserCache]-ActionFilterAttribute from my C# code above. Instead I added the following statements in the  section of my _Layout.cshtml:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

I confirm that these three lines are being rendered to my browser (used my browser's developer tools to inspect). However, caching still works. I can still move backward without any server requests. Tested this with Google Chrome v62, Firefox Quantum v57 and Microsoft Edge v41 (all on Win10). #

EDIT 2017-6-12
Again following @grek40's suggestions: tried Expires: 0 as well as Expires: -1. No difference. I still didn't manage, to turn off my browser's cache.

Body:
Finally I found a solution. It's javascript based, but very simple.

I just had to add the following snippet to my Page-2 (the page I don't want users to leave anymore once they got there):

<script type="text/javascript">

$(document).ready(function () {
    history.pushState({ page: 1 }, "title 1", "#nbb");
    window.onhashchange = function (event) {
        window.location.hash = "nbb";
    };
});

I found this here: how to stop browser back button using javascript

Thanks to all your support guys. But "my own" solution was the only one that worked.


问:
Runtime.exec() issues with java when attempting to execute scripts, but certain commands work
I am attempting to have my java program execute a python script using

```<code>import java.lang.Runtime;
public class test
{
  public static void main(String[] args)
  {
  try
  {
    System.out.println("testing");
    Runtime.getRuntime().exec("/usr/bin/python print.py");
  }catch(Exception e){System.out.println("not working");}

  }
}
</code>```

However, nothing is shown on the terminal, (print.py simple prints "THIS IS WORKING"). In contrast to this, when I use

```<code>Runtime.getRuntime().exec("touch dog.txt");
</code>```

A file named dog.txt is created.

I also attempted to run

```<code>Runtime.getRuntime()exec("./shellscript.sh");
</code>```

Which is just a script that runs the touch command, that also did not work.

Not really sure what the issue is here, and even more interesting is that yesterday the java program was working as intended with no large changes to my computer in the time in between. Anybody have any ideas on whats going on?

I am not receiving any errors.

答:
Ok I ended up having success by using

```<code>process p = Runtime.getRuntime().exec("./pyshellthing.sh");
p.waitFor();
</code>```

The shell script simply executes the python script.

Body:
I am attempting to have my java program execute a python script using

import java.lang.Runtime;
public class test
{
  public static void main(String[] args)
  {
  try
  {
    System.out.println("testing");
    Runtime.getRuntime().exec("/usr/bin/python print.py");
  }catch(Exception e){System.out.println("not working");}

  }
}

However, nothing is shown on the terminal, (print.py simple prints "THIS IS WORKING"). In contrast to this, when I use

Runtime.getRuntime().exec("touch dog.txt");

A file named dog.txt is created.

I also attempted to run

Runtime.getRuntime()exec("./shellscript.sh");

Which is just a script that runs the touch command, that also did not work.

Not really sure what the issue is here, and even more interesting is that yesterday the java program was working as intended with no large changes to my computer in the time in between. Anybody have any ideas on whats going on?

I am not receiving any errors.

Body:
Ok I ended up having success by using

process p = Runtime.getRuntime().exec("./pyshellthing.sh");
p.waitFor();

The shell script simply executes the python script.


问:
Display data json to table in react
I'm going to build a web with react js. I'm very new to react so I have a problem to make CRUD. For the first I want to display some data json to table. I have file .js that named keranjang.js. it contains jsx to display the table. and I have another named barang.js and want to fill it with the method named tampildata() used to hold json data for example {"nama_barang" : "bolu", "harga" : "10000"}. How I write the method? and how do I call the method and data to display that data into the existing table in keranjang.js? Hope everyone helps me.

答:
I am assuming that you trying to call external file's method in current component. In your barang.js file export your function that holds json data like

```<code>export function tampildata() {
    return [{ "firstname": "first", "lastname": "f"}, {"firstname": "second", "lastname": "l"}];
}
</code>```

or

```<code>export default {
  tampildata() {
    return [{ "firstname": "first", "lastname": "f"}, {"firstname": "second", "lastname": "l"}];
  }
};
</code>```

Then in your keranjang.js file import your tampildata method and call that method in componentDidMount and set state like below

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { tampildata } from 'barang';

class TableComponent extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            json: []
        }
    }

    componentDidMount() {
        this.setState((prevState) => {
            return {
                json: tampildata()
            }
        })
    }

    render() {
        return (
            <div>
                <table>
                    <thead>
                        <th>First Name</th>
                        <th>Last Name</th>
                    </thead>
                    <tbody>
                        {this.state.json.map((data, i) => {
                            return (
                                <tr key={i}>
                                    <td>{data.firstname}</td>
                                    <td>{data.lastname}</td>
                                </tr>
                            )
                        })}
                    </tbody>
                </table>
            </div>
        )
    }
}

ReactDOM.render(
  <TableComponent />,
  document.getElementById("app")
);
</code>```

Here is the working jsfiddle. Hope this will helps you!

Title: Display data json to table in react

Body:
I am assuming that you trying to call external file's method in current component. In your barang.js file export your function that holds json data like

export function tampildata() {
    return [{ "firstname": "first", "lastname": "f"}, {"firstname": "second", "lastname": "l"}];
}

or

export default {
  tampildata() {
    return [{ "firstname": "first", "lastname": "f"}, {"firstname": "second", "lastname": "l"}];
  }
};

Then in your keranjang.js file import your tampildata method and call that method in componentDidMount and set state like below

import React from 'react';
import ReactDOM from 'react-dom';
import { tampildata } from 'barang';

class TableComponent extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            json: []
        }
    }

    componentDidMount() {
        this.setState((prevState) => {
            return {
                json: tampildata()
            }
        })
    }

    render() {
        return (
            <div>
                <table>
                    <thead>
                        <th>First Name</th>
                        <th>Last Name</th>
                    </thead>
                    <tbody>
                        {this.state.json.map((data, i) => {
                            return (
                                <tr key={i}>
                                    <td>{data.firstname}</td>
                                    <td>{data.lastname}</td>
                                </tr>
                            )
                        })}
                    </tbody>
                </table>
            </div>
        )
    }
}

ReactDOM.render(
  <TableComponent />,
  document.getElementById("app")
);

Here is the working jsfiddle. Hope this will helps you!


问:
Port Forwarding for compute engine google cloud platform
I'm trying to open port TCP 28016 and UDP 28015 for a game server in my compute engine VM running on Microsoft Windows Server 2016.

I've tried opening the opening inside my server using RDP, going to Windows Firewall setting and creating new inbound rules for both TCP 28016 and UDP 28015.
Also done setting firewall rules on my Cloud Platform Firewall Rules for both port.

When running my game server application, running netstat didn't show any of the port being used / not listening . Not even shows up. What did i do wrong ?

Edit : it now shows up on netstat -a -b , but didn't have LISTENING

答: If it doesn't show as LISTENING, it's not a firewall or "port forwarding" issue; rather, the application either isn't running, or is running but isn't configured to listen for connections on that port.


问:
Multiple object request using Volley Android
I want to call API Using Volley. There is an Multiple object Request So i don't Know Proper way. I was tried to code as below.But it does not give me Response.So can Anyone help me???

MainActivity

```<code>public void  getJsonResponsePost(){

    JSONObject jsonData = new JSONObject();
    JSONObject json = new JSONObject();

    /*{"data":{"lang_type":"1","keyword":"","latitude":23.022499999999997,"longitude":72.57139833333333,"category":6}}*/
    try {
        jsonData.put("data",json);
        json.put("lang_type","1");
        json.put("keyword","");
        json.put("latitude",23.022499999999997);
        json.put("longitude",72.57139833333333);
        json.put("category",6);
        Log.d("TAG",jsonData.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response)
                {
                    Log.d("String Response :",response.toString());
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(" Error getting  :",error.toString());
        }
    });

    jsonObjectRequest.setTag(REQ_TAG);
    requestQueue.add(jsonObjectRequest);
}
</code>```

I get the following response

```<code>String Response :: {"status":"0","message":"Please pass the language type."}
</code>```

答:
Can you try this?</p>

```<code>    try {
    json.put("lang_type","1");
    json.put("keyword","");
    json.put("latitude",23.022499999999997);
    json.put("longitude",72.57139833333333);
    json.put("category",6);
    jsonData.put("data",json);
    Log.d("TAG",jsonData.toString());
} catch (JSONException e) {
    e.printStackTrace();
}

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonData, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response)
            {
                Log.d("String Response :",response.toString());
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.d(" Error getting  :",error.toString());
    }
});
</code>```

Body:
I want to call API Using Volley. There is an Multiple object Request So i don't Know Proper way. I was tried to code as below.But it does not give me Response.So can Anyone help me???

MainActivity

public void  getJsonResponsePost(){

    JSONObject jsonData = new JSONObject();
    JSONObject json = new JSONObject();

    /*{"data":{"lang_type":"1","keyword":"","latitude":23.022499999999997,"longitude":72.57139833333333,"category":6}}*/
    try {
        jsonData.put("data",json);
        json.put("lang_type","1");
        json.put("keyword","");
        json.put("latitude",23.022499999999997);
        json.put("longitude",72.57139833333333);
        json.put("category",6);
        Log.d("TAG",jsonData.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response)
                {
                    Log.d("String Response :",response.toString());
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(" Error getting  :",error.toString());
        }
    });

    jsonObjectRequest.setTag(REQ_TAG);
    requestQueue.add(jsonObjectRequest);
}

I get the following response

String Response :: {"status":"0","message":"Please pass the language type."}

Body:
Can you try this?

    try {
    json.put("lang_type","1");
    json.put("keyword","");
    json.put("latitude",23.022499999999997);
    json.put("longitude",72.57139833333333);
    json.put("category",6);
    jsonData.put("data",json);
    Log.d("TAG",jsonData.toString());
} catch (JSONException e) {
    e.printStackTrace();
}

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonData, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response)
            {
                Log.d("String Response :",response.toString());
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.d(" Error getting  :",error.toString());
    }
});


问:
Execute a XQuery with PHP
How to execute a XQuery in PHP? Can you give me an example?

Thank you.

答:
There is this page at http://phpxmlclasses.sourceforge.net/ that has an XQuery Lite class:

http://phpxmlclasses.sourceforge.net/show_doc.php?class=class_xquery_lite.html

A PHP implementation of the Xquery Lite 1.0 language, a language to query XML documents based on Xquery 1.0 This class is based on the DOM extension and allows to execute Xquery Lite queries for XML documents in files, php strings or combinations.

I have never used it and do not know how it performs.

Title: Execute a XQuery with PHP


问:
Determining If a File Exists in Laravel 5
Goal : If the file exist, load the file, else load the default.png.

I've tried

```<code>  @if(file_exists(public_path().'/images/photos/account/{{Auth::user()->account_id}}.png'))
    <img src="/images/photos/account/{{Auth::user()->account_id}}.png" alt="">
  @else
    <img src="/images/photos/account/default.png" alt="">
  @endif
</code>```

Result

It kept load my default image while I'm 100% sure that 1002.png is exist.

How do I properly check if that file is exist ?

答:
In Laravel 5.5, you can use the exists method on the storage facade:

https://laravel.com/docs/5.5/filesystem

```<code>$exists = Storage::disk('s3')->exists('file.jpg');
</code>```

You could use a ternary expression:

```<code>$file = ($exists) ? Storage::disk('s3')->get('file.jpg') :
         Storage::disk('s3')->get('default.jpg');
</code>```

Body:
Goal : If the file exist, load the file, else load the default.png.

I've tried

  @if(file_exists(public_path().'/images/photos/account/{{Auth::user()->account_id}}.png'))
    account_id}}.png" alt="">
  @else

  @endif

Result

It kept load my default image while I'm 100% sure that 1002.png is exist.

How do I properly check if that file is exist ?

Body:
In Laravel 5.5, you can use the exists method on the storage facade:

https://laravel.com/docs/5.5/filesystem

$exists = Storage::disk('s3')->exists('file.jpg');

You could use a ternary expression:

$file = ($exists) ? Storage::disk('s3')->get('file.jpg') :
         Storage::disk('s3')->get('default.jpg');


问:
Regular Expressions in java trying to match a string in specific format (format consists of | sysbol)
Regular Expressions in java

```<code>String s1="Anil-anilorg|anotherorg";
String s2="Anil-anilorg|";
</code>```

I want to find weather s2 is present or sub-string of s1 by using regular expressions, but while I am doing that it is considering this symbol  "|" as logical OR
I am using hbaseStringRegexComparator to compare

答:
You can use String.contains method. No regex needed:</p>

```<code>    String s1="Anil-anilorg|anotherorg";
    String s2="Anil-anilorg|";
    System.out.println(s1.contains(s2));
</code>```

Body:
Regular Expressions in java

String s1="Anil-anilorg|anotherorg";
String s2="Anil-anilorg|";

I want to find weather s2 is present or sub-string of s1 by using regular expressions, but while I am doing that it is considering this symbol  "|" as logical OR
I am using hbaseStringRegexComparator to compare

Body:
You can use String.contains method. No regex needed:

    String s1="Anil-anilorg|anotherorg";
    String s2="Anil-anilorg|";
    System.out.println(s1.contains(s2));


问:
Make Session last longer
In my web.config I have this:

```<code><sessionState timeout="70"/>
</code>```

However, after 5 minutes my session is null and my program crashes. How to make this time longer?

Here is how I initialize it:

```<code>Session["mySession"] = "blah blah";
</code>```

答:
the time that you putting inside the Web.Config

<sessionState timeout="60"/> (it in minutes)

affect on the

```<code>HttpContext.Current.Session.Timeout = 60
</code>```

or

```<code> System.Web.HttpContext.Current.Session.Timeout = 60
</code>```

Title: Make Session last longer

Body:
In my web.config I have this:

<sessionState timeout="70"/>

However, after 5 minutes my session is null and my program crashes. How to make this time longer?

Here is how I initialize it:

Session["mySession"] = "blah blah";

Body:
the time that you putting inside the Web.Config

<sessionState timeout="60"/> (it in minutes)

affect on the

HttpContext.Current.Session.Timeout = 60

or

 System.Web.HttpContext.Current.Session.Timeout = 60


问:
Spring REST docs: How to migrate Rule to JUnit 5
I migrated my Spring tests to JUnit 5, and they work fine. However, I don't know how to migrate @Rule public JUnitRestDocumentation restDocumentation = ....
Any hint is appreciated.

答:
Spring RestDocs 2 introduces a new class : RestDocumentationExtension for JUnit 5. You can use it instead of Rule

@ExtendWith(RestDocumentationExtension.class)
public class JUnit5ExampleTests {

A complete example is available on https://github.com/spring-projects/spring-restdocs/blob/v2.0.0.RELEASE/samples/junit5/src/test/java/com/example/junit5/SampleJUnit5ApplicationTests.java

The extension is documented on https://github.com/spring-projects/spring-restdocs/blob/master/docs/src/docs/asciidoc/getting-started.adoc#setting-up-your-junit-5-tests

Spring RestDocs 2 requires Spring 5 and JDK 8


问:
iOS - NSInternalInconsistencyException happens on iOS 9 and 10 but working fine on iOS 11
This is the error I am getting on devices with iOS 9 and 10 :

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'request for number of
  items before section 9223372036854775807 when there are only 1
  sections in the collection view'

The error seems clear to me, however I am unable to understand why this is not happening on devices with iOS 11.

I don't know how to fix it.

Here is my code :

```<code>extension MainTileViewController: MainForecastsDelegate {
func mainForecasts(_ forecastVC: MainForecastsViewController!, didChangeWith object: Any!) {
    if let cell = self.outletWeatherForecastCollectionView.cellForItem(at: self.currentIndexPath) as? MainTileCollectionViewCell {
        // Some stuff...
    }
}
</code>```

The crash happens here. This is a protocol method triggered when the user switch day etc...

Obviously I have an issue with my currentIndexPath.

Here is my initialization :

```<code> var currentIndexPath : IndexPath = []
</code>```

And in the viewDidLoad :

```<code>self.currentIndexPath = IndexPath(item: 0, section: 0)
</code>```

How can I secure my code so that it won't crash ? Can you explain me the changing behavior between collectionView from iOS 9/10 with iOS 11 ones (except prefetching).

答:
What's happening is that setting currentIndexPath = [] is not assigning any value to its item or section; it's creating an "empty" IndexPath (IndexPath objects are basically arbitrary-length tuples or arrays of values and can be created/manipulated as such). Any code attempting to use it in that way (such as passing it to a cellForItem call) will have potentially undefined behavior. Looks like something is effectively interpreting the missing section value as -1, and then something else is interpreting that -1 as an unsigned 64-bit integer.

Instead, if you want to use the same general logic that you have now, I'd suggest declaring indexPath as an optional:

```<code>var currentIndexPath: IndexPath?
</code>```

Then, use if-let syntax in your usages of currentIndexPath:

```<code>extension MainTileViewController: MainForecastsDelegate {
func mainForecasts(_ forecastVC: MainForecastsViewController!, didChangeWith object: Any!) {
    if let currentIndexPath = currentIndexPath,
        let cell = outletWeatherForecastCollectionView.cellForItem(at: currentIndexPath) as? MainTileCollectionViewCell {
        // Some stuff...
    }
}
</code>```

This follows Swift idioms and makes clear the concept that you start with an "unknown" index path.

But - as @picciano's answer suggests, you may want to rethink your overall design to better fit the larger design patterns of iOS apps.

Body:
This is the error I am getting on devices with iOS 9 and 10 :

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'request for number of
  items before section 9223372036854775807 when there are only 1
  sections in the collection view'

The error seems clear to me, however I am unable to understand why this is not happening on devices with iOS 11.

I don't know how to fix it.

Here is my code :

extension MainTileViewController: MainForecastsDelegate {
func mainForecasts(_ forecastVC: MainForecastsViewController!, didChangeWith object: Any!) {
    if let cell = self.outletWeatherForecastCollectionView.cellForItem(at: self.currentIndexPath) as? MainTileCollectionViewCell {
        // Some stuff...
    }
}

The crash happens here. This is a protocol method triggered when the user switch day etc...

Obviously I have an issue with my currentIndexPath.

Here is my initialization :

 var currentIndexPath : IndexPath = []

And in the viewDidLoad :

self.currentIndexPath = IndexPath(item: 0, section: 0)

How can I secure my code so that it won't crash ? Can you explain me the changing behavior between collectionView from iOS 9/10 with iOS 11 ones (except prefetching).

Body:
What's happening is that setting currentIndexPath = [] is not assigning any value to its item or section; it's creating an "empty" IndexPath (IndexPath objects are basically arbitrary-length tuples or arrays of values and can be created/manipulated as such). Any code attempting to use it in that way (such as passing it to a cellForItem call) will have potentially undefined behavior. Looks like something is effectively interpreting the missing section value as -1, and then something else is interpreting that -1 as an unsigned 64-bit integer.

Instead, if you want to use the same general logic that you have now, I'd suggest declaring indexPath as an optional:

var currentIndexPath: IndexPath?

Then, use if-let syntax in your usages of currentIndexPath:

extension MainTileViewController: MainForecastsDelegate {
func mainForecasts(_ forecastVC: MainForecastsViewController!, didChangeWith object: Any!) {
    if let currentIndexPath = currentIndexPath,
        let cell = outletWeatherForecastCollectionView.cellForItem(at: currentIndexPath) as? MainTileCollectionViewCell {
        // Some stuff...
    }
}

This follows Swift idioms and makes clear the concept that you start with an "unknown" index path.

But - as @picciano's answer suggests, you may want to rethink your overall design to better fit the larger design patterns of iOS apps.


问:
LiveFiltering on ListCollectionView doesn't reevaluate the Filter when a property of an item in the list changes
I have a class Person, which implements INotifyPropertyChanged for the property Name:

```<code>public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string property)
    {
        Console.WriteLine("PropertyChanged: " + Name + ": " + property);
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }

    private string _name;
    public string Name
    {
        get => _name;
        set
        {
            if (_name == value)
                return;
            _name = value;
            OnPropertyChanged("Name");
        }
    }
}
</code>```

I am using a ListCollectionView with LiveFiltering to display a ObservableCollection, filtered to Match only a person whose name starts with "A":

```<code>var coll = new ObservableCollection<Person>();
ListCollectionView view = new ListCollectionView(coll)
{
    Filter = p => ((Person)p).Name[0]=='A',
    IsLiveFiltering = true,
    LiveFilteringProperties = { nameof(Person.Name) }
};
</code>```

When items are added to the collection, they are filtered correctly.

Here is the Problem: When the Name of a Person is changed, the Filter isn't reevaluated, which is what I thought the IsLiveFiltering and LiveFilteringProperties are for in the first place.
So, if i have change a Name from "Anna" to "Elsa" I would expect the view to update and not contain the item anymore. Likewise, changing "Eric" to "Arnold" should update the view so that the changed item is container in the view.

```<code>var p1 = new Person { Name = "Anna" };
var p2 = new Person { Name = "Eric" };

coll.Add(p1); // view is updated automatically and contains Anna now
coll.Add(p2); // view is updated, but Eric is filtered out

view.Dump(); // shows only "Anna" (LINQPad - Dump)

p1.Name = "Elsa"; // change Anna to Elsa -> the instance p1 should be removed from view (not from collection)
p2.Name = "Arnold"; // change Eric to Arnold -> the instance p2 should now be in the view

//view.Refresh(); // uncommenting this line leads to the behaviour I actually expected from LiveFiltering to be handled automatically.

view.Dump(); // shows "Elsa", but we are filtering for A*
</code>```

Did I miss enabling something to get this behaviour? I do not really want to attach to PropertyChanged of each instance of Person manually - I still expect that this is what LiveFiltering does for me.

Edit:
I have experienced the problem in my application with a bigger model and extracted the relevant parts to reproduce the problem in LinqPad. Here is the complete LinqPad-script. It will also require the using clauses:

```<code>using System.Collections.ObjectModel;
using System.Windows.Data;
using System.ComponentModel;
</code>```

Here's the script

```<code>void Main()
{
    var coll = new ObservableCollection<Person>();
    ListCollectionView view = new ListCollectionView(coll)
    {
        IsLiveFiltering = true,
        LiveFilteringProperties = { nameof(Person.Name) },
        Filter = p => ((Person)p).Name[0] == 'A'
    };

    var p1 = new Person { Name = "Anna" };
    var p2 = new Person { Name = "Eric" };

    coll.Add(p1);
    coll.Add(p2);

    view.Dump();

    p1.Name = "Elsa";
    p2.Name = "Arnold";

    //view.Refresh();

    view.Dump();
    Debug.Assert(view.Cast<Person>().Single().Name == "Arnold", "Wrong item in view, expected Arnold");
}

public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string property)
    {
        Console.WriteLine("PropertyChanged: " + Name + ": " + property);
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }

    private string _name;
    public string Name
    {
        get => _name;
        set
        {
            if (_name == value)
                return;
            _name = value;
            OnPropertyChanged("Name");
        }
    }
}
</code>```

答:
Where is your view and sample data...?

The following code certainly works as expected.

XAML:

```<code><ListBox x:Name="lb" DisplayMemberPath="Name" />
<Button Content="Filter" Click="Button_Click" />
</code>```

Sample code:

```<code>public partial class MainWindow : Window
{
    Person _p = new Person() { Name = "Anna" };

    public MainWindow()
    {
        InitializeComponent();

        var coll = new ObservableCollection<Person>() { _p };
        ListCollectionView view = new ListCollectionView(coll)
        {
            Filter = p => ((Person)p).Name[0] == 'A',
            IsLiveFiltering = true,
            LiveFilteringProperties = { nameof(Person.Name) }
        };

        lb.ItemsSource = view;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        _p.Name = "Elsa";
    }
}
</code>```

You should probably read this before you post another question.

Body:
I have a class Person, which implements INotifyPropertyChanged for the property Name:

public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string property)
    {
        Console.WriteLine("PropertyChanged: " + Name + ": " + property);
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }

    private string _name;
    public string Name
    {
        get => _name;
        set
        {
            if (_name == value)
                return;
            _name = value;
            OnPropertyChanged("Name");
        }
    }
}

I am using a ListCollectionView with LiveFiltering to display a ObservableCollection, filtered to Match only a person whose name starts with "A":

var coll = new ObservableCollection<Person>();
ListCollectionView view = new ListCollectionView(coll)
{
    Filter = p => ((Person)p).Name[0]=='A',
    IsLiveFiltering = true,
    LiveFilteringProperties = { nameof(Person.Name) }
};

When items are added to the collection, they are filtered correctly.

Here is the Problem: When the Name of a Person is changed, the Filter isn't reevaluated, which is what I thought the IsLiveFiltering and LiveFilteringProperties are for in the first place.
So, if i have change a Name from "Anna" to "Elsa" I would expect the view to update and not contain the item anymore. Likewise, changing "Eric" to "Arnold" should update the view so that the changed item is container in the view.

var p1 = new Person { Name = "Anna" };
var p2 = new Person { Name = "Eric" };

coll.Add(p1); // view is updated automatically and contains Anna now
coll.Add(p2); // view is updated, but Eric is filtered out

view.Dump(); // shows only "Anna" (LINQPad - Dump)

p1.Name = "Elsa"; // change Anna to Elsa -> the instance p1 should be removed from view (not from collection)
p2.Name = "Arnold"; // change Eric to Arnold -> the instance p2 should now be in the view

//view.Refresh(); // uncommenting this line leads to the behaviour I actually expected from LiveFiltering to be handled automatically.

view.Dump(); // shows "Elsa", but we are filtering for A*

Did I miss enabling something to get this behaviour? I do not really want to attach to PropertyChanged of each instance of Person manually - I still expect that this is what LiveFiltering does for me.

Edit:
I have experienced the problem in my application with a bigger model and extracted the relevant parts to reproduce the problem in LinqPad. Here is the complete LinqPad-script. It will also require the using clauses:

using System.Collections.ObjectModel;
using System.Windows.Data;
using System.ComponentModel;

Here's the script

void Main()
{
    var coll = new ObservableCollection<Person>();
    ListCollectionView view = new ListCollectionView(coll)
    {
        IsLiveFiltering = true,
        LiveFilteringProperties = { nameof(Person.Name) },
        Filter = p => ((Person)p).Name[0] == 'A'
    };

    var p1 = new Person { Name = "Anna" };
    var p2 = new Person { Name = "Eric" };

    coll.Add(p1);
    coll.Add(p2);

    view.Dump();

    p1.Name = "Elsa";
    p2.Name = "Arnold";

    //view.Refresh();

    view.Dump();
    Debug.Assert(view.Cast<Person>().Single().Name == "Arnold", "Wrong item in view, expected Arnold");
}

public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string property)
    {
        Console.WriteLine("PropertyChanged: " + Name + ": " + property);
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }

    private string _name;
    public string Name
    {
        get => _name;
        set
        {
            if (_name == value)
                return;
            _name = value;
            OnPropertyChanged("Name");
        }
    }
}

Body:
Where is your view and sample data...?

The following code certainly works as expected.

XAML:

<ListBox x:Name="lb" DisplayMemberPath="Name" />
<Button Content="Filter" Click="Button_Click" />

Sample code:

public partial class MainWindow : Window
{
    Person _p = new Person() { Name = "Anna" };

    public MainWindow()
    {
        InitializeComponent();

        var coll = new ObservableCollection<Person>() { _p };
        ListCollectionView view = new ListCollectionView(coll)
        {
            Filter = p => ((Person)p).Name[0] == 'A',
            IsLiveFiltering = true,
            LiveFilteringProperties = { nameof(Person.Name) }
        };

        lb.ItemsSource = view;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        _p.Name = "Elsa";
    }
}

You should probably read this before you post another question.


问:
How can I combine two excel columns during import to a database?

I am trying to combine a date and time columns in excel and map it to one column in a database using sqlbulkcopy. I am getting an error:

Date][time does not match any column mapping

See my sample code below. Any ideas on how to accomplish this without copying it to a Datatable?

```<code>Dim sSourceConstr As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath)

Dim sDestConstr As String = ConfigurationManager.ConnectionStrings("SolCards").ConnectionString
Dim sSourceConnection As New OleDbConnection(sSourceConstr)
Using sSourceConnection
    Dim sql As String = String.Format("Select [Customer Cod],[Customer],[PAN],[Vehicle],[Date],[Station],[Driver],[Authorized],[Product]" &
                                          ", [Pump], [Tran No], [Odo], [Metric], [UPrice], [Qty], [Amount], [TimeFormat] FROM [{0}$]", "trans")
    Dim command As New OleDbCommand(sql, sSourceConnection)

    sSourceConnection.Open()
    Using dr As OleDbDataReader = command.ExecuteReader()
        Using bulkCopy As New SqlBulkCopy(sDestConstr)
            bulkCopy.DestinationTableName = "FuelInformation"
            'column mapping

          bulkCopy.ColumnMappings.Add("[Date] [Time]", "DatePurchased")

            bulkCopy.WriteToServer(dr)
        End Using
    End Using
End Using
</code>```

答:
I got it to work by using CStr() as below, the issue with combining the two columns was the column header names having keywords as their names.</p>

```<code> Dim sSourceConstr As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;""", sPath)

    Dim sDestConstr As String = ConfigurationManager.ConnectionStrings("SolCards").ConnectionString
    Dim sSourceConnection As New OleDbConnection(sSourceConstr)
    Using sSourceConnection
        Dim sql As String = String.Format("SELECT CStr([Date]) + ' ' + CStr([Time]) as [DatePurchased] ,[Customer Cod],[Customer],[PAN],[Vehicle],[Station],[Driver],[Authorized],[Product], [Pump], [Tran No], [Odo], [Metric], [UPrice], [Qty], [Amount], [TimeFormat] FROM [{0}$]", "trans")
        Dim command As New OleDbCommand(sql, sSourceConnection)

        sSourceConnection.Open()
        Using dr As OleDbDataReader = command.ExecuteReader()
            Using bulkCopy As New SqlBulkCopy(sDestConstr)
                bulkCopy.DestinationTableName = "FuelInformation"
                'column mapping
                bulkCopy.ColumnMappings.Add("[DatePurchased]", "DatePurchased")

                bulkCopy.WriteToServer(dr)
            End Using
        End Using

    End Using
</code>```

Body:
I am trying to combine a date and time columns in excel and map it to one column in a database using sqlbulkcopy. I am getting an error:

Date][time does not match any column mapping

See my sample code below. Any ideas on how to accomplish this without copying it to a Datatable?

Dim sSourceConstr As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath)

Dim sDestConstr As String = ConfigurationManager.ConnectionStrings("SolCards").ConnectionString
Dim sSourceConnection As New OleDbConnection(sSourceConstr)
Using sSourceConnection
    Dim sql As String = String.Format("Select [Customer Cod],[Customer],[PAN],[Vehicle],[Date],[Station],[Driver],[Authorized],[Product]" &
                                          ", [Pump], [Tran No], [Odo], [Metric], [UPrice], [Qty], [Amount], [TimeFormat] FROM [{0}$]", "trans")
    Dim command As New OleDbCommand(sql, sSourceConnection)

    sSourceConnection.Open()
    Using dr As OleDbDataReader = command.ExecuteReader()
        Using bulkCopy As New SqlBulkCopy(sDestConstr)
            bulkCopy.DestinationTableName = "FuelInformation"
            'column mapping

          bulkCopy.ColumnMappings.Add("[Date] [Time]", "DatePurchased")

            bulkCopy.WriteToServer(dr)
        End Using
    End Using
End Using

Body:
I got it to work by using CStr() as below, the issue with combining the two columns was the column header names having keywords as their names.

 Dim sSourceConstr As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;""", sPath)

    Dim sDestConstr As String = ConfigurationManager.ConnectionStrings("SolCards").ConnectionString
    Dim sSourceConnection As New OleDbConnection(sSourceConstr)
    Using sSourceConnection
        Dim sql As String = String.Format("SELECT CStr([Date]) + ' ' + CStr([Time]) as [DatePurchased] ,[Customer Cod],[Customer],[PAN],[Vehicle],[Station],[Driver],[Authorized],[Product], [Pump], [Tran No], [Odo], [Metric], [UPrice], [Qty], [Amount], [TimeFormat] FROM [{0}$]", "trans")
        Dim command As New OleDbCommand(sql, sSourceConnection)

        sSourceConnection.Open()
        Using dr As OleDbDataReader = command.ExecuteReader()
            Using bulkCopy As New SqlBulkCopy(sDestConstr)
                bulkCopy.DestinationTableName = "FuelInformation"
                'column mapping
                bulkCopy.ColumnMappings.Add("[DatePurchased]", "DatePurchased")

                bulkCopy.WriteToServer(dr)
            End Using
        End Using

    End Using


问:
Where is an array initialized by an initializer list stored?
Given this piece of code:

```<code>(void)someFunction(void) {
    int array[] = {1,2,3,4,5,6,7,8,9,10};
}
</code>```

Where are the values of the array stored?

Stack?

Heap?

Together with those string literals. (Is it called High Frequency Heap?)

Somewhere else?

I'm asking because I'm unsure regarding this question:

Create an array of integers property in objective-c

答: As Micheal has said, where the values of the initializer list will be stored depends on the compiler and the optimization levels. For example, gcc without optimizations will just generate the code to move constants to the appropriate locations in the array, ie the actual values will only be stored in the code itself. You can easily check what will happen if you don't compile to object code, but let your compiler output assembler instead.</p>

OwnerDisplayName: gs

Body:
Given this piece of code:

(void)someFunction(void) {
    int array[] = {1,2,3,4,5,6,7,8,9,10};
}

Where are the values of the array stored?

Stack?

Heap?

Together with those string literals. (Is it called High Frequency Heap?)

Somewhere else?

I'm asking because I'm unsure regarding this question:

Create an array of integers property in objective-c

OwnerDisplayName: Christoph


问:
How can I do this query with MyDbAdapter on Android?
I have a MyDBAdapter class, that can do some simple selects, but now I need a special select. I need to implement this select:

```<code>SELECT * FROM position WHERE fk_email='given value by variable'
</code>```

But my dbadapter skills with android are very low... I don't know how to do it.

I must add two new methods:

```<code>public Cursor fetchPositionsByEmail(String fk_email)

public List<Position> retrievePositionsByEmail(String fk_email)
</code>```

I tried with these implementations but they didn't work, they return me an empty array of positions:

```<code>public Cursor fetchPositionsByEmail(String email) throws SQLException {

    Cursor mCursor = mDb.query(true, "position", new String[] {"idposition", "latitude", "longitude", "timestamp", "fk_email"}
        , "fk_email" + "='" + email+"'", null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

public List<Position> retrievePositionsByEmail(String email)
{
 List <Position> positions=new ArrayList<Position>();
 Cursor result=fetchPositionsByEmail(email);
 if( result.moveToFirst() ){
        do{
         positions.add(new Position(result.getString(result.getColumnIndexOrThrow("idposition")),
           result.getString(result.getColumnIndexOrThrow("latitude")),
           result.getString(result.getColumnIndexOrThrow("longitude")),
           result.getString(result.getColumnIndexOrThrow("timestamp")),
           result.getString(result.getColumnIndexOrThrow("fk_email"))));
        }while( result.moveToNext() );
    }
 return positions;
}
</code>```

Can someone help me to implement these two methods on this MyDBAdapter Class?

This is the class:

```<code>public class MyDbAdapter {

    private static final String TAG = "NotesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private static final String DATABASE_NAME = "gpslocdb";
    private static final String PERMISSION_TABLE_CREATE = "CREATE TABLE permission ( fk_email1 varchar, fk_email2 varchar, validated tinyint, hour1 time default '08:00:00', hour2 time default '20:00:00', date1 date, date2 date, weekend tinyint default '0', fk_type varchar, PRIMARY KEY  (fk_email1,fk_email2))";
    private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY  (email))";
    private static final String POSITION_TABLE_CREATE = "CREATE TABLE position (idposition bigint, latitude varchar, longitude varchar, timestamp datetime, fk_email varchar, PRIMARY KEY (idposition))";

    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
         db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            db.execSQL("DROP TABLE IF EXISTS position");
            db.execSQL(PERMISSION_TABLE_CREATE);
            db.execSQL(USER_TABLE_CREATE);
            db.execSQL(POSITION_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //db.execSQL("DROP TABLE IF EXISTS user");
            //db.execSQL("DROP TABLE IF EXISTS permission");
            //onCreate(db);
        }

  @Override
  public void onOpen(SQLiteDatabase db) {
   super.onOpen(db);
            //onCreate(db);
  }
  public void clearDb(SQLiteDatabase db){
   db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            db.execSQL("DROP TABLE IF EXISTS position");
            onCreate(db);
  }
  public void deleteUser(SQLiteDatabase db, String email)
  {
   db.execSQL("DELETE FROM user Where email='"+email+"'");
  }
  public void deletePermission(SQLiteDatabase db, String email)
  {
   db.execSQL("DELETE FROM permission Where fk_email2='"+email+"'");
  }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public MyDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     *
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public MyDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
     //clearDB();
        mDbHelper.close();
    }

    public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("email",email);
        initialValues.put("password",password);
        initialValues.put("fullName",fullName);
        initialValues.put("mobilePhone",mobilePhone);
        initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
        return mDb.insert("user", null, initialValues);
    }
    public long createPermission(String email1, String email2, String validated, String hour1, String hour2,
   String date1, String date2, String weekend, String fk_type)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("fk_email1",email1);
        initialValues.put("fk_email2",email2);
        initialValues.put("validated",validated);
        initialValues.put("hour1",hour1);
        initialValues.put("hour2",hour2);
        initialValues.put("date1",date1);
        initialValues.put("date2",date2);
        initialValues.put("weekend",weekend);
        initialValues.put("fk_type",fk_type);
        return mDb.insert("permission", null, initialValues);
    }
    public long createPosition(String idposition, String latitude, String longitude, String timestamp, String fk_email)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("idposition",idposition);
        initialValues.put("latitude",latitude);
        initialValues.put("longitude",longitude);
        initialValues.put("timestamp",timestamp);
        initialValues.put("fk_email",fk_email);
        return mDb.insert("position", null, initialValues);
    }

    public void clearDB() {
     mDbHelper.clearDb(mDb);
    }

    public Cursor fetchAllUsers() {

        return mDb.query("user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}, null, null, null, null, null);
    }
    public Cursor fetchAllPermissions() {

        return mDb.query("permission", new String[] {"fk_email1", "fk_email2", "validated", "hour1", "hour2", "date1", "date2", "weekend", "fk_type"}, null, null, null, null, null);
    }

    public Cursor fetchUser(String email) throws SQLException {

        Cursor mCursor = mDb.query(true, "user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}
            , "email" + "=" + email, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public List<Friend> retrieveAllFriends()
    {
     List <Friend> friends=new ArrayList<Friend>();
     Cursor result=fetchAllUsers();
     if( result.moveToFirst() ){
            do{
                friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")),result.getString(result.getColumnIndexOrThrow("password")), result.getString(result.getColumnIndexOrThrow("fullName")),result.getString(result.getColumnIndexOrThrow("mobilePhone")),result.getString(result.getColumnIndexOrThrow("mobileOperatingSystem"))));
            }while( result.moveToNext() );
        }
     return friends;
    }
    public List<Permission> retrieveAllPermissions()
    {
     List <Permission> permissions=new ArrayList<Permission>();
     Cursor result=fetchAllPermissions();
     if( result.moveToFirst() ){
            do{
             permissions.add(new Permission(result.getString(result.getColumnIndexOrThrow("fk_email1")),
               result.getString(result.getColumnIndexOrThrow("fk_email2")),
               Integer.parseInt(result.getString(result.getColumnIndexOrThrow("validated"))),
               result.getString(result.getColumnIndexOrThrow("hour1")),
               result.getString(result.getColumnIndexOrThrow("hour2")),
               result.getString(result.getColumnIndexOrThrow("date1")),
               result.getString(result.getColumnIndexOrThrow("date2")),
               Integer.parseInt(result.getString(result.getColumnIndexOrThrow("weekend"))),
               result.getString(result.getColumnIndexOrThrow("fk_type"))));
            }while( result.moveToNext() );
        }
     return permissions;
    }

    public void deleteUser(String email) throws SQLException
    {
     mDbHelper.deleteUser(mDb, email);
    }
    public void deletePermission(String email) throws SQLException
    {
     mDbHelper.deletePermission(mDb, email);
    }

}
</code>```

答:
Try using placeholder instead of concatenating values.

```<code>  Cursor mCursor = mDb.query(true, "position", new String[] {"idposition", "latitude", "longitude", "timestamp", "fk_email"}
        , "fk_email=?", new String[] { email } , null, null, null, null);
</code>```

Since you are passing an email adress by concatenation, the problem may come from the @ symbol.

I found this post about the @ in sql

Body:
I have a MyDBAdapter class, that can do some simple selects, but now I need a special select. I need to implement this select:

SELECT * FROM position WHERE fk_email='given value by variable'

But my dbadapter skills with android are very low... I don't know how to do it.

I must add two new methods:

public Cursor fetchPositionsByEmail(String fk_email)

public List<Position> retrievePositionsByEmail(String fk_email)

I tried with these implementations but they didn't work, they return me an empty array of positions:

public Cursor fetchPositionsByEmail(String email) throws SQLException {

    Cursor mCursor = mDb.query(true, "position", new String[] {"idposition", "latitude", "longitude", "timestamp", "fk_email"}
        , "fk_email" + "='" + email+"'", null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

public List<Position> retrievePositionsByEmail(String email)
{
 List <Position> positions=new ArrayList<Position>();
 Cursor result=fetchPositionsByEmail(email);
 if( result.moveToFirst() ){
        do{
         positions.add(new Position(result.getString(result.getColumnIndexOrThrow("idposition")),
           result.getString(result.getColumnIndexOrThrow("latitude")),
           result.getString(result.getColumnIndexOrThrow("longitude")),
           result.getString(result.getColumnIndexOrThrow("timestamp")),
           result.getString(result.getColumnIndexOrThrow("fk_email"))));
        }while( result.moveToNext() );
    }
 return positions;
}

Can someone help me to implement these two methods on this MyDBAdapter Class?

This is the class:

public class MyDbAdapter {

    private static final String TAG = "NotesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private static final String DATABASE_NAME = "gpslocdb";
    private static final String PERMISSION_TABLE_CREATE = "CREATE TABLE permission ( fk_email1 varchar, fk_email2 varchar, validated tinyint, hour1 time default '08:00:00', hour2 time default '20:00:00', date1 date, date2 date, weekend tinyint default '0', fk_type varchar, PRIMARY KEY  (fk_email1,fk_email2))";
    private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY  (email))";
    private static final String POSITION_TABLE_CREATE = "CREATE TABLE position (idposition bigint, latitude varchar, longitude varchar, timestamp datetime, fk_email varchar, PRIMARY KEY (idposition))";

    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
         db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            db.execSQL("DROP TABLE IF EXISTS position");
            db.execSQL(PERMISSION_TABLE_CREATE);
            db.execSQL(USER_TABLE_CREATE);
            db.execSQL(POSITION_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //db.execSQL("DROP TABLE IF EXISTS user");
            //db.execSQL("DROP TABLE IF EXISTS permission");
            //onCreate(db);
        }

  @Override
  public void onOpen(SQLiteDatabase db) {
   super.onOpen(db);
            //onCreate(db);
  }
  public void clearDb(SQLiteDatabase db){
   db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            db.execSQL("DROP TABLE IF EXISTS position");
            onCreate(db);
  }
  public void deleteUser(SQLiteDatabase db, String email)
  {
   db.execSQL("DELETE FROM user Where email='"+email+"'");
  }
  public void deletePermission(SQLiteDatabase db, String email)
  {
   db.execSQL("DELETE FROM permission Where fk_email2='"+email+"'");
  }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public MyDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     *
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public MyDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
     //clearDB();
        mDbHelper.close();
    }

    public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("email",email);
        initialValues.put("password",password);
        initialValues.put("fullName",fullName);
        initialValues.put("mobilePhone",mobilePhone);
        initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
        return mDb.insert("user", null, initialValues);
    }
    public long createPermission(String email1, String email2, String validated, String hour1, String hour2,
   String date1, String date2, String weekend, String fk_type)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("fk_email1",email1);
        initialValues.put("fk_email2",email2);
        initialValues.put("validated",validated);
        initialValues.put("hour1",hour1);
        initialValues.put("hour2",hour2);
        initialValues.put("date1",date1);
        initialValues.put("date2",date2);
        initialValues.put("weekend",weekend);
        initialValues.put("fk_type",fk_type);
        return mDb.insert("permission", null, initialValues);
    }
    public long createPosition(String idposition, String latitude, String longitude, String timestamp, String fk_email)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("idposition",idposition);
        initialValues.put("latitude",latitude);
        initialValues.put("longitude",longitude);
        initialValues.put("timestamp",timestamp);
        initialValues.put("fk_email",fk_email);
        return mDb.insert("position", null, initialValues);
    }

    public void clearDB() {
     mDbHelper.clearDb(mDb);
    }

    public Cursor fetchAllUsers() {

        return mDb.query("user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}, null, null, null, null, null);
    }
    public Cursor fetchAllPermissions() {

        return mDb.query("permission", new String[] {"fk_email1", "fk_email2", "validated", "hour1", "hour2", "date1", "date2", "weekend", "fk_type"}, null, null, null, null, null);
    }

    public Cursor fetchUser(String email) throws SQLException {

        Cursor mCursor = mDb.query(true, "user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}
            , "email" + "=" + email, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public List<Friend> retrieveAllFriends()
    {
     List <Friend> friends=new ArrayList<Friend>();
     Cursor result=fetchAllUsers();
     if( result.moveToFirst() ){
            do{
                friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")),result.getString(result.getColumnIndexOrThrow("password")), result.getString(result.getColumnIndexOrThrow("fullName")),result.getString(result.getColumnIndexOrThrow("mobilePhone")),result.getString(result.getColumnIndexOrThrow("mobileOperatingSystem"))));
            }while( result.moveToNext() );
        }
     return friends;
    }
    public List<Permission> retrieveAllPermissions()
    {
     List <Permission> permissions=new ArrayList<Permission>();
     Cursor result=fetchAllPermissions();
     if( result.moveToFirst() ){
            do{
             permissions.add(new Permission(result.getString(result.getColumnIndexOrThrow("fk_email1")),
               result.getString(result.getColumnIndexOrThrow("fk_email2")),
               Integer.parseInt(result.getString(result.getColumnIndexOrThrow("validated"))),
               result.getString(result.getColumnIndexOrThrow("hour1")),
               result.getString(result.getColumnIndexOrThrow("hour2")),
               result.getString(result.getColumnIndexOrThrow("date1")),
               result.getString(result.getColumnIndexOrThrow("date2")),
               Integer.parseInt(result.getString(result.getColumnIndexOrThrow("weekend"))),
               result.getString(result.getColumnIndexOrThrow("fk_type"))));
            }while( result.moveToNext() );
        }
     return permissions;
    }

    public void deleteUser(String email) throws SQLException
    {
     mDbHelper.deleteUser(mDb, email);
    }
    public void deletePermission(String email) throws SQLException
    {
     mDbHelper.deletePermission(mDb, email);
    }

}

Body:
Try using placeholder instead of concatenating values.

  Cursor mCursor = mDb.query(true, "position", new String[] {"idposition", "latitude", "longitude", "timestamp", "fk_email"}
        , "fk_email=?", new String[] { email } , null, null, null, null);

Since you are passing an email adress by concatenation, the problem may come from the @ symbol.

I found this post about the @ in sql