问:
How can I make my TextView font as shown in image
I am trying to style my text of STUDENT LOGIN which is shown in the image.
But I don't know how can use a different custom font to make my STUDENT LOGIN to look like as shown in the image.

I want Style in that way. How Can I make my S and L shown in image

答:
If you do not want to use spannable you can use this :</p>

```<code>String sourceString = "<b>" + id + "</b> " + name;
mytextview.setText(Html.fromHtml(sourceString));
</code>```

Body:
If you do not want to use spannable you can use this :

String sourceString = "<b>" + id + "</b> " + name;
mytextview.setText(Html.fromHtml(sourceString));


来源: stackexchange

问:
Convert Date string in NodeIS
I have a TranDate "2017/07/05 12:12:22", i want to convert it to this style : 20170705121222, can you help me what function of nodejs can I use to do this issue ? Thank you !</p>

答:
You could also do it with a replace.

var result = "2017/07/05 12:12:22".replace(/[\/ :]/g, '');
console.log(result)```

ContentLicense: CC BY-SA 3.0

Title: Convert Date string in NodeIS


问:
Sending data between sites
What is a good method to send data from site A to site B without passing a new URL parameter?

For instance, on site A I submit apples are red via a form. How can I send that data to site B without modifying site B's URL structure?

example http://siteb.com/?data=apples+are+red

Not sure if trackbacks or pingbacks use a similar method.

答:
if you're just trying to submit the form directly to siteb, simply use method="get" and action="http://siteb.com"

lets say you are sending an offset where siteb will use it to determine a page number from an arcticles listing, your form on sitea would be something like:

```<code><form method="get" action="http://siteb.com">
  <input type="text" name="offset" id="offset" value="0" />
  <input type="submit" value="OK" />
</form>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Sending data between sites

Body:
if you're just trying to submit the form directly to siteb, simply use method="get" and action="http://siteb.com"

lets say you are sending an offset where siteb will use it to determine a page number from an arcticles listing, your form on sitea would be something like:

<form method="get" action="http://siteb.com">
  <input type="text" name="offset" id="offset" value="0" />
  <input type="submit" value="OK" />
</form>


答:
Convert it to integer type using astype(int) as follows:</p>

```<code>DFinal = pd.merge(df_aviris.astype(int),df_geomap.astype(int),how='outer',on=['x','y'],left_index=False,right_index=False,copy=False)
</code>```

Title: TypeError: an integer is required in pd.merge python

Body:
I'm trying to combine two panda dataframes as shown below

df_aviris

            0    1    2         3          4
0         0.0  0.0  0.0  482636.5  4155009.5
1         0.0  0.0  0.0  482637.5  4155009.5
2         0.0  0.0  0.0  482638.5  4155009.5
3         0.0  0.0  0.0  482639.5  4155009.5
4         0.0  0.0  0.0  482640.5  4155009.5
5         0.0  0.0  0.0  482641.5  4155009.5
6         0.0  0.0  0.0  482642.5  4155009.5
7         0.0  0.0  0.0  482643.5  4155009.5
8         0.0  0.0  0.0  482644.5  4155009.5
       ...  ...  ...       ...        ...

16730996  0.0  0.0  0.0  485932.5  4149940.5
16730997  0.0  0.0  0.0  485933.5  4149940.5
16730998  0.0  0.0  0.0  485934.5  4149940.5
16730999  0.0  0.0  0.0  485935.5  4149940.5
[16731000 rows x 5 columns]

df_geomap

              0      1      2         x          y
0         255.0  255.0  255.0  477642.5  4158373.5
1         255.0  255.0  255.0  477643.5  4158373.5
2         255.0  255.0  255.0  477644.5  4158373.5
3         255.0  255.0  255.0  477645.5  4158373.5
4         255.0  255.0  255.0  477646.5  4158373.5
5         255.0  255.0  255.0  477647.5  4158373.5
6         255.0  255.0  255.0  477648.5  4158373.5
         ...    ...    ...       ...        ...

79026747  255.0  255.0  255.0  487218.5  4150124.5
79026748  255.0  255.0  255.0  487219.5  4150124.5
79026749  255.0  255.0  255.0  487220.5  4150124.5
[79026750 rows x 5 columns]

I tried to merge these two based on x and y.

DFinal = pd.merge(df_aviris,df_geomap,how='outer',on=['x','y'],left_index=False,right_index=False,copy=False)

and using concat also

DFinal = pd.concat([df_aviris.set_index(['x','y']),df_geomap.set_index(['x','y'])],join='inner',axis=1)

But getting the error as below

Traceback (most recent call last):
  File "pandas/index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas/index.c:4279)
  File "pandas/src/hashtable_class_helper.pxi", line 404, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:8543)
TypeError: an integer is required
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/indexes/base.py", line 2134, in get_loc
    return self._engine.get_loc(key)
  File "pandas/index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas/index.c:4433)
  File "pandas/index.pyx", line 156, in pandas.index.IndexEngine.get_loc (pandas/index.c:4363)
KeyError: 'x'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "pandas/index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas/index.c:4279)
  File "pandas/src/hashtable_class_helper.pxi", line 404, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:8543)
TypeError: an integer is required
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-38-0a4bfba1b1f4>", line 1, in <module>
    DFinal = pd.concat([df_aviris.set_index(['x','y']),df_geomap.set_index(['x','y'])],join='inner',axis=1)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 2917, in set_index
    level = frame[col]._values
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 2059, in __getitem__
    return self._getitem_column(key)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 2066, in _getitem_column
    return self._get_item_cache(key)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/generic.py", line 1386, in _get_item_cache
    values = self._data.get(item)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/internals.py", line 3543, in get
    loc = self.items.get_loc(item)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/indexes/base.py", line 2136, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas/index.c:4433)
  File "pandas/index.pyx", line 156, in pandas.index.IndexEngine.get_loc (pandas/index.c:4363)
KeyError: 'x'

I'm using python 3.6.1

Body:
Convert it to integer type using astype(int) as follows:

DFinal = pd.merge(df_aviris.astype(int),df_geomap.astype(int),how='outer',on=['x','y'],left_index=False,right_index=False,copy=False)


问:
type of object while implementing interface
Below is my code...

Its not that much complex.

Here I want to understand that In class D, b is an interface type variable and in that variable we are storing reference to new object of class(C) which implements that interface(B). How we are able to assign object of type C to interface B type variable b..? Class and Interface both are of different types then what makes it special when we implements a interface on class and we are able to do it which is my question

```<code>public interface A {

}

public interface B {

    public A methodABCD();
}

public class C implements B {

    final A typeA;

    public A methodABCD() {
        return typeA;
    }
}

public class D {
  static private B b;

  static public A methodABCD() {
    if (b == null) {
        b = new C();-------------->How..?
    }
    return b.methodABCD();
  }
}
</code>```

答:
Ok lets take an Example and illustrate it.

```<code>interface Animal {
   public void eat();
 }
 class Human implements Animal{
   public void eat(){
     // Eat cakes and Buns
   }
 }
 class Dog implements Animal{
   public void eat(){
     // Eat bones
   }
 }
</code>```

Now let see how you can use them

```<code>Animal h = new Human();
Animal d = new Dog();
</code>```

Now at  some point you might want to change your Human to behave like a Dog.

```<code>   h =d;
   h.eat();// Eat bones
</code>```

Your thought became a possibility because, they belongs to the same type. Imagine that there is not Animal interface and see how difficult it is convert a Human to Dog.

You see the flexibility and the advantages in type varying. You are allowed to do that because of they both are Animal nothing but an Interface.

Body:
Below is my code...

Its not that much complex.

Here I want to understand that In class D, b is an interface type variable and in that variable we are storing reference to new object of class(C) which implements that interface(B). How we are able to assign object of type C to interface B type variable b..? Class and Interface both are of different types then what makes it special when we implements a interface on class and we are able to do it which is my question

public interface A {

}

public interface B {

    public A methodABCD();
}

public class C implements B {

    final A typeA;

    public A methodABCD() {
        return typeA;
    }
}

public class D {
  static private B b;

  static public A methodABCD() {
    if (b == null) {
        b = new C();-------------->How..?
    }
    return b.methodABCD();
  }
}

Body:
Ok lets take an Example and illustrate it.

interface Animal {
   public void eat();
 }
 class Human implements Animal{
   public void eat(){
     // Eat cakes and Buns
   }
 }
 class Dog implements Animal{
   public void eat(){
     // Eat bones
   }
 }

Now let see how you can use them

Animal h = new Human();
Animal d = new Dog();

Now at  some point you might want to change your Human to behave like a Dog.

   h =d;
   h.eat();// Eat bones

Your thought became a possibility because, they belongs to the same type. Imagine that there is not Animal interface and see how difficult it is convert a Human to Dog.

You see the flexibility and the advantages in type varying. You are allowed to do that because of they both are Animal nothing but an Interface.


问:
Sorting table records in django
I am using a search field in django that searches hotel names from the hotel table based on the hotel names.
For searching I am using django's  function __search

```<code>data=request.POST.get("data")
data=models.hotels.objects.filter(name__search=name)
</code>```

By default it searches in BOOLEAN MODE

```<code>SELECT name FROM table WHERE MATCH(name)AGAINST('data' IN BOOLEAN MODE );
</code>```

But results comming are not arranged according to bests match
is there any method to change the search function to make query like this :

```<code>SELECT name FROM table WHERE MATCH(name)AGAINST('data');
</code>```

that remove the boolean sorting mode with the best match on top ?

答:
Using "search" is easy in Django. Here I am trying to search names from a report generated.

```<code>from django.db.models import Q

def report(request):
    data = Subscribers.objects.all()
    template = 'report.html'
    query = request.GET.get("q")
    if query:
        data = data.filter(
            Q(billNumber__icontains=query) |
            Q(name__icontains=query) |
            Q(area__icontains=query) |
            Q(phoneNumber__icontains=query)
        ).distinct()
    return render(request, template, {'entries': data})
</code>```

In the html page where you want to implement the search add the following code:

```<code><form>
  <input type="text" name="q" placeholder="Search Subscribers.." value="{{ request.GET.q }}">
</form>
</code>```

Title: Sorting table records in django

Body:
I am using a search field in django that searches hotel names from the hotel table based on the hotel names.
For searching I am using django's  function __search

data=request.POST.get("data")
data=models.hotels.objects.filter(name__search=name)

By default it searches in BOOLEAN MODE

SELECT name FROM table WHERE MATCH(name)AGAINST('data' IN BOOLEAN MODE );

But results comming are not arranged according to bests match
is there any method to change the search function to make query like this :

SELECT name FROM table WHERE MATCH(name)AGAINST('data');

that remove the boolean sorting mode with the best match on top ?

Body:
Using "search" is easy in Django. Here I am trying to search names from a report generated.

from django.db.models import Q

def report(request):
    data = Subscribers.objects.all()
    template = 'report.html'
    query = request.GET.get("q")
    if query:
        data = data.filter(
            Q(billNumber__icontains=query) |
            Q(name__icontains=query) |
            Q(area__icontains=query) |
            Q(phoneNumber__icontains=query)
        ).distinct()
    return render(request, template, {'entries': data})

In the html page where you want to implement the search add the following code:

<form>
  <input type="text" name="q" placeholder="Search Subscribers.." value="{{ request.GET.q }}">
</form>


问:
Java Thread: Run method cannot throw checked exception
In Java thread, the 'run' method cannot throw a 'checked exception'. I came across this in the Core Java (vol 1)  book. Can someone please explain the reasoning behind it? </p>

答:
throws declarations are part of the methods signature. To allow checked exceptions for Runnable#run, one had to declare them on the Runnable interface and had to try/catch everytime we start a thread.

Then again, we usually don't call the run method, we just implement it. We start() a Thread and then, somehow, the run method is called.

But the most obvious reason: When we start threads, we usually don't want to wait until the run method terminates just to catch exceptions like this:

```<code>try {
   new Worker().start();  // now wait until run has finished
} catch (SomeThreadException oops) {
   // handle checked exception
}
</code>```

Body:
throws declarations are part of the methods signature. To allow checked exceptions for Runnable#run, one had to declare them on the Runnable interface and had to try/catch everytime we start a thread.

Then again, we usually don't call the run method, we just implement it. We start() a Thread and then, somehow, the run method is called.

But the most obvious reason: When we start threads, we usually don't want to wait until the run method terminates just to catch exceptions like this:

try {
   new Worker().start();  // now wait until run has finished
} catch (SomeThreadException oops) {
   // handle checked exception
}


问:
SQL return selected result to EF
In Entity Framework, I tried executing these two queries:

Query #1:

```<code>var deptInput = new SqlParameter("@DepartmentName", deptString);
var departmentTable = Database.Users.FromSql("EXECUTE dbo.
[ViewEmployeeListByDepartment] @DepartmentName", deptInput).ToList();
</code>```

Query #2:

```<code>var deptInput = new SqlParameter("@DepartmentName", deptString);
var departmentTable = Database.Database.ExecuteSqlCommand("EXECUTE dbo.
[ViewEmployeeListByDepartment] @DepartmentName", deptInput);
</code>```

And this is my stored procedure in SQL Server:

```<code>Declare @CounterForEmployees int
Declare @NumberOfEmployees int
Declare @TableCount int = 1

Declare @DepartmentTable TABLE(
    Id nvarchar(450),
    UserName nvarchar(256),
    Display_Name nvarchar(256),
    Direct_Supervisor nvarchar(256),
    Ranking int
);

SET @NumberOfEmployees = (SELECT Count(*)
                          FROM dbo.[User]
                          WHERE Department = @DepartmentName)
SET @CounterForEmployees = 0

--Get the HOD of the Department First
INSERT INTO @DepartmentTable
    SELECT
        Id, UserName, Display_Name, Direct_Supervisor, ''
    FROM
        [ASEAppraisalDB].[dbo].[User]
    WHERE
        Department = @DepartmentName AND
        UserName IN (SELECT Distinct(Head_Of_Department)
                     FROM [ASEAppraisalDB].[dbo].[User]
                     WHERE Department = @DepartmentName)

UPDATE @DepartmentTable
SET Ranking = @TableCount
WHERE Ranking = 0
.
.
.
.
.
.
.
.
SELECT * FROM @DepartmentTable
</code>```

When I execute the first one, it returns a error message saying there is missing column from the dbo.[User] table inside @DepartmentTable. The dbo.[User] table has some columns I did not select into @DepartmentTable.

When I execute the second one, it returns only a number (which is the number of employees). It seems that the second query has only selected the part that counts the employee. The number of employee is only needed for my other parts of my code for calculations for a while loop. I do not need to return it to the EF.

I only want the result from select * from @DepartmentTable to be returned to Entity Framework. In the parameter of the stored procedure in SQL Server Object Explorer, it also says that it returns integer shown below:

How do I fix this? Also Which query is more efficient and more 'correct' to use?

答:
All stored procedures return an integer only.It also return the data for multiple data tables.

You check in SQL Server when you execute stored procedure it's return two set of data table in SQL Server optionally returns int.

You can verify this Link RETURN (Transact-SQL)

Title: SQL return selected result to EF

Body:
In Entity Framework, I tried executing these two queries:

Query #1:

var deptInput = new SqlParameter("@DepartmentName", deptString);
var departmentTable = Database.Users.FromSql("EXECUTE dbo.
[ViewEmployeeListByDepartment] @DepartmentName", deptInput).ToList();

Query #2:

var deptInput = new SqlParameter("@DepartmentName", deptString);
var departmentTable = Database.Database.ExecuteSqlCommand("EXECUTE dbo.
[ViewEmployeeListByDepartment] @DepartmentName", deptInput);

And this is my stored procedure in SQL Server:

Declare @CounterForEmployees int
Declare @NumberOfEmployees int
Declare @TableCount int = 1

Declare @DepartmentTable TABLE(
    Id nvarchar(450),
    UserName nvarchar(256),
    Display_Name nvarchar(256),
    Direct_Supervisor nvarchar(256),
    Ranking int
);

SET @NumberOfEmployees = (SELECT Count(*)
                          FROM dbo.[User]
                          WHERE Department = @DepartmentName)
SET @CounterForEmployees = 0

--Get the HOD of the Department First
INSERT INTO @DepartmentTable
    SELECT
        Id, UserName, Display_Name, Direct_Supervisor, ''
    FROM
        [ASEAppraisalDB].[dbo].[User]
    WHERE
        Department = @DepartmentName AND
        UserName IN (SELECT Distinct(Head_Of_Department)
                     FROM [ASEAppraisalDB].[dbo].[User]
                     WHERE Department = @DepartmentName)

UPDATE @DepartmentTable
SET Ranking = @TableCount
WHERE Ranking = 0
.
.
.
.
.
.
.
.
SELECT * FROM @DepartmentTable

When I execute the first one, it returns a error message saying there is missing column from the dbo.[User] table inside @DepartmentTable. The dbo.[User] table has some columns I did not select into @DepartmentTable.

When I execute the second one, it returns only a number (which is the number of employees). It seems that the second query has only selected the part that counts the employee. The number of employee is only needed for my other parts of my code for calculations for a while loop. I do not need to return it to the EF.

I only want the result from select * from @DepartmentTable to be returned to Entity Framework. In the parameter of the stored procedure in SQL Server Object Explorer, it also says that it returns integer shown below:

How do I fix this? Also Which query is more efficient and more 'correct' to use?


问:
How to fetch last row using distinct and group by same column
I want to retrieve balance of last row from table  using distinct accountid from last ledgerid

```<code>|---ledgerid---|--accountid--|--blance--|
|     1        |      1      |    500   |
|     2        |      1      |    800   |
</code>```

i want output as

```<code>|---ledgerid---|--accountid--|--blance--|
|     2        |      1      |    800   |
</code>```

答:
Try using the partition by as below.

```<code>select * from(select *
,row_number()over(partition by accountid order by ledgerid desc) r
from
[yourtable])
where r=1
order by accountid
</code>```

The above query is for SQL Server.

Body:
I want to retrieve balance of last row from table  using distinct accountid from last ledgerid

|---ledgerid---|--accountid--|--blance--|
|     1        |      1      |    500   |
|     2        |      1      |    800   |

i want output as

|---ledgerid---|--accountid--|--blance--|
|     2        |      1      |    800   |

Body:
Try using the partition by as below.

select * from(select *
,row_number()over(partition by accountid order by ledgerid desc) r
from
[yourtable])
where r=1
order by accountid

The above query is for SQL Server.


问:
JDOPersistenceManager memory leak
Using JDO JDOPersistenceManager, I keep getting memory leak detection reports from Plumbr, what is the correct way to create and destroy a JDOPersistenceManager

Plumbr report:

The objects are created at

```<code>org.datanucleus.api.jdo.JDOPersistenceManagerFactory.newPM(org.datanucleus.api.jdo.JDOPersistenceManagerFactory, java.lang.String, java.lang.String):838
</code>```

and are being held

```<code>in key of java.util.HashMap$Entry
in table of java.util.HashMap
in map of java.util.HashSet
in pmCache of org.datanucleus.api.jdo.JDOPersistenceManagerFactory
in pmf of com.example.MyServlet
</code>```

the last line, pmf is a singleton which initiates the object and used through the lifetime of the request. MyServlet is an httpservlet and a doPost is being called.

PMF.java:

```<code>public class PMF {

    private static PersistenceManagerFactory instance;

    public static PersistenceManagerFactory get() {

        if (instance == null) {
            Properties props = new Properties();
            props.setProperty("javax.jdo.PersistenceManagerFactoryClass",
                    "org.datanucleus.api.jdo.JDOPersistenceManagerFactory");
            props.put("datanucleus.PersistenceUnitName", "pmf");
            instance = JDOHelper.getPersistenceManagerFactory(props);
        }
        return instance;
    }
}
</code>```

typically i use the pmf instance in a try / finally block and use pmf:

```<code>PersistenceManager pm = pmf.getPersistenceManager();

    try {
    //do stuff
    }
    finally {
    pm.close();
    }
</code>```

what is the correct way to dispose of the pmf singlton so as not to cause a memory leak as reported by plumbr?

答:
I don't know Nikem's answer works and don't think you should explicitly call public void releasePersistenceManager(JDOPersistenceManager pm) because

It is internally called by JDOPersistenceManager's public void close().

The comments for this method says:

Only the PersistenceManager is allowed to call this method

Title: JDOPersistenceManager memory leak

Body:
Using JDO JDOPersistenceManager, I keep getting memory leak detection reports from Plumbr, what is the correct way to create and destroy a JDOPersistenceManager

Plumbr report:

The objects are created at

org.datanucleus.api.jdo.JDOPersistenceManagerFactory.newPM(org.datanucleus.api.jdo.JDOPersistenceManagerFactory, java.lang.String, java.lang.String):838

and are being held

in key of java.util.HashMap$Entry
in table of java.util.HashMap
in map of java.util.HashSet
in pmCache of org.datanucleus.api.jdo.JDOPersistenceManagerFactory
in pmf of com.example.MyServlet

the last line, pmf is a singleton which initiates the object and used through the lifetime of the request. MyServlet is an httpservlet and a doPost is being called.

PMF.java:

public class PMF {

    private static PersistenceManagerFactory instance;

    public static PersistenceManagerFactory get() {

        if (instance == null) {
            Properties props = new Properties();
            props.setProperty("javax.jdo.PersistenceManagerFactoryClass",
                    "org.datanucleus.api.jdo.JDOPersistenceManagerFactory");
            props.put("datanucleus.PersistenceUnitName", "pmf");
            instance = JDOHelper.getPersistenceManagerFactory(props);
        }
        return instance;
    }
}

typically i use the pmf instance in a try / finally block and use pmf:

PersistenceManager pm = pmf.getPersistenceManager();

    try {
    //do stuff
    }
    finally {
    pm.close();
    }

what is the correct way to dispose of the pmf singlton so as not to cause a memory leak as reported by plumbr?


问:
nodemon, babel-node: how to set environment variable?
Dev environment starts with this command:

```<code>nodemon -w src --exec \"babel-node src --presets es2015,stage-0\"
</code>```

How do i create a global variable (or process.env variable) __DEV__ = true?

答:
If you don't want to handle the env variables in the nodemon call, you can do something like this.

Create a file called '.env' and put something like this in it:

DEV=true

Then in your application entry file put the following line in as early as possible:

```<code>require('dotenv').config();
</code>```

Body:
Dev environment starts with this command:

nodemon -w src --exec \"babel-node src --presets es2015,stage-0\"

How do i create a global variable (or process.env variable) __DEV__ = true?

Body:
If you don't want to handle the env variables in the nodemon call, you can do something like this.

Create a file called '.env' and put something like this in it:

DEV=true

Then in your application entry file put the following line in as early as possible:

require('dotenv').config();

ContentLicense: CC BY-SA 4.0


问:
SQL Count no result if condition is 0
Hi my code is right about showing the right result wherein count in another table with same value of column

My Database:

Clientgroup table

```<code>id | clientgroup_name | clientgroup_color
10   Business Customer  green
11   Super VIP          red
12   Ultimate VIP       pink
</code>```

Client List Table:

```<code>id | name   | group_id
1    John      10
2    Mark      10
3    Paul      12
4    Nico      12
</code>```

My code:

```<code>SELECT Count(*) as Count,clientgroup_table.clientgroup_name,clientgroup_table.clientgroup_color FROM clientgroup_table, client_list WHERE client_list.group_id = clientgroup_table.id GROUP BY clientgroup_table.clientgroup_name
</code>```

My result:

```<code>Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink
</code>```

My desired result:

```<code>Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink
0       SUPER VIP           red
</code>```

I want to show 0 even there's no row equal to it

Is it possible?

thanks

答:
Try this one</p>

```<code>if object_id('tempdb..#t1') is not null
drop table #t1
CREATE TABLE #t1
    ([id] int, [clientgroup_name] varchar(17), [clientgroup_color] varchar(5))
;

INSERT INTO #t1
    ([id], [clientgroup_name], [clientgroup_color])
VALUES
    (10, 'Business Customer', 'green'),
    (11, 'Super VIP', 'red'),
    (12, 'Ultimate VIP', 'pink')
;

if object_id('tempdb..#t2') is not null
drop table #t2
CREATE TABLE #t2
    ([id] int, [name] varchar(4), [group_id] int)
;

INSERT INTO #t2
    ([id], [name], [group_id])
VALUES
    (1, 'John', 10),
    (2, 'Mark', 10),
    (3, 'Paul', 12),
    (4, 'Nico', 12)
;

select count(r.group_id) count,t.clientgroup_name,t.clientgroup_color from #t1 t left join #t2 r on r.group_id=t.id
group by t.clientgroup_name,t.clientgroup_color
</code>```

Title: SQL Count no result if condition is 0

Body:
Hi my code is right about showing the right result wherein count in another table with same value of column

My Database:

Clientgroup table

id | clientgroup_name | clientgroup_color
10   Business Customer  green
11   Super VIP          red
12   Ultimate VIP       pink

Client List Table:

id | name   | group_id
1    John      10
2    Mark      10
3    Paul      12
4    Nico      12

My code:

SELECT Count(*) as Count,clientgroup_table.clientgroup_name,clientgroup_table.clientgroup_color FROM clientgroup_table, client_list WHERE client_list.group_id = clientgroup_table.id GROUP BY clientgroup_table.clientgroup_name

My result:

Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink

My desired result:

Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink
0       SUPER VIP           red

I want to show 0 even there's no row equal to it

Is it possible?

thanks

Body:
Try this one

if object_id('tempdb..#t1') is not null
drop table #t1
CREATE TABLE #t1
    ([id] int, [clientgroup_name] varchar(17), [clientgroup_color] varchar(5))
;

INSERT INTO #t1
    ([id], [clientgroup_name], [clientgroup_color])
VALUES
    (10, 'Business Customer', 'green'),
    (11, 'Super VIP', 'red'),
    (12, 'Ultimate VIP', 'pink')
;

if object_id('tempdb..#t2') is not null
drop table #t2
CREATE TABLE #t2
    ([id] int, [name] varchar(4), [group_id] int)
;

INSERT INTO #t2
    ([id], [name], [group_id])
VALUES
    (1, 'John', 10),
    (2, 'Mark', 10),
    (3, 'Paul', 12),
    (4, 'Nico', 12)
;

select count(r.group_id) count,t.clientgroup_name,t.clientgroup_color from #t1 t left join #t2 r on r.group_id=t.id
group by t.clientgroup_name,t.clientgroup_color


问:
wholesale replacement of options html string within select?
I would like to 'toggle' the list of options in a select box.

I have the two sets of options as strings (American states and Canadian Provinces). However, I notice that in the DOM, the select object has no 'innerhtml' property (at least not according to w3schools).

Do I have to go and remove and replace the options one by one? How do I do this?

答:
Making use of jQuery, I usually do something like this:

```<code>var html = '[your html string with all the options elements]';
$('#mySelectId').empty();
$('#mySelectId').append(html);
</code>```

As for the one-by-one idea, make sure you keep in mind the general slowness of DOM interaction.  Wholesale replacement with the entire string is going to be pretty quick, but if you manipulate the DOM for each element in the select then expect it to be slow.

Body:
Making use of jQuery, I usually do something like this:

var html = '[your html string with all the options elements]';
$('#mySelectId').empty();
$('#mySelectId').append(html);

As for the one-by-one idea, make sure you keep in mind the general slowness of DOM interaction.  Wholesale replacement with the entire string is going to be pretty quick, but if you manipulate the DOM for each element in the select then expect it to be slow.


问:
Why is GRANT not working in MySQL?
I'm scratching my head on this one as I see a ton of helper websites showing how to create MySQL users and grant privileges but for some reason it just does not work for me.  I tried on both WinXP and a MacBook Pro laptop with the latest MySQL version installed.

The following is just an example from when I worked with WordPress.  The actual database is something different but same issues.

Here are the steps:

```<code>mysql> mysql -uroot -p<password>
mysql> CREATE DATABASE wwordpress;
mysql> CREATE USER 'www'@'localhost' IDENTIFIED BY 'basic';
</code>```

Query OK, 0 rows affected (0.14 sec)

```<code>mysql> GRANT INSERT ON wordpress.* TO 'www'@'localhost' IDENTIFIED BY 'basic';
</code>```

Query OK, 0 rows affected (0.00 sec)

```<code>mysql> FLUSH PRIVILEGES;
</code>```

Query OK, 0 rows affected (0.03 sec)

```<code>mysql> SELECT * FROM mysql.user WHERE User='www' \G
</code>```

```
*************************** 1. row ***************************
                 Host: localhost
                 User: www
             Password: *E85C94AF0F09C892339D31CF7570A970BCDC5805
          Select_priv: N
          Insert_priv: N
          Update_priv: N
          Delete_priv: N
          Create_priv: N
            Drop_priv: N
          Reload_priv: N
        Shutdown_priv: N
         Process_priv: N
            File_priv: N
           Grant_priv: N
      References_priv: N
           Index_priv: N
           Alter_priv: N
         Show_db_priv: N
           Super_priv: N
Create_tmp_table_priv: N
     Lock_tables_priv: N
         Execute_priv: N
      Repl_slave_priv: N
     Repl_client_priv: N
     Create_view_priv: N
       Show_view_priv: N
  Create_routine_priv: N
   Alter_routine_priv: N
     Create_user_priv: N
           Event_priv: N
         Trigger_priv: N
             ssl_type:
           ssl_cipher:
          x509_issuer:
         x509_subject:
        max_questions: 0
          max_updates: 0
      max_connections: 0
 max_user_connections: 0
1 row in set (0.00 sec)

mysql>
```

As you can see "Insert_priv: N" should be "Y".

Any suggestions?

Thanks in advance.

答:
This should work:</p>

```<code>GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost';
</code>```

Title: Why is GRANT not working in MySQL?

Body:
I'm scratching my head on this one as I see a ton of helper websites showing how to create MySQL users and grant privileges but for some reason it just does not work for me.  I tried on both WinXP and a MacBook Pro laptop with the latest MySQL version installed.

The following is just an example from when I worked with WordPress.  The actual database is something different but same issues.

Here are the steps:

mysql> mysql -uroot -p<password>
mysql> CREATE DATABASE wwordpress;
mysql> CREATE USER 'www'@'localhost' IDENTIFIED BY 'basic';

Query OK, 0 rows affected (0.14 sec)

mysql> GRANT INSERT ON wordpress.* TO 'www'@'localhost' IDENTIFIED BY 'basic';

Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;

Query OK, 0 rows affected (0.03 sec)

mysql> SELECT * FROM mysql.user WHERE User='www' \G

*************************** 1. row ***************************
                 Host: localhost
                 User: www
             Password: *E85C94AF0F09C892339D31CF7570A970BCDC5805
          Select_priv: N
          Insert_priv: N
          Update_priv: N
          Delete_priv: N
          Create_priv: N
            Drop_priv: N
          Reload_priv: N
        Shutdown_priv: N
         Process_priv: N
            File_priv: N
           Grant_priv: N
      References_priv: N
           Index_priv: N
           Alter_priv: N
         Show_db_priv: N
           Super_priv: N
Create_tmp_table_priv: N
     Lock_tables_priv: N
         Execute_priv: N
      Repl_slave_priv: N
     Repl_client_priv: N
     Create_view_priv: N
       Show_view_priv: N
  Create_routine_priv: N
   Alter_routine_priv: N
     Create_user_priv: N
           Event_priv: N
         Trigger_priv: N
             ssl_type:
           ssl_cipher:
          x509_issuer:
         x509_subject:
        max_questions: 0
          max_updates: 0
      max_connections: 0
 max_user_connections: 0
1 row in set (0.00 sec)

mysql>

As you can see "Insert_priv: N" should be "Y".

Any suggestions?

Thanks in advance.

Body:
This should work:

GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost';


问:
Update multiple documents with mongoose using node-cron
I'm trying to update multiple document with mongoose using node-cron. What I'm trying to accomplish is all documents that was created, let's say, July 1, will have an status of inactive after 30 days.

I manage to update multiple document using the code below but I don't know how to update multiple documents with products which date is less than the current date:

I know how to get the list of product that is less than the current date using but I don't know how to apply this logic to the code below -

```<code>let currentDate = new Date();
let query = Product.find({ dateCreated: {$lt: currentDate}});
</code>```

Code is unrelated to what I'm trying to accomplish. This is a sample
  code that will update multiple documents every 10 seconds.

```<code>const mongoose  = require('mongoose');
const Product   = require('../model/product');
const cron      = require('node-cron');

cron.schedule('*/10 * * * * *', function(){
    let productArray = ['Bacon', 'Apple', 'Fork', 'Beans'];
    productArray.map(product => updateProduct(product));
});

let updateProduct = (name) => {
    let randomNumber = Math.floor(Math.random() * (999 - 1 + 1));
    let query = Product.findOne({name: name}).select({ 'name': 1 });
    query.exec((err, product) => {
        if(err) throw err;
        if(product){
            product.description = `Random description generate every 10 seconds: ${randomNumber}`;
            product.save(err =>{
                if(err) throw err;
                console.log(`Successfully updated random description for: ${product.name}\n ${product.description}\n`);
            });
        }
    });
};
</code>```

Product Schema

```<code>const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const productSchema = mongoose.Schema({
    name            :   String,
    description     :   String,
    status          :   String,
    dateCreated     :   { type: Date, default: Date.now }, //
});

module.exports = mongoose.model( 'Product', productSchema );
</code>```

This is the only way I know to update multiple document in mongoose. So is there other way to update multiple document in mongoose after 30 days of creation using mongoose and node-cron? Pardon me if my question is confusing.

答:
Here you go the full version of code.

Here you no need to make multiple queries, like first selecting all
  the products whose currentdate has matched your criteria. Cause that
  you can do while updating the products itself.

```<code>const mongoose = require('mongoose');
const Product = require('../model/product');
const cron = require('node-cron');

cron.schedule('*/10 * * * * *', function() {
    let productArray = ['Bacon', 'Apple', 'Fork', 'Beans'];
    updateAllProducts(productArray, (err, res) => {
        if (err)
            //error handle, you can log here
        else
        //success handle, you can log here
    })
});

let updateAllProducts = (productArray, callbackFn) => {
    let randomNumber = Math.floor(Math.random() * (999 - 1 + 1));
    description = `Random description generate every 10 seconds: ${randomNumber}`;
    Product.update({
        name: {
            $in: productArray
        },
        dateCreated: {
            $lt: currentDate
        }
    }, {
        description: description
    }, {
        multi: true
    }, (err, res) => {
        if (err) {
            callbackFn(err, null)
        } else {
            callbackFn(null, err);
        }

    });

};
</code>```

In this case you can also log if Db update was failure or success. So there is better control over code. Rather than making multiple Calls in loop. That would be really time consuming and error prone.

Hope this helps!

Body:
I'm trying to update multiple document with mongoose using node-cron. What I'm trying to accomplish is all documents that was created, let's say, July 1, will have an status of inactive after 30 days.

I manage to update multiple document using the code below but I don't know how to update multiple documents with products which date is less than the current date:

I know how to get the list of product that is less than the current date using but I don't know how to apply this logic to the code below -

let currentDate = new Date();
let query = Product.find({ dateCreated: {$lt: currentDate}});

Code is unrelated to what I'm trying to accomplish. This is a sample
  code that will update multiple documents every 10 seconds.

const mongoose  = require('mongoose');
const Product   = require('../model/product');
const cron      = require('node-cron');

cron.schedule('*/10 * * * * *', function(){
    let productArray = ['Bacon', 'Apple', 'Fork', 'Beans'];
    productArray.map(product => updateProduct(product));
});

let updateProduct = (name) => {
    let randomNumber = Math.floor(Math.random() * (999 - 1 + 1));
    let query = Product.findOne({name: name}).select({ 'name': 1 });
    query.exec((err, product) => {
        if(err) throw err;
        if(product){
            product.description = `Random description generate every 10 seconds: ${randomNumber}`;
            product.save(err =>{
                if(err) throw err;
                console.log(`Successfully updated random description for: ${product.name}\n ${product.description}\n`);
            });
        }
    });
};

Product Schema

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const productSchema = mongoose.Schema({
    name            :   String,
    description     :   String,
    status          :   String,
    dateCreated     :   { type: Date, default: Date.now }, //
});

module.exports = mongoose.model( 'Product', productSchema );

This is the only way I know to update multiple document in mongoose. So is there other way to update multiple document in mongoose after 30 days of creation using mongoose and node-cron? Pardon me if my question is confusing.

Body:
Here you go the full version of code.

Here you no need to make multiple queries, like first selecting all
  the products whose currentdate has matched your criteria. Cause that
  you can do while updating the products itself.

const mongoose = require('mongoose');
const Product = require('../model/product');
const cron = require('node-cron');

cron.schedule('*/10 * * * * *', function() {
    let productArray = ['Bacon', 'Apple', 'Fork', 'Beans'];
    updateAllProducts(productArray, (err, res) => {
        if (err)
            //error handle, you can log here
        else
        //success handle, you can log here
    })
});

let updateAllProducts = (productArray, callbackFn) => {
    let randomNumber = Math.floor(Math.random() * (999 - 1 + 1));
    description = `Random description generate every 10 seconds: ${randomNumber}`;
    Product.update({
        name: {
            $in: productArray
        },
        dateCreated: {
            $lt: currentDate
        }
    }, {
        description: description
    }, {
        multi: true
    }, (err, res) => {
        if (err) {
            callbackFn(err, null)
        } else {
            callbackFn(null, err);
        }

    });

};

In this case you can also log if Db update was failure or success. So there is better control over code. Rather than making multiple Calls in loop. That would be really time consuming and error prone.

Hope this helps!


问:
AngularJS randomly show data bug
Here is my running code in Plunker

First issue I want to solve is: I want to randomly show the data. For my case, I have two questions. One is "Do you like Foo", another one is "Do you like Bar".
When I reload the page, I want these questions to show up randomly. For example, maybe "Do you like Foo" show first this time. But when I reload the page, "Do you like Bar" show first.

I made a custom random filter as below, but this will cause bug that "I cannot see the check symbol when I check the checkBox"

```<code>$scope.random = function () {
     return 0.5 - Math.random();
}
</code>```

Another in my line 14 of my Plunker, I added

Updated: Based on comment, I created another post for my another.

答:
Instead of picking up questions randomly, you can try shuffling your array before showing any question on your page.

This way, the array's elements will be randomly indexed, and you won't need to run the random function for each question.

Here is a post to help you with shuffling the array using JavaScript. Alternatively, you can also use Lodash's Shuffle function.

Title: AngularJS randomly show data bug

Body:
Here is my running code in Plunker

First issue I want to solve is: I want to randomly show the data. For my case, I have two questions. One is "Do you like Foo", another one is "Do you like Bar".
When I reload the page, I want these questions to show up randomly. For example, maybe "Do you like Foo" show first this time. But when I reload the page, "Do you like Bar" show first.

I made a custom random filter as below, but this will cause bug that "I cannot see the check symbol when I check the checkBox"

$scope.random = function () {
     return 0.5 - Math.random();
}

Another in my line 14 of my Plunker, I added

Updated: Based on comment, I created another post for my another.


问:
How does one iterate over an Array of Ranges?
Swift 3's compiler will not let me compile the following:

```<code>let a = 0
let b = 10
var arr = [ClosedRange<Int>]()
let myRange: ClosedRange = a...b
arr.append(myRange)

for each in arr {
    for every in each {
        print(every)
    }
}
</code>```

...due to ClosedRange<Int> not conforming to the Sequence protocol. In the past, a simple extension to the class like so would have been enough:

```<code>extension ClosedRange<Int>: Sequence {}
</code>```

...but now the compiler asks that the extension be declared with a where clause, which makes me think that I'm going about this all wrong. What am I missing?

答:
The problem is not that you have an array of ranges, but that
ClosedRange in Swift 3 represents

An interval over a comparable type, from a lower bound up to, and including, an upper bound.

For example, a closed range can be used with Double

```<code>let r: ClosedRange<Double> = 1.1...2.2
</code>```

where enumerating all possible values does not make much sense.

What you need is CountableClosedRange which is

A closed range that forms a collection of consecutive values.

and in particular is a collection and can be iterated over:

```<code>let a = 0
let b = 10
var arr = [CountableClosedRange<Int>]()
let myRange: CountableClosedRange = a...b
arr.append(myRange)

for each in arr {
    for every in each {
        print(every)
    }
}
</code>```

You can just write

```<code>let myRange = a...b
</code>```

since by default, the ... operator produces a CountableClosedRange
if its operands are Strideable.

Similarly there is Range and CountableRange for half-open ranges.
For more information, see Range Types in SE-0065 A New Model for Collections and Indices.

Body:
Swift 3's compiler will not let me compile the following:

let a = 0
let b = 10
var arr = [ClosedRange<Int>]()
let myRange: ClosedRange = a...b
arr.append(myRange)

for each in arr {
    for every in each {
        print(every)
    }
}

...due to ClosedRange<Int> not conforming to the Sequence protocol. In the past, a simple extension to the class like so would have been enough:

extension ClosedRange<Int>: Sequence {}

...but now the compiler asks that the extension be declared with a where clause, which makes me think that I'm going about this all wrong. What am I missing?

Body:
The problem is not that you have an array of ranges, but that
ClosedRange in Swift 3 represents

An interval over a comparable type, from a lower bound up to, and including, an upper bound.

For example, a closed range can be used with Double

let r: ClosedRange<Double> = 1.1...2.2

where enumerating all possible values does not make much sense.

What you need is CountableClosedRange which is

A closed range that forms a collection of consecutive values.

and in particular is a collection and can be iterated over:

let a = 0
let b = 10
var arr = [CountableClosedRange<Int>]()
let myRange: CountableClosedRange = a...b
arr.append(myRange)

for each in arr {
    for every in each {
        print(every)
    }
}

You can just write

let myRange = a...b

since by default, the ... operator produces a CountableClosedRange
if its operands are Strideable.

Similarly there is Range and CountableRange for half-open ranges.
For more information, see Range Types in SE-0065 A New Model for Collections and Indices.


问:
Where to place the call to a external API that has a dependency on a Model?
Suppose I have a Django app named "blog".

There's a model called Post and I have an external API call that returns the list of the most popular posts in a given time, e.g., the Google Analytics API.

My question is: Where is the expected place that I should place the code that makes the call to the external API, parses the id from each post, query the database and sort the list of models accordingly?

I don't think that it should live in the Manager or in a templatetag. Any tips or suggestions?

Thanks in advance!

EDIT: The desired result might be need in several places across the project, so if I place the code in view, I'll have duplication.

答:
It should be done in a view, or better, if your view code is getting cluttered, put it in a helper module.

```<code>import util
def view(request):
    util.process_post_rankings(request.user.id)
    # ... write additional logic and render to template
</code>```

However, be cautious with relying on external apis to render a page to your user. Things might go wrong, take an awful lot of time, API might not respond etc... Better to do that asynchronously with Javascript, and update the page when data is ready.

Body:
It should be done in a view, or better, if your view code is getting cluttered, put it in a helper module.

import util
def view(request):
    util.process_post_rankings(request.user.id)
    # ... write additional logic and render to template

However, be cautious with relying on external apis to render a page to your user. Things might go wrong, take an awful lot of time, API might not respond etc... Better to do that asynchronously with Javascript, and update the page when data is ready.


问:
Anchor tag is not working in safari iphone
Let me first add the anchor tag code

```<code><a id="store_follow"
    class="primary-button"
    data-user-action='on'
    data-id='<?php echo $value->storeId;?>'
    data-mode='<?php echo UserUtils::ACTION_MODE_STORE_FOLLOW;?>'
    data-toggle="true"
    data-callback="_obs_follow_stores"
> Follow </a>
</code>```

PHP is being used with this and this button works on all browser in all devices except safari in iphone.

When someone clicks on follow if user is logged in it will follow that thing and button will change to unfollow

If user is not logged in then it will open the login window popup for user.

What could be wrong with this ?

On unfollow button I am doing actions using onclick event from javascript and jquery ajax call so it's working

But in above button calling happening from PHP side.

What needs to changed to make it work on iphone safari ?

Unfollow code

```<code><a class="primary-button active" onclick="unfollowStore('<?php echo $value->storeId;?>');"> Unfollow </a>
</code>```

I can't do onclick on follow because PHP and I am just modifying this project.

答:
Try adding the href attribute to your tag and return false from your onclick method.

```<code><a href="#" class="primary-button active" onclick="unfollowStore('<?php echo $value->storeId;?>');return false;"> Unfollow </a>
</code>```

I know you said it works in all browsers but I have seen numerous times on desktop browsers where onclick does not work in an  tag when it does not have an href set.

If it still doesn't work try firing a different JavaScript method. Your code might be causeing causing a JavaScript error.

To alleviate the latter make sure your unfollowStore function or any other method is wrapped in a try {} catch{} block.

Body:
Let me first add the anchor tag code

<a id="store_follow"
    class="primary-button"
    data-user-action='on'
    data-id='<?php echo $value->storeId;?>'
    data-mode='<?php echo UserUtils::ACTION_MODE_STORE_FOLLOW;?>'
    data-toggle="true"
    data-callback="_obs_follow_stores"
> Follow

PHP is being used with this and this button works on all browser in all devices except safari in iphone.

When someone clicks on follow if user is logged in it will follow that thing and button will change to unfollow

If user is not logged in then it will open the login window popup for user.

What could be wrong with this ?

On unfollow button I am doing actions using onclick event from javascript and jquery ajax call so it's working

But in above button calling happening from PHP side.

What needs to changed to make it work on iphone safari ?

Unfollow code

<a class="primary-button active" onclick="unfollowStore('<?php echo $value->storeId;?>');"> Unfollow

I can't do onclick on follow because PHP and I am just modifying this project.

Body:
Try adding the href attribute to your tag and return false from your onclick method.

<a href="#" class="primary-button active" onclick="unfollowStore('<?php echo $value->storeId;?>');return false;"> Unfollow </a>

I know you said it works in all browsers but I have seen numerous times on desktop browsers where onclick does not work in an <a> tag when it does not have an href set.

If it still doesn't work try firing a different JavaScript method. Your code might be causeing causing a JavaScript error.

To alleviate the latter make sure your unfollowStore function or any other method is wrapped in a try {} catch{} block.


答: just define in codes (server file) like this proccess.env.VARIABLE="true"

Title: nodemon, babel-node: how to set environment variable?


问:
How to get the last id from inserted row?
I'm trying to get the ID of my master table to be inserted to my transaction table. The insert is happening inside a loop.

Behavior:

Insert master

Get id

Insert Transaction

Insert Master

Get id

Insert Transaction

Controller:

```<code> //Insert Master
 foreach($arr_master as $res_master){

    /*$data['ID_REQUIREMENT_TRANS'] this is an auto-increment column. Inserted automatically*/

    $data['ID_REQUIREMENT']     = $res_master;
    $data['SENT_BY_DATE']       = date("Y-m-d H:i:s");
    $data['STATUS']             = 1;

    $this->MAdmin->ins_assign_pic($data);

        //Insert Trans
        foreach($arr_trans as $res_trans){

            $data_d['ID_REQUIREMENT_TRANS'] = $id; //Need to get the last inserted id of the master table
            $data_d['RECEIVED_BY']              = $res_trans;
            $data_d['RECEIVED_BY_DATE']     = NULL;
            $data_d['STATUS']                   = 1;

            $this->MAdmin->ins_assign_pic_d($data_d);
        }
    }
</code>```

Model:

```<code>function ins_assign_pic($data){
    $q_ins_assign_pic   = $this->db->insert('pm_requirement_assign_pic',$data);
    return $q_ins_assign_pic;

    $id = $this->db->insert_id();
    return $id;      //How to send this to my controller
    return true;
}

function ins_assign_pic_d($data_d){
    $q_ins_assign_pic_d = $this->db->insert('pm_requirement_assign_pic_d',$data_d);

    return $q_ins_assign_pic_d;
}
</code>```

答:
Try controller </p>

```<code>$id = $this->MAdmin->ins_assign_pic($data);
</code>```

<p>And model </p>

```<code>function ins_assign_pic($data){
    $q_ins_assign_pic   = $this->db->insert('pm_requirement_assign_pic',$data);
    //return $q_ins_assign_pic;

    $id = $this->db->insert_id();
    return $id;      //How to send this to my controller
   // return true;
}
</code>```

Body:
I'm trying to get the ID of my master table to be inserted to my transaction table. The insert is happening inside a loop.

Behavior:

Insert master

Get id

Insert Transaction

Insert Master

Get id

Insert Transaction

Controller:

 //Insert Master
 foreach($arr_master as $res_master){

    /*$data['ID_REQUIREMENT_TRANS'] this is an auto-increment column. Inserted automatically*/

    $data['ID_REQUIREMENT']     = $res_master;
    $data['SENT_BY_DATE']       = date("Y-m-d H:i:s");
    $data['STATUS']             = 1;

    $this->MAdmin->ins_assign_pic($data);

        //Insert Trans
        foreach($arr_trans as $res_trans){

            $data_d['ID_REQUIREMENT_TRANS'] = $id; //Need to get the last inserted id of the master table
            $data_d['RECEIVED_BY']              = $res_trans;
            $data_d['RECEIVED_BY_DATE']     = NULL;
            $data_d['STATUS']                   = 1;

            $this->MAdmin->ins_assign_pic_d($data_d);
        }
    }

Model:

function ins_assign_pic($data){
    $q_ins_assign_pic   = $this->db->insert('pm_requirement_assign_pic',$data);
    return $q_ins_assign_pic;

    $id = $this->db->insert_id();
    return $id;      //How to send this to my controller
    return true;
}

function ins_assign_pic_d($data_d){
    $q_ins_assign_pic_d = $this->db->insert('pm_requirement_assign_pic_d',$data_d);

    return $q_ins_assign_pic_d;
}

Body:
Try controller

$id = $this->MAdmin->ins_assign_pic($data);

And model

function ins_assign_pic($data){
    $q_ins_assign_pic   = $this->db->insert('pm_requirement_assign_pic',$data);
    //return $q_ins_assign_pic;

    $id = $this->db->insert_id();
    return $id;      //How to send this to my controller
   // return true;
}


问:
Arabic in Chtml::label Yii
I've got a problem with arabic and some other languages like greek when I'm trying to show text with Chtml::label with Yii and user access to website without log in.
Everything is ok when the user is logged in and the curious thing is that the form is exactly the same.
If got charset ok in the html:

```<code><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</code>```

That's an example of how I see the text in arabic:

ل� يش�ل التقرير كل �ا كنت أنتظره

And that's the same text in the same form when the user is logged in:

لم يشمل التقرير كل ما كنت أنتظره

Code in yii to retrieve the data:

```<code><div class="section row principal_question">
        <?php echo CHtml::label($textt, null, array('class'=>'question_nps')); ?>
</div>
</code>```

答:
Test with below code somewhere in your code and update your label text with Yii::t return text.

```<code>Yii::app()->language = 'ar';
echo Yii::t('TransalorTest', 'لم يشمل التقرير كل ما كنت أنتظره');
Yii::app()->end();
</code>```

I hope, this will help you.

Title: Arabic in Chtml::label Yii

Body:
I've got a problem with arabic and some other languages like greek when I'm trying to show text with Chtml::label with Yii and user access to website without log in.
Everything is ok when the user is logged in and the curious thing is that the form is exactly the same.
If got charset ok in the html:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

That's an example of how I see the text in arabic:

ل� يش�ل التقرير كل �ا كنت أنتظره

And that's the same text in the same form when the user is logged in:

لم يشمل التقرير كل ما كنت أنتظره

Code in yii to retrieve the data:

        <?php echo CHtml::label($textt, null, array('class'=>'question_nps')); ?>

Body:
Test with below code somewhere in your code and update your label text with Yii::t return text.

Yii::app()->language = 'ar';
echo Yii::t('TransalorTest', 'لم يشمل التقرير كل ما كنت أنتظره');
Yii::app()->end();

I hope, this will help you.


问:
How does Hibernate Metamodel Generator work?
Recently just making a move from Hibernate Session api to JPA2.  I am assuming it should be some setup problem. But basically my eclipse does not recognize Metamodel attribute.

For example: builder.like( root.get(Book_.name) , search)  Book_ can not be resolved as variable.

Now I have followed this http://hibernate.org/orm/tooling/  and added

```<code><dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-jpamodelgen</artifactId>
  <version>5.2.6.Final</version>
</dependency>
</code>```

As it stated here https://docs.jboss.org/hibernate/orm/5.0/topical/html/metamodelgen/MetamodelGenerator.html

In most cases the annotation processor will automatically run provided the processor jar is added to the build classpath

I have checked my build path it included all maven dependency including jpamodelgen, but my eclipse still say Book_ can not be resolved.

What am I doing wrong here?

This is my Dao...

```<code>CriteriaBuilder builder = entityManager.getCriteriaBuilder();

    CriteriaQuery<Book> criteria = builder.createQuery(Book.class);

    Root<Book> root = criteria.from(Book.class);

    criteria.select(root);

    if( search != null && !search.isEmpty() ){

        criteria.where(builder.add(
                builder.like( root.get(Book_.name) , search),  // Book_ cannot be resolved a variable
                builder.like(root.get(Book_.ispn), search)    //  ""
                )
        );

    }

    List<Book> books = entityManager.createQuery(criteria).getResultList();

    return books;
</code>```

My dependency

```<code>   <properties>
    <spring-version>4.3.5.RELEASE</spring-version>
    <hibernate-version>5.2.6.Final</hibernate-version>
   </properties>
   <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate-version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-orm-modules</artifactId>
        <version>${hibernate-version}</version>
        <type>pom</type>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-jpamodelgen</artifactId>
      <version>${hibernate-version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.3.4.Final</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.40</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.6</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.6</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.6</version>
    </dependency>
    <dependency>
        <groupId>javax.transaction</groupId>
        <artifactId>jta</artifactId>
        <version>1.1</version>
    </dependency>
</code>```

Thank you

答:
Rafik solution does work but I just wanted to add another method that also worked for me is to enable annotation processing in your eclipse project.  The doc from hibernate https://docs.jboss.org/hibernate/orm/5.0/topical/html/metamodelgen/MetamodelGenerator.html  wasn't really clear to me as it doesn't have step by step setup.  So here is how I did it.

This is project specific.

Click on project.

Right click and chose properties

Java Compiler> Annotation Processing :: enable this

Java Compiler> Annotation Processing> FactoryPath  select add External JARS

Add hibernate-jpamodelgen-x.x.x.Final.jar

Click okey / clean project

This should work as well.

Hope this helps others

Update
I stumbled upon this site that has pictures might be easier to follow.
https://docs.jboss.org/hibernate/orm/5.0/topical/html/metamodelgen/MetamodelGenerator.html

Body:
Recently just making a move from Hibernate Session api to JPA2.  I am assuming it should be some setup problem. But basically my eclipse does not recognize Metamodel attribute.

For example: builder.like( root.get(Book_.name) , search)  Book_ can not be resolved as variable.

Now I have followed this http://hibernate.org/orm/tooling/  and added

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-jpamodelgen</artifactId>
  <version>5.2.6.Final</version>
</dependency>

As it stated here https://docs.jboss.org/hibernate/orm/5.0/topical/html/metamodelgen/MetamodelGenerator.html

In most cases the annotation processor will automatically run provided the processor jar is added to the build classpath

I have checked my build path it included all maven dependency including jpamodelgen, but my eclipse still say Book_ can not be resolved.

What am I doing wrong here?

This is my Dao...

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

    CriteriaQuery<Book> criteria = builder.createQuery(Book.class);

    Root<Book> root = criteria.from(Book.class);

    criteria.select(root);

    if( search != null && !search.isEmpty() ){

        criteria.where(builder.add(
                builder.like( root.get(Book_.name) , search),  // Book_ cannot be resolved a variable
                builder.like(root.get(Book_.ispn), search)    //  ""
                )
        );

    }

    List<Book> books = entityManager.createQuery(criteria).getResultList();

    return books;

My dependency

   <properties>
    <spring-version>4.3.5.RELEASE</spring-version>
    <hibernate-version>5.2.6.Final</hibernate-version>
   </properties>
   <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate-version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-orm-modules</artifactId>
        <version>${hibernate-version}</version>
        <type>pom</type>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-jpamodelgen</artifactId>
      <version>${hibernate-version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.3.4.Final</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.40</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.6</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.6</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.6</version>
    </dependency>
    <dependency>
        <groupId>javax.transaction</groupId>
        <artifactId>jta</artifactId>
        <version>1.1</version>
    </dependency>

Thank you


问:
Extract one or more qualifying substrings from each string in an array
I am trying to extract qualifying substrings from an array of strings. Some strings in the array have just one qualifying substring, but others may have more.  I need to build a flat array of all of these wanted values.

The following is my current Codeigniter method, but it doesn't handle cases when more than one qualifying substring exists.

```<code>public function generatenewname()
{
    $this->load->helper('directory');
    $map = directory_map('./assets/file_upload/md/temp/', FALSE, TRUE);
    for ($x = 0; $x < count($map); $x++) {
        $newest[$x] = explode(" ", $map[$x]);
        for ($y = 0; $y < count($newest[$x]); $y++) {
            if (strlen($newest[$x][$y]) >= 7) {
                $file[] = $newest[$x][$y];
            }
        }
    }
    for ($x = 0; $x < count($file); $x++) {
        echo $x . ' ' . $file[$x] . '<br>';
    }
}
</code>```

Assume that my $map array contains this:

```<code>$map = [
    'BACK PACK BBP160800103  G086-1 8#.JPG',
    'BACKPACK BBP160500010 G114-3#1.JPG',
    'WSL160800024-WSL160800025 L83-5.JPG',
    'IA041017 L83-5.JPG'
];
</code>```

Desired result:

```<code>[
    'BBP160800103',
    'BBP160500010',
    'WSL160800024',
    'WSL160800025',
    'IA041017'
]
</code>```

答:
You can match against the patterns based on starting keys.

```<code>$array = [
    ['BACK', 'PACK', 'BBP160800103', '', 'G086-1', '8#.JPG'],
    ['BACKPACK', 'BBP160500010', 'G114-3#1.JPG'],
    ['WSL160800024-WSL160800025', 'L83-5.JPG'],
    ['IA041017', 'L83-5.JPG']
];

$patterns = ['(BBP\w+)', '(WSL\w+)', '(IA\w+)'];

$codes = [];
$matcher = '/' . implode($patterns, '|') . '/';

foreach ($array as $arr) {
    array_map(function ($value) use ($matcher, &$codes) {
        preg_match_all($matcher, $value, $matches);

        foreach($matches as $match) {
            $codes = array_merge(array_filter($match), $codes);
        }
    }, $arr);
}

print_r(array_unique($codes));

// output
Array
(
    [0] => IA041017
    [2] => WSL160800024
    [3] => WSL160800025
    [6] => BBP160500010
    [8] => BBP160800103
)
</code>```

Body:
I am trying to extract qualifying substrings from an array of strings. Some strings in the array have just one qualifying substring, but others may have more.  I need to build a flat array of all of these wanted values.

The following is my current Codeigniter method, but it doesn't handle cases when more than one qualifying substring exists.

public function generatenewname()
{
    $this->load->helper('directory');
    $map = directory_map('./assets/file_upload/md/temp/', FALSE, TRUE);
    for ($x = 0; $x < count($map); $x++) {
        $newest[$x] = explode(" ", $map[$x]);
        for ($y = 0; $y < count($newest[$x]); $y++) {
            if (strlen($newest[$x][$y]) >= 7) {
                $file[] = $newest[$x][$y];
            }
        }
    }
    for ($x = 0; $x < count($file); $x++) {
        echo $x . ' ' . $file[$x] . '
';
    }
}

Assume that my $map array contains this:

$map = [
    'BACK PACK BBP160800103  G086-1 8#.JPG',
    'BACKPACK BBP160500010 G114-3#1.JPG',
    'WSL160800024-WSL160800025 L83-5.JPG',
    'IA041017 L83-5.JPG'
];

Desired result:

[
    'BBP160800103',
    'BBP160500010',
    'WSL160800024',
    'WSL160800025',
    'IA041017'
]

Body:
You can match against the patterns based on starting keys.

$array = [
    ['BACK', 'PACK', 'BBP160800103', '', 'G086-1', '8#.JPG'],
    ['BACKPACK', 'BBP160500010', 'G114-3#1.JPG'],
    ['WSL160800024-WSL160800025', 'L83-5.JPG'],
    ['IA041017', 'L83-5.JPG']
];

$patterns = ['(BBP\w+)', '(WSL\w+)', '(IA\w+)'];

$codes = [];
$matcher = '/' . implode($patterns, '|') . '/';

foreach ($array as $arr) {
    array_map(function ($value) use ($matcher, &$codes) {
        preg_match_all($matcher, $value, $matches);

        foreach($matches as $match) {
            $codes = array_merge(array_filter($match), $codes);
        }
    }, $arr);
}

print_r(array_unique($codes));

// output
Array
(
    [0] => IA041017
    [2] => WSL160800024
    [3] => WSL160800025
    [6] => BBP160500010
    [8] => BBP160800103
)


问:
Selecting multiple photos from camera roll
I'm building a simple app to take pictures of events in React Native. and am stuck on a problem.

I want to submit a photo album to a database to be displayed later. The album will include -- Album Name, Album Description, and Photos... but I'm having a hard time visualizing how to select multiple photos from the camera roll, manipulate them, submit them to a db.

I tried to figure out an order of how I would do accomplish this..

Create new event

Add event name

Add event description

Click button > Open Gallery

Select Multiple photos

Save photos to cache and display thumbnails in "Preview" component

Submit "Event" and photos to DB.

Am I even close? Any link to an article, or anything to point me in the right direction would be greatly appreciated.

答:
You can these two libraries to easily complete your task.

https://github.com/react-community/react-native-image-picker ( For selecting multiple images from camera roll)

https://github.com/wkh237/react-native-fetch-blob (For uploading images )


问:
How can i access the tag of button in CollectionView's cell contained in TableView cell
I'm working on a project in which i have a UICollectionView in UITableViewCell. My View hierarchy is like below:

TableViewCell

CollectionView

CollectionView Cell

Button(for which i want to access the know the tagValue).

I have two table view cell and in each tableView cell there is a UICollectionView And each UICollectionView contain 4 UICollectionViewCell, So i want to know the exact tagValue of my button contained within a UICollectionViewCell whenever it is pressed.
I have also given the tag value to button in cellForItem atIndexpath TableView cell class like so

```<code>cell.button.tag = indexpath.item
</code>```

and i have also given selector to the button.

答:
Try this :

Remove this line :

```<code>cell.button.tag = indexpath.item
</code>```

Add this fuction

```<code> @IBAction func clickCollectionCellButton(sender : UIButton){
            var cell: UICollectionViewCell? = (sender.superview?.superview as? UICollectionViewCell) //track your view hierarchy
            var indexpath: IndexPath? = collectionView?.indexPath(for: cell!)
           // do your additional work
        }
</code>```

Body:
I'm working on a project in which i have a UICollectionView in UITableViewCell. My View hierarchy is like below:

TableViewCell

CollectionView

CollectionView Cell

Button(for which i want to access the know the tagValue).

I have two table view cell and in each tableView cell there is a UICollectionView And each UICollectionView contain 4 UICollectionViewCell, So i want to know the exact tagValue of my button contained within a UICollectionViewCell whenever it is pressed.
I have also given the tag value to button in cellForItem atIndexpath TableView cell class like so

cell.button.tag = indexpath.item

and i have also given selector to the button.

Body:
Try this :

Remove this line :

cell.button.tag = indexpath.item

Add this fuction

 @IBAction func clickCollectionCellButton(sender : UIButton){
            var cell: UICollectionViewCell? = (sender.superview?.superview as? UICollectionViewCell) //track your view hierarchy
            var indexpath: IndexPath? = collectionView?.indexPath(for: cell!)
           // do your additional work
        }


问:
Kotlin Simplify Boolean Expression
Why do I get a minor error that says "Simplify boolean expression" in my if condition line?

For instance this snippet of code:

```<code>if (isClear==true){
    displayText.setText("")
}
</code>```

答:
I'd just like to add that in the case of warnings and errors in IDEA, you can invoke intention actions when your cursor is at them (Alt + Enter on Windows and Linux, Command + Return on Mac) to get possible fixes.

In your case, bringing up intention actions on the warning will look something like this:

Choosing the single available option will do the transformation to the simplifed code for you:

Title: Kotlin Simplify Boolean Expression

Body:
Why do I get a minor error that says "Simplify boolean expression" in my if condition line?

For instance this snippet of code:

if (isClear==true){
    displayText.setText("")
}


问:
What are practical guidelines for evaluating a language's "Turing Completeness"?
I've read "what-is-turing-complete" and the wikipedia page, but I'm less interested in a formal proof than in the practical implications of requirements for being Turing Complete.

What I'm actually trying to decide is if the toy language I've just designed could be used as a general-purpose language.  I know I can prove it is if I can write a Turing machine with it.  But I don't want to go through that exercise until I'm fairly certain of success.

Is there a minimum set of features without which Turing Completeness is impossible?
Is there a set of features which virtually guarantees completeness?

(My guess is that conditional branching and a readable/writeable memory store will get me most of the way there)

EDIT:

I think I've gone off on a tangent by saying "Turing Complete".   I'm trying to guess with reasonable confidence that a newly invented language with a certain feature set (or alternately, a VM with a certain instruction set) would be able to compute anything worth computing.  I know that proving you can build a Turing machine with it is one way, but not the only way.

What I was hoping for was a set of guidelines like: "if a language can do X,Y,and Z, it can probably do anything".

答:
If you can implement a Turing machine (as far as they can be implemented, as they're mathematical constructs with unlimited memory [the tape size is infinte]) then you can be sure it's Turing complete.

Some indications:

You can check memory and manipulate it based on the current value as well as using it to control program flow.

That memory can be allocated memory, strings which you're able to append to, a stack which you can allocate memory on through recursion etc.

Program flow can be through iteration or through selection based recursion.

OwnerDisplayName: AShelly

LastEditorDisplayName: AShelly


问:
JQuery tooltip that supports new line
I'm looking for a lightweight jquery plugin for displaying tooltips when the user hovers over an element. I would like the plugin to get the content from the title attribute and also it's important that I can make new lines.

Any help is appreciated!

答: http://elliotlings.com/jquery/tooltip is a good tooltip to manage tooltips which need to hold more content</p>

Title: JQuery tooltip that supports new line