问:
Best practice to implement method getXXX from db using cursor for Android
For example code below. Do we need to close cursor? Do we better use try/catch/finally instead of using if()?

```<code>public int getCount() {

    final Cursor countCursor = contentResolver.query(
            AnalyticContract.CONTENT_URI,
            new String[] {"count(*) AS count"},
            null,
            null,
            null);
    if (countCursor == null) {
        return 0;
    }

    countCursor.moveToFirst();
    final int count = countCursor.getInt(0);
    return count;
}
</code>```

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

答:
I prefer to make a database helper class and through that database access becomes much much easier. Sample of a database helper Class -

```<code>public class DatabaseHelperClass extends SQLiteOpenHelper {

public DatabaseHelperClass(Context context)
{
    super(context,"hakeem.db",null,1);
}

//Tables
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("Your SQL Query to create a table");
   }

//Delete Tables
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table table_name if exists");
    onCreate(db);
}

//Insertion of data into tables
long insertData(Various Parameters you like to pass for insertion)
{
    SQLiteDatabase db=getWritableDatabase();
    ContentValues values=new ContentValues();

values.put("col_name1",value);
values.put("col_name2",value);
values.put("col_name3",value);
values.put("col_name4",value);

    return db.insert("signup_details",null,values);
}

//Delete record
public int deleteData(int id)
{
    SQLiteDatabase sb=getWritableDatabase();
    return sb.delete("hospital_details","id="+id,null);
}

//Update data in table
int updateData(Parameters you want to pass for update. Make sure you include a primary key)
{
    ContentValues values=new ContentValues();

     values.put("col_name1",value);
     values.put("col_name2",value);
      values.put("col_name3",value);
      values.put("col_name4",value);

    return getWritableDatabase().update("signup_details",values,"id="+id,null);
}

//Read data from tables
Cursor getSigninDetails() { return getWritableDatabase().rawQuery("select  * from table_name",null); }
}
</code>```

and to access results from the database-

```<code> private void getDataFromDatabase() {

    Cursor cursor = db.getUserData();

    if (cursor.moveToFirst()) {
        do {

            var_name1= cursor.getString(0);
            var_name2= cursor.getString(1);
            var_name3= cursor.getString(2);
            var_name4= cursor.getString(3);

        } while (cursor.moveToNext());
    }
cursor.close();

}
</code>```

Body:
For example code below. Do we need to close cursor? Do we better use try/catch/finally instead of using if()?

public int getCount() {

    final Cursor countCursor = contentResolver.query(
            AnalyticContract.CONTENT_URI,
            new String[] {"count(*) AS count"},
            null,
            null,
            null);
    if (countCursor == null) {
        return 0;
    }

    countCursor.moveToFirst();
    final int count = countCursor.getInt(0);
    return count;
}

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Body:
I prefer to make a database helper class and through that database access becomes much much easier. Sample of a database helper Class -

public class DatabaseHelperClass extends SQLiteOpenHelper {

public DatabaseHelperClass(Context context)
{
    super(context,"hakeem.db",null,1);
}

//Tables
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("Your SQL Query to create a table");
   }

//Delete Tables
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table table_name if exists");
    onCreate(db);
}

//Insertion of data into tables
long insertData(Various Parameters you like to pass for insertion)
{
    SQLiteDatabase db=getWritableDatabase();
    ContentValues values=new ContentValues();

values.put("col_name1",value);
values.put("col_name2",value);
values.put("col_name3",value);
values.put("col_name4",value);

    return db.insert("signup_details",null,values);
}

//Delete record
public int deleteData(int id)
{
    SQLiteDatabase sb=getWritableDatabase();
    return sb.delete("hospital_details","id="+id,null);
}

//Update data in table
int updateData(Parameters you want to pass for update. Make sure you include a primary key)
{
    ContentValues values=new ContentValues();

     values.put("col_name1",value);
     values.put("col_name2",value);
      values.put("col_name3",value);
      values.put("col_name4",value);

    return getWritableDatabase().update("signup_details",values,"id="+id,null);
}

//Read data from tables
Cursor getSigninDetails() { return getWritableDatabase().rawQuery("select  * from table_name",null); }
}

and to access results from the database-

 private void getDataFromDatabase() {

    Cursor cursor = db.getUserData();

    if (cursor.moveToFirst()) {
        do {

            var_name1= cursor.getString(0);
            var_name2= cursor.getString(1);
            var_name3= cursor.getString(2);
            var_name4= cursor.getString(3);

        } while (cursor.moveToNext());
    }
cursor.close();

}


来源: stackexchange

问:
Twitter OAuth : Invalid or expired token [its NOT duplicate]
Before anyone goes in a hurry and mark this question as Duplicate, let me tell you that ITS NOT DUPLICATE

I have already checked similar question like this, this, this and this, but those are all 2 years old and the library has been changed too much since then so those answers are not useful.

So here's the question. I'm using abraham's libraray which can be found here.  Below is the code that I'm using:

```<code>if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret']))
{
    $connection = new TwitterOAuth('MY_CONSUMER_KEY', 'MY_CONSUMER_SECRET', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

    $access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));
    $_SESSION['access_token'] = $access_token;

    $user_info = $connection->get("account/verify_credentials");
    print_r($user_info);
}
</code>```

From the print_r which I did above, I get the result as follows:

```<code>stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code] => 89 [message] => Invalid or expired token. ) ) )
</code>```

Due to this invalid/expired token I'm not able to get ahead in my work. So I went 1 step back and did:

```<code>var_dump($access_token);
</code>```

The result obtained is:

```<code>array(5) {
   ["oauth_token"]=> string(50) "*********"
   ["oauth_token_secret"]=> string(45) "*********"
   ["user_id"]=> string(10) "***My user id****"
   ["screen_name"]=> string(9) "***My screen name****"
   ["x_auth_expires"]=> string(1) "0"
}
</code>```

Here you see that the last element is ["x_auth_expires"] whose value is 0. I think this element did not appear in the older version of the library. And I suppose this is the thing which is causing the problem.

I tried re-generating my Customer_Key and Customer_Secret, but even that didn't seem to help.

Any kind of help will be appreciated. Thank you.

答:
I have use this in CI callback function </p>

```<code>if($this->input->get('denied') != ''){
   /* Remove all token from session  */
   $this->connection = NULL;
   $this->connection = $this->twitteroauth->create($this->config->item('twitter_consumer_token'), $this->config->item('twitter_consumer_secret'));
   $this->session->set_flashdata('account_block_error_msg',"Access denied");
   redirect(base_url('/Sign-in'));
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Before anyone goes in a hurry and mark this question as Duplicate, let me tell you that ITS NOT DUPLICATE

I have already checked similar question like this, this, this and this, but those are all 2 years old and the library has been changed too much since then so those answers are not useful.

So here's the question. I'm using abraham's libraray which can be found here.  Below is the code that I'm using:

if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret']))
{
    $connection = new TwitterOAuth('MY_CONSUMER_KEY', 'MY_CONSUMER_SECRET', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

    $access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));
    $_SESSION['access_token'] = $access_token;

    $user_info = $connection->get("account/verify_credentials");
    print_r($user_info);
}

From the print_r which I did above, I get the result as follows:

stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code] => 89 [message] => Invalid or expired token. ) ) )

Due to this invalid/expired token I'm not able to get ahead in my work. So I went 1 step back and did:

var_dump($access_token);

The result obtained is:

array(5) {
   ["oauth_token"]=> string(50) "*********"
   ["oauth_token_secret"]=> string(45) "*********"
   ["user_id"]=> string(10) "***My user id****"
   ["screen_name"]=> string(9) "***My screen name****"
   ["x_auth_expires"]=> string(1) "0"
}

Here you see that the last element is ["x_auth_expires"] whose value is 0. I think this element did not appear in the older version of the library. And I suppose this is the thing which is causing the problem.

I tried re-generating my Customer_Key and Customer_Secret, but even that didn't seem to help.

Any kind of help will be appreciated. Thank you.

Body:
I have use this in CI callback function

if($this->input->get('denied') != ''){
   /* Remove all token from session  */
   $this->connection = NULL;
   $this->connection = $this->twitteroauth->create($this->config->item('twitter_consumer_token'), $this->config->item('twitter_consumer_secret'));
   $this->session->set_flashdata('account_block_error_msg',"Access denied");
   redirect(base_url('/Sign-in'));
}


问:
Scala implicit conversion of container nested types
Consider the following example:

```<code>case class A()

case class B()

object Conversions {
  implicit def aToB(a: A): B = B()

  implicit def convert[U, T](seq: Seq[U])(implicit converter: U => T): Seq[T] = {
    seq.map(converter)
  }
}

object Main {
  import Conversions._

  def main(args: Array[String]): Unit = {

    val sa = Seq(A())

    def example(): Seq[B] = sa
  }
}
</code>```

This example won't compile by scala compiler for version 2.11.8. I do compilation with IntelliJ Idea, but actually idea don't produce error on the fly and shows that implicit is used for conversion:
Screenshot from Intellij Idea

To workaround this issue I've used the approach described here:
"Scala: Making implicit conversion A->B work for Option[A] -> Option[B]"

My code started to look as follow:

```<code>case class A()

case class B()

object Conversions {
  implicit def aToB(a: A): B = B()

  trait ContainerFunctor[Container[_]] {
    def map[A, B](container: Container[A], f: A => B): Container[B]
  }

  implicit object SeqFunctor extends ContainerFunctor[Seq] {
    override def map[A, B](container: Seq[A], f: (A) => B): Seq[B] = {
      Option(container).map(_.map(f)).getOrElse(Seq.empty[B])
    }
  }

  implicit def functorConvert[F[_], A, B](x: F[A])(implicit f: A => B, functor: ContainerFunctor[F]): F[B] = functor.map(x, f)
}

object Main {

  import Conversions._

  def main(args: Array[String]): Unit = {

    val sa = Seq(A())

    def example(): Seq[B] = sa
  }
}
</code>```

This code compiles well and works as needed.

My questions are:

Why the first approach fails to compile?

Is this somehow related to type erasure and if yes, how usage of Functor helps with it?

How compiler resolves implicits for both of this cases?

答:
Why the first approach fails to compile?

I've opened a bug for this issue.

This seems like a compiler quirk in implicit search. Since you're providing the convert method which converts Seq[A] => Seq[B], the compiler isn't able to properly align the types. This is the output of compiling with Ytyper-debug:

```<code>|    [search #3] start `[U, T](seq: Seq[U])(implicit converter: U => T)Seq[T]` inferring type T, searching for adaptation to pt=A => T (silent: method example in Test) implicits disabled
|    [search #3] considering aToB
|    |-- { ((a: A) => Conversions.aToB(a)) } : pt=A => ? EXPRmode (silent: method example in Test) implicits disabled
|    |    |-- ((a: A) => Conversions.aToB(a)) : pt=A => ? EXPRmode (silent: method example in Test) implicits disabled
|    |    |    |-- Conversions.aToB(a) EXPRmode (silent: value $anonfun in Test) implicits disabled
|    |    |    |    |-- Conversions.aToB BYVALmode-EXPRmode-FUNmode-POLYmode (silent: value $anonfun in Test) implicits disabled
|    |    |    |    |    \-> (a: A)B
|    |    |    |    |-- a : pt=A BYVALmode-EXPRmode (silent: value $anonfun in Test) implicits disabled
|    |    |    |    |    \-> A
|    |    |    |    \-> B
|    |    |    \-> A => B
|    |    \-> A => B
|    [adapt] aToB adapted to { ((a: A) => Conversions.aToB(a)) } based on pt A => T
|    [search #3] solve tvars=?T, tvars.constr= >: B
|    solving for (T: ?T)
|    [search #3] success inferred value of type A => =?B is SearchResult({
|      ((a: A) => Conversions.aToB(a))
|    }, TreeTypeSubstituter(List(type T),List(B)))
|    solving for (A: ?A)
|    solving for (A: ?A)
|    solving for (A: ?A)
|    solving for (A: ?A)
|    [search #3] considering $conforms
|    solving for (A: ?A)
|    [adapt] $conforms adapted to [A]=> <:<[A,A] based on pt A => T
|    [search #3] solve tvars=?T, tvars.constr= >: A
|    solving for (T: ?T)
|    [search #3] success inferred value of type A => =?A is SearchResult(scala.Predef.$conforms[A], TreeTypeSubstituter(List(type T),List(A)))
</code>```

It seems like the search #3 is trying to adapt conforms (<:<) which takes the entire implicit search from A => B to A => A. If I compile with the -Yno-predef, the implicit conversion succeeds:

```<code>|    |    |-- [U, T](seq: Seq[U])(implicit converter: U => T)Seq[T] : pt=Seq[B] EXPRmode (silent: method example in Test) implicits disabled
|    |    |    [search #4] start `[U, T](seq: Seq[U])(implicit converter: U => T)Seq[T]`, searching for adaptation to pt=A => B (silent: method example in Test) implicits disabled
|    |    |    [search #4] considering aToB
|    |    |    |-- { ((a: A) => Conversions.aToB(a)) } : pt=A => B EXPRmode (silent: method example in Test) implicits disabled
|    |    |    |    |-- ((a: A) => Conversions.aToB(a)) : pt=A => B EXPRmode (silent: method example in Test) implicits disabled
|    |    |    |    |    |-- Conversions.aToB(a) : pt=B EXPRmode (silent: value $anonfun in Test) implicits disabled
|    |    |    |    |    |    |-- Conversions.aToB BYVALmode-EXPRmode-FUNmode-POLYmode (silent: value $anonfun in Test) implicits disabled
|    |    |    |    |    |    |    \-> (a: A)B
|    |    |    |    |    |    |-- a : pt=A BYVALmode-EXPRmode (silent: value $anonfun in Test) implicits disabled
|    |    |    |    |    |    |    \-> A
|    |    |    |    |    |    \-> B
|    |    |    |    |    \-> A => B
|    |    |    |    \-> A => B
|    |    |    [adapt] aToB adapted to { ((a: A) => Conversions.aToB(a)) } based on pt A => B
|    |    |    [search #4] success inferred value of type A => B is SearchResult({
|    |    |      ((a: A) => Conversions.aToB(a))
|    |    |    }, )
|    |    |    |-- [U, T](seq: Seq[U])(implicit converter: U => T)Seq[T] : pt=Seq[B] EXPRmode (silent: method example in Test) implicits disabled
|    |    |    |    \-> Seq[B]
|    |    |    [adapt] [U, T](seq: Seq[U])(implicit converter: U => T)Seq[T] adapted to [U, T](seq: Seq[U])(implicit converter: U => T)Seq[T] based on pt Seq[B]
|    |    |    \-> Seq[B]
|    |    [adapt] Seq[A] adapted to [U, T](seq: Seq[U])(implicit converter: U => T)Seq[T] based on pt Seq[B]
|    |    \-> Seq[B]
|    \-> [def example] ()Seq[B]
</code>```

Is this somehow related to type erasure and if yes, how usage of
  Functor helps with it?

The second example works because you're now laying out explicitly how to map a Seq[A] into a Seq[B] by using the Functor type class and thus when the compiler sees a Seq[A], it has an implicit to convert it to Seq[B]:

```<code>def example(): Seq[B] = Conversions.functorConvert[Seq, A, B](sa)({
        ((a: A) => Conversions.aToB(a))
}, Conversions.SeqFunctor);
</code>```

Note you require both a conversion from A => B, and a Functor[Seq] to be able to map over all As to convert them to Bs, which is what it does using conversions.aToB.

Body:
Consider the following example:

case class A()

case class B()

object Conversions {
  implicit def aToB(a: A): B = B()

  implicit def convert[U, T](seq: Seq[U])(implicit converter: U => T): Seq[T] = {
    seq.map(converter)
  }
}

object Main {
  import Conversions._

  def main(args: Array[String]): Unit = {

    val sa = Seq(A())

    def example(): Seq[B] = sa
  }
}

This example won't compile by scala compiler for version 2.11.8. I do compilation with IntelliJ Idea, but actually idea don't produce error on the fly and shows that implicit is used for conversion:
Screenshot from Intellij Idea

To workaround this issue I've used the approach described here:
"Scala: Making implicit conversion A->B work for Option[A] -> Option[B]"

My code started to look as follow:

case class A()

case class B()

object Conversions {
  implicit def aToB(a: A): B = B()

  trait ContainerFunctor[Container[_]] {
    def map[A, B](container: Container[A], f: A => B): Container[B]
  }

  implicit object SeqFunctor extends ContainerFunctor[Seq] {
    override def map[A, B](container: Seq[A], f: (A) => B): Seq[B] = {
      Option(container).map(_.map(f)).getOrElse(Seq.empty[B])
    }
  }

  implicit def functorConvert[F[_], A, B](x: F[A])(implicit f: A => B, functor: ContainerFunctor[F]): F[B] = functor.map(x, f)
}

object Main {

  import Conversions._

  def main(args: Array[String]): Unit = {

    val sa = Seq(A())

    def example(): Seq[B] = sa
  }
}

This code compiles well and works as needed.

My questions are:

Why the first approach fails to compile?

Is this somehow related to type erasure and if yes, how usage of Functor helps with it?

How compiler resolves implicits for both of this cases?

Body:
Why the first approach fails to compile?

I've opened a bug for this issue.

This seems like a compiler quirk in implicit search. Since you're providing the convert method which converts Seq[A] => Seq[B], the compiler isn't able to properly align the types. This is the output of compiling with Ytyper-debug:

|    [search #3] start `[U, T](seq: Seq[U])(implicit converter: U => T)Seq[T]` inferring type T, searching for adaptation to pt=A => T (silent: method example in Test) implicits disabled
|    [search #3] considering aToB
|    |-- { ((a: A) => Conversions.aToB(a)) } : pt=A => ? EXPRmode (silent: method example in Test) implicits disabled
|    |    |-- ((a: A) => Conversions.aToB(a)) : pt=A => ? EXPRmode (silent: method example in Test) implicits disabled
|    |    |    |-- Conversions.aToB(a) EXPRmode (silent: value $anonfun in Test) implicits disabled
|    |    |    |    |-- Conversions.aToB BYVALmode-EXPRmode-FUNmode-POLYmode (silent: value $anonfun in Test) implicits disabled
|    |    |    |    |    \-> (a: A)B
|    |    |    |    |-- a : pt=A BYVALmode-EXPRmode (silent: value $anonfun in Test) implicits disabled
|    |    |    |    |    \-> A
|    |    |    |    \-> B
|    |    |    \-> A => B
|    |    \-> A => B
|    [adapt] aToB adapted to { ((a: A) => Conversions.aToB(a)) } based on pt A => T
|    [search #3] solve tvars=?T, tvars.constr= >: B
|    solving for (T: ?T)
|    [search #3] success inferred value of type A => =?B is SearchResult({
|      ((a: A) => Conversions.aToB(a))
|    }, TreeTypeSubstituter(List(type T),List(B)))
|    solving for (A: ?A)
|    solving for (A: ?A)
|    solving for (A: ?A)
|    solving for (A: ?A)
|    [search #3] considering $conforms
|    solving for (A: ?A)
|    [adapt] $conforms adapted to [A]=> <:<[A,A] based on pt A => T
|    [search #3] solve tvars=?T, tvars.constr= >: A
|    solving for (T: ?T)
|    [search #3] success inferred value of type A => =?A is SearchResult(scala.Predef.$conforms[A], TreeTypeSubstituter(List(type T),List(A)))

It seems like the search #3 is trying to adapt conforms (<:<) which takes the entire implicit search from A => B to A => A. If I compile with the -Yno-predef, the implicit conversion succeeds:

|    |    |-- [U, T](seq: Seq[U])(implicit converter: U => T)Seq[T] : pt=Seq[B] EXPRmode (silent: method example in Test) implicits disabled
|    |    |    [search #4] start `[U, T](seq: Seq[U])(implicit converter: U => T)Seq[T]`, searching for adaptation to pt=A => B (silent: method example in Test) implicits disabled
|    |    |    [search #4] considering aToB
|    |    |    |-- { ((a: A) => Conversions.aToB(a)) } : pt=A => B EXPRmode (silent: method example in Test) implicits disabled
|    |    |    |    |-- ((a: A) => Conversions.aToB(a)) : pt=A => B EXPRmode (silent: method example in Test) implicits disabled
|    |    |    |    |    |-- Conversions.aToB(a) : pt=B EXPRmode (silent: value $anonfun in Test) implicits disabled
|    |    |    |    |    |    |-- Conversions.aToB BYVALmode-EXPRmode-FUNmode-POLYmode (silent: value $anonfun in Test) implicits disabled
|    |    |    |    |    |    |    \-> (a: A)B
|    |    |    |    |    |    |-- a : pt=A BYVALmode-EXPRmode (silent: value $anonfun in Test) implicits disabled
|    |    |    |    |    |    |    \-> A
|    |    |    |    |    |    \-> B
|    |    |    |    |    \-> A => B
|    |    |    |    \-> A => B
|    |    |    [adapt] aToB adapted to { ((a: A) => Conversions.aToB(a)) } based on pt A => B
|    |    |    [search #4] success inferred value of type A => B is SearchResult({
|    |    |      ((a: A) => Conversions.aToB(a))
|    |    |    }, )
|    |    |    |-- [U, T](seq: Seq[U])(implicit converter: U => T)Seq[T] : pt=Seq[B] EXPRmode (silent: method example in Test) implicits disabled
|    |    |    |    \-> Seq[B]
|    |    |    [adapt] [U, T](seq: Seq[U])(implicit converter: U => T)Seq[T] adapted to [U, T](seq: Seq[U])(implicit converter: U => T)Seq[T] based on pt Seq[B]
|    |    |    \-> Seq[B]
|    |    [adapt] Seq[A] adapted to [U, T](seq: Seq[U])(implicit converter: U => T)Seq[T] based on pt Seq[B]
|    |    \-> Seq[B]
|    \-> [def example] ()Seq[B]

Is this somehow related to type erasure and if yes, how usage of
  Functor helps with it?

The second example works because you're now laying out explicitly how to map a Seq[A] into a Seq[B] by using the Functor type class and thus when the compiler sees a Seq[A], it has an implicit to convert it to Seq[B]:

def example(): Seq[B] = Conversions.functorConvert[Seq, A, B](sa)({
        ((a: A) => Conversions.aToB(a))
}, Conversions.SeqFunctor);

Note you require both a conversion from A => B, and a Functor[Seq] to be able to map over all As to convert them to Bs, which is what it does using conversions.aToB.


问:
How to achieve service discovery like "Printer Discover" on android?
I would like to know about the 'service discovery' mechanisms supported by android - particularly, Printer Discovery.

Does android provide such a discovery option? example : support for snmp broadcast?

I tried out an application "PrinterShare" link : http://www.printeranywhere.com/mobile.sdf where Printer Discovery is achieved through ipp.

Any help is appreciated.

答:
Roy, I came across the same problem as you, and was even getting the same behavior when running that code snippet on an actual device (while running the code standalone, not in android, worked fine). I found this page and got it working, although only on the device, by using the following to figure out the Broadcast IP (instead of 239.255.255.250):

```<code>InetAddress getBroadcastAddress() throws IOException {
    WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE);
    DhcpInfo dhcp = wifi.getDhcpInfo();
    // handle null somehow

    int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
    byte[] quads = new byte[4];
    for (int k = 0; k < 4; k++)
        quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
    return InetAddress.getByAddress(quads);
}
</code>```

Hope that helps:)

ContentLicense: CC BY-SA 2.5

Body:
Roy, I came across the same problem as you, and was even getting the same behavior when running that code snippet on an actual device (while running the code standalone, not in android, worked fine). I found this page and got it working, although only on the device, by using the following to figure out the Broadcast IP (instead of 239.255.255.250):

InetAddress getBroadcastAddress() throws IOException {
    WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE);
    DhcpInfo dhcp = wifi.getDhcpInfo();
    // handle null somehow

    int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
    byte[] quads = new byte[4];
    for (int k = 0; k < 4; k++)
        quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
    return InetAddress.getByAddress(quads);
}

Hope that helps:)


问:
No output from script run under crontab
I want to execute a Perl script every two minutes.

This script sends me an email that contains files. It works fine manually.

I tried in a crontab

```<code>*/2 * * * * /sw/freetools/perl/5.8.8/Linux/rh6/x86_64/bin/perl /home/httpldev/iLicoMetrics/metrique.pl &> /dev/null
</code>```

I also tried with

```<code>*/2 * * * * /home/httpldev/iLicoMetrics/metrique.pl &> /dev/null
</code>```

but I got no output.

答:
I find my mistake, i make a mistake in the path of Perl :
/sw/freetools/perl/5.8.8/Linux/rh6/x86_64/bin/perl

/sw/freetools/perl/5.8.8/Linux/rh60/x86_64/bin/perl

Thank you for your help.

Title: No output from script run under crontab

Body:
I want to execute a Perl script every two minutes.

This script sends me an email that contains files. It works fine manually.

I tried in a crontab

*/2 * * * * /sw/freetools/perl/5.8.8/Linux/rh6/x86_64/bin/perl /home/httpldev/iLicoMetrics/metrique.pl &> /dev/null

I also tried with

*/2 * * * * /home/httpldev/iLicoMetrics/metrique.pl &> /dev/null

but I got no output.


问:
Extract from string separated by colon and semicolon in R
I have a vector of strings and I want to extract information from it. The strings look like following:

```<code>obs, product
  1, apple:pink lady;grade 1
  2, apple--pink lady
  3, orange
</code>```

I wanted to extract information and organised like this:

```<code>obs, product_1, product_2, product_3
  1, apple, pink lady, grade 1
  2, apple, pink lady, NA,
  3, orange, NA, NA
</code>```

I am new to programming and have tried to use sub(';.*$','',datasetname), which will return a new vector, for obs 1, I can get product 1 & 2 conbined Consequently, I will need to do another round to separate the new-formed strings. However, for obs 3 (without any special characters, colon or semicolon), the function will return the whole thing. In addition, I also need to consider some cases that the separator can be different, like "--", instead of colon and semicolon.

I am wondering how can I get what I want using sqldf, or other packages in R?

答:
We can use base R to do this

```<code>df2 <- cbind(df1[1], read.csv(text=gsub('[:;-]+', ',', df1$product),
       header = FALSE, na.strings = "", col.names = paste0("product_", 1:3)))

df2
#   obs product_1 product_2 product_3
#1   1     apple pink lady   grade 1
#2   2     apple pink lady      <NA>
#3   3    orange      <NA>      <NA>
</code>```

Body:
I have a vector of strings and I want to extract information from it. The strings look like following:

obs, product
  1, apple:pink lady;grade 1
  2, apple--pink lady
  3, orange

I wanted to extract information and organised like this:

obs, product_1, product_2, product_3
  1, apple, pink lady, grade 1
  2, apple, pink lady, NA,
  3, orange, NA, NA

I am new to programming and have tried to use sub(';.*$','',datasetname), which will return a new vector, for obs 1, I can get product 1 & 2 conbined Consequently, I will need to do another round to separate the new-formed strings. However, for obs 3 (without any special characters, colon or semicolon), the function will return the whole thing. In addition, I also need to consider some cases that the separator can be different, like "--", instead of colon and semicolon.

I am wondering how can I get what I want using sqldf, or other packages in R?

Body:
We can use base R to do this

df2 <- cbind(df1[1], read.csv(text=gsub('[:;-]+', ',', df1$product),
       header = FALSE, na.strings = "", col.names = paste0("product_", 1:3)))

df2
#   obs product_1 product_2 product_3
#1   1     apple pink lady   grade 1
#2   2     apple pink lady      <NA>
#3   3    orange      <NA>      <NA>


问:
React-router : how to pass "match" object into a component declared as an ES6 class?
I'am new to react-router (v4) and I was following the tutorial until this little problem :

This code works quite well

```<code>class App extends Component {
render() {
return (
    <Router>
       <div>
           <ul>
              <li><Link to="/link/value1" className="nav-link">Value1</Link></li>
              <li><Link to="/link/value2" className="nav-link">Value2</Link></li>
              <li><Link to="/link/value3" className="nav-link">Value3</Link></li>
         </ul>
         <hr/>
         <Route path="/link/:id" component={Generic}/>
       </div>
    </Router>
);
}
}
</code>```

I defined a route to /link/:id with 3 links to it. Then I declare my "Generic" component like this (as a function) :

```<code>const Generic = ({ match }) => (
<div className="wrapper">
    <div className="section">
        <div className="container">
            <h3>Menu : {match.params.id}</h3>
        </div>
    </div>
</div>
)
</code>```

This work as expected, no problem. But now, I'd like to declare my component with the ES6 class syntaxe like this :

```<code>class Generic extends React.Component {
constructor(props) {
    super(props);
}

render() {
    return (
        <div className="wrapper">
            <div className="section">
                <div className="container">
                    <h3>Menu : {this.props.params.id}</h3>
                </div>
            </div>
        </div>
    );
}
}
</code>```

And here I have an error : Cannot read property 'id' of undefined

How can I access the "match.params.id" properties using the ES6 class approach?

Thank you for your help.

答: Use {this.props.match.params.id}

Body:
I'am new to react-router (v4) and I was following the tutorial until this little problem :

This code works quite well

class App extends Component {
render() {
return (
    <Router>

<Link to="/link/value1" className="nav-link">Value1</Link>

<Link to="/link/value2" className="nav-link">Value2</Link>

<Link to="/link/value3" className="nav-link">Value3</Link>

         <Route path="/link/:id" component={Generic}/>

    </Router>
);
}
}

I defined a route to /link/:id with 3 links to it. Then I declare my "Generic" component like this (as a function) :

const Generic = ({ match }) => (

Menu : {match.params.id}

)

This work as expected, no problem. But now, I'd like to declare my component with the ES6 class syntaxe like this :

class Generic extends React.Component {
constructor(props) {
    super(props);
}

render() {
    return (

Menu : {this.props.params.id}

    );
}
}

And here I have an error : Cannot read property 'id' of undefined

How can I access the "match.params.id" properties using the ES6 class approach?

Thank you for your help.

Body: Use {this.props.match.params.id}


问:
<cfif> a value is in an array without looping?
This seems like it should be an easy one, but CF seems to have different ways of accomplishing the same thing when it comes to Arrays, so I want to be sure I'm doing it the best way;

I have a simple cfoutput;

```<code><cfoutput query="getusers">
Username: #username# ID:#fnid#
</cfoutput>
</code>```

I'm also using cfwebsocket elsewhere on the page, and the value of the 'fnid' (which is a session.auth variable) is part of the subscription.  A dump of wsGetSubscribers gives me the following;

What I'd like to do is during the output of the 'getusers' query, check to see if the FNID under subscriberinfo.fndid is there - the goal being to add a note to say that user is subscribed at that point.

I know I can do this using a cfloop, but that seems longwinded!

答:
What I'm trying to avoid is having to use cfloop (on the array) within the cfoutput query

So you want a kind of look-up for fnId? How about:

<cfset subscribersById = StructNew()>

<cfloop array="#wsGetSubscribers()#" index="subsciption">
  <cfset subscribersById[subsciption.subscriberInfo.fnId] = subsciption>
</cfloop>

<cfoutput query="getusers">
  Username: #username# ID: #fnid# Subscribed: #StructKeyExists(subscribersById, fnid)#
</cfoutput>
```

CF10+ has arrayEach() as well, if you prefer this syntax over the <cfloop>.

Body:
This seems like it should be an easy one, but CF seems to have different ways of accomplishing the same thing when it comes to Arrays, so I want to be sure I'm doing it the best way;

I have a simple cfoutput;

<cfoutput query="getusers">
Username: #username# ID:#fnid#
</cfoutput>

I'm also using cfwebsocket elsewhere on the page, and the value of the 'fnid' (which is a session.auth variable) is part of the subscription.  A dump of wsGetSubscribers gives me the following;

What I'd like to do is during the output of the 'getusers' query, check to see if the FNID under subscriberinfo.fndid is there - the goal being to add a note to say that user is subscribed at that point.

I know I can do this using a cfloop, but that seems longwinded!

Body:
What I'm trying to avoid is having to use cfloop (on the array) within the cfoutput query

So you want a kind of look-up for fnId? How about:

<cfset subscribersById = StructNew()>

<cfloop array="#wsGetSubscribers()#" index="subsciption">
  <cfset subscribersById[subsciption.subscriberInfo.fnId] = subsciption>
</cfloop>

<cfoutput query="getusers">
  Username: #username# ID: #fnid# Subscribed: #StructKeyExists(subscribersById, fnid)#
</cfoutput>

CF10+ has arrayEach() as well, if you prefer this syntax over the <cfloop>.


问:
Cannot explicitly call operator or accessor and static
I have two stupid questions :

The first one :

I have already asked this and I'm truly sorry to ask it again (even more so because there are a lot of posts about it), but now I really don't understand why that happens even if I read every other post, here is my code :

```<code>public class PageTitre {
    ...
    public void situation(string s) {
        onglet.get_Range("C11").Value = "(" + s + ")";
    }
}

public class PPE_Process {

    public static PageTitre pageTitre;

    public static void MainProcess() {
        ...
        pageTitre = new PageTitre();
        ...
    }
}

public partial class PPE_Ribbon {
    private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
    {
        PPE_Process.pageTitre.situation(SituationEditBox.Text);
    }
}
</code>```

I have tried some other things, like putting situation as a variable of PageTitre and having a get and a set, and

```<code>private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
    {
        PPE_Process.pageTitre.set_situation(SituationEditBox.Text);
    }
</code>```

Or

```<code>private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
    {
        PPE_Process.pageTitre.situation = SituationEditBox.Text;
    }
</code>```

But nothing worked, with the same error: cannot explicitly call operator or accessor.

I guess there is a problem with the static? If that is the case, here is my second question:

Second one :

I read a lot of documentation about it but I really can't understand what is the use of "static"... Is it just so that we can't change the value outside of the class, or something like this? Then, would it really change something if I take off every static there is in my code?

Again, I am sorry that you have to answer this question again and again, but I understand a lot better if that is directly related to my code, and not someone answering someone else about some other random code, which has a different problem than mine. :/

Edit to add more information:

There shouldn't be any problem with .Value or .get_Range, as it works on other parts of the code, but
For .Value, here is the information given by Visual Studio:

void Range.set_Value([object RangeValueDataType = System.Type.Missing], [object value = System.Type.Missing])

For .get_Range: Excel.Range_Worksheet.get_Range(object Cell1, [object Cell2 = System.Type.Missing])

For static, I still don't really understand all these "instances" things, but I will try to look more, and add another question in this forum if I still don't understand after this.

答:
Alrighty, I changed nothing in my code but now it works with

```<code>private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
    PPE_Process.pageTitre.situation = SituationEditBox.Text;
}
</code>```

So... I don't know, it was maybe a problem with the build of my solution, but that's pretty fortunate :)

Body:
I have two stupid questions :

The first one :

I have already asked this and I'm truly sorry to ask it again (even more so because there are a lot of posts about it), but now I really don't understand why that happens even if I read every other post, here is my code :

public class PageTitre {
    ...
    public void situation(string s) {
        onglet.get_Range("C11").Value = "(" + s + ")";
    }
}

public class PPE_Process {

    public static PageTitre pageTitre;

    public static void MainProcess() {
        ...
        pageTitre = new PageTitre();
        ...
    }
}

public partial class PPE_Ribbon {
    private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
    {
        PPE_Process.pageTitre.situation(SituationEditBox.Text);
    }
}

I have tried some other things, like putting situation as a variable of PageTitre and having a get and a set, and

private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
    {
        PPE_Process.pageTitre.set_situation(SituationEditBox.Text);
    }

Or

private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
    {
        PPE_Process.pageTitre.situation = SituationEditBox.Text;
    }

But nothing worked, with the same error: cannot explicitly call operator or accessor.

I guess there is a problem with the static? If that is the case, here is my second question:

Second one :

I read a lot of documentation about it but I really can't understand what is the use of "static"... Is it just so that we can't change the value outside of the class, or something like this? Then, would it really change something if I take off every static there is in my code?

Again, I am sorry that you have to answer this question again and again, but I understand a lot better if that is directly related to my code, and not someone answering someone else about some other random code, which has a different problem than mine. :/

Edit to add more information:

There shouldn't be any problem with .Value or .get_Range, as it works on other parts of the code, but
For .Value, here is the information given by Visual Studio:

void Range.set_Value([object RangeValueDataType = System.Type.Missing], [object value = System.Type.Missing])

For .get_Range: Excel.Range_Worksheet.get_Range(object Cell1, [object Cell2 = System.Type.Missing])

For static, I still don't really understand all these "instances" things, but I will try to look more, and add another question in this forum if I still don't understand after this.

Body:
Alrighty, I changed nothing in my code but now it works with

private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
    PPE_Process.pageTitre.situation = SituationEditBox.Text;
}

So... I don't know, it was maybe a problem with the build of my solution, but that's pretty fortunate :)


问:
Extracting decimal value from a number in imacros
I'm extracting data from this website

And using this code to get the number with decimal from the text, but it gives only the whole number not along with the decimal

```<code>TAG POS=1 TYPE=span ATTR=CLASS:proPriceField&&TXT:* EXTRACT=TXT
SET ProPrice EVAL("'{{!EXTRACT}}'.match(/[0-9,]+/);")
</code>```

This gives 14 instead of 14.1

Any suggestion what changes should be made to the code, so as o get the proper output.
Any help would be much appreciated.
Thanks

答:
The regex you're looking for is

```<code>\d+(?:(?:\.|,)\d+|)
</code>```

Take a look at this online test on Regex101

Instead of using [0-9], you can simply use \d to simplify your regex:

\d+ Matches one or more occurrences of digits

(?: Start of a non-capturing group (2x)

\. As the dot is a selector in regex, it must be escaped.

| The OR operator (to match or the literal dot, or a comma)

, Literal text (comma)

) End of the capturing group

\d+ Matches one or more occurrences of digits (the decimal part)

| The OR operator (to match or the decimal part, or the digit by itself (nothing))

) End of the capturing group

Body:
I'm extracting data from this website

And using this code to get the number with decimal from the text, but it gives only the whole number not along with the decimal

TAG POS=1 TYPE=span ATTR=CLASS:proPriceField&&TXT:* EXTRACT=TXT
SET ProPrice EVAL("'{{!EXTRACT}}'.match(/[0-9,]+/);")

This gives 14 instead of 14.1

Any suggestion what changes should be made to the code, so as o get the proper output.
Any help would be much appreciated.
Thanks

Body:
The regex you're looking for is

\d+(?:(?:\.|,)\d+|)

Take a look at this online test on Regex101

Instead of using [0-9], you can simply use \d to simplify your regex:

\d+ Matches one or more occurrences of digits

(?: Start of a non-capturing group (2x)

\. As the dot is a selector in regex, it must be escaped.

| The OR operator (to match or the literal dot, or a comma)

, Literal text (comma)

) End of the capturing group

\d+ Matches one or more occurrences of digits (the decimal part)

| The OR operator (to match or the decimal part, or the digit by itself (nothing))

) End of the capturing group


问:
How to extract the elements of an Array[String] in Scala?
Suppose we have an Array:

```<code>val arr = Array("Id:1; Apple; Red; 2; Out",
                "Id:2; Banana; Yellow; 5",
                "Id:3; Peach; Red; 3",
                "Id:4; Grape; Green; 5; Out")
</code>```

I want to apply a function on each element of the array, which extracts the fruit type and the number and returns a Map. The output in this case would be:

```<code>(Apple, 2)
(Banana, 5)
(Peach, 3)
(Grape, 5)
</code>```

I tried:

```<code>val pairMap = arr.foreach(r => r.split(";")(1) zip r.split(";")(3))
</code>```

but I always obtain Unit

答:
Close, but you should have used map instead of foreach.

Both these higher-order functions take a function and apply that to each element of the collection.

The difference between the two can be seen in the (simplified, not actual) signature:

```<code>trait Collection[A] {

  def map[B](f: A => B): Collection[B]

  def foreach(f: A => Unit): Unit

}
</code>```

The difference is that foreach is used to make some sort of action or side effect happen (e.g. printing), while mapping yields a collection whose elements are those of the starting collection with the function applied:

```<code>List(1, 2, 3, 4).map(_ * 2).forech(print) // prints 2468
</code>```

Furthermore, the function has to be edited a little bit in order to work as intended:

```<code>arr.map {
  row =>
    val split = row.split(";") // split only once
    (split(1).trim, split(3).trim) // no zipping necessary
}
</code>```

zip is not necessary because you are already processing each item, one at a time, while zip allows you to zip together two collection.

```<code>Seq(1, 2, 3) zip Seq('a', 'b', 'c') == Seq((1, 'a'), (2, 'b'), (3, 'c')) // true
</code>```

Body:
Suppose we have an Array:

val arr = Array("Id:1; Apple; Red; 2; Out",
                "Id:2; Banana; Yellow; 5",
                "Id:3; Peach; Red; 3",
                "Id:4; Grape; Green; 5; Out")

I want to apply a function on each element of the array, which extracts the fruit type and the number and returns a Map. The output in this case would be:

(Apple, 2)
(Banana, 5)
(Peach, 3)
(Grape, 5)

I tried:

val pairMap = arr.foreach(r => r.split(";")(1) zip r.split(";")(3))

but I always obtain Unit

Body:
Close, but you should have used map instead of foreach.

Both these higher-order functions take a function and apply that to each element of the collection.

The difference between the two can be seen in the (simplified, not actual) signature:

trait Collection[A] {

  def map[B](f: A => B): Collection[B]

  def foreach(f: A => Unit): Unit

}

The difference is that foreach is used to make some sort of action or side effect happen (e.g. printing), while mapping yields a collection whose elements are those of the starting collection with the function applied:

List(1, 2, 3, 4).map(_ * 2).forech(print) // prints 2468

Furthermore, the function has to be edited a little bit in order to work as intended:

arr.map {
  row =>
    val split = row.split(";") // split only once
    (split(1).trim, split(3).trim) // no zipping necessary
}

zip is not necessary because you are already processing each item, one at a time, while zip allows you to zip together two collection.

Seq(1, 2, 3) zip Seq('a', 'b', 'c') == Seq((1, 'a'), (2, 'b'), (3, 'c')) // true


问:
How to disable a button dynamically
I want to gray out a button dynamically. How to do that?</p>

答:
here id more sophisticated way (WPF way) is to bind Command to the Button.

```<code> <Button Name="button1" VerticalAlignment="Top" Width="94" Command="{Binding MyCommand}"
</code>```

in ViewModel which is bound to the view's dataContext:

```<code>public ICommand MyCommand
    {
        get
        {
           return  new DelegateCommand<string>(ExecuteSomething,IsExecutable);
        }
    }
</code>```

here is ExecuteSomething the method which will be executed by clicking your button
IsExecutable - perdicate while it returns false the Button will be disable

Title: How to disable a button dynamically

Body:
here id more sophisticated way (WPF way) is to bind Command to the Button.

 <Button Name="button1" VerticalAlignment="Top" Width="94" Command="{Binding MyCommand}"

in ViewModel which is bound to the view's dataContext:

public ICommand MyCommand
    {
        get
        {
           return  new DelegateCommand<string>(ExecuteSomething,IsExecutable);
        }
    }

here is ExecuteSomething the method which will be executed by clicking your button
IsExecutable - perdicate while it returns false the Button will be disable


问:
Searching for commands to replace a panel with another
I am making a graphic program with swing that involves placing various panels with components on the frame. One of them is a panel with buttons that, when an option in an options menu is chosen, is entirely replaced with a different one that has different buttons. We've been thinking and it seems that the best way to do this would be to, each time the option is selected, to rebuild the frame from scratch.

This is the snippet of code in which I'm building the main panels:

```<code>import java.awt.Color;
import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

import com.jtattoo.plaf.graphite.GraphiteLookAndFeel;
import com.nacher.calc.Main;
import com.nacher.calc.controller.Controller;

import net.miginfocom.swing.MigLayout;

/**
 *
 * @author chema && Sergio
 * This Panel contains buttons and textbox to perform the calculator actions
 */
public class PanelCalculator extends JPanel implements PropertyChangeListener {
    private static final long serialVersionUID = -8377215712645516042L;

    private PanelNumbers panelNumbers;
    private PanelScreen panelScreen;
    private PanelOptions panelOptions;
    private PanelScientific panelScientific;

    public Controller controller;

    public PanelCalculator(Controller controller) {
        this.controller = controller;

        //Initialize JTattoo Library
        try{
            UIManager.setLookAndFeel(new GraphiteLookAndFeel());
        }catch(UnsupportedLookAndFeelException ulafe){
            System.out.println("JTattoo Graphite failed to set");
        }
        this.setLayout(new MigLayout("wrap"));
        buildComponents();
        situateComponents();

        //controller = new Controller();
        controller.addPropertyChangeListener(panelScreen);//panelScreen escucha al controller
        panelOptions.addPropertyChangeListener(controller);//controller escucha al panelOptions
        panelNumbers.addPropertyChangeListener(controller);//controller escucha al panelNumbers
        panelScreen.addPropertyChangeListener(controller);//controller escucha al panelScreen
    }

    private void buildComponents(){
        this.setPreferredSize(new Dimension(210, 280));
        this.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelOptions = new PanelOptions();
        panelOptions.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelOptions.setPreferredSize(new Dimension(200, 50));

        panelScreen = new PanelScreen();
        panelScreen.setBorder(BorderFactory.createEtchedBorder());
        panelScreen.setPreferredSize(new Dimension(200, 40));
        panelScreen.setBackground(new Color(255, 255, 255));

        panelNumbers = new PanelNumbers();
        panelNumbers.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelNumbers.setPreferredSize(new Dimension(200, 185));

        panelOptions.addPropertyChangeListener(panelScreen);//panelScreen escucha al panelOptions
        panelNumbers.addPropertyChangeListener(panelScreen);//panelScreen escucha al panelNumbers
    }

    private void situateComponents(){
        this.add(panelOptions, "span");
        this.add(panelScreen, "span");
        this.add(panelNumbers, "span" );
    }

    /**
     * To build the Scientific Calculator
     */
    private void buildScientific() {
        //Instantiate the panelScientific
        panelScientific = new PanelScientific();
        panelScientific.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelScientific.setPreferredSize(new Dimension(200, 185));
        //Reordering the Panel Calculator
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        String c = evt.getPropertyName();
        if (c.equals(Constants.SET_CALC_SCIENTIFIC)) {
            System.out.println("Set the Scientific Calculator");
            buildScientific();
        }
    }

}
</code>```

And this is the main class where we build the frame:

```<code>import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import com.jtattoo.plaf.bernstein.BernsteinLookAndFeel;
import com.jtattoo.plaf.fast.FastLookAndFeel;
import com.jtattoo.plaf.graphite.GraphiteLookAndFeel;
import com.jtattoo.plaf.hifi.HiFiLookAndFeel;
import com.jtattoo.plaf.luna.LunaLookAndFeel;
import com.nacher.calc.controller.Controller;
import com.nacher.calc.ui.Constants;
import com.nacher.calc.ui.ImageConstants;
import com.nacher.calc.ui.PanelCalculator;

public class Main extends JFrame implements PropertyChangeListener {

    private static final long serialVersionUID = -4136829057174783241L;

    private static Main mySelf;
    private static PanelCalculator panelCalc;

    public static Controller controller;

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {

        controller = new Controller();
        panelCalc = new PanelCalculator(controller);
        controller.addPropertyChangeListener(panelCalc);
        mySelf = new Main();
        try {
            mySelf.setTitle("Calculator");
            mySelf.setLocationRelativeTo(null);
            mySelf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mySelf.setIconImage(new ImageIcon(mySelf.getClass().getResource(ImageConstants.CALC_IMAGE_THREE)).getImage());
            mySelf.getContentPane().add(panelCalc);
            mySelf.setResizable(false);
            mySelf.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e) {
                    System.out.println("Quitting the application.");
                }
            });
            mySelf.pack();
            mySelf.setVisible(true);
            controller.addPropertyChangeListener(mySelf);
        }catch(Exception ex) {
            System.out.println("The application could not run.");
            System.out.println(ex.getMessage());
            System.exit(-1);
        }
    }
</code>```

What commands should I use to 'unbuild' the frame, then rebuild it from scratch? Is there a more efficient way to replace one panel with another?

答:
I don't know if I totally get your problem, but if, that would be my solution (just a simple example):

```<code>public class Main extends JFrame{
    public Main(){
        setTitle("Calculator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        Panels panels = new Panels();
        add(panels, BorderLayout.CENTER);

        setLocationRelativeTo(null);
        pack();
        setVisible(true);
    }
}
</code>```

.

```<code>public class Panels extends JPanel{

    public JPanel p1, p2;

    public Panels(){
        p1 = new JPanel();
        add(p1);
        p2 = new JPanel();
        add(p2);
        //p1 and p2 might be more complex Components
        //place them using your preferred LayoutManager
        //(set their preferredSize etc.)
    }

    public void updateP1(JPanel np1){
        remove(p1);
        p1 = np1;
        add(p1);
    }

    public void updateP2(JPanel np2){
        remove(p2);
        p2 = np2;
        add(p2);
    }

}
</code>```

I think what you're looking for is the method remove(Component comp) of a JComponent, i.e. a JPanel. Hope that helps.

Body:
I am making a graphic program with swing that involves placing various panels with components on the frame. One of them is a panel with buttons that, when an option in an options menu is chosen, is entirely replaced with a different one that has different buttons. We've been thinking and it seems that the best way to do this would be to, each time the option is selected, to rebuild the frame from scratch.

This is the snippet of code in which I'm building the main panels:

import java.awt.Color;
import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

import com.jtattoo.plaf.graphite.GraphiteLookAndFeel;
import com.nacher.calc.Main;
import com.nacher.calc.controller.Controller;

import net.miginfocom.swing.MigLayout;

/**
 *
 * @author chema && Sergio
 * This Panel contains buttons and textbox to perform the calculator actions
 */
public class PanelCalculator extends JPanel implements PropertyChangeListener {
    private static final long serialVersionUID = -8377215712645516042L;

    private PanelNumbers panelNumbers;
    private PanelScreen panelScreen;
    private PanelOptions panelOptions;
    private PanelScientific panelScientific;

    public Controller controller;

    public PanelCalculator(Controller controller) {
        this.controller = controller;

        //Initialize JTattoo Library
        try{
            UIManager.setLookAndFeel(new GraphiteLookAndFeel());
        }catch(UnsupportedLookAndFeelException ulafe){
            System.out.println("JTattoo Graphite failed to set");
        }
        this.setLayout(new MigLayout("wrap"));
        buildComponents();
        situateComponents();

        //controller = new Controller();
        controller.addPropertyChangeListener(panelScreen);//panelScreen escucha al controller
        panelOptions.addPropertyChangeListener(controller);//controller escucha al panelOptions
        panelNumbers.addPropertyChangeListener(controller);//controller escucha al panelNumbers
        panelScreen.addPropertyChangeListener(controller);//controller escucha al panelScreen
    }

    private void buildComponents(){
        this.setPreferredSize(new Dimension(210, 280));
        this.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelOptions = new PanelOptions();
        panelOptions.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelOptions.setPreferredSize(new Dimension(200, 50));

        panelScreen = new PanelScreen();
        panelScreen.setBorder(BorderFactory.createEtchedBorder());
        panelScreen.setPreferredSize(new Dimension(200, 40));
        panelScreen.setBackground(new Color(255, 255, 255));

        panelNumbers = new PanelNumbers();
        panelNumbers.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelNumbers.setPreferredSize(new Dimension(200, 185));

        panelOptions.addPropertyChangeListener(panelScreen);//panelScreen escucha al panelOptions
        panelNumbers.addPropertyChangeListener(panelScreen);//panelScreen escucha al panelNumbers
    }

    private void situateComponents(){
        this.add(panelOptions, "span");
        this.add(panelScreen, "span");
        this.add(panelNumbers, "span" );
    }

    /**
     * To build the Scientific Calculator
     */
    private void buildScientific() {
        //Instantiate the panelScientific
        panelScientific = new PanelScientific();
        panelScientific.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelScientific.setPreferredSize(new Dimension(200, 185));
        //Reordering the Panel Calculator
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        String c = evt.getPropertyName();
        if (c.equals(Constants.SET_CALC_SCIENTIFIC)) {
            System.out.println("Set the Scientific Calculator");
            buildScientific();
        }
    }

}

And this is the main class where we build the frame:

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import com.jtattoo.plaf.bernstein.BernsteinLookAndFeel;
import com.jtattoo.plaf.fast.FastLookAndFeel;
import com.jtattoo.plaf.graphite.GraphiteLookAndFeel;
import com.jtattoo.plaf.hifi.HiFiLookAndFeel;
import com.jtattoo.plaf.luna.LunaLookAndFeel;
import com.nacher.calc.controller.Controller;
import com.nacher.calc.ui.Constants;
import com.nacher.calc.ui.ImageConstants;
import com.nacher.calc.ui.PanelCalculator;

public class Main extends JFrame implements PropertyChangeListener {

    private static final long serialVersionUID = -4136829057174783241L;

    private static Main mySelf;
    private static PanelCalculator panelCalc;

    public static Controller controller;

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {

        controller = new Controller();
        panelCalc = new PanelCalculator(controller);
        controller.addPropertyChangeListener(panelCalc);
        mySelf = new Main();
        try {
            mySelf.setTitle("Calculator");
            mySelf.setLocationRelativeTo(null);
            mySelf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mySelf.setIconImage(new ImageIcon(mySelf.getClass().getResource(ImageConstants.CALC_IMAGE_THREE)).getImage());
            mySelf.getContentPane().add(panelCalc);
            mySelf.setResizable(false);
            mySelf.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e) {
                    System.out.println("Quitting the application.");
                }
            });
            mySelf.pack();
            mySelf.setVisible(true);
            controller.addPropertyChangeListener(mySelf);
        }catch(Exception ex) {
            System.out.println("The application could not run.");
            System.out.println(ex.getMessage());
            System.exit(-1);
        }
    }

What commands should I use to 'unbuild' the frame, then rebuild it from scratch? Is there a more efficient way to replace one panel with another?

Body:
I don't know if I totally get your problem, but if, that would be my solution (just a simple example):

public class Main extends JFrame{
    public Main(){
        setTitle("Calculator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        Panels panels = new Panels();
        add(panels, BorderLayout.CENTER);

        setLocationRelativeTo(null);
        pack();
        setVisible(true);
    }
}

.

public class Panels extends JPanel{

    public JPanel p1, p2;

    public Panels(){
        p1 = new JPanel();
        add(p1);
        p2 = new JPanel();
        add(p2);
        //p1 and p2 might be more complex Components
        //place them using your preferred LayoutManager
        //(set their preferredSize etc.)
    }

    public void updateP1(JPanel np1){
        remove(p1);
        p1 = np1;
        add(p1);
    }

    public void updateP2(JPanel np2){
        remove(p2);
        p2 = np2;
        add(p2);
    }

}

I think what you're looking for is the method remove(Component comp) of a JComponent, i.e. a JPanel. Hope that helps.


问:
ES6 template literals inside jQuery $.each method
Is it possible to use ES6 template literals inside jQuery's $.each method?

Tried to do like this, without success:

```<code>let arr = this.arr;

  $.each($("g#texts").children(), function (i, contents) {
    $("#`${contents.id}` tspan")
        .text(arr.find(a => a.name == "`${contents.id}`")
        .displayedName);
  })
</code>```

What should be corrected here?

答:
It's certainly possible. The issue you have is because you've placed the template literal inside a string literal. The second template literal is also redundant. If you fix the syntax the code you have written will work fine:

$("g#texts").children().each(function (i, contents) {
  $(`#${contents.id} tspan`).text(arr.find(a => a.name == contents.id).displayedName);
});
```

Body:
Is it possible to use ES6 template literals inside jQuery's $.each method?

Tried to do like this, without success:

let arr = this.arr;

  $.each($("g#texts").children(), function (i, contents) {
    $("#`${contents.id}` tspan")
        .text(arr.find(a => a.name == "`${contents.id}`")
        .displayedName);
  })

What should be corrected here?


问:
Why is toggleClass not working here?
I'm trying to add / remove a class on click here, but toggleClass is not working as I'm expecting it to. On the contrary, addClass works fine, but I need it to remove the class on the second click.

```<code>$('.label1').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).toggleClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})

$('.label2').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).addClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})
</code>```

Can you tell me what am I doing wrong?

See it in action here: Test jquery.

Thanks!

答:
The checkbox is inside you label so when it gets clicked it is clicking the checkbox too.

```<code>  $('.label1, .label2').on('change', function() {
    $(this).toggleClass('checked');
  })
</code>```

https://codepen.io/ankurace/pen/OgoQLG

Title: Why is toggleClass not working here?

Body:
I'm trying to add / remove a class on click here, but toggleClass is not working as I'm expecting it to. On the contrary, addClass works fine, but I need it to remove the class on the second click.

$('.label1').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).toggleClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})

$('.label2').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).addClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})

Can you tell me what am I doing wrong?

See it in action here: Test jquery.

Thanks!

Body:
The checkbox is inside you label so when it gets clicked it is clicking the checkbox too.

  $('.label1, .label2').on('change', function() {
    $(this).toggleClass('checked');
  })

https://codepen.io/ankurace/pen/OgoQLG


问:
Returning a Python object instance of an inner class of a function
I wrote a function in Python that is supposed to work similar to a factory in Java, as it instances the correct class for the given parameters and returns this instance.

A minimal example with only one class inside the function would be this:

```<code>def create_object(param):

    class SpecialClass(ParentClass):
        def func(self, param):
            doSomething()

    class_instance = SpecialClass(param)
    return class_instance
</code>```

I can flawlessly use this object when I call this function from outside. Coming from a Java background, I assume this has something to do with the dynamic typing in Python but I'm still not sure why this actually works. Isn't the scope where that class is known just within the function itself?

答:
Excuse my terrible Java, but I can't see how your Python code is any different from this:

```<code>class NestedScope {
    public static void main(String[] args) {
      OuterClass oc = new OuterClass();
      oc.bar().foo();
    }
}

class OuterClass {
  class InnerClass {
    public void foo() {
        System.out.println("in here");
    }
  }
  public InnerClass bar() {
    return new InnerClass();
  }
}
</code>```

Here in the main class I reference the object of class InnerClass without that class ever being in scope, and I can successfully call its foo() method.

Body:
I wrote a function in Python that is supposed to work similar to a factory in Java, as it instances the correct class for the given parameters and returns this instance.

A minimal example with only one class inside the function would be this:

def create_object(param):

    class SpecialClass(ParentClass):
        def func(self, param):
            doSomething()

    class_instance = SpecialClass(param)
    return class_instance

I can flawlessly use this object when I call this function from outside. Coming from a Java background, I assume this has something to do with the dynamic typing in Python but I'm still not sure why this actually works. Isn't the scope where that class is known just within the function itself?

Body:
Excuse my terrible Java, but I can't see how your Python code is any different from this:

class NestedScope {
    public static void main(String[] args) {
      OuterClass oc = new OuterClass();
      oc.bar().foo();
    }
}

class OuterClass {
  class InnerClass {
    public void foo() {
        System.out.println("in here");
    }
  }
  public InnerClass bar() {
    return new InnerClass();
  }
}

Here in the main class I reference the object of class InnerClass without that class ever being in scope, and I can successfully call its foo() method.


问:
Incorrect output for UTF8 conversion using iconv
I am trying to convert string encoded in ISO-8859-1 to UTF-8 on Linux. I am using iconv function to do that in C++. This is the code that I have:

```<code>//Conversion from ISO-8859-1 to UTF-8
iconv_t cd = iconv_open("UTF-8","ISO-8859-1");

char *input = "€"; // the byte value is 128 in ISO-8859-1
char *inputbuf= input;
size_t inputSize=1;

char *output = (char*)malloc(inputSize*4); // maximum size of a character in UTF8 is 4
char *outputbuf = output;
size_t outputSize = inputSize*4;

//Conversion Function
iconv (cd, &inputbuf, &inputSize, &outputbuf, &outputSize);

//Display input bytes(ISO-8859-1)
cout << "input bytes(ISO-8859-1):"
for (int i=0; i<inputSize; i++)
{
    cout <<(int) *(input+i) << ", ";
}
cout<< std::endl;

//Display Converted bytes(UTF-8)
cout << "output bytes(UTF-8):"
for (int i=0; i<outputSize; i++) //displaying all the 4 bytes allocated
{
    cout <<(int) *(output+i) << ", ";
}
cout<< std::endl;
iconv(cd);
</code>```

This is the output I observe:

```<code>input bytes(ISO-8859-1): 128
output bytes(UTF-8): 194, 128, 0, 0
</code>```

As you can see, the output UTF-8 converted bytesis 194,128. However, the expected UTF-8 output is 226,130,172. I verified that there is no error thrown by any of the iconv functions.

Can anyone please help me figure out if I am missing anything here?

答:
This is a bug of iconv, as 0xc2 0x80 is a valid utf-8 sequence for the code point U+0080 glyph <control>.

This glyph is often mistaken for the glyph EURO SIGN, code point U+20AC encoded as 0xe2 0x82 0xac in UTF-8.

Body:
I am trying to convert string encoded in ISO-8859-1 to UTF-8 on Linux. I am using iconv function to do that in C++. This is the code that I have:

//Conversion from ISO-8859-1 to UTF-8
iconv_t cd = iconv_open("UTF-8","ISO-8859-1");

char *input = "€"; // the byte value is 128 in ISO-8859-1
char *inputbuf= input;
size_t inputSize=1;

char *output = (char*)malloc(inputSize*4); // maximum size of a character in UTF8 is 4
char *outputbuf = output;
size_t outputSize = inputSize*4;

//Conversion Function
iconv (cd, &inputbuf, &inputSize, &outputbuf, &outputSize);

//Display input bytes(ISO-8859-1)
cout << "input bytes(ISO-8859-1):"
for (int i=0; i<inputSize; i++)
{
    cout <<(int) *(input+i) << ", ";
}
cout<< std::endl;

//Display Converted bytes(UTF-8)
cout << "output bytes(UTF-8):"
for (int i=0; i<outputSize; i++) //displaying all the 4 bytes allocated
{
    cout <<(int) *(output+i) << ", ";
}
cout<< std::endl;
iconv(cd);

This is the output I observe:

input bytes(ISO-8859-1): 128
output bytes(UTF-8): 194, 128, 0, 0

As you can see, the output UTF-8 converted bytesis 194,128. However, the expected UTF-8 output is 226,130,172. I verified that there is no error thrown by any of the iconv functions.

Can anyone please help me figure out if I am missing anything here?


问:
Accessing to nested comments in a Symfony Blog
I'm working on a project which implements a public feed. I have a Comment entity which let's users to submit comments to each feed. However, I want users to be able to submit responses to the comments as well.

For that purpose I have $response property in my Comment entity. I assume that saving the response is same as with saving the comment since response is also a comment.

But, I'm not sure about how I can access to a comment without its id and save the response for that comment.

In my FeedController I save a comment like this;

```<code> $commentForm = $this->createForm(CommentType::class);
    $commentForm->handleRequest($request);
    if ($commentForm->isSubmitted() && $commentForm->isValid()) {
        $content = $commentForm->get('content')->getData();
        $feed_id = $feed;

        $comment= EntityBuilder::newComment($content, $user, $feed_id);

        $commentService->saveEntity($comment);

        if(!is_null($comment)){
            $this->addFlash(
                'commentsuccess',
                'Your reply was successfully posted!'
            );
        }

        return $this->redirect($this->generateUrl('showFeed', array('slug' => $feed->getSlug()), UrlGeneratorInterface::ABSOLUTE_URL));

    }
</code>```

Here is the Comment entity;

```<code>/**
* Class Comment
* @package AppBundle\Entity
* @ORM\Entity(repositoryClass="AppBundle\Repository\CommentRepository")
* @ORM\Table(name="comment")
* @ORM\HasLifecycleCallbacks()
*
*/
class Comment
{

/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Feed", inversedBy="comments")
 * @ORM\JoinColumn(name="feedid", referencedColumnName="id")
 */
private $feedid;

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="comments")
 * @ORM\JoinColumn(name="createdby", referencedColumnName="id")
 */
private $createdby;

/**
 * @ORM\Column(type="string")
 * @Assert\NotBlank(message="Please fill in the description")
 */
private $content;

/**
 * @ORM\OneToOne(targetEntity="Comment")
 */
protected $response;

/**
 * @ORM\Column(type="datetime")
 */
private $createdAt;

/**
 * @ORM\Column(type="datetime")
 */
private $updatedAt;

/**
 * Constructor
 */
public function __construct()
{
    $this->createdAt= new \DateTime();
    $this->updatedAt= new \DateTime();
}

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set content
 *
 * @param string $content
 *
 * @return Comment
 */
public function setContent($content)
{
    $this->content = $content;

    return $this;
}

/**
 * Get content
 *
 * @return string
 */
public function getContent()
{
    return $this->content;
}

/**
 * Set feedid
 *
 * @param \AppBundle\Entity\Feed $feedid
 *
 * @return Comment
 */
public function setFeedid(\AppBundle\Entity\Feed $feedid = null)
{
    $this->feedid = $feedid;

    return $this;
}

/**
 * Get feedid
 *
 * @return \AppBundle\Entity\Feed
 */
public function getFeedid()
{
    return $this->feedid;
}

/**
 * Set createdby
 *
 * @param \AppBundle\Entity\User $createdby
 *
 * @return Comment
 */
public function setCreatedby(\AppBundle\Entity\User $createdby = null)
{
    $this->createdby = $createdby;

    return $this;
}

/**
 * Get createdby
 *
 * @return \AppBundle\Entity\User
 */
public function getCreatedby()
{
    return $this->createdby;
}

/**
 * Set createdAt
 *
 * @param \DateTime $createdAt
 *
 * @return Comment
 */
public function setCreatedAt($createdAt)
{
    $this->createdAt = $createdAt;

    return $this;
}

/**
 * Get createdAt
 *
 * @return \DateTime
 */
public function getCreatedAt()
{
    return $this->createdAt;
}

/**
 * Set updatedAt
 *
 * @param \DateTime $updatedAt
 *
 * @return Comment
 */
public function setUpdatedAt($updatedAt)
{
    $this->updatedAt = $updatedAt;

    return $this;
}

/**
 * Get updatedAt
 *
 * @return \DateTime
 */
public function getUpdatedAt()
{
    return $this->updatedAt;
}

/**
 * Set response
 *
 * @param \AppBundle\Entity\Comment $response
 *
 * @return Comment
 */
public function setResponse(\AppBundle\Entity\Comment $response = null)
{
    $this->response = $response;

    return $this;
}

/**
 * Get response
 *
 * @return \AppBundle\Entity\Comment
 */
public function getResponse()
{
    return $this->response;
}
</code>```

}

Even if I create another form type for responses, I'm still not sure about how I can save a response for a specific comment.

答:
My recomendation is to implement a Parent/Children approach, adding a (ManyToOne) $parent field to the Comment entity and its inversed
(OneToMany) $children property. Later, you could add a CollectionType form field into CommentType for $children property, so you might need more than one response per comment.

Don't worry about parent id, the CollectionType does the work for you.
See more about how CollectionType works here.

Body:
I'm working on a project which implements a public feed. I have a Comment entity which let's users to submit comments to each feed. However, I want users to be able to submit responses to the comments as well.

For that purpose I have $response property in my Comment entity. I assume that saving the response is same as with saving the comment since response is also a comment.

But, I'm not sure about how I can access to a comment without its id and save the response for that comment.

In my FeedController I save a comment like this;

 $commentForm = $this->createForm(CommentType::class);
    $commentForm->handleRequest($request);
    if ($commentForm->isSubmitted() && $commentForm->isValid()) {
        $content = $commentForm->get('content')->getData();
        $feed_id = $feed;

        $comment= EntityBuilder::newComment($content, $user, $feed_id);

        $commentService->saveEntity($comment);

        if(!is_null($comment)){
            $this->addFlash(
                'commentsuccess',
                'Your reply was successfully posted!'
            );
        }

        return $this->redirect($this->generateUrl('showFeed', array('slug' => $feed->getSlug()), UrlGeneratorInterface::ABSOLUTE_URL));

    }

Here is the Comment entity;

/**
* Class Comment
* @package AppBundle\Entity
* @ORM\Entity(repositoryClass="AppBundle\Repository\CommentRepository")
* @ORM\Table(name="comment")
* @ORM\HasLifecycleCallbacks()
*
*/
class Comment
{

/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Feed", inversedBy="comments")
 * @ORM\JoinColumn(name="feedid", referencedColumnName="id")
 */
private $feedid;

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="comments")
 * @ORM\JoinColumn(name="createdby", referencedColumnName="id")
 */
private $createdby;

/**
 * @ORM\Column(type="string")
 * @Assert\NotBlank(message="Please fill in the description")
 */
private $content;

/**
 * @ORM\OneToOne(targetEntity="Comment")
 */
protected $response;

/**
 * @ORM\Column(type="datetime")
 */
private $createdAt;

/**
 * @ORM\Column(type="datetime")
 */
private $updatedAt;

/**
 * Constructor
 */
public function __construct()
{
    $this->createdAt= new \DateTime();
    $this->updatedAt= new \DateTime();
}

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set content
 *
 * @param string $content
 *
 * @return Comment
 */
public function setContent($content)
{
    $this->content = $content;

    return $this;
}

/**
 * Get content
 *
 * @return string
 */
public function getContent()
{
    return $this->content;
}

/**
 * Set feedid
 *
 * @param \AppBundle\Entity\Feed $feedid
 *
 * @return Comment
 */
public function setFeedid(\AppBundle\Entity\Feed $feedid = null)
{
    $this->feedid = $feedid;

    return $this;
}

/**
 * Get feedid
 *
 * @return \AppBundle\Entity\Feed
 */
public function getFeedid()
{
    return $this->feedid;
}

/**
 * Set createdby
 *
 * @param \AppBundle\Entity\User $createdby
 *
 * @return Comment
 */
public function setCreatedby(\AppBundle\Entity\User $createdby = null)
{
    $this->createdby = $createdby;

    return $this;
}

/**
 * Get createdby
 *
 * @return \AppBundle\Entity\User
 */
public function getCreatedby()
{
    return $this->createdby;
}

/**
 * Set createdAt
 *
 * @param \DateTime $createdAt
 *
 * @return Comment
 */
public function setCreatedAt($createdAt)
{
    $this->createdAt = $createdAt;

    return $this;
}

/**
 * Get createdAt
 *
 * @return \DateTime
 */
public function getCreatedAt()
{
    return $this->createdAt;
}

/**
 * Set updatedAt
 *
 * @param \DateTime $updatedAt
 *
 * @return Comment
 */
public function setUpdatedAt($updatedAt)
{
    $this->updatedAt = $updatedAt;

    return $this;
}

/**
 * Get updatedAt
 *
 * @return \DateTime
 */
public function getUpdatedAt()
{
    return $this->updatedAt;
}

/**
 * Set response
 *
 * @param \AppBundle\Entity\Comment $response
 *
 * @return Comment
 */
public function setResponse(\AppBundle\Entity\Comment $response = null)
{
    $this->response = $response;

    return $this;
}

/**
 * Get response
 *
 * @return \AppBundle\Entity\Comment
 */
public function getResponse()
{
    return $this->response;
}

}

Even if I create another form type for responses, I'm still not sure about how I can save a response for a specific comment.


问:
issue converting file to base 64bit javascript
I am trying to make a java script web resource for dynamics CRM that essentially lets a user chose a file to upload and then stores it onto the annotation entity. I know the general procedure to do this however it keeps uploading empty files. The data is not getting converted to base 64 using the base 64 function. I am having a hard time using the File reader function to convert the file uploaded into base 64. The dataURL variable keeps returning empty. Can someone help me convert the chosen file to base 64? this does not have to be dynamics specific I think its a general java script html problem. I think i am using the File reader function wrong.

Thank you

function uploadFile(event) {
    var input = event.target;
    var file = input.files[0];
    //var file = document.getElementById("myFile").files[0];

    var str;
    var reader = new FileReader();
    reader.onload = function() {
        var dataURL = reader.result;

        str = _arrayBufferToBase64(dataURL);
    };

    reader.readAsDataURL(input.files[0]);

    var id = window.parent.Xrm.Page.data.entity.getId();
    var nam = window.parent.Xrm.Page.data.entity.getEntityName();

    var entity = {};
    entity.Subject = "first new annotation3";
    entity.NoteText = "way to go you just made a new annotation";
    entity.DocumentBody = str;
    entity.FileName = file.name;
    entity.MimeType = file.type;
    entity.ObjectId = {
        Id: id,
        LogicalName: nam
    };

    SDK.REST.createRecord(entity, "Annotation", SucessCallback2, errorCallback2);
}

function _arrayBufferToBase64(buffer) { // Convert Array Buffer to Base 64 string
    var binary = '';
    var bytes = new Uint8Array(buffer);
    var len = bytes.byteLength;

    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><
input type = "file"
id = "myFile"
placeholder = "Choose File"
onchange = "uploadFile(event)" > </code>```

答:
i figured it out, for anyone else having a similar issue. It turns out that you cant take the data outside the onload function, you have to pass the data out to another function using a callback function. See below.

function uploadFile(event)
{
    var input  = event.target;
    var file = input.files[0];
    //var file = document.getElementById("myFile").files[0];
    var str;

    var reader = new FileReader();

    reader.onload = function(eve){
    var theResult = reader.result;
    str = _arrayBufferToBase64(theResult);
    AttachFileFunction(file.name,file.type,str);
};

reader.readAsArrayBuffer(file);
  ```

Body:
I am trying to make a java script web resource for dynamics CRM that essentially lets a user chose a file to upload and then stores it onto the annotation entity. I know the general procedure to do this however it keeps uploading empty files. The data is not getting converted to base 64 using the base 64 function. I am having a hard time using the File reader function to convert the file uploaded into base 64. The dataURL variable keeps returning empty. Can someone help me convert the chosen file to base 64? this does not have to be dynamics specific I think its a general java script html problem. I think i am using the File reader function wrong.

Thank you

function uploadFile(event) {
    var input = event.target;
    var file = input.files[0];
    //var file = document.getElementById("myFile").files[0];

    var str;
    var reader = new FileReader();
    reader.onload = function() {
        var dataURL = reader.result;

        str = _arrayBufferToBase64(dataURL);
    };

    reader.readAsDataURL(input.files[0]);

    var id = window.parent.Xrm.Page.data.entity.getId();
    var nam = window.parent.Xrm.Page.data.entity.getEntityName();

    var entity = {};
    entity.Subject = "first new annotation3";
    entity.NoteText = "way to go you just made a new annotation";
    entity.DocumentBody = str;
    entity.FileName = file.name;
    entity.MimeType = file.type;
    entity.ObjectId = {
        Id: id,
        LogicalName: nam
    };

    SDK.REST.createRecord(entity, "Annotation", SucessCallback2, errorCallback2);
}

function _arrayBufferToBase64(buffer) { // Convert Array Buffer to Base 64 string
    var binary = '';
    var bytes = new Uint8Array(buffer);
    var len = bytes.byteLength;

    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
}

<
input type = "file"
id = "myFile"
placeholder = "Choose File"
onchange = "uploadFile(event)" >


问:
How to ignore certain folders in HG?
I have my project folder - Project.  In Project I have other sub projects - SUBPROJECT1, SUBPROJECT2, SUBPROJECT3.

In each sub project I have folders, among which I have BIN and OBJ.  However, I want the latter to be ignored such that when I commit I don`t have the changes made to BIN and OBJ.  How can I do that?

答:
You'll need to edit your .hgignore file, and include the following lines:

```
glob:bin\
glob:obj\
```

You probably want at least these other things as well:

```
glob:*.user
glob:*.suo
glob:_ReSharper.*\
```

There's other examples out there of more complete .hgignore files.

Title: How to ignore certain folders in HG?

Body:
You'll need to edit your .hgignore file, and include the following lines:

glob:bin\
glob:obj\

You probably want at least these other things as well:

glob:*.user
glob:*.suo
glob:_ReSharper.*\

There's other examples out there of more complete .hgignore files.


问:
Add .js scripts in Angular 2 project
I am building a web app with Angular 2 framework and I want to use an external template (https://freehtml5.co/preview/?item=splash-free-html5-bootstrap-template-for-any-websites).

I need to run some scripts (jquery.min.js, bootstrap.js, ...) in my components template but if I put it into scripts tag don't work.

If I run scripts tag in index.html it works but when I browse to another page script are not reloaded.

How can I load the scripts without script tag in template??

index.html

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Angular2App</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <!-- Facebook and Twitter integration -->
  <meta property="og:title" content="" />
  <meta property="og:image" content="" />
  <meta property="og:url" content="" />
  <meta property="og:site_name" content="" />
  <meta property="og:description" content="" />
  <meta name="twitter:title" content="" />
  <meta name="twitter:image" content="" />
  <meta name="twitter:url" content="" />
  <meta name="twitter:card" content="" />

  <!--<link href="build/main.css" rel="stylesheet">-->
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700" rel="stylesheet">

  <!-- Animate.css -->
  <link rel="stylesheet" href="assets/css/animate.css">
  <!-- Icomoon Icon Fonts-->
  <link rel="stylesheet" href="assets/css/icomoon.css">
  <!-- Themify Icons-->
  <link rel="stylesheet" href="assets/css/themify-icons.css">
  <!-- Bootstrap  -->
  <link rel="stylesheet" href="assets/css/bootstrap.css">

  <!-- Magnific Popup -->
  <link rel="stylesheet" href="assets/css/magnific-popup.css">

  <!-- Owl Carousel  -->
  <link rel="stylesheet" href="assets/css/owl.carousel.min.css">
  <link rel="stylesheet" href="assets/css/owl.theme.default.min.css">

  <!-- Theme style  -->
  <link rel="stylesheet" href="assets/css/style.css">

  // SCRIPTS THAT I NEED TO LOAD
  <!-- Modernizr JS -->
  <script src="assets/js/modernizr-2.6.2.min.js"></script>
  <!-- FOR IE9 below -->
  <!--[if lt IE 9]>
    <script src="assets/js/respond.min.js"></script>
    <![endif]-->
  <!-- jQuery -->
  <script src="assets/js/jquery.min.js"></script>
  <!-- jQuery Easing -->
  <script src="assets/js/jquery.easing.1.3.js"></script>
  <!-- Bootstrap -->
  <script src="assets/js/bootstrap.min.js"></script>
  <!-- Waypoints -->
  <script src="assets/js/jquery.waypoints.min.js"></script>
  <!-- Carousel -->
  <script src="assets/js/owl.carousel.min.js"></script>
  <!-- countTo -->
  <script src="assets/js/jquery.countTo.js"></script>
  <!-- Magnific Popup -->
  <script src="assets/js/jquery.magnific-popup.min.js"></script>
  <script src="assets/js/magnific-popup-options.js"></script>
  <!-- Main -->
  <script src="assets/js/main.js"></script>
  // SCRIPTS THAT I NEED TO LOAD

</head>
<body>
  <app-root></app-root>
</body>
</html>
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { routing } from './app.routing.module';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}
</code>```

app.routing.module.ts

```<code>import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';

const routes: Routes = [
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: 'home',
        component: HomeComponent
    },
    {
        path: '',
        component: LoginComponent
    },
    {
        path: '**',
        component: LoginComponent
    }
];

export const routing = RouterModule.forRoot(routes);
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
}
</code>```

app.component.html

```<code><router-outlet></router-outlet>
</code>```

答:
If you're using the Angular CLI you can include .js files from your node_modules in your .angular-cli.json.

Right under the the styles array and above the environmentSource you should see the scripts array. I've included a little bit (I've truncated it) of the JSON as reference for you.

```<code>{
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "styles": [
        "styles.scss"
      ],
      "scripts": [
        "../node_modules/hammerjs/hammer.min.js"
      ],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ]
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Add .js scripts in Angular 2 project

Body:
I am building a web app with Angular 2 framework and I want to use an external template (https://freehtml5.co/preview/?item=splash-free-html5-bootstrap-template-for-any-websites).

I need to run some scripts (jquery.min.js, bootstrap.js, ...) in my components template but if I put it into scripts tag don't work.

If I run scripts tag in index.html it works but when I browse to another page script are not reloaded.

How can I load the scripts without script tag in template??

index.html

<!doctype html>

  <meta charset="utf-8">
  <title>Angular2App</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <meta property="og:title" content="" />
  <meta property="og:image" content="" />
  <meta property="og:url" content="" />
  <meta property="og:site_name" content="" />
  <meta property="og:description" content="" />
  <meta name="twitter:title" content="" />
  <meta name="twitter:image" content="" />
  <meta name="twitter:url" content="" />
  <meta name="twitter:card" content="" />

  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700" rel="stylesheet">

  <link rel="stylesheet" href="assets/css/animate.css">

  <link rel="stylesheet" href="assets/css/icomoon.css">

  <link rel="stylesheet" href="assets/css/themify-icons.css">

  <link rel="stylesheet" href="assets/css/bootstrap.css">

  <link rel="stylesheet" href="assets/css/magnific-popup.css">

  <link rel="stylesheet" href="assets/css/owl.carousel.min.css">
  <link rel="stylesheet" href="assets/css/owl.theme.default.min.css">

  <link rel="stylesheet" href="assets/css/style.css">

  // SCRIPTS THAT I NEED TO LOAD

  // SCRIPTS THAT I NEED TO LOAD

  <app-root></app-root>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { routing } from './app.routing.module';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

app.routing.module.ts

import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';

const routes: Routes = [
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: 'home',
        component: HomeComponent
    },
    {
        path: '',
        component: LoginComponent
    },
    {
        path: '**',
        component: LoginComponent
    }
];

export const routing = RouterModule.forRoot(routes);

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
}

app.component.html

<router-outlet></router-outlet>

Body:
If you're using the Angular CLI you can include .js files from your node_modules in your .angular-cli.json.

Right under the the styles array and above the environmentSource you should see the scripts array. I've included a little bit (I've truncated it) of the JSON as reference for you.

{
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "styles": [
        "styles.scss"
      ],
      "scripts": [
        "../node_modules/hammerjs/hammer.min.js"
      ],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ]
}