问:
What happens to a promise that's abandoned?
I have the following code defined in a view controller.

```<code>    _ = accountService.getAccount()

      .then { user -> Void in

         self.txtBxUser.text = user.username
         self.txtBxEmail.text = user.email
   }
</code>```

getAccount makes a REST API request.

If the user dismisses the view controller before the call has returned, what happens to the call back chain? Does it still run given that, I presume, it's still referenced?

答:
Should I be concerned about retain cycles? tl;dr: it’s safe to use
  self in promise handlers.

This is safe:

```<code>somePromise.then {
    self.doSomething()
}
</code>```

Provided somePromise resolves, the function passed to then will be
  released, thus specifying [weak self] is not necessary.

Specifying [unowned self] is likely dangerous.

You’re telling me not to worry about retain cycles?! No, it’s just
  that by default you are not going to cause retain cycles when using
  PromiseKit. But it is still possible, for example:

```<code>self.handler = {
    self.doSomething
    self.doSomethingElse }
somePromise.then(execute: self.handler)
</code>```

The closure we assign to
  handler strongly retains self. handler is strongly retained by self.
  It’s a typical retain cycle. Don’t write typical retain cycles!

Notably, this is not a retain cycle:

```<code> somePromise.then(execute: self.doSomething).then(execute: self.doSomethingElse)
</code>```

source

Body:
I have the following code defined in a view controller.

    _ = accountService.getAccount()

      .then { user -> Void in

         self.txtBxUser.text = user.username
         self.txtBxEmail.text = user.email
   }

getAccount makes a REST API request.

If the user dismisses the view controller before the call has returned, what happens to the call back chain? Does it still run given that, I presume, it's still referenced?

Body:
Should I be concerned about retain cycles? tl;dr: it’s safe to use
  self in promise handlers.

This is safe:

somePromise.then {
    self.doSomething()
}

Provided somePromise resolves, the function passed to then will be
  released, thus specifying [weak self] is not necessary.

Specifying [unowned self] is likely dangerous.

You’re telling me not to worry about retain cycles?! No, it’s just
  that by default you are not going to cause retain cycles when using
  PromiseKit. But it is still possible, for example:

self.handler = {
    self.doSomething
    self.doSomethingElse }
somePromise.then(execute: self.handler)

The closure we assign to
  handler strongly retains self. handler is strongly retained by self.
  It’s a typical retain cycle. Don’t write typical retain cycles!

Notably, this is not a retain cycle:

 somePromise.then(execute: self.doSomething).then(execute: self.doSomethingElse)

source


来源: stackexchange

问:
Modeling user account referring to different entities
I'm starting a new project which will act as an authorization/authentication server and a simple user management for certain type of users. A user can be a HelpDeskResponsible, GroupManager, Employee, Customer and more. All these groups members will be able to login with the same form on the web interface. Each model will contain different set of data describing them.

My problem is model design. I am pretty sure I need some User entity with all data necessary to login and read roles but I don't know how to associate rest of models with user account to easily fetch info about logged-in user. Another problem is users management - given user account is created I'd need to somehow link it to model of one of types I mentioned above.

Is my concept an over-engineering? Are there any solutions for such problem? Maybe I don't need multiple entities for different account types?

Thanks for any advice.

EDIT: Different permission levels are not the bigest problem here - I want to store different info about user depending on a role he belongs to. Customer will have different dataset than Employee. I'm pretty sure they are different models but I want to save an ability to login with the same login form.

答:
Since your additional entities extend User entity with other additional data, I would probably use Class Table Inheritance.

Class Table Inheritance is an inheritance mapping strategy where each
  class in a hierarchy is mapped to several tables: its own table and
  the tables of all parent classes. The table of a child class is linked
  to the table of a parent class through a foreign key constraint.
  Doctrine 2 implements this strategy through the use of a discriminator
  column in the topmost table of the hierarchy because this is the
  easiest way to achieve polymorphic queries with Class Table
  Inheritance.

This way, you will have a base table User with base data (username, password, email, etc.) and then another table for each additional entity which extends User with additional data (e.g. column salary on table Employee).

Define the parent entity

Here we're telling to Doctrine that User is our base class. Then Doctrine use a discriminator column to identify which entity your user belongs to. Of course you need to map all entities you want to extend from User (here I add only Employee).

```<code>/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 * @ORM\Table(name="user")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"user" = "User", "employee" = "Employee"})
 */
class User {
    // your class..
}
</code>```

Define the child entity

```<code>/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\EmployeeRepository")
 * @ORM\Table(name="employee")
 */
class Employee extends User {

    /**
     * @ORM\Column(name="salary", type="float")
     */
    private $salary;

    public function setSalary($salary)
    {
        $this->salary = $salary;
        return $this;
    }

    public function getSalary()
    {
        return $this->salary;
    }

}
</code>```

Of course Employee class can override parent methods (e.g. getRoles() if you implement UserInterface into User).

Finally (backup your DB and) update your DB schema with php bin/console doctrine:schema:update --force. Doctrine will create the new table with defined data plus a column id which refer to relative User.

So when a normal user logs in, Symfony will load User entity while when an employee logs in, it will load Employee entity.

ContentLicense: CC BY-SA 3.0

Body:
Since your additional entities extend User entity with other additional data, I would probably use Class Table Inheritance.

Class Table Inheritance is an inheritance mapping strategy where each
  class in a hierarchy is mapped to several tables: its own table and
  the tables of all parent classes. The table of a child class is linked
  to the table of a parent class through a foreign key constraint.
  Doctrine 2 implements this strategy through the use of a discriminator
  column in the topmost table of the hierarchy because this is the
  easiest way to achieve polymorphic queries with Class Table
  Inheritance.

This way, you will have a base table User with base data (username, password, email, etc.) and then another table for each additional entity which extends User with additional data (e.g. column salary on table Employee).

Define the parent entity

Here we're telling to Doctrine that User is our base class. Then Doctrine use a discriminator column to identify which entity your user belongs to. Of course you need to map all entities you want to extend from User (here I add only Employee).

/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 * @ORM\Table(name="user")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"user" = "User", "employee" = "Employee"})
 */
class User {
    // your class..
}

Define the child entity

/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\EmployeeRepository")
 * @ORM\Table(name="employee")
 */
class Employee extends User {

    /**
     * @ORM\Column(name="salary", type="float")
     */
    private $salary;

    public function setSalary($salary)
    {
        $this->salary = $salary;
        return $this;
    }

    public function getSalary()
    {
        return $this->salary;
    }

}

Of course Employee class can override parent methods (e.g. getRoles() if you implement UserInterface into User).

Finally (backup your DB and) update your DB schema with php bin/console doctrine:schema:update --force. Doctrine will create the new table with defined data plus a column id which refer to relative User.

So when a normal user logs in, Symfony will load User entity while when an employee logs in, it will load Employee entity.


问:
Uncaught RangeError after adding on change function
My JS code was doing great until i added the following function :

```<code>   $(".meassure-combo").change(function() {
 switch ($(this).attr("name")) {
   case "bust-combo":
   case "shou-combo":
   case "wais-combo":
   case "hips-combo":
   case "imse-combo":
   $("[rel='"+$(this).attr("name")+"']").val( $(this).val() ).change();
   break;
 }
 switch ($(this).attr("rel")) {
   case "bust-combo":
   case "shou-combo":
   case "wais-combo":
   case "hips-combo":
   case "imse-combo":
    var type = $(this).attr("rel");
    var val = $(this).val();
   $("[name='"+type+"']").val(val).change();
    CL3D.interpolation(type,val);
   break;
 }
   });
</code>```

after adding this code i started getting the following error in console

Uncaught RangeError: Maximum call stack size exceeded
    at RegExp.test ()

what is the problem and how can i solve it ?

thank you in advance

答: .change() is called within change event handler. If $("[rel='"+$(this).attr("name")+"']") or $("[name='"+type+"']") also have .className "meassure-combo" then result would be Uncaught RangeError.

Body:
My JS code was doing great until i added the following function :

   $(".meassure-combo").change(function() {
 switch ($(this).attr("name")) {
   case "bust-combo":
   case "shou-combo":
   case "wais-combo":
   case "hips-combo":
   case "imse-combo":
   $("[rel='"+$(this).attr("name")+"']").val( $(this).val() ).change();
   break;
 }
 switch ($(this).attr("rel")) {
   case "bust-combo":
   case "shou-combo":
   case "wais-combo":
   case "hips-combo":
   case "imse-combo":
    var type = $(this).attr("rel");
    var val = $(this).val();
   $("[name='"+type+"']").val(val).change();
    CL3D.interpolation(type,val);
   break;
 }
   });

after adding this code i started getting the following error in console

Uncaught RangeError: Maximum call stack size exceeded
    at RegExp.test ()

what is the problem and how can i solve it ?

thank you in advance


问:
Implementing Generic Repository Pattern - entity key type
I'm implementing a repository pattern in Asp.Net web api application.

```<code>public abstract class Repository<T> : IRepository<T> where T : EntityBase
 {
     private DbContext context_;

     public Repository(DbContext context)
     {
         context_ = context;
     }

     public virtual async Task<T> GetAsync(int id)
     {
         return await context_.Set<T>().FindAsync(id);
     }

     ...

 }
</code>```

Problem:

Here I have a method GetAsync(int id), which will work for entity which has a single key with int type.

But there are some entity with key of string type and some entities with composite keys.

Question:

How can I overcome this issue?

Is it possible to overcome the issue in a generic way?

答:
You can notice that FindAsync accepts array of objects as a parameter, so you can change your GetAsync like this:

```<code>public virtual Task<T> GetAsync(params object[] keys)
{
     return context_.Set<T>().FindAsync(keys);
}
</code>```

Then you are able to call GetAsync with any keys you like, for example:

```<code>GetAsync(1);
GetAsync("string key");
GetAsync(1, "composite key");
</code>```

Side note: entity framework Set<T> is already generic repository, so adding another repository over that one does not really add much benefits.

Body:
I'm implementing a repository pattern in Asp.Net web api application.

public abstract class Repository<T> : IRepository<T> where T : EntityBase
 {
     private DbContext context_;

     public Repository(DbContext context)
     {
         context_ = context;
     }

     public virtual async Task<T> GetAsync(int id)
     {
         return await context_.Set<T>().FindAsync(id);
     }

     ...

 }

Problem:

Here I have a method GetAsync(int id), which will work for entity which has a single key with int type.

But there are some entity with key of string type and some entities with composite keys.

Question:

How can I overcome this issue?

Is it possible to overcome the issue in a generic way?

Body:
You can notice that FindAsync accepts array of objects as a parameter, so you can change your GetAsync like this:

public virtual Task<T> GetAsync(params object[] keys)
{
     return context_.Set<T>().FindAsync(keys);
}

Then you are able to call GetAsync with any keys you like, for example:

GetAsync(1);
GetAsync("string key");
GetAsync(1, "composite key");

Side note: entity framework Set<T> is already generic repository, so adding another repository over that one does not really add much benefits.


问:
How I can generate all combinations from RegEx (regular expression)?
For example, I have the following regular expression:

60[FP]LP[FP]XXXXXX

And now need all possible combinations, in this case:

60FLPFXXXXXX

60FLPPXXXXXX

60PLPFXXXXXX

60PLPPXXXXXX

Input RegEx is 12 characters long and consists of uppercase letters [A-Z] and numbers [0-9]

答:
A regular expression patterns defines a set of strings, so it's theoretically possible to use it to generate the list of strings in the set, but they aren't meant to do that. I'm not sure if someone's written a module to do that.

A glob, on the other hand, is designed to do exactly what you want. Could you use a glob instead?

```<code>say while glob('60{F,P}LP{F,P}XXXXXX');
</code>```

Body:
A regular expression patterns defines a set of strings, so it's theoretically possible to use it to generate the list of strings in the set, but they aren't meant to do that. I'm not sure if someone's written a module to do that.

A glob, on the other hand, is designed to do exactly what you want. Could you use a glob instead?

say while glob('60{F,P}LP{F,P}XXXXXX');


问:
Calc in calc not working in safari
I'm using SCSS & some calc fonction to do a very good responsive design for my website.

I have this calc in my file :

```<code>height: calc(#{75vh} - #{$header-height});
</code>```

In chrome is working perfectly, my image take the correct size, but in safari the generated css do no work.

Here the generated css :

```<code>height: calc(75vh - calc(110px));
</code>```

If you have an idea...

答:
Your nested calc() is unnecessary. Works fine if you remove that.

```<code>height: calc(75vh - 110px);
</code>```

html,body {
  height: 100vh;
}
div {
  background: red;
  height: calc(75vh - 110px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Title: Calc in calc not working in safari

Body:
I'm using SCSS & some calc fonction to do a very good responsive design for my website.

I have this calc in my file :

height: calc(#{75vh} - #{$header-height});

In chrome is working perfectly, my image take the correct size, but in safari the generated css do no work.

Here the generated css :

height: calc(75vh - calc(110px));

If you have an idea...

Body:
Your nested calc() is unnecessary. Works fine if you remove that.

height: calc(75vh - 110px);

html,body {
  height: 100vh;
}
div {
  background: red;
  height: calc(75vh - 110px);
}

<div></div>


问:
Given a rectangular MATRIX(MxN) of integers, already charged, calculate how many are symmetric elements with respect to the vertical axis
i don't know what's wrong with my code  ..
if the MATRIX is formed by (2x4) and
i give in input :

```<code>(0x0):1
(0x1):2
(0x2):2
(0x3):1
(1x0):7
(1x1):4
(1x2):5
(1x3):7
</code>```

symmetric elements should be :3 if im not wrong , but my code prints 0 elements

here's my code

```<code> int elementiSimmetrici(int colonne <--(MAXcolumns OF matrix(matrixIS FORMED BY THIS COLUMNS) ,int matrix[][colonne]<--(matrix ),int righe <-//matrix IS FORMED BY THIS ROWS)
{
    int r <--(row),c <--(columns),elementisimm=0 <--elements counter;
    colonne/=2; //columns/2 because i have to compare only first with last
    for(r=0;r<righe;r++){//for row<Maxrow's of matrix
        for(c=0;c<colonne;c++){ //for columns <maxcolums of matrix
            if ( matrix[r][c] == matrix[r][colonne-1-c] //i think you can understand this ){

              elementisimm++; //increase  COUNTER

            }

        }

    }

    return elementisimm;

}
</code>```

答:
You divide colonne by 2. That's fine for the loop condition but not for the comparison. This should work:

```<code>  // Don't do this: colonne/=2;
  for(c = 0; c < colonne / 2; c++){
      if ( vettore[r][c] == vettore[r][colonne-1-c] ){
          elementisimm++;
      }
  }
</code>```

Body:
i don't know what's wrong with my code  ..
if the MATRIX is formed by (2x4) and
i give in input :

(0x0):1
(0x1):2
(0x2):2
(0x3):1
(1x0):7
(1x1):4
(1x2):5
(1x3):7

symmetric elements should be :3 if im not wrong , but my code prints 0 elements

here's my code

 int elementiSimmetrici(int colonne <--(MAXcolumns OF matrix(matrixIS FORMED BY THIS COLUMNS) ,int matrix[][colonne]<--(matrix ),int righe <-//matrix IS FORMED BY THIS ROWS)
{
    int r <--(row),c <--(columns),elementisimm=0 <--elements counter;
    colonne/=2; //columns/2 because i have to compare only first with last
    for(r=0;r<righe;r++){//for row<Maxrow's of matrix
        for(c=0;c<colonne;c++){ //for columns <maxcolums of matrix
            if ( matrix[r][c] == matrix[r][colonne-1-c] //i think you can understand this ){

              elementisimm++; //increase  COUNTER

            }

        }

    }

    return elementisimm;

}

Body:
You divide colonne by 2. That's fine for the loop condition but not for the comparison. This should work:

  // Don't do this: colonne/=2;
  for(c = 0; c < colonne / 2; c++){
      if ( vettore[r][c] == vettore[r][colonne-1-c] ){
          elementisimm++;
      }
  }


问:
Does datatable filter results from database or just from the fetched result?
I am working on the datatables integration in php and mysql and I am confuse about that when I filter the data would it be filter from database or just from the data on the client side?</p>

答: Using AJAX request to method which will send query to your database with condition and getting limited number of results is probably the best way. Ajax response will be in around 300ms-500ms.</p>


问:
How can I read an array of doubles with mmap from text file
I tried this:

```<code>double *mat = (double *) mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
</code>```

where sb.st_size is the size of the file and fd is the descriptor of the opened file.
If I want to iterate through all the elements I get only 0s, but the file has only non 0 values. What is wrong with this?

答:
You cannot.

If you truly have a text file, then you have text numbers, almost like a spreadsheet:

```<code>1.0 2.0 3.0
1.1 2.1 3.1
</code>```

You cannot mmap that file and treat the mapped memory as double*, because that is character data.

In order to convert the file from character data to doubles, you will have to do something like fscanf or scanf to process the digits.

On the other hand, if you wrote out a blob of doubles as binary data, then you could do the mmap, pretty much as you describe.

Body:
I tried this:

double *mat = (double *) mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);

where sb.st_size is the size of the file and fd is the descriptor of the opened file.
If I want to iterate through all the elements I get only 0s, but the file has only non 0 values. What is wrong with this?

Body:
You cannot.

If you truly have a text file, then you have text numbers, almost like a spreadsheet:

1.0 2.0 3.0
1.1 2.1 3.1

You cannot mmap that file and treat the mapped memory as double*, because that is character data.

In order to convert the file from character data to doubles, you will have to do something like fscanf or scanf to process the digits.

On the other hand, if you wrote out a blob of doubles as binary data, then you could do the mmap, pretty much as you describe.


问:
Using Aggregate Function in sql
Why this query is not working:-

```<code>SELECT b.byhub,
       Count(awbno)
FROM   (SELECT awbno,
               byhub,
               entrydatetime,
               Max(entrydatetime)
        FROM   wbbooking
        GROUP  BY awbno,
                  byhub,
                  entrydatetime) B
       INNER JOIN (SELECT refno,
                          Max(entrydatetime)
                   FROM   wbmmreceiving
                   GROUP  BY refno) R
               ON B.awbno = R.refno
WHERE  CONVERT(DATE, b.entrydatetime) BETWEEN '2016-10-13' AND '2016-10-13'
GROUP  BY b.byhub
</code>```

After Execute this query I have obtain this type of Error:-

```<code>Msg 8155, Level 16, State 2, Line 2
No column name was specified for column 4 of 'b'.
Msg 8155, Level 16, State 2, Line 3
No column name was specified for column 2 of 'r'.
</code>```

答:
The errors occur, because you have not specified a name for the aggregate column Max(entrydatetime). Change it to Max(entrydatetime) AS max_entrydatetime.

This query is a bit strange. The subquery B selects entrydatetime as well as Max(entrydatetime). But since entrydatetime is included in the group by list, Max(entrydatetime) will always be the same as entrydattetime.

If you want the last entrydatetime per awbno and byhub, then don't group by entrydatetime and only include it as Max(entrydatetime) in the select list. If you really want to group by this date column, then don't include it as Max(entrydatetime).

What is the purpose of the second subquery? None of its returned columns are used except for joining. Is it needed for the count?

Why include a where-clause in the outer query? If you include it in the first subquery, it is more efficient and the entrydatetime column needs not to be returned any more.

Title: Using Aggregate Function in sql

Body:
Why this query is not working:-

SELECT b.byhub,
       Count(awbno)
FROM   (SELECT awbno,
               byhub,
               entrydatetime,
               Max(entrydatetime)
        FROM   wbbooking
        GROUP  BY awbno,
                  byhub,
                  entrydatetime) B
       INNER JOIN (SELECT refno,
                          Max(entrydatetime)
                   FROM   wbmmreceiving
                   GROUP  BY refno) R
               ON B.awbno = R.refno
WHERE  CONVERT(DATE, b.entrydatetime) BETWEEN '2016-10-13' AND '2016-10-13'
GROUP  BY b.byhub

After Execute this query I have obtain this type of Error:-

Msg 8155, Level 16, State 2, Line 2
No column name was specified for column 4 of 'b'.
Msg 8155, Level 16, State 2, Line 3
No column name was specified for column 2 of 'r'.


问:
Tutorial about Writing a JNDI Service Provider
Is there any tutorial about Writing a JNDI Service Provider and accessing the objects and methods from another project to it step by step. There are some information on Building a service provider but it is not easy to implement.

Thanks.

答:
Now I solved my problem with annotations and global usage of InitialContext class.
Stateless annotation and ejb-jar xml files and accessing the global jndi addresses the keys for usage.

Access Code:

```<code>this.jndiAddress="ejb/service/IMyInterface";
Context context = new InitialContext();
IMyInterface object = (IMyInterface) context.lookup(this.jndiAddress);
object.doSomething();
</code>```

Service Code;

IMyInterface.java:

```<code>public interface IMyInterface {

    void doSomething();

}
</code>```

MyClass.java:

```<code>@Remote(IMyInterface.class)
@Stateless(mappedName="ejb/service/IMyInterface")
public class MyClass implements IMyInterface {

    @EJB
    private IMyUserDao userDao;

    @Override
    public void doSomething() {
        User user = userDao.get(1);
        System.out.println(user.getName());
    }

}
</code>```

ejb-jar.xml;

```<code><?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:ejb="http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" version="3.0">
    <display-name>Service</display-name>
    <enterprise-beans>
        <session>
            <ejb-name>MyClass</ejb-name>
            <ejb-class>package.MyClass</ejb-class>
        </session>
        <session>
            <ejb-name>UserDao</ejb-name>
            <ejb-class>package.dao.UserDao</ejb-class>
        </session>
    </enterprise-beans>
</ejb-jar>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Now I solved my problem with annotations and global usage of InitialContext class.
Stateless annotation and ejb-jar xml files and accessing the global jndi addresses the keys for usage.

Access Code:

this.jndiAddress="ejb/service/IMyInterface";
Context context = new InitialContext();
IMyInterface object = (IMyInterface) context.lookup(this.jndiAddress);
object.doSomething();

Service Code;

IMyInterface.java:

public interface IMyInterface {

    void doSomething();

}

MyClass.java:

@Remote(IMyInterface.class)
@Stateless(mappedName="ejb/service/IMyInterface")
public class MyClass implements IMyInterface {

    @EJB
    private IMyUserDao userDao;

    @Override
    public void doSomething() {
        User user = userDao.get(1);
        System.out.println(user.getName());
    }

}

ejb-jar.xml;

<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:ejb="http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" version="3.0">
    <display-name>Service</display-name>
    <enterprise-beans>
        <session>
            <ejb-name>MyClass</ejb-name>
            <ejb-class>package.MyClass</ejb-class>
        </session>
        <session>
            <ejb-name>UserDao</ejb-name>
            <ejb-class>package.dao.UserDao</ejb-class>
        </session>
    </enterprise-beans>
</ejb-jar>


问:
What is perl's equivalent one liner of grep -o
My question is simple as my title says "What is perl's equivalent one liner of grep -o?". That is print the matched regex only instead of whole line?</p>

```<code>perl -pe some_option?? 'm/regex/' file
</code>```

答:
If you want to do the minimal amount of work, change

```<code>grep -o -P 'PATTERN' file
</code>```

to

```<code>perl -nle'print $& if m{PATTERN}' file
</code>```

So from

```<code>grep -o -P '(?<=foo)bar(?=baz)' file
</code>```

you get:

```<code>perl -nle'print $& if m{(?<=foo)bar(?=baz)}' file
</code>```

However, it can be simpler to use a capture.

```<code>perl -nle'print $1 if /foo(bar)baz/' file
</code>```

Body:
My question is simple as my title says "What is perl's equivalent one liner of grep -o?". That is print the matched regex only instead of whole line?

perl -pe some_option?? 'm/regex/' file

Body:
If you want to do the minimal amount of work, change

grep -o -P 'PATTERN' file

to

perl -nle'print $& if m{PATTERN}' file

So from

grep -o -P '(?<=foo)bar(?=baz)' file

you get:

perl -nle'print $& if m{(?<=foo)bar(?=baz)}' file

However, it can be simpler to use a capture.

perl -nle'print $1 if /foo(bar)baz/' file


问:
Python 3.6.1 why don't I receive UDP packets
I have a server where I have a script which sends UDP packets to my ip address and I have a client script on my PC that receives UDP packets.

```<code>#python3.6.1

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('myip', 49999))

data, address = sock.recvfrom(100)
print('Received {}'.format(data.decode('ascii')))
</code>```

On the server side my scripts connects to ('myip', 49999) and starts sending packets.
I took my ip from ip4.me i tried to bind my socket to '0.0.0.0' too and i tried other ports nothing seems to work.

答:
If that is the server script, i guess it should have a while loop in it:

while True:
    data, address = sock.recvfrom(100)
    print('Received {}'.format(data.decode('ascii')))

Body:
I have a server where I have a script which sends UDP packets to my ip address and I have a client script on my PC that receives UDP packets.

#python3.6.1

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('myip', 49999))

data, address = sock.recvfrom(100)
print('Received {}'.format(data.decode('ascii')))

On the server side my scripts connects to ('myip', 49999) and starts sending packets.
I took my ip from ip4.me i tried to bind my socket to '0.0.0.0' too and i tried other ports nothing seems to work.


问:
Generating multiplication questions in Java
The code should output a table for Farenheit and Celsius</p>

```<code>public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |",          temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int)sum );
            System.out.println();
</code>```

答:
There's a few errors in your code but instead of giving you the entire solution to your homework problem I suggest you start with the simple case of reading input until the user enters 'n':

```<code>    String input = "";
    Scanner scanner = new Scanner(System. in);

    while (!input.equals("n")) {
        System.out.println("continue y/n?");
        input = scanner.nextLine();
    }
</code>```

Add the generation of random ints, checking of answers etc inside the while loop body. Make sure to use equals instead of == when comparing two Strings

Body:
The code should output a table for Farenheit and Celsius

public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |",          temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int)sum );
            System.out.println();

Body:
There's a few errors in your code but instead of giving you the entire solution to your homework problem I suggest you start with the simple case of reading input until the user enters 'n':

    String input = "";
    Scanner scanner = new Scanner(System. in);

    while (!input.equals("n")) {
        System.out.println("continue y/n?");
        input = scanner.nextLine();
    }

Add the generation of random ints, checking of answers etc inside the while loop body. Make sure to use equals instead of == when comparing two Strings


问:
socket connect() being mistaken for QT connect()
I'm trying to create a socket connection from my QT application to a server(regular socket, not a QTcpSocket), to receive data from the server.
The problem is, the connect method, upon compilation, gives an error, and points me in the direction of the QT connect method for connecting signals to slots.
How do I tell the compiler to ignore the signal and slot function of QT and find the original socket.h connect function instead?

答:
You should write

```<code>::connect(...);
</code>```

To use the proper function. This ensures that resolution occurs from the global namespace.

Body:
You should write

::connect(...);

To use the proper function. This ensures that resolution occurs from the global namespace.


问:
Updating an AWS ECS Service
I have a service running on AWS EC2 Container Service (ECS). My setup is a relatively simple one. It operates with a single task definition and the following details:

Desired capacity set at 2

Minimum healthy set at 50%

Maximum available set at 200%

Tasks run with 80% CPU and memory reservations

Initially, I am able to get the necessary EC2 instances registered to the cluster that holds the service without a problem. The associated task then starts running on the two instances. As expected – given the CPU and memory reservations – the tasks take up almost the entirety of the EC2 instances' resources.

Sometimes, I want the task to use a new version of the application it is running. In order to make this happen, I create a revision of the task, de-register the previous revision, and then update the service. Note that I have set the minimum healthy percentage to require 2 * 0.50 = 1 instance running at all times and the maximum healthy percentage to permit up to 2 * 2.00 = 4 instances running.

Accordingly, I expected 1 of the de-registered task instances to be drained and taken offline so that 1 instance of the new revision of the task could be brought online. Then the process would repeat itself, bringing the deployment to a successful state.

Unfortunately, the cluster does nothing. In the events log, it tells me that it cannot place the new tasks, even though the process I have described above would permit it to do so.

How can I get the cluster to perform the behavior that I am expecting? I have only been able to get it to do so when I manually register another EC2 instance to the cluster and then tear it down after the update is complete (which is not desirable).

答:
I have faced the same issue where the tasks used to get stuck and had no space to place them. Below snippet from AWS doc on updating a service helped me to make the below decision.

If your service has a desired number of four tasks and a maximum
  percent value of 200%, the scheduler may start four new tasks before
  stopping the four older tasks (provided that the cluster resources
  required to do this are available). The default value for maximum
  percent is 200%.

We should have the cluster resources available / container instances available to have the new tasks get started so they can start and the older one can drain.

These are the things i do

Before doing a service update add like 20% capacity to your cluster. You can use the ASG (Autoscaling group) commandline and from the desired capacity add 20% to your cluster. This way you will have some additional instance during deployment.

Once you have the instance the new tasks will start spinning up quickly and the older one will start draining.

But does this mean i will have extra container instances ?

Yes, during the deployment you will add some instances but as the older tasks drain they will hang around. The way to remove them is

Create a MemoryReservationLow alarm (~70% threshold in your case) for like 25 mins (longer duration to be sure that we have over commissioned). As the reservation will go low once you have those extra server not being used they can be removed.

Title: Updating an AWS ECS Service


问:
Why the same result both DES Encrypt and DESede Encrypt?
I'm try to be compatible Encrypt/Decrypt both C# and Java.

As I know the default mode is 'ecb/pkcs5' in Java, and 'cbc/pkcs7' in C#.

So I match these things.

1st question is that PKCS7 and PKCS5 are compatible each other??,

there is no PKCS7 in Java so I use PKCS5. but I can get same encrypted data [even the padding-way is different ,pkcs7/pkcs5,] Is it possible? or these are compatible?

2nd question is that Why I get same result even though the mode, way are all different?

I compare 'DES-ECB / DES-CBC / TripleDES-ECB' these things. and C# is working well, results are all different.

Input > HELLO Output > (ECB)/dZf3gUY150=  (CBC) V17s5QLzynM= (Triple)sWGS0GMe1jE

but I get same reulst in Java ..

Input > HELLO Output > (ECB)/dZf3gUY150= (CBC)/dZf3gUY150= (Triple)/dZf3gUY150=

When debugging the flow is right.

Here is my code.

C#

```<code>public static string Encrypt_DES(string originalString, byte[] key, string mode)
    {
        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();

        if (mode.Equals("ECB"))
            cryptoProvider.Mode = CipherMode.ECB;
        else if (mode.Equals("CBC"))
        {
            cryptoProvider.Mode = CipherMode.CBC;
            cryptoProvider.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
        }

        cryptoProvider.Padding = PaddingMode.PKCS7;
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(key, key), CryptoStreamMode.Write);
        StreamWriter writer = new StreamWriter(cryptoStream);
        writer.Write(originalString);
        writer.Flush();
        cryptoStream.FlushFinalBlock();
        writer.Flush();
        return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
    }

public static string Encrypt_TripleDES(string source, string key)
    {
        TripleDESCryptoServiceProvider desCryptoProvider = new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider();

        byte[] byteHash;
        byte[] byteBuff;

        byteHash = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(key));
        desCryptoProvider.Key = byteHash;
        desCryptoProvider.Mode = CipherMode.ECB; //CBC, CFB
        desCryptoProvider.Padding = PaddingMode.PKCS7;
        byteBuff = Encoding.UTF8.GetBytes(source);

        string encoded = Convert.ToBase64String(desCryptoProvider.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
        return encoded;
    }
</code>```

Java(Android)

```<code>public String Encrypt(String str, String desKey, String mode) {
    try {
        KeySpec keySpec = null;
        SecretKey key = null;
        Cipher ecipher = null;
        if (desKey.length() == 8) {
            keySpec = new DESKeySpec(desKey.getBytes("UTF8"));
            key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
            if(mode.equals(ECB)){
                ecipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
                ecipher.init(Cipher.ENCRYPT_MODE, key);
            }else if (mode.equals(CBC)){
                ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
                AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
                ecipher.init(Cipher.ENCRYPT_MODE, key,ivSpec);
            }
        } else if (desKey.length() == 24) {
            keySpec = new DESedeKeySpec(desKey.getBytes("UTF8"));
            key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
            ecipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            ecipher.init(Cipher.ENCRYPT_MODE, key);
        }

        byte[] data = str.getBytes("UTF-8");
        byte[] crypt = ecipher.doFinal(data);

        return Base64.encodeToString(crypt, 0);
    } catch (Exception ex) {
        Log.d("ZVM", ex.getMessage());
    }
    return null;
}
</code>```

As I understand 'IV' is for CBC, When making password, it is mixed with IV(not the key but like key). Is it right?

Thanks.

答:
PKCS7 and PKCS5 are compatible each other

PKCS#5 and PKCS#7 paddings are compatible (equal) for DES. For AES, Java actually uses PKCS#7 padding even though you would write AES/xyz/PKCS5Padding.

Why I get same result even though the mode, way are all different?

First, let's see how Java behaves. The ciphertexts for DES-ECB, DES-CBC and DESede-ECB are all equal. This is correct if

the key is the same (DES supports only 8 byte keys, but Triple DES supports 8, 16 and 24 byte keys where non-24 byte keys are expanded to 24 byte keys),

the plaintext is the same,

the plaintext is less than 8 bytes long (block size of DES/Triple DES) and

the IV is an all 0x00 bytes IV.

Those are all true in the Java code. If you have trouble grasping that, combine the encryption routines for the ECB and CBC modes of operation.

The result of Triple DES might be a bit confusing. I assume that you've taken your 8 byte key for DES and replicated it either twice or thrice for use in Triple DES. This is an issue, because Triple DES encryption consists of three steps of normal DES: EDE means Encryption + Decryption + Encryption. If all the three subkeys are the same, the one of the Encryption steps cancels out with the Decryption step and the whole thing is equivalent to a single DES encryption.

Let's see why C# behaves differently:

The ciphertext from DES-CBC is different from DES-ECB, because the IV is not an all 0x00 bytes IV. cryptoProvider.CreateEncryptor(key, key) creates an Encryptor with the IV set to key (the second argument). That's not what you want. Just use cryptoProvider.CreateEncryptor() instead.

The ciphertext from DESede-ECB is different from DES-ECB, because you're running the key through a hash function. The key is therefore different.

Don't use DES nowadays. It only provides 56 bit of security. AES would be a much better, because it's more secure with the lowest key size of 128 bit. There is also a practical limit on the maximum ciphertext size with DES. See Security comparison of 3DES and AES.

Body:
I'm try to be compatible Encrypt/Decrypt both C# and Java.

As I know the default mode is 'ecb/pkcs5' in Java, and 'cbc/pkcs7' in C#.

So I match these things.

1st question is that PKCS7 and PKCS5 are compatible each other??,

there is no PKCS7 in Java so I use PKCS5. but I can get same encrypted data [even the padding-way is different ,pkcs7/pkcs5,] Is it possible? or these are compatible?

2nd question is that Why I get same result even though the mode, way are all different?

I compare 'DES-ECB / DES-CBC / TripleDES-ECB' these things. and C# is working well, results are all different.

Input > HELLO Output > (ECB)/dZf3gUY150=  (CBC) V17s5QLzynM= (Triple)sWGS0GMe1jE

but I get same reulst in Java ..

Input > HELLO Output > (ECB)/dZf3gUY150= (CBC)/dZf3gUY150= (Triple)/dZf3gUY150=

When debugging the flow is right.

Here is my code.

C#

public static string Encrypt_DES(string originalString, byte[] key, string mode)
    {
        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();

        if (mode.Equals("ECB"))
            cryptoProvider.Mode = CipherMode.ECB;
        else if (mode.Equals("CBC"))
        {
            cryptoProvider.Mode = CipherMode.CBC;
            cryptoProvider.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
        }

        cryptoProvider.Padding = PaddingMode.PKCS7;
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(key, key), CryptoStreamMode.Write);
        StreamWriter writer = new StreamWriter(cryptoStream);
        writer.Write(originalString);
        writer.Flush();
        cryptoStream.FlushFinalBlock();
        writer.Flush();
        return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
    }

public static string Encrypt_TripleDES(string source, string key)
    {
        TripleDESCryptoServiceProvider desCryptoProvider = new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider();

        byte[] byteHash;
        byte[] byteBuff;

        byteHash = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(key));
        desCryptoProvider.Key = byteHash;
        desCryptoProvider.Mode = CipherMode.ECB; //CBC, CFB
        desCryptoProvider.Padding = PaddingMode.PKCS7;
        byteBuff = Encoding.UTF8.GetBytes(source);

        string encoded = Convert.ToBase64String(desCryptoProvider.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
        return encoded;
    }

Java(Android)

public String Encrypt(String str, String desKey, String mode) {
    try {
        KeySpec keySpec = null;
        SecretKey key = null;
        Cipher ecipher = null;
        if (desKey.length() == 8) {
            keySpec = new DESKeySpec(desKey.getBytes("UTF8"));
            key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
            if(mode.equals(ECB)){
                ecipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
                ecipher.init(Cipher.ENCRYPT_MODE, key);
            }else if (mode.equals(CBC)){
                ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
                AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
                ecipher.init(Cipher.ENCRYPT_MODE, key,ivSpec);
            }
        } else if (desKey.length() == 24) {
            keySpec = new DESedeKeySpec(desKey.getBytes("UTF8"));
            key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
            ecipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            ecipher.init(Cipher.ENCRYPT_MODE, key);
        }

        byte[] data = str.getBytes("UTF-8");
        byte[] crypt = ecipher.doFinal(data);

        return Base64.encodeToString(crypt, 0);
    } catch (Exception ex) {
        Log.d("ZVM", ex.getMessage());
    }
    return null;
}

As I understand 'IV' is for CBC, When making password, it is mixed with IV(not the key but like key). Is it right?

Thanks.


问:
Make myOwnTriangle function with point
I am writing my own function for drawing a triangle using only point() with the programming language "Processing".
This is my code:

void setup()
{
  size(400, 400);
  background(#99c2ff);
  noLoop();
}

void myOwnTriangle(int x1, int y1, int x2, int y2, int x3, int y3)
{
  int x=x1;
  int differenceY=abs(y1-y2); //y1=380; y2=50; (380-50)=330
  int differenceX=abs(x2-x1); //x2=300; x1=30; (300-30)=270
  int smallStep = differenceY/differenceX;// 330-270=60
  int stepcount=0;
  if (x1<=x2)
    for (int i=x1; i<=x2; i++)
    {
      for (int j=y2; j<=y1; j++)
        point(i, j);
        println("test1");
      stepcount++;

     }

    }
}

void draw()
{
  stroke(#ff3399);
  myOwnTriangle(30, 380, 300, 50, 380, 250);
}
```

Until println("test1"); I have checked and the program works, then I don't understand why it won't draw the point with if (smallStep%stepcount==0);
the expected behavior should be the first triangle's line(of point).

Can someone help me to complete this function?

thanks.

答:
The most important skill you need to learn is how to debug your program.

You've added a println("test1"); line, and that's a great start. But you need to go a step further and print out the values of every variable, that way you can better understand what your code is doing.

First off, notice that your for loop does not end in a { curly bracket:

```<code>for (int j=y1; j<=y2; j++)
    point(i, j);
    println("test1");
</code>```

This means that only the point(i, j); line is "inside" the for loop, and your println() statement is outside that loop! You can fix that by adding { } curly brackets:

```<code>for (int j=y1; j<=y2; j++){
    println(i + ", " + j);
    point(i, j);
    println("test1");
}
</code>```

Also notice that I've added another println() statement to figure out what the values of i and j are inside this loop. But if your run this program, you'll find out that this loop never runs!

To figure out why that's happening, you can add more println() statements just before the inner loop:

```<code>for (int i=x1; i<=x2; i++){
  println("i: " + i);
  println("y1: " + y1);
  println("y2: " + y2);
  for (int j=y1; j<=y2; j++){
    println(i + ", " + j);
    point(i, j);
    println("test1");
  }
}
</code>```

If you run this, you'll see that y1 is 380 and y2 is 50. So then your loop sets j equal to y1 (which is 300) and then checks whether it's less than y2 (which is 50). That is never true (380 is never less than 50), so your loop doesn't run. That's why you aren't seeing any points being drawn.

You're going to have to take a step back and figure out exactly what you want to do in this case. But more importantly, you need to get into the habit of debugging your code to understand exactly what it's doing.

Title: Make myOwnTriangle function with point

Body:
I am writing my own function for drawing a triangle using only point() with the programming language "Processing".
This is my code:

void setup()
{
  size(400, 400);
  background(#99c2ff);
  noLoop();
}

void myOwnTriangle(int x1, int y1, int x2, int y2, int x3, int y3)
{
  int x=x1;
  int differenceY=abs(y1-y2); //y1=380; y2=50; (380-50)=330
  int differenceX=abs(x2-x1); //x2=300; x1=30; (300-30)=270
  int smallStep = differenceY/differenceX;// 330-270=60
  int stepcount=0;
  if (x1<=x2)
    for (int i=x1; i<=x2; i++)
    {
      for (int j=y2; j<=y1; j++)
        point(i, j);
        println("test1");
      stepcount++;

     }

    }
}

void draw()
{
  stroke(#ff3399);
  myOwnTriangle(30, 380, 300, 50, 380, 250);
}

Until println("test1"); I have checked and the program works, then I don't understand why it won't draw the point with if (smallStep%stepcount==0);
the expected behavior should be the first triangle's line(of point).

Can someone help me to complete this function?

thanks.

Body:
The most important skill you need to learn is how to debug your program.

You've added a println("test1"); line, and that's a great start. But you need to go a step further and print out the values of every variable, that way you can better understand what your code is doing.

First off, notice that your for loop does not end in a { curly bracket:

for (int j=y1; j<=y2; j++)
    point(i, j);
    println("test1");

This means that only the point(i, j); line is "inside" the for loop, and your println() statement is outside that loop! You can fix that by adding { } curly brackets:

for (int j=y1; j<=y2; j++){
    println(i + ", " + j);
    point(i, j);
    println("test1");
}

Also notice that I've added another println() statement to figure out what the values of i and j are inside this loop. But if your run this program, you'll find out that this loop never runs!

To figure out why that's happening, you can add more println() statements just before the inner loop:

for (int i=x1; i<=x2; i++){
  println("i: " + i);
  println("y1: " + y1);
  println("y2: " + y2);
  for (int j=y1; j<=y2; j++){
    println(i + ", " + j);
    point(i, j);
    println("test1");
  }
}

If you run this, you'll see that y1 is 380 and y2 is 50. So then your loop sets j equal to y1 (which is 300) and then checks whether it's less than y2 (which is 50). That is never true (380 is never less than 50), so your loop doesn't run. That's why you aren't seeing any points being drawn.

You're going to have to take a step back and figure out exactly what you want to do in this case. But more importantly, you need to get into the habit of debugging your code to understand exactly what it's doing.


问:
how to add alternative row formatting in EPP Plus C# .XLSX download
I am upgrading .xls download in .aspx page to .xlsx download using c# EppPlus. How can I add Alternative row background color like each other row has gray background ?

I am using the below code

```<code>public void DumpExcel(DataTable tbl)
{
    using (ExcelPackage pck = new ExcelPackage())
    {
        //Create the worksheet
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");

        ws.Cells["A1"].LoadFromDataTable(tbl, true);

        using (ExcelRange rng = ws.Cells["A1:AA1"])
        {
            rng.Style.Font.Bold = false;
            rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
            rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0, 51, 153));  //Set color to dark blue
            rng.Style.Font.Color.SetColor(Color.White);
            rng.Style.Font.Size = 10;
        }

        // Add Word wrap
        for (int i = 1; i <= tbl.Columns.Count; i++)
        {
            ws.Column(i).AutoFit();
            ws.Column(i).Width = 20;
            ws.Column(i).Style.WrapText = true;
            ws.Column(i).Style.VerticalAlignment = ExcelVerticalAlignment.Top;
            ws.Column(i).Style.Font.Size = 9;
        }

        //Write it back to the client
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;  filename=UserEntitleDLX.xlsx");
        Response.BinaryWrite(pck.GetAsByteArray());
    }
}
</code>```

答:
Here's a variation of the given answers I use (as extension). My requirements required a subset of columns be colored, not the whole row, and with more than just two colors.

```<code>public static void ApplyBackgroundColorsPerRow(
    this ExcelWorksheet worksheet,
    int startRow, int startColumn, int endRow, int endColumn,
    List<System.Drawing.Color> colors)
{
    if (startRow <= endRow)
    {
        int numberOfColors = colors.Count;
        for (int row = startRow; row <= endRow; row++)
        {
            using (ExcelRange range = worksheet.Cells[row, startColumn, row, endColumn])
            {
                range.Style.Fill.PatternType = ExcelFillStyle.Solid;
                range.Style.Fill.BackgroundColor.SetColor(colors[(row - startRow) % numberOfColors]);
            }
        }
    }
}
</code>```

Alternating white / gray (light gray is my recommendation over grey) would look like this:

```<code>worksheet.ApplyBackgroundColorsPerRow(
    startRow: 1,
    startColumn: 1,
    endRow: 20,
    endColumn: 5,
    colors: new List<System.Drawing.Color>()
    {
        System.Drawing.Color.White,
        System.Drawing.Color.LightGray
    }
);
</code>```

Body:
I am upgrading .xls download in .aspx page to .xlsx download using c# EppPlus. How can I add Alternative row background color like each other row has gray background ?

I am using the below code

public void DumpExcel(DataTable tbl)
{
    using (ExcelPackage pck = new ExcelPackage())
    {
        //Create the worksheet
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");

        ws.Cells["A1"].LoadFromDataTable(tbl, true);

        using (ExcelRange rng = ws.Cells["A1:AA1"])
        {
            rng.Style.Font.Bold = false;
            rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
            rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0, 51, 153));  //Set color to dark blue
            rng.Style.Font.Color.SetColor(Color.White);
            rng.Style.Font.Size = 10;
        }

        // Add Word wrap
        for (int i = 1; i <= tbl.Columns.Count; i++)
        {
            ws.Column(i).AutoFit();
            ws.Column(i).Width = 20;
            ws.Column(i).Style.WrapText = true;
            ws.Column(i).Style.VerticalAlignment = ExcelVerticalAlignment.Top;
            ws.Column(i).Style.Font.Size = 9;
        }

        //Write it back to the client
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;  filename=UserEntitleDLX.xlsx");
        Response.BinaryWrite(pck.GetAsByteArray());
    }
}

Body:
Here's a variation of the given answers I use (as extension). My requirements required a subset of columns be colored, not the whole row, and with more than just two colors.

public static void ApplyBackgroundColorsPerRow(
    this ExcelWorksheet worksheet,
    int startRow, int startColumn, int endRow, int endColumn,
    List<System.Drawing.Color> colors)
{
    if (startRow <= endRow)
    {
        int numberOfColors = colors.Count;
        for (int row = startRow; row <= endRow; row++)
        {
            using (ExcelRange range = worksheet.Cells[row, startColumn, row, endColumn])
            {
                range.Style.Fill.PatternType = ExcelFillStyle.Solid;
                range.Style.Fill.BackgroundColor.SetColor(colors[(row - startRow) % numberOfColors]);
            }
        }
    }
}

Alternating white / gray (light gray is my recommendation over grey) would look like this:

worksheet.ApplyBackgroundColorsPerRow(
    startRow: 1,
    startColumn: 1,
    endRow: 20,
    endColumn: 5,
    colors: new List<System.Drawing.Color>()
    {
        System.Drawing.Color.White,
        System.Drawing.Color.LightGray
    }
);


问:
Problems when sending XML data from HTTP Java client to a servlet with HttpURLConnection
I have standalone java client sending xml data to http servlet using httpURLconnection class.but data appearing in non printable character format.

For simulation i have been trying to send simple string but still it was appearing in non printable format.

I have written the following client code to communicate with servlet,

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class HttpClient implements IClient {

    private static IClient client = null;

    private HttpURLConnection httpConn = null;

    private OutputStream output = null;

    private InputStream input = null;

    private OutputStreamWriter out = null;

    private HttpClient() {
    }

    public static IClient getHttpClient() {
        if (client == null) {
            client = new HttpClient();
        }
        return client;
    }

    @Override
    public void connect(String urlString) throws IOException {
        URL url = new URL(urlString);
        httpConn = (HttpURLConnection) url.openConnection();
        initConnection();
        httpConn.connect();
        output = httpConn.getOutputStream();
        input = httpConn.getInputStream();
        System.out.println("Connection Response:" + httpConn.getResponseCode());
    }

    @Override
    public void sendFile(File file) throws IOException {
        // BufferedOutputStream bos = new BufferedOutputStream(output);
        // InputStream fis = new FileInputStream(file);
        // int bytesRead = 0;
        // byte[] buffer = new byte[8192];
        // while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
        // bos.write(buffer, 0, bytesRead);
        // System.out.println("write:"+buffer);
        // }
        // bos.close();
        // fis.close();

        OutputStreamWriter out = new OutputStreamWriter(output, "UTF-16");
        out.write("test me");
    }

    @Override
    public boolean isConnected() {
        return httpConn != null ? true : false;
    }

    @Override
    public void close() {
        httpConn.disconnect();
    }

    private void initConnection() throws ProtocolException {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setRequestMethod("POST");
        httpConn.setUseCaches(false);
        httpConn.setRequestProperty("Content-Type",
                "text/xml; charset=\"UTF-16\"");
        httpConn.setRequestProperty("Connection", "Keep-Alive");

    }

    private static byte[] getBytesFromFile(File file) throws IOException {

        InputStream is = new FileInputStream(file);
        System.out.println("\nDEBUG: FileInputStream is " + file);

        // Get the size of the file
        long length = file.length();
        System.out.println("DEBUG: Length of " + file + " is " + length + "\n");

        /*
         * You cannot create an array using a long type. It needs to be an int
         * type. Before converting to an int type, check to ensure that file is
         * not loarger than Integer.MAX_VALUE;
         */
        if (length > Integer.MAX_VALUE) {
            System.out.println("File is too large to process");
            return null;
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while ((offset < bytes.length)
                && ((numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)) {

            offset += numRead;

        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }

        return bytes;

    }

}
</code>```

and servlet code is given below,

```<code>import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class XMLServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("=========inside doPost=========");
//      BufferedInputStream bis = new BufferedInputStream(req.getInputStream());
//      OutputStream fos = new FileOutputStream("test.xml");
//      int bytesRead = 0;
//      byte[] buffer = new byte[8192];
//      while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
//          System.out.println("read:"+buffer);
//          fos.write(buffer, 0, bytesRead);
//      }
//      fos.close();
//      bis.close();
//

        req.setCharacterEncoding("UTF-16");
        InputStreamReader isr = new InputStreamReader(req.getInputStream(),"UTF-16");
        char[] data = new char[10];
        isr.read(data);
        System.out.println(data);
        for (char c : data) {
            System.out.println(c);
        }
    }

}
</code>```

Please any help me to get out of this problem.

答:
I have standalone java client sending xml data to http servlet using httpURLconnection class.but data appearing in non printable character format.

I can understand that. You're sending the data as UTF-16, but the XML file itself is likely not saved in UTF-16. You need to use the same character encoding as the XML file is saved in. That's usually UTF-8.

For simulation i have been trying to send simple string but still it was appearing in non printable format.

I don't understand that. It should work fine the way as you have in the code. Probably you didn't test it properly.

Body:
I have standalone java client sending xml data to http servlet using httpURLconnection class.but data appearing in non printable character format.

For simulation i have been trying to send simple string but still it was appearing in non printable format.

I have written the following client code to communicate with servlet,

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class HttpClient implements IClient {

    private static IClient client = null;

    private HttpURLConnection httpConn = null;

    private OutputStream output = null;

    private InputStream input = null;

    private OutputStreamWriter out = null;

    private HttpClient() {
    }

    public static IClient getHttpClient() {
        if (client == null) {
            client = new HttpClient();
        }
        return client;
    }

    @Override
    public void connect(String urlString) throws IOException {
        URL url = new URL(urlString);
        httpConn = (HttpURLConnection) url.openConnection();
        initConnection();
        httpConn.connect();
        output = httpConn.getOutputStream();
        input = httpConn.getInputStream();
        System.out.println("Connection Response:" + httpConn.getResponseCode());
    }

    @Override
    public void sendFile(File file) throws IOException {
        // BufferedOutputStream bos = new BufferedOutputStream(output);
        // InputStream fis = new FileInputStream(file);
        // int bytesRead = 0;
        // byte[] buffer = new byte[8192];
        // while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
        // bos.write(buffer, 0, bytesRead);
        // System.out.println("write:"+buffer);
        // }
        // bos.close();
        // fis.close();

        OutputStreamWriter out = new OutputStreamWriter(output, "UTF-16");
        out.write("test me");
    }

    @Override
    public boolean isConnected() {
        return httpConn != null ? true : false;
    }

    @Override
    public void close() {
        httpConn.disconnect();
    }

    private void initConnection() throws ProtocolException {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setRequestMethod("POST");
        httpConn.setUseCaches(false);
        httpConn.setRequestProperty("Content-Type",
                "text/xml; charset=\"UTF-16\"");
        httpConn.setRequestProperty("Connection", "Keep-Alive");

    }

    private static byte[] getBytesFromFile(File file) throws IOException {

        InputStream is = new FileInputStream(file);
        System.out.println("\nDEBUG: FileInputStream is " + file);

        // Get the size of the file
        long length = file.length();
        System.out.println("DEBUG: Length of " + file + " is " + length + "\n");

        /*
         * You cannot create an array using a long type. It needs to be an int
         * type. Before converting to an int type, check to ensure that file is
         * not loarger than Integer.MAX_VALUE;
         */
        if (length > Integer.MAX_VALUE) {
            System.out.println("File is too large to process");
            return null;
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while ((offset < bytes.length)
                && ((numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)) {

            offset += numRead;

        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }

        return bytes;

    }

}

and servlet code is given below,

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class XMLServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("=========inside doPost=========");
//      BufferedInputStream bis = new BufferedInputStream(req.getInputStream());
//      OutputStream fos = new FileOutputStream("test.xml");
//      int bytesRead = 0;
//      byte[] buffer = new byte[8192];
//      while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
//          System.out.println("read:"+buffer);
//          fos.write(buffer, 0, bytesRead);
//      }
//      fos.close();
//      bis.close();
//

        req.setCharacterEncoding("UTF-16");
        InputStreamReader isr = new InputStreamReader(req.getInputStream(),"UTF-16");
        char[] data = new char[10];
        isr.read(data);
        System.out.println(data);
        for (char c : data) {
            System.out.println(c);
        }
    }

}

Please any help me to get out of this problem.


问:
Retrieve Mac address in powershell and convert it to decimal format
I can easily get Mac address in powershell by:

```<code>$localMac=Get-WmiObject win32_networkadapterconfiguration | select macaddress
echo $localMac[0]
</code>```

The result is:

```<code>macaddress
----------
E8:21:32:E5:F4:6A
</code>```

How can I change result to decimal format in powershell? Just for example 7436378647

I tried

```<code>$MacAddressConverted = $localMac[0] -replace '(:|-|\.)'
echo $MacAddressConverted
</code>```

It returns

```<code>@{macaddress=E82132E5F46A}
</code>```

It's close what I would like to achive but it still has @{macadress= and it's not converted to decimal

答:
```<code>Get-WmiObject Win32_NetworkAdapterConfiguration |
    Where-Object { $_.MacAddress } |
    ForEach-Object { [convert]::ToInt64($_.MacAddress.Replace(':', ''), 16) }
</code>```

It gives the next result on my laptop:

```<code>147163166963
19938372466931
</code>```

Body:
I can easily get Mac address in powershell by:

$localMac=Get-WmiObject win32_networkadapterconfiguration | select macaddress
echo $localMac[0]

The result is:

macaddress
----------
E8:21:32:E5:F4:6A

How can I change result to decimal format in powershell? Just for example 7436378647

I tried

$MacAddressConverted = $localMac[0] -replace '(:|-|\.)'
echo $MacAddressConverted

It returns

@{macaddress=E82132E5F46A}

It's close what I would like to achive but it still has @{macadress= and it's not converted to decimal

Body:
Get-WmiObject Win32_NetworkAdapterConfiguration |
    Where-Object { $_.MacAddress } |
    ForEach-Object { [convert]::ToInt64($_.MacAddress.Replace(':', ''), 16) }

It gives the next result on my laptop:

147163166963
19938372466931


问:
How can I send a JSON object from a Python script to jQuery?
I've looked through APIs and all sorts of resources, but I can't seem to get the hang of fetching a JSON object from a Python script using AJAX. I'm sure the issue is with how I'm dealing with the JSON object.

First, in a python script on my server, I generate and print a JSON array

```<code>import json
print "Content-type: application/json"
print
print json.dumps(['Price',{'Cost':'99'}])
</code>```

Then, in a separate html file, I try something like

```<code><body>
<div id="test">
</div>

<script>
 $(document).ready(function() {
  $.getJSON("http://www.example.com/cgi-bin/makeJSON.py", function(data) {
        $('#test').html("JSON Data: " + data.Price);
    });
});
</script>
</body>
</code>```

But I don't get anything. I'm sure that data.Price is wrong, but I'm also pretty certain that I should be doing something instead of just printing the results of json.dumps

Any help is appreciated! Thanks in advance, and sorry if this is an obvious question.

答:
Please provide more context to what you're trying to do. Can you just hard-code the JSON object into the HTML? Or, are you trying to do something more dynamic, like AJAX?

For the former, view the HTML source of the page that Python generates. It must look something like:

```<code><script type="text/javascript">
   var MY_GLOBAL_JSON_OBJECT = { ... };
</script>
</code>```

Or you could just spit out the JSON object inside the function that's actually using it instead of assigning it first to a global variable.

Body:
I've looked through APIs and all sorts of resources, but I can't seem to get the hang of fetching a JSON object from a Python script using AJAX. I'm sure the issue is with how I'm dealing with the JSON object.

First, in a python script on my server, I generate and print a JSON array

import json
print "Content-type: application/json"
print
print json.dumps(['Price',{'Cost':'99'}])

Then, in a separate html file, I try something like

But I don't get anything. I'm sure that data.Price is wrong, but I'm also pretty certain that I should be doing something instead of just printing the results of json.dumps

Any help is appreciated! Thanks in advance, and sorry if this is an obvious question.

Body:
Please provide more context to what you're trying to do. Can you just hard-code the JSON object into the HTML? Or, are you trying to do something more dynamic, like AJAX?

For the former, view the HTML source of the page that Python generates. It must look something like:

<script type="text/javascript">
   var MY_GLOBAL_JSON_OBJECT = { ... };
</script>

Or you could just spit out the JSON object inside the function that's actually using it instead of assigning it first to a global variable.


问:
Operating terminal session from Java
I am trying to make a terminal emulator in Java. The java program will accept the commands from user, and show its output to them. I can emulate simple commands like 'ls', but I don't know how to handle commands like 'cd'. This is because, I am using exec() method for executing terminal commands. So, all the commands are executed at current directory. The commands like 'cd ..' are executed, but then they have no persistent effect, because each command is separately executed by exec().

Any Ideas How I can emulate a whole session??

答:
You should really give a try to Ganymed.

Ganymed SSH-2 for Java is a library which implements the SSH-2
  protocol in pure Java (tested on J2SE 1.4.2 and 5.0). It allows one to
  connect to SSH servers from within Java programs. It supports SSH
  sessions (remote command execution and shell access), local and remote
  port forwarding, local stream forwarding, X11 forwarding, SCP and
  SFTP.

http://www.ganymed.ethz.ch/ssh2/

Ganymed along with apache FTP client you can also download and upload files.

Also there is a inbuilt example code for terminal emulation in Ganymed.

The following is a link to a project which is did using Ganymed along with apache FTP client.

GITHUB

Happy Coding!!

Title: Operating terminal session from Java


问:
Shell built-in execution
I'm a little confused about the definition of a shell built-in. According to the Bash Reference Manual, for any built-in, the shell executes the command directly, without invoking another program. What exactly does it mean that a "command is executed directly"? For example, let's look at the cd built-in:

```<code>$ which cd
/usr/bin/cd
$ type cd
cd is a shell builtin
</code>```

Now, let's look at the non built-ingrep:

```<code>$ which grep
/usr/bin/grep
$ type grep
grep is /usr/bin/grep
</code>```

It appears that cd is a separate binary. How is executing cd (or any other builtin) any different than executing grep (or any other non-builtin)?

答:
In addition to Fred's correct answer:

I understand your confusion about builtins and external commands. The cd command is actually good for a little demonstration.

For example on my system, the situation is the following:

```<code>$ which cd    # gives no output
$ whereis cd  # again, no path found
cd:
$ type -a cd  # verifies that it's a real builtin command
cd is a shell builtin
</code>```

This clearly shows that a cd command in terms of an external program is not installed on my machine. In your case, the which cd shows that an additional cd command (separate program) is installed under /usr/bin/cd.

Sometimes it is not clear when you type cd whether you're going to invoke the builtin or external command. To make sure, you really invoke the builtin cd command, you can execute the following:

```<code>$ builtin cd
</code>```

From the help page of the builtin cd command:

```<code>$ help builtin
</code>```

builtin: builtin [shell-builtin [arg ...]]
      Execute shell builtins.

```<code>Execute SHELL-BUILTIN with arguments ARGs without performing command
lookup.  This is useful when you wish to reimplement a shell builtin
as a shell function, but need to execute the builtin within the function.
</code>```

Now you can see how the builtin command can be used to enforce execution of a shell builtin command. This can be very helpful in special cases.

Furthermore, you can (it's actually obvious) expect better performance from builtin commands [source]:

In general, an external command in a script forks off a subprocess,
  [*] whereas a Bash builtin does not. For this reason, builtins execute
  more quickly and use fewer system resources than their external
  command equivalents.

Title: Shell built-in execution

Body:
I'm a little confused about the definition of a shell built-in. According to the Bash Reference Manual, for any built-in, the shell executes the command directly, without invoking another program. What exactly does it mean that a "command is executed directly"? For example, let's look at the cd built-in:

$ which cd
/usr/bin/cd
$ type cd
cd is a shell builtin

Now, let's look at the non built-ingrep:

$ which grep
/usr/bin/grep
$ type grep
grep is /usr/bin/grep

It appears that cd is a separate binary. How is executing cd (or any other builtin) any different than executing grep (or any other non-builtin)?

Body:
In addition to Fred's correct answer:

I understand your confusion about builtins and external commands. The cd command is actually good for a little demonstration.

For example on my system, the situation is the following:

$ which cd    # gives no output
$ whereis cd  # again, no path found
cd:
$ type -a cd  # verifies that it's a real builtin command
cd is a shell builtin

This clearly shows that a cd command in terms of an external program is not installed on my machine. In your case, the which cd shows that an additional cd command (separate program) is installed under /usr/bin/cd.

Sometimes it is not clear when you type cd whether you're going to invoke the builtin or external command. To make sure, you really invoke the builtin cd command, you can execute the following:

$ builtin cd

From the help page of the builtin cd command:

$ help builtin

builtin: builtin [shell-builtin [arg ...]]
      Execute shell builtins.

Execute SHELL-BUILTIN with arguments ARGs without performing command
lookup.  This is useful when you wish to reimplement a shell builtin
as a shell function, but need to execute the builtin within the function.

Now you can see how the builtin command can be used to enforce execution of a shell builtin command. This can be very helpful in special cases.

Furthermore, you can (it's actually obvious) expect better performance from builtin commands [source]:

In general, an external command in a script forks off a subprocess,
  [*] whereas a Bash builtin does not. For this reason, builtins execute
  more quickly and use fewer system resources than their external
  command equivalents.


问:
Firebase observer during all the app life
I'm trying to create a firebase observer that remains alive during all the app life. What I want is to change a property of my tabBarController when some data change in firebase. Here's my code:

```<code>self.ref.child("mySubRef").observe(.value , with: {snapshot in

        self.tabBarController?.tabBar.items?[3].badgeValue = "!"

    })
</code>```

So, I've tried creating it in the viewDidLoad of my first viewController and also in the viewDidAppear. I don't remove it since I want it to be there always. In the viewDidAppear it works only if I'm in that viewController at the moment of the change. If I want that change to happen no matter where  I am (always inside the tabBar) where do I have to put that code?

Thanks for the help!

答:
I think, you can use Appdelegate didFinishLaunchingWithOptions method but I'm not sure.

Like this:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    FIRApp.configure()

    FIRDatabase.database().reference().child("mySubRef").observe(.value, with: { (snapshot) in
        //I'm not sure for this part.
        UITabBarController.init().tabBar.items?[3].badgeValue = "!"
    })

    return true
}
</code>```

Body:
I'm trying to create a firebase observer that remains alive during all the app life. What I want is to change a property of my tabBarController when some data change in firebase. Here's my code:

self.ref.child("mySubRef").observe(.value , with: {snapshot in

        self.tabBarController?.tabBar.items?[3].badgeValue = "!"

    })

So, I've tried creating it in the viewDidLoad of my first viewController and also in the viewDidAppear. I don't remove it since I want it to be there always. In the viewDidAppear it works only if I'm in that viewController at the moment of the change. If I want that change to happen no matter where  I am (always inside the tabBar) where do I have to put that code?

Thanks for the help!

Body:
I think, you can use Appdelegate didFinishLaunchingWithOptions method but I'm not sure.

Like this:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    FIRApp.configure()

    FIRDatabase.database().reference().child("mySubRef").observe(.value, with: { (snapshot) in
        //I'm not sure for this part.
        UITabBarController.init().tabBar.items?[3].badgeValue = "!"
    })

    return true
}


问:
how to work with radio buttons in text file
I am creating a simple multiple choice quiz in python 3 with tkinter

i am planning to add all questions along with answer in a text file. But i don't know how to get my radio buttons to work with text file and then call them. i need a small example so i can complete my program.
i have tried to use google and other python documents but i am not getting anything proper.

```<code>import sys
from tkinter import *

root=Tk()
name=StringVar(value='Enter Name Here')
cn=StringVar(value='Enter CN Here')

def random():
    mlabel=Label(root,text="U CLicked Me").pack()
    return

def random1():
    mtext=name.get()
    mno=cn.get()
    mlabel2=Label(root,text=mtext).pack()
    mlabel3=Label(root,text=mno).pack()

def mquit():
    mexit=messagebox.askyesno(title="Quit",message="Quit The Test ?")
    if mexit > 0:
        root.destroy()
        return

root.geometry('700x700+400+400')
root.title('Welcome To Quiz')

mainmenu=Menu(root)

root.configure(menu=mainmenu)

submenu=Menu(mainmenu,tearoff=0)
mainmenu.add_cascade(label="Options",menu=submenu)
submenu.add_command(label="Restart",command=random)
submenu.add_command(label="Close",command=mquit)

mentry=Entry(root,textvariable=name).pack()
mentry=Entry(root,textvariable=cn).pack()
mbutton=Button(root,text='Ok',command=random1,fg='red',bg='blue').pack()

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

答:
There are 2 parts you need to understand.

First part is to get the values from your text file. How you do this depends on the format of your text file (which you haven't specified). I would suggest you use either a csv (csv documentation) or even a config file (config parser documentation).

Once you have the questions and answers loaded into variables, you can assign the values to the radiobuttons. The key point to remember is that radiobuttons in a group all point to one variable. If you programmatically set the variable to a valid option, that button will be selected; if the user selects a radiobutton, the variable will be set to that value - and you can test that value against the answer you loaded from the csv or config file.

(From Modern TKinter for the Busy Python DEveloper by Rocci Rossi):

Radiobuttons are created using the ttk.Radiobutton function, and typically as a set:

```<code>phone = StringVar()
home = ttk.Radiobutton(parent, text='Home', variable=phone, value='home')
office = ttk.Radiobutton(parent, text='Office', variable=phone, value='office')
cell = ttk.Radiobutton(parent, text='Mobile', variable=phone, value='cell')
</code>```

Each of the radiobuttons of the set will have the same linked variable, but a different value; when the variable has the given value, the radiobutton will be selected, otherwise unselected. When the linked variable does not exist, radiobuttons also display a "tristate" or indeterminate, which can be checked
via the "alternate" state flag.

Body:
I am creating a simple multiple choice quiz in python 3 with tkinter

i am planning to add all questions along with answer in a text file. But i don't know how to get my radio buttons to work with text file and then call them. i need a small example so i can complete my program.
i have tried to use google and other python documents but i am not getting anything proper.

import sys
from tkinter import *

root=Tk()
name=StringVar(value='Enter Name Here')
cn=StringVar(value='Enter CN Here')

def random():
    mlabel=Label(root,text="U CLicked Me").pack()
    return

def random1():
    mtext=name.get()
    mno=cn.get()
    mlabel2=Label(root,text=mtext).pack()
    mlabel3=Label(root,text=mno).pack()

def mquit():
    mexit=messagebox.askyesno(title="Quit",message="Quit The Test ?")
    if mexit > 0:
        root.destroy()
        return

root.geometry('700x700+400+400')
root.title('Welcome To Quiz')

mainmenu=Menu(root)

root.configure(menu=mainmenu)

submenu=Menu(mainmenu,tearoff=0)
mainmenu.add_cascade(label="Options",menu=submenu)
submenu.add_command(label="Restart",command=random)
submenu.add_command(label="Close",command=mquit)

mentry=Entry(root,textvariable=name).pack()
mentry=Entry(root,textvariable=cn).pack()
mbutton=Button(root,text='Ok',command=random1,fg='red',bg='blue').pack()

root.mainloop()

Body:
There are 2 parts you need to understand.

First part is to get the values from your text file. How you do this depends on the format of your text file (which you haven't specified). I would suggest you use either a csv (csv documentation) or even a config file (config parser documentation).

Once you have the questions and answers loaded into variables, you can assign the values to the radiobuttons. The key point to remember is that radiobuttons in a group all point to one variable. If you programmatically set the variable to a valid option, that button will be selected; if the user selects a radiobutton, the variable will be set to that value - and you can test that value against the answer you loaded from the csv or config file.

(From Modern TKinter for the Busy Python DEveloper by Rocci Rossi):

Radiobuttons are created using the ttk.Radiobutton function, and typically as a set:

phone = StringVar()
home = ttk.Radiobutton(parent, text='Home', variable=phone, value='home')
office = ttk.Radiobutton(parent, text='Office', variable=phone, value='office')
cell = ttk.Radiobutton(parent, text='Mobile', variable=phone, value='cell')

Each of the radiobuttons of the set will have the same linked variable, but a different value; when the variable has the given value, the radiobutton will be selected, otherwise unselected. When the linked variable does not exist, radiobuttons also display a "tristate" or indeterminate, which can be checked
via the "alternate" state flag.


问:
Unsigned Int to Void* and then Back
I have an unsigned int where I am using each of the 32 bits to store a specific piece of information..

```<code>function( void * a);
unsigned int val = 0xFFFFFFFF;
function( (void *) (long) val );
</code>```

Within the function, I want to modify the unsigned int.. I can't figure out how to uncast it without losing precision or any of the bits. Is tjere a correct way to do this.. can't seem to figure it out..

答:
You should pass the address of val to the function by casting in to a void* like this:

```<code>function((void*)&val);
</code>```

and design your function like:

```<code>void function(void* ptr) {
    unsigned int *p = (unsigned int*)ptr;
    (*p)++; //example of a change
}
</code>```

Title: Unsigned Int to Void* and then Back

Body:
I have an unsigned int where I am using each of the 32 bits to store a specific piece of information..

function( void * a);
unsigned int val = 0xFFFFFFFF;
function( (void *) (long) val );

Within the function, I want to modify the unsigned int.. I can't figure out how to uncast it without losing precision or any of the bits. Is tjere a correct way to do this.. can't seem to figure it out..

Body:
You should pass the address of val to the function by casting in to a void* like this:

function((void*)&val);

and design your function like:

void function(void* ptr) {
    unsigned int *p = (unsigned int*)ptr;
    (*p)++; //example of a change
}


问:
Install cocos2D-iPhone manually
How can I install cocos2D-iPhone manually? I want to include the cocos2D framework into an existing project. Thus, I will not be able to use a cocos2D project template.

Tutorials or web sites would be appreciated (couldn't find any)

答:
I would create a new project using the template, and compare it to your own project. For a list of files to compare, and a rough procedure:

Copy all cocos2d files from the template over to your project

Check Info.plist, and make any necessary changes

Modify main.m in your target to specify your AppDelegate class. For a project called Untitled, you'd use

```<code>int retVal = UIApplicationMain(argc, argv, nil, @"UntitledAppDelegate");
</code>```

Add a target that builds the cocos2d files. This will be a "Static Library" target. use "Get Info" on the template version to figure out exactly what's going on inside.

Link required frameworks to your target: CoreGraphics, OpenGLES, QuartzCore, OpenAL, AudioToolbox, libz.dylib, AVFoundation. I think this is all

Use "Get Info" on the template target and your target, and make sure you've added the cocos2d library to "Linked Libraries". Also, add "cocos2d libraries" as a linked target.

Compare AppDelegate files, and check how the project is instantiated. The main difference is that you won't be using a Window.xib file to boot up the project, and will have to manually instantiate the cocos2d stuff. The best way to see the proper startup procedure is to take a look at the template code.

That said, I actually DO use a UINavigationController and a UIViewController with a nib file for my initial view. To do this, instantiate the navController like usual, and use this sort of code to attach it to cocos2d:

```<code>[[[[CCDirector sharedDirector] openGLView] window] addSubview:navController.view];
</code>```

That should be everything you need to do for a basic conversion.

If you want access to the project internals, you might use the method of shared libraries, which will allow you to build a new cocos2d library every time you build your app. The link has a great tutorial on this.

Title: Install cocos2D-iPhone manually

Body:
I would create a new project using the template, and compare it to your own project. For a list of files to compare, and a rough procedure:

Copy all cocos2d files from the template over to your project

Check Info.plist, and make any necessary changes

Modify main.m in your target to specify your AppDelegate class. For a project called Untitled, you'd use

int retVal = UIApplicationMain(argc, argv, nil, @"UntitledAppDelegate");

Add a target that builds the cocos2d files. This will be a "Static Library" target. use "Get Info" on the template version to figure out exactly what's going on inside.

Link required frameworks to your target: CoreGraphics, OpenGLES, QuartzCore, OpenAL, AudioToolbox, libz.dylib, AVFoundation. I think this is all

Use "Get Info" on the template target and your target, and make sure you've added the cocos2d library to "Linked Libraries". Also, add "cocos2d libraries" as a linked target.

Compare AppDelegate files, and check how the project is instantiated. The main difference is that you won't be using a Window.xib file to boot up the project, and will have to manually instantiate the cocos2d stuff. The best way to see the proper startup procedure is to take a look at the template code.

That said, I actually DO use a UINavigationController and a UIViewController with a nib file for my initial view. To do this, instantiate the navController like usual, and use this sort of code to attach it to cocos2d:

[[[[CCDirector sharedDirector] openGLView] window] addSubview:navController.view];

That should be everything you need to do for a basic conversion.

If you want access to the project internals, you might use the method of shared libraries, which will allow you to build a new cocos2d library every time you build your app. The link has a great tutorial on this.


问:
Difference calculation within a numeric vector in R
I have a vector

```<code>tyu <- c(11,8,5,4,2,1)
</code>```

whose structure is

```<code>str(tyu)
num [1:6] 11 8 5 4 2 1
</code>```

I would like to calculate the difference between the 1st value and the last value i.e the 6th value of the numeric vector using R programming

Answer would be = 11 - 1 = 10

答:
We can use

```<code>tyu[1] - tyu[length(tyu)]
</code>```

Or

```<code>head(tyu,1) - tail(tyu, 1)
</code>```

Body:
I have a vector

tyu <- c(11,8,5,4,2,1)

whose structure is

str(tyu)
num [1:6] 11 8 5 4 2 1

I would like to calculate the difference between the 1st value and the last value i.e the 6th value of the numeric vector using R programming

Answer would be = 11 - 1 = 10

Body:
We can use

tyu[1] - tyu[length(tyu)]

Or

head(tyu,1) - tail(tyu, 1)


问:
How to Set Desktop shortcut icon different and task bar icon different for a QT Windows application?
I need to set title.ico as my application icon and shortcut.ico as my desktop shortcut. Is there any way to do it in a Qt application itself while building?

Whenever the user right-clicks on my application and clicks on sendto->desktop(create shortcut), the shortcut should have shortcut.ico. But now it's always displaying title.ico.

I checked WinApi IShell_link but it didn't help.

答:
I am also a beginner, but turns out this is possible. See this thread: https://forum.qt.io/topic/45324/taskbar-icon-different-from-the-icon-of-the-window/8

Hope I understood you right. Enjoy!

Edit 2018-03-13:

Create your icon in diffrent sizes (e.g. 16px, 32px, ...) as an .ico (while on Windows), for further information visit: http://doc.qt.io/qt-5/appicon.html

Call QWindow::setIcon() (http://doc.qt.io/qt-5/qwindow.html#setIcon)

Profit. The icon should now be visible in the greater resolution in the taskbar, while the smaller one is choosen for the app window.


问:
facebook redirected you too many times
i made wordpress website in 2012 and since then i am using facebook graph api(php sdk) tool to upload pictures to users fb profile, now i dont know why its saying facebook redirected you too many times

here is the example link of picture where you can see upload to fb option

http://www.punjabidharti.com/punjabi/punjabi-sad/roula-kaavan-da/

This is my code in fb index file

```<code>    <?php
if(isset($_POST["source"]))
{
    try {
        $access_token=$facebook->getAccessToken();
        $graph_url= "https://graph.facebook.com/me/photos?"
      . "url=" . urlencode($_POST["source"])
      . "&message=" . urlencode($_POST['message'])
      . "&method=POST"
      . "&access_token=" .$access_token;
        $response=file_get_contents($graph_url);
        $json=json_decode($response);
      }
      catch (FacebookApiException $e) {
        error_log('Could not post image to Facebook.');
      }
}
?>
</code>```

i am using api 2.0 and in base_facbook file

```<code>public static $CURL_OPTS = array(
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_USERAGENT      => 'facebook-php-3.1',
      );
</code>```

please help me

答:
Your question doesn't explain too much about you error, but as far as I know you are doing a GET request and it seems that the API request its a POST.

I recommend you to update your request to use the last API version and to do a POST request for example using curl as follows:

```<code>$data = "url=" . urlencode($_POST["source"])
  . "&caption=" . urlencode($_POST['message'])
  . "&access_token=" .$facebook->getAccessToken();

$endpoint = "https://graph.facebook.com/v2.4/me/photos";

$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$reply=curl_exec($ch);
curl_close($ch);
</code>```

This snippet was not tested but I think it shows the idea.

Hope it helps!

Title: facebook redirected you too many times

Body:
i made wordpress website in 2012 and since then i am using facebook graph api(php sdk) tool to upload pictures to users fb profile, now i dont know why its saying facebook redirected you too many times

here is the example link of picture where you can see upload to fb option

http://www.punjabidharti.com/punjabi/punjabi-sad/roula-kaavan-da/

This is my code in fb index file

    <?php
if(isset($_POST["source"]))
{
    try {
        $access_token=$facebook->getAccessToken();
        $graph_url= "https://graph.facebook.com/me/photos?"
      . "url=" . urlencode($_POST["source"])
      . "&message=" . urlencode($_POST['message'])
      . "&method=POST"
      . "&access_token=" .$access_token;
        $response=file_get_contents($graph_url);
        $json=json_decode($response);
      }
      catch (FacebookApiException $e) {
        error_log('Could not post image to Facebook.');
      }
}
?>

i am using api 2.0 and in base_facbook file

public static $CURL_OPTS = array(
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_USERAGENT      => 'facebook-php-3.1',
      );

please help me

Body:
Your question doesn't explain too much about you error, but as far as I know you are doing a GET request and it seems that the API request its a POST.

I recommend you to update your request to use the last API version and to do a POST request for example using curl as follows:

$data = "url=" . urlencode($_POST["source"])
  . "&caption=" . urlencode($_POST['message'])
  . "&access_token=" .$facebook->getAccessToken();

$endpoint = "https://graph.facebook.com/v2.4/me/photos";

$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$reply=curl_exec($ch);
curl_close($ch);

This snippet was not tested but I think it shows the idea.

Hope it helps!