问:
g_cache_insert() crashes with null pointer error
I wrote a test example in glib:

```<code>#undef G_DISABLE_ASSERT
#undef G_LOG_DOMAIN

#include <stdio.h>
#include <string.h>
#include "glib.h"

void function(gchar *key,gchar *value,gint *user_data)
{
 // give the count of the number of times the function was called
 (*user_data)++;
}

void cache_test()
{
 gchar *str1,*str2,*str3;
 GCache *cache = NULL;
 gint user_data = 0;

 g_assert((cache = g_cache_new( (GCacheNewFunc) g_ascii_strup,
     g_free, (GCacheDupFunc) g_strdup, g_free, g_str_hash,
        g_str_hash, g_str_equal)) != NULL);
 g_print("\n g_assert g_cache_new");
    str1 = g_cache_insert(cache,"test");
    g_print("\n str1 = g_cache_insert(cache,test)");
    g_assert(!strcmp("TEST",str1));
    g_print("\n g_assert(!strcmp(TEST,str1))");
 str2 = g_cache_insert(cache,"test");
 g_print("\n str2 = g_cache_insert(cache,test)");
 g_assert(!strcmp("TEST",str1));
 g_print("\n g_assert(!strcmp(TEST,str1))");
 str3 = g_cache_insert(cache,"glib");
 g_print("\n str3 = g_cache_insert(cache,glib)");
 g_assert(!strcmp("GLIB",str3));
 g_print("\n g_assert(!strcmp(GLIB,str3))");
 g_cache_key_foreach (cache,(GHFunc)function,&user_data);
 g_print("\n g_cache_key_foreach (cache,(GHFunc)function,&user_data)");
 //g_cache_key_foreach would call function twice and make user_data == 2
 g_assert(user_data == 2);

 g_cache_value_foreach (cache,(GHFunc)function,&user_data);
 g_print("\n g_cache_key_foreach (cache,(GHFunc)function,&user_data)");
 //g_cache_value_foreach would call function twice and make user_data == 4
 g_assert(user_data == 4);

 g_cache_remove(cache,str1);
 g_print("\n g_cache_remove(cache,str1)");
 g_cache_remove(cache,str2);
 g_print("\n g_cache_remove(cache,str1)");
 g_cache_remove(cache,str3);
 g_print("\n g_cache_remove(cache,str1)");
 g_cache_destroy(cache);
 g_print("\n g_cache_destroy(cache)");
}

int main (int   argc,
      char *argv[])
{
 cache_test();
 return 0;
}
</code>```

Now my test example crashes at str1 = g_cache_insert(cache,"test"); because of null pointer dereferencing.
Any help where I could be going wrong?

Edit

I just tried 1 more quick fix to the test code to confirm your suggestion (of the bug in g_ascii_strup). I used the call

```<code>cache = g_cache_new((GCacheNewFunc) g_strdup,
  g_free, (GCacheDupFunc)g_strdup, g_free, g_str_hash,
  g_str_hash, g_str_equal);
</code>```

ie instead of g_ascii_strup() I used g_strdup... I didn't see any crash. Am I missing anything here?

And is the g_ascii_strup() bug fixed in the latest glib releases? Can I please have the bug number if you are aware of it?

答:
I'd take out the (GCacheNewFunc) and (GCacheDupFunc) casts because they are breaking type safety, and in this case, hiding a bug: g_ascii_strup takes a length parameter which will probably be garbage. Instead make a function with the proper signature, and call g_ascii_strup inside that function. Then you don't need a cast.

I'd guess that's the issue. But if not, what I'd do is get debug symbols on your GLib, and get a backtrace in gdb.

Body:
I wrote a test example in glib:

#undef G_DISABLE_ASSERT
#undef G_LOG_DOMAIN

#include <stdio.h>
#include <string.h>
#include "glib.h"

void function(gchar *key,gchar *value,gint *user_data)
{
 // give the count of the number of times the function was called
 (*user_data)++;
}

void cache_test()
{
 gchar *str1,*str2,*str3;
 GCache *cache = NULL;
 gint user_data = 0;

 g_assert((cache = g_cache_new( (GCacheNewFunc) g_ascii_strup,
     g_free, (GCacheDupFunc) g_strdup, g_free, g_str_hash,
        g_str_hash, g_str_equal)) != NULL);
 g_print("\n g_assert g_cache_new");
    str1 = g_cache_insert(cache,"test");
    g_print("\n str1 = g_cache_insert(cache,test)");
    g_assert(!strcmp("TEST",str1));
    g_print("\n g_assert(!strcmp(TEST,str1))");
 str2 = g_cache_insert(cache,"test");
 g_print("\n str2 = g_cache_insert(cache,test)");
 g_assert(!strcmp("TEST",str1));
 g_print("\n g_assert(!strcmp(TEST,str1))");
 str3 = g_cache_insert(cache,"glib");
 g_print("\n str3 = g_cache_insert(cache,glib)");
 g_assert(!strcmp("GLIB",str3));
 g_print("\n g_assert(!strcmp(GLIB,str3))");
 g_cache_key_foreach (cache,(GHFunc)function,&user_data);
 g_print("\n g_cache_key_foreach (cache,(GHFunc)function,&user_data)");
 //g_cache_key_foreach would call function twice and make user_data == 2
 g_assert(user_data == 2);

 g_cache_value_foreach (cache,(GHFunc)function,&user_data);
 g_print("\n g_cache_key_foreach (cache,(GHFunc)function,&user_data)");
 //g_cache_value_foreach would call function twice and make user_data == 4
 g_assert(user_data == 4);

 g_cache_remove(cache,str1);
 g_print("\n g_cache_remove(cache,str1)");
 g_cache_remove(cache,str2);
 g_print("\n g_cache_remove(cache,str1)");
 g_cache_remove(cache,str3);
 g_print("\n g_cache_remove(cache,str1)");
 g_cache_destroy(cache);
 g_print("\n g_cache_destroy(cache)");
}

int main (int   argc,
      char *argv[])
{
 cache_test();
 return 0;
}

Now my test example crashes at str1 = g_cache_insert(cache,"test"); because of null pointer dereferencing.
Any help where I could be going wrong?

Edit

I just tried 1 more quick fix to the test code to confirm your suggestion (of the bug in g_ascii_strup). I used the call

cache = g_cache_new((GCacheNewFunc) g_strdup,
  g_free, (GCacheDupFunc)g_strdup, g_free, g_str_hash,
  g_str_hash, g_str_equal);

ie instead of g_ascii_strup() I used g_strdup... I didn't see any crash. Am I missing anything here?

And is the g_ascii_strup() bug fixed in the latest glib releases? Can I please have the bug number if you are aware of it?


来源: stackexchange

问:
Python Extract Range of Cells from Worksheet
I need to pull 16 rows from 2 columns in an excel spreadsheet with many worksheets.  I have figured out how to print the output from the place where the output needs to start, but I only want 16 rows.  My script prints all the way to the bottom.  Here's the script:

```<code>import xlrd
import csv

wb = xlrd.open_workbook('myworkbook.xlsx').sheet_by_index(16)
mydata = open("myoutput.csv", 'w')

try:
    for rownum in range(47, wb.nrows):
        ipaddr.write(str(wb.cell(rownum, 4).value)+ ", " +(wb.cell(rownum, 6).value)+"\n")
finally:
  mydata.close()
</code>```

When I try to restrict the range like this:

for rownum in range(47, 63 wb.nrows):

it only prints row 47.  Any ideas how I can restrict the output to 16 rows? TIA

答:
How about:</p>

```<code>import xlrd
import codecs

wb = xlrd.open_workbook('myworkbook.xlsx').sheet_by_index(16)
with codecs.open('myoutput.csv', 'w') as mydata:

for rownum in range(47, min(63,wb.nrows)):
    mydata.write(str(wb.cell(rownum, 4).value) + ", " + str(wb.cell(rownum, 6).value) + "\n")

mydata.close()
wb.close()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to pull 16 rows from 2 columns in an excel spreadsheet with many worksheets.  I have figured out how to print the output from the place where the output needs to start, but I only want 16 rows.  My script prints all the way to the bottom.  Here's the script:

import xlrd
import csv

wb = xlrd.open_workbook('myworkbook.xlsx').sheet_by_index(16)
mydata = open("myoutput.csv", 'w')

try:
    for rownum in range(47, wb.nrows):
        ipaddr.write(str(wb.cell(rownum, 4).value)+ ", " +(wb.cell(rownum, 6).value)+"\n")
finally:
  mydata.close()

When I try to restrict the range like this:

for rownum in range(47, 63 wb.nrows):

it only prints row 47.  Any ideas how I can restrict the output to 16 rows? TIA

Body:
How about:

import xlrd
import codecs

wb = xlrd.open_workbook('myworkbook.xlsx').sheet_by_index(16)
with codecs.open('myoutput.csv', 'w') as mydata:

for rownum in range(47, min(63,wb.nrows)):
    mydata.write(str(wb.cell(rownum, 4).value) + ", " + str(wb.cell(rownum, 6).value) + "\n")

mydata.close()
wb.close()


问:
How to add a custom button on an item that does not have Stock?
I'm working with Wordpress and WooCommerce, I need to add a contact button if in my store some product runs out of stock, ie:

If Stock is 0, show me a contact button.

The following image looks more specific about where I want to insert it:

I have found out how to add the button, but it is added to all the products, and I just want the button to appear when I have no stock on any of my products.
Here is the code used:

```<code>add_action('woocommerce_after_add_to_cart_button', 'boton_subasta');
function boton_subasta(){
     global $product;
    if ( ! $product->is_in_stock()){

        echo '<button type="submit" class="button alt" onclick="window.location.href=http://http://138.197.9.71/prov-individuales/">contacto</button>';
    }
}
</code>```

答:
The action woocommerce_after_add_to_cart_button is only called if $product->is_in_stock() is true. So, this action will not be called if $product->is_in_stock() is false.

In other words, the Add to Cart button exists only when $product->is_in_stock() is true and will not exists at all if the product is out of stock so there is no button to add after.

You may want to do research on the filter woocommerce_get_stock_html instead.

However, I don't understand why your button is being displayed. The given code should not show the button. Are you sure the code written in the question is exactly the code you are using?

ContentLicense: CC BY-SA 4.0

Body:
I'm working with Wordpress and WooCommerce, I need to add a contact button if in my store some product runs out of stock, ie:

If Stock is 0, show me a contact button.

The following image looks more specific about where I want to insert it:

I have found out how to add the button, but it is added to all the products, and I just want the button to appear when I have no stock on any of my products.
Here is the code used:

add_action('woocommerce_after_add_to_cart_button', 'boton_subasta');
function boton_subasta(){
     global $product;
    if ( ! $product->is_in_stock()){

        echo '<button type="submit" class="button alt" onclick="window.location.href=http://http://138.197.9.71/prov-individuales/">contacto</button>';
    }
}


问:
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>```

答:
You are doing little wrong here.
once return call in function then it will not execute further.

Model:

```<code>function ins_assign_pic($data){

    $q_ins_assign_pic   = $this->db->insert('pm_requirement_assign_pic',$data);

    if($q_ins_assign_pic){
        return $this->db->insert_id();
    } else {
        retun false;
    }

}
</code>```

Controller :

```<code> $newID = $this->MAdmin->ins_assign_pic($data);
</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:
You are doing little wrong here.
once return call in function then it will not execute further.

Model:

function ins_assign_pic($data){

    $q_ins_assign_pic   = $this->db->insert('pm_requirement_assign_pic',$data);

    if($q_ins_assign_pic){
        return $this->db->insert_id();
    } else {
        retun false;
    }

}

Controller :

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


答:
You could get the max id from the table: </p>

```<code>select max(id) from table
</code>```

Title: How to get the last id from inserted row?

Body:
You could get the max id from the table:

select max(id) from table


问:
How to fetch all records using SQL query using JOIN command (related to Distinct)
This is my SQL Query

```<code>SELECT tmdb_movies.movie_title
,GROUP_CONCAT(DISTINCT recommendations.recommendations_vote_average) as recommendations_vote_average

FROM tmdb_movies

LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id=155

GROUP BY tmdb_movies.movie_title
</code>```

This is how my recommentions able looks like:

So, now ,GROUP_CONCAT(DISTINCT recommendations.recommendations_vote_average) as recommendations_vote_average
 If I use DISTINCT here, then it do not show vote_average of the following movies: The Matrix, Inception, Iron Man 2, Captain America: The First Avenger. +it shows wrong vote_average of all movies (leaving first)

If i do not use Distinct then it shows 7.5 in all records.

How to solve this problem? Let me know, if you need more information.

答:
If you need the average recommendation, you can use the AVG aggregate function:</p>

```<code>SELECT tmdb_movies.movie_title
,AVG( recommendations.recommendations_vote_average) as recommendations_vote_average
FROM tmdb_movies
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id
Where tmdb_movies.tmdb_id=155
GROUP BY tmdb_movies.movie_title
</code>```

Body:
This is my SQL Query

SELECT tmdb_movies.movie_title
,GROUP_CONCAT(DISTINCT recommendations.recommendations_vote_average) as recommendations_vote_average

FROM tmdb_movies

LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id=155

GROUP BY tmdb_movies.movie_title

This is how my recommentions able looks like:

So, now ,GROUP_CONCAT(DISTINCT recommendations.recommendations_vote_average) as recommendations_vote_average
 If I use DISTINCT here, then it do not show vote_average of the following movies: The Matrix, Inception, Iron Man 2, Captain America: The First Avenger. +it shows wrong vote_average of all movies (leaving first)

If i do not use Distinct then it shows 7.5 in all records.

How to solve this problem? Let me know, if you need more information.

Body:
If you need the average recommendation, you can use the AVG aggregate function:

SELECT tmdb_movies.movie_title
,AVG( recommendations.recommendations_vote_average) as recommendations_vote_average
FROM tmdb_movies
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id
Where tmdb_movies.tmdb_id=155
GROUP BY tmdb_movies.movie_title


问:
Should methods have the same preconditions as the methods they call?
I've recently had a few scenarios where small changes to code have resulted in changing preconditions across multiple classes and I was wondering if design by contract is supposed to be that way or not.

```<code>public Goal getNextGoal() {
    return goalStack.pop();
}
</code>```

If goalStack.pop() has a precondition that the stack isn't empty, then does getNextGoal() need to explicitly have the same precondition? It seems like inheriting the preconditions would make things brittle, and changing to a queue or other structure would change the preconditions to getNextGoal(), it's callers, and it's callers' callers. But it seems like not inheriting the preconditions would hide the contracts and the callers, and the callers' callers, wouldn't know about the preconditions.

So brittle code where all callers know and inherit the preconditions and postconditions of the code they call, or mysterious code where callers never know what the deeper preconditions and postconditions are?

答:
Exceptions are one solution but perhaps not feasible for your situation.

Documenting what happens if there are no goals is normal.E.G. This is what malloc() does in C

I can't tell if you are using Java or C++ or something else as each language might have slightly more natural ways for that specific language.

ContentLicense: CC BY-SA 2.5

Body:
I've recently had a few scenarios where small changes to code have resulted in changing preconditions across multiple classes and I was wondering if design by contract is supposed to be that way or not.

public Goal getNextGoal() {
    return goalStack.pop();
}

If goalStack.pop() has a precondition that the stack isn't empty, then does getNextGoal() need to explicitly have the same precondition? It seems like inheriting the preconditions would make things brittle, and changing to a queue or other structure would change the preconditions to getNextGoal(), it's callers, and it's callers' callers. But it seems like not inheriting the preconditions would hide the contracts and the callers, and the callers' callers, wouldn't know about the preconditions.

So brittle code where all callers know and inherit the preconditions and postconditions of the code they call, or mysterious code where callers never know what the deeper preconditions and postconditions are?


问:
org.mule.api.transformer.TransformerException: An invalid return type "class [B" was specified for transformer "JAXBMarshallerTransformer"
I am using CXF component in Mule to consume a webserice. I am getting the following error with Mule 3.8

```<code>Message               : An invalid return type "class [B" was specified for transformer "JAXBMarshallerTransformer"
Transformer           : JAXBMarshallerTransformer{this=52baa6b2, name='JAXBMarshallerTransformer', ignoreBadInput=false, returnClass=SimpleDataType{type=[B, mimeType='*/*', encoding='null'}, sourceTypes=[SimpleDataType{type=java.lang.Object, mimeType='*/*', encoding='null'}]}

Root Exception stack trace:
  org.mule.api.transformer.TransformerException: An invalid return type "class [B" was specified for transformer "JAXBMarshallerTransformer"
</code>```

Tried multiple options, adding different transformers in response; nothing works! My flow is finally looking like this:

```<code><http:listener-config name="HTTP_Listener_Configuration" host="localhost" port="8081" basePath="/mule" doc:name="HTTP Listener Configuration"/>
<cxf:configuration name="CXF_Configuration" enableMuleSoapHeaders="false" initializeStaticBusInstance="false" doc:name="CXF Configuration"/>
<spring:beans>
    <spring:bean name="StringToDocumentXfm" class="invoke.StringToDocumentTransformer"/>
</spring:beans>
<mulexml:jaxb-context name="JAXB_Context" packageNames="EmployeeSOAClient" doc:name="JAXB Context"/>
<flow name="mule-testproj-soapclientFlow">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/sample" doc:name="HTTP" allowedMethods="GET"/>
    <set-payload value="#[message.inboundProperties.'http.query.params'.empno]" doc:name="Set Payload"/>
    <cxf:jaxws-client operation="getEmployeeDetails" clientClass="EmployeeSOAClient.EmployeeService" port="EmployeePort" wsdlLocation="classpath:Employee.wsdl" doc:name="CXF">
        <cxf:aegis-databinding/>
    </cxf:jaxws-client>
    <outbound-endpoint address="http://localhost:8080/EmployeeSOA/services/Employee" doc:name="Generic" exchange-pattern="request-response"/>
    <response>
        <object-to-string-transformer doc:name="Object to String"/>
        <logger message="#[payload]" level="INFO" doc:name="Logger"/>
        <invoke name="Invoke" object-ref="StringToDocumentXfm" method="covertStringToDocument" methodArguments="#[payload]" methodArgumentTypes="java.lang.String"/>
        <mulexml:dom-to-xml-transformer doc:name="DOM to XML"/>
        <logger message="Output after DOM to XML: #[payload]" level="INFO" doc:name="Logger"/>
    </response>
</flow>
</code>```

What am i missing?

Thanks,
Aneesh.

答: JAXBMarshallerTransformer does not know how to transform to a byte array ("class [B"). Try setting the Return Class to java.lang.String</p>

Body:
I am using CXF component in Mule to consume a webserice. I am getting the following error with Mule 3.8

Message               : An invalid return type "class [B" was specified for transformer "JAXBMarshallerTransformer"
Transformer           : JAXBMarshallerTransformer{this=52baa6b2, name='JAXBMarshallerTransformer', ignoreBadInput=false, returnClass=SimpleDataType{type=[B, mimeType='*/*', encoding='null'}, sourceTypes=[SimpleDataType{type=java.lang.Object, mimeType='*/*', encoding='null'}]}

Root Exception stack trace:
  org.mule.api.transformer.TransformerException: An invalid return type "class [B" was specified for transformer "JAXBMarshallerTransformer"

Tried multiple options, adding different transformers in response; nothing works! My flow is finally looking like this:

<http:listener-config name="HTTP_Listener_Configuration" host="localhost" port="8081" basePath="/mule" doc:name="HTTP Listener Configuration"/>
<cxf:configuration name="CXF_Configuration" enableMuleSoapHeaders="false" initializeStaticBusInstance="false" doc:name="CXF Configuration"/>
<spring:beans>
    <spring:bean name="StringToDocumentXfm" class="invoke.StringToDocumentTransformer"/>
</spring:beans>
<mulexml:jaxb-context name="JAXB_Context" packageNames="EmployeeSOAClient" doc:name="JAXB Context"/>
<flow name="mule-testproj-soapclientFlow">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/sample" doc:name="HTTP" allowedMethods="GET"/>
    <set-payload value="#[message.inboundProperties.'http.query.params'.empno]" doc:name="Set Payload"/>
    <cxf:jaxws-client operation="getEmployeeDetails" clientClass="EmployeeSOAClient.EmployeeService" port="EmployeePort" wsdlLocation="classpath:Employee.wsdl" doc:name="CXF">
        <cxf:aegis-databinding/>
    </cxf:jaxws-client>
    <outbound-endpoint address="http://localhost:8080/EmployeeSOA/services/Employee" doc:name="Generic" exchange-pattern="request-response"/>
    <response>
        <object-to-string-transformer doc:name="Object to String"/>
        <logger message="#[payload]" level="INFO" doc:name="Logger"/>
        <invoke name="Invoke" object-ref="StringToDocumentXfm" method="covertStringToDocument" methodArguments="#[payload]" methodArgumentTypes="java.lang.String"/>
        <mulexml:dom-to-xml-transformer doc:name="DOM to XML"/>
        <logger message="Output after DOM to XML: #[payload]" level="INFO" doc:name="Logger"/>
    </response>
</flow>

What am i missing?

Thanks,
Aneesh.


问:
Binary Operator '+=' cannot be applied to operands of type UICollectionViewLayoutAttributes in Swift 3
We have the following code in Swift 3 no longer working but was working in previous version of Swift. In the line of code array += [attributes] we're getting error "Binary Operator '+=' cannot be applied to operands of type UICollectionViewLayoutAttributes and UICollectionViewLayoutAttributes?". Any suggestions: Here is the code:

```<code>override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    var array: [UICollectionViewLayoutAttributes] = []
    for i in 0 ... max(0, numberOfItems - 1) {
        var indexPath = IndexPath(item: i, section: 0)
        var attributes = layoutAttributesForItem(at: indexPath)
        if attributes != nil {
            array += [attributes]
        }
    }
    return array
}
</code>```

答:
Try using

```<code>array.append(attributes)
</code>```

instead of

```<code>array += [attributes]
</code>```

Body:
We have the following code in Swift 3 no longer working but was working in previous version of Swift. In the line of code array += [attributes] we're getting error "Binary Operator '+=' cannot be applied to operands of type UICollectionViewLayoutAttributes and UICollectionViewLayoutAttributes?". Any suggestions: Here is the code:

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    var array: [UICollectionViewLayoutAttributes] = []
    for i in 0 ... max(0, numberOfItems - 1) {
        var indexPath = IndexPath(item: i, section: 0)
        var attributes = layoutAttributesForItem(at: indexPath)
        if attributes != nil {
            array += [attributes]
        }
    }
    return array
}

Body:
Try using

array.append(attributes)

instead of

array += [attributes]


问:
Enum vs String/Integer Enum
I notice that some databases like Postgres add Enum but the question is,

At what point integer/string based enum becomes a performance issue?

Following this answer about differences Postgresql enum what are the advantages and disadvantages?

Because when you use Rails or in this case Ecto from Elixir language, there is a level of abstraction so the one of the two advantages listed there becomes no an problem at all so there is only missing performance concern.

So when that advantage is really important that you dropped the disadvantages listed there

答:
Enum in PostgreSQL

supported by PostgreSQL for Create Data Type.

static data with ordered set values (Which is can be sort by PostgreSQL)

case sensitive 'happy' is not same with 'HAPPY'

Cannot input other values if not created in data type.

For Performance issue: PostgreSQL never has performance issue cause by data-type. most of them cause by indexing, configuration, and bad database design.

For Enum:  in PostgreSQL They are equivalent to the enum types supported in a number of programming languages. An example of an enum type might be the days of the week, or a set of status values for a piece of data.

The translations from internal enum values to textual labels are kept in the system catalog pg_enum. Querying this catalog directly can be useful.

Note: both Native or String/Integer based type enum can't cause performance issue.

Title: Enum vs String/Integer Enum


问:
JUnit - RunListener is not called
I'm trying to collect data about tests that runs in the system. The tests are coming from external jar:

```<code>        Class<?> classToLoad = Class.forName ("tests.tests", true, child);
        RunListener rl = new ExecutionListener();
        JUnitCore jUnit = new JUnitCore();
        jUnit.addListener(rl);
        Result result = jUnit.runClasses(classToLoad);
</code>```

and ExecutionListener is:

```<code>public class ExecutionListener extends RunListener
{
    private StringBuilder _strBuilder;

    public ExecutionListener()
    {
        _strBuilder = new StringBuilder();
    }

    @Override
    public String toString()
    {
        return _strBuilder.toString();
    }

    /**
     * Called before any tests have been run.
     * */
    @Override
    public void testRunStarted(Description description) throws java.lang.Exception
    {
        _strBuilder.append("Number of testcases to execute : " + description.testCount());
    }

    /**
     *  Called when all tests have finished
     * */
    @Override
    public void testRunFinished(Result result) throws java.lang.Exception
    {
        _strBuilder.append("Number of testcases executed : " + result.getRunCount());
    }

    /**
     *  Called when an atomic test is about to be started.

     * */
    @Override
    public void testStarted(Description description) throws java.lang.Exception
    {
        _strBuilder.append("Starting execution of test case : "+ description.getMethodName());
    }

    /**
     *  Called when an atomic test has finished, whether the test succeeds or fails.
     * */
    @Override
    public void testFinished(Description description) throws java.lang.Exception
    {
        _strBuilder.append("Finished execution of test case : "+ description.getMethodName());
    }

    /**
     *  Called when an atomic test fails.
     * */
    @Override
    public void testFailure(Failure failure) throws java.lang.Exception
    {
        _strBuilder.append("Execution of test case failed : "+ failure.getMessage());
    }

    /**
     *  Called when a test will not be run, generally because a test method is annotated with Ignore.
     * */
    @Override
    public void testIgnored(Description description) throws java.lang.Exception
    {
        _strBuilder.append("Execution of test case ignored : "+ description.getMethodName());
    }
}
</code>```

But none of the of the function are being called... So (rl.toString() returns empty string).

How can I fixed it?

Thanks in advance!

答:
Had the same issue, not sure why but this doesn't seem to work for JUnitCore .runClasses() but does work for JUnitCore.run().

I realize this is a 4 year old but given I ran across this today figured worth posting an answer.

Title: JUnit - RunListener is not called

Body:
I'm trying to collect data about tests that runs in the system. The tests are coming from external jar:

        Class<?> classToLoad = Class.forName ("tests.tests", true, child);
        RunListener rl = new ExecutionListener();
        JUnitCore jUnit = new JUnitCore();
        jUnit.addListener(rl);
        Result result = jUnit.runClasses(classToLoad);

and ExecutionListener is:

public class ExecutionListener extends RunListener
{
    private StringBuilder _strBuilder;

    public ExecutionListener()
    {
        _strBuilder = new StringBuilder();
    }

    @Override
    public String toString()
    {
        return _strBuilder.toString();
    }

    /**
     * Called before any tests have been run.
     * */
    @Override
    public void testRunStarted(Description description) throws java.lang.Exception
    {
        _strBuilder.append("Number of testcases to execute : " + description.testCount());
    }

    /**
     *  Called when all tests have finished
     * */
    @Override
    public void testRunFinished(Result result) throws java.lang.Exception
    {
        _strBuilder.append("Number of testcases executed : " + result.getRunCount());
    }

    /**
     *  Called when an atomic test is about to be started.

     * */
    @Override
    public void testStarted(Description description) throws java.lang.Exception
    {
        _strBuilder.append("Starting execution of test case : "+ description.getMethodName());
    }

    /**
     *  Called when an atomic test has finished, whether the test succeeds or fails.
     * */
    @Override
    public void testFinished(Description description) throws java.lang.Exception
    {
        _strBuilder.append("Finished execution of test case : "+ description.getMethodName());
    }

    /**
     *  Called when an atomic test fails.
     * */
    @Override
    public void testFailure(Failure failure) throws java.lang.Exception
    {
        _strBuilder.append("Execution of test case failed : "+ failure.getMessage());
    }

    /**
     *  Called when a test will not be run, generally because a test method is annotated with Ignore.
     * */
    @Override
    public void testIgnored(Description description) throws java.lang.Exception
    {
        _strBuilder.append("Execution of test case ignored : "+ description.getMethodName());
    }
}

But none of the of the function are being called... So (rl.toString() returns empty string).

How can I fixed it?

Thanks in advance!


问:
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?

答:
```<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 [Int](each.lowerBound..<each.upperBound) {
            print(every)
        }
    }
</code>```

and remove that extention.

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:
    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 [Int](each.lowerBound..<each.upperBound) {
            print(every)
        }
    }

and remove that extention.


问:
Animating search bar
I want to do something similar to the search bar in the IOS 10 Music app.
How might I do this? Here are some pictures:

答:
Do you want to implement Search bar with scope? Please elaborate.

Sample :

```<code>[self.searchDisplayController.searchBar setScopeButtonTitles:@["Apple Music",@"Your Library"]];
</code>```

Check below properties in File Inspector:

Capabilities - Show Cancel Button

Capabilities - Show Scope Bar

Title: Animating search bar

Body:
Do you want to implement Search bar with scope? Please elaborate.

Sample :

[self.searchDisplayController.searchBar setScopeButtonTitles:@["Apple Music",@"Your Library"]];

Check below properties in File Inspector:

Capabilities - Show Cancel Button

Capabilities - Show Scope Bar


问:
host not found error in host names with ip's side by side in ipscanner
This code is saying that host not found but there are some hosts in that ip range? error is at socket.gethostbyaddr(ip) but i don't know why because it is the command to find hostnames by ip address?</p>

```<code>import subprocess
import socket
import os
with open(os.devnull, "wb") as limbo:
        for n in xrange(10, 240):
                ip="10.4.16.{0}".format(n)
                result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print (ip, "inactive")
                else:
                        print (ip, "active", socket.gethostbyaddr(ip))
</code>```

答:
before everything, your IP address must have a ptr record in DNS that show it names.otherwise, you with this code you can check is

active or not

```<code>import subprocess
import socket
import os
import sys

def lookup(addr):
     try:
         return socket.gethostbyaddr(addr)
     except socket.herror:
         return None, None, None
with open(os.devnull, "wb") as limbo:
    for n in xrange(10, 240):
        ip="10.4.16.{0}".format(n)
        if sys.platform=="linux" or sys.platform=="darwin":
            result=os.system("ping -c 1 -t 1 " + ip+ " > /dev/null 2>&1")
        else:
            result=os.system("ping -w 1000 -n 1 " + ip)

        if result==0:
            print (ip, "active")
            name,alias,addresslist = lookup(ip)
            if name != None:
                print ("name", name)
        else:
            print (ip, "inactive")
        print "#################################"
</code>```

Body:
This code is saying that host not found but there are some hosts in that ip range? error is at socket.gethostbyaddr(ip) but i don't know why because it is the command to find hostnames by ip address?

import subprocess
import socket
import os
with open(os.devnull, "wb") as limbo:
        for n in xrange(10, 240):
                ip="10.4.16.{0}".format(n)
                result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print (ip, "inactive")
                else:
                        print (ip, "active", socket.gethostbyaddr(ip))

Body:
before everything, your IP address must have a ptr record in DNS that show it names.otherwise, you with this code you can check is

active or not

import subprocess
import socket
import os
import sys

def lookup(addr):
     try:
         return socket.gethostbyaddr(addr)
     except socket.herror:
         return None, None, None
with open(os.devnull, "wb") as limbo:
    for n in xrange(10, 240):
        ip="10.4.16.{0}".format(n)
        if sys.platform=="linux" or sys.platform=="darwin":
            result=os.system("ping -c 1 -t 1 " + ip+ " > /dev/null 2>&1")
        else:
            result=os.system("ping -w 1000 -n 1 " + ip)

        if result==0:
            print (ip, "active")
            name,alias,addresslist = lookup(ip)
            if name != None:
                print ("name", name)
        else:
            print (ip, "inactive")
        print "#################################"


答:
try using array.append(attributes).
because to add something in an array, we use the append function

The +=operator works fine for Int, Float, Double',String` and other data types not for an array

Title: Binary Operator '+=' cannot be applied to operands of type UICollectionViewLayoutAttributes in Swift 3


问:
Unexpected layout behavior in JavaFX
I want to write a new custom container class extending Region. The children list of this CustomContainer should not be visible. It contains a Pane (called rootPane) which in turn contains a VBox. And the children list of this VBox should be used to really add children to the container (accessible through getInnerChildren). That is the simplified structure of it.

My problem is that adding a new child causes a wrong layout behavior of the CustomContainer itself in case a border is applied to it because it grows in its height. But only the first time a child is added! Here is a really simple executable Demo to test it:

```<code>public class LayoutDemo extends Application
{
    @Override
    public void start(Stage stage)
    {
        CustomContainer container = new CustomContainer(new Label("First Label"), new Label("Second Label"), new Label("Third Label"));
        // The border here is involved in the problem. In fact, only the top width has influence.
        container.setBorder(new Border(new BorderStroke(Color.GRAY, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, new BorderWidths(30, 3, 3, 3))));

        Button buttonAddNode = new Button("Add node");
        buttonAddNode.setOnAction(e -> container.specialAction());
        Button buttonSysout = new Button("Sysout height");
        buttonSysout.setOnAction(e -> System.out.println(container.getHeight()));

        HBox boxButtons = new HBox(10, buttonAddNode, buttonSysout);
        VBox sceneRoot = new VBox(20, container, boxButtons);
        sceneRoot.setPadding(new Insets(15)); // Just to make it look nicer.
        stage.setScene(new Scene(sceneRoot, 200, 200));
        stage.show();
    }

    public static class CustomContainer extends Region
    {
        private VBox innerBox = new VBox();
        private Pane rootPane = new StackPane(innerBox);

        public CustomContainer(Node... children)
        {
            getChildren().addAll(rootPane);
            getInnerChildren().addAll(children);
        }

        public void specialAction()
        {
            // Just for testing... Forces the CustomContainer to add a child to itself. And this is where the trouble begins...
            Node newChild = new Pane();
            newChild.setManaged(false); // I tried this, but it really has no influence.

            // The new child won't be visible in this test because it is not considered by layoutChildren(). But even layouting it would have no influence.
            getChildren().add(newChild);
        }

        @Override
        protected void layoutChildren()
        {
            System.out.println("LAYOUT");
            Insets borderInsets = getBorder().getInsets();
            double left = borderInsets.getLeft(),
                top = borderInsets.getTop(),
                width = getWidth() - left - borderInsets.getRight(),
                height = getHeight() - top - borderInsets.getBottom();
            layoutInArea(rootPane, left, top, width, height, 0, HPos.CENTER, VPos.CENTER);
        }

        public ObservableList<Node> getInnerChildren()
        {
            return innerBox.getChildren();
        }
    }

    public static void main(String... args)
    {
        launch();
    }
}
</code>```

Further hints:

- The size it grows in its height is equal to the top width of the border.

- If you replace the VBox with a HBox the left width of the border is decisive instead.

- It has to do with my overridden layoutChildren() method. If not overridden the problem not appears (but of course I need to implement this method, just correctly).

- As mentioned it only appears the first time a child is added. But removing it does not revert the size.

- The "specialAction" method represents some logic that is done internally. That is because I want to internally add and remove some new children to the CustomContainer (and not to the VBox!) but the problem appears the same way when adding children to the VBox.

In case you are curious what I plan with this container: It will implement some drag and drop behaviour to move children around with some custom visual feedback. And this visual feedback will be installed on the non public children list of the CustomContainer.

Please do not suggest to alter the container structure. Instead I hope you can give me advice why my layoutChildren method causes this problem and how to do it right.

答: Try to set minimum width and height to your nodes. I have quite similar behavior as yours and I come across this article https://dzone.com/articles/size-does-matter-in-javafx, then I set minimum height to my AnchorPane and the unexpected behavior is gone.</p>

Title: Unexpected layout behavior in JavaFX

Body:
I want to write a new custom container class extending Region. The children list of this CustomContainer should not be visible. It contains a Pane (called rootPane) which in turn contains a VBox. And the children list of this VBox should be used to really add children to the container (accessible through getInnerChildren). That is the simplified structure of it.

My problem is that adding a new child causes a wrong layout behavior of the CustomContainer itself in case a border is applied to it because it grows in its height. But only the first time a child is added! Here is a really simple executable Demo to test it:

public class LayoutDemo extends Application
{
    @Override
    public void start(Stage stage)
    {
        CustomContainer container = new CustomContainer(new Label("First Label"), new Label("Second Label"), new Label("Third Label"));
        // The border here is involved in the problem. In fact, only the top width has influence.
        container.setBorder(new Border(new BorderStroke(Color.GRAY, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, new BorderWidths(30, 3, 3, 3))));

        Button buttonAddNode = new Button("Add node");
        buttonAddNode.setOnAction(e -> container.specialAction());
        Button buttonSysout = new Button("Sysout height");
        buttonSysout.setOnAction(e -> System.out.println(container.getHeight()));

        HBox boxButtons = new HBox(10, buttonAddNode, buttonSysout);
        VBox sceneRoot = new VBox(20, container, boxButtons);
        sceneRoot.setPadding(new Insets(15)); // Just to make it look nicer.
        stage.setScene(new Scene(sceneRoot, 200, 200));
        stage.show();
    }

    public static class CustomContainer extends Region
    {
        private VBox innerBox = new VBox();
        private Pane rootPane = new StackPane(innerBox);

        public CustomContainer(Node... children)
        {
            getChildren().addAll(rootPane);
            getInnerChildren().addAll(children);
        }

        public void specialAction()
        {
            // Just for testing... Forces the CustomContainer to add a child to itself. And this is where the trouble begins...
            Node newChild = new Pane();
            newChild.setManaged(false); // I tried this, but it really has no influence.

            // The new child won't be visible in this test because it is not considered by layoutChildren(). But even layouting it would have no influence.
            getChildren().add(newChild);
        }

        @Override
        protected void layoutChildren()
        {
            System.out.println("LAYOUT");
            Insets borderInsets = getBorder().getInsets();
            double left = borderInsets.getLeft(),
                top = borderInsets.getTop(),
                width = getWidth() - left - borderInsets.getRight(),
                height = getHeight() - top - borderInsets.getBottom();
            layoutInArea(rootPane, left, top, width, height, 0, HPos.CENTER, VPos.CENTER);
        }

        public ObservableList<Node> getInnerChildren()
        {
            return innerBox.getChildren();
        }
    }

    public static void main(String... args)
    {
        launch();
    }
}

Further hints:

- The size it grows in its height is equal to the top width of the border.

- If you replace the VBox with a HBox the left width of the border is decisive instead.

- It has to do with my overridden layoutChildren() method. If not overridden the problem not appears (but of course I need to implement this method, just correctly).

- As mentioned it only appears the first time a child is added. But removing it does not revert the size.

- The "specialAction" method represents some logic that is done internally. That is because I want to internally add and remove some new children to the CustomContainer (and not to the VBox!) but the problem appears the same way when adding children to the VBox.

In case you are curious what I plan with this container: It will implement some drag and drop behaviour to move children around with some custom visual feedback. And this visual feedback will be installed on the non public children list of the CustomContainer.

Please do not suggest to alter the container structure. Instead I hope you can give me advice why my layoutChildren method causes this problem and how to do it right.


问:
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.

答:
No need to assign tag value you can directly get cell indexPath in your button exist

suppose you assign a selector to your button like this:-

```<code>@IBAction function buttonAction(_ sender:UIBUtton){
      if let indexPath = viewIndexPathInCollectionView(sender , collView:pass your collectionView here){
         // here you will get indexPath of your collectionView Cell
         print(indexPath.item)
      }
}
</code>```

use this function to get index of collection view  cell by passing cell item in this function

```<code>func viewIndexPathInCollectionView(_ cellItem: UIView, collView: UICollectionView) -> IndexPath? {
    let pointInTable: CGPoint = cellItem.convert(cellItem.bounds.origin, to: collView)
    if let cellIndexPath = collView.indexPathForItem(at: pointInTable){
        return cellIndexPath
    }
    return nil

}
</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:
No need to assign tag value you can directly get cell indexPath in your button exist

suppose you assign a selector to your button like this:-

@IBAction function buttonAction(_ sender:UIBUtton){
      if let indexPath = viewIndexPathInCollectionView(sender , collView:pass your collectionView here){
         // here you will get indexPath of your collectionView Cell
         print(indexPath.item)
      }
}

use this function to get index of collection view  cell by passing cell item in this function

func viewIndexPathInCollectionView(_ cellItem: UIView, collView: UICollectionView) -> IndexPath? {
    let pointInTable: CGPoint = cellItem.convert(cellItem.bounds.origin, to: collView)
    if let cellIndexPath = collView.indexPathForItem(at: pointInTable){
        return cellIndexPath
    }
    return nil

}


问:
How to ignore accessibility fonts resize in NativeScript?
I'm using NativeScript with Angular.
Is there an attribute to specify on Labels/buttons to ignore the font increase due to accessibility settings?
I need a solution for both android and ios.
Thank you!

答: If anybody interested, I found a workaround of using FormattedString for Labels, this object does not scale.</p>


问:
Building OpenWrt with ImageBuilder offline
I'm having a Carambola2 developer Board and building a firmware with the ImageBuilder from OpenWrt. This works great. But I would like to build the firmware when I'm offline. Because by default it tries to download data from 8devices.com. When I'm offline it compiles well but it's slow because it tries to access the internet. Any sugestions?</p>

答:
Image builder will need internet, or otherwise you download all packages which you need and save it to "dl" folder or you can build it offline you can try building openwrt using source code. You can check this link
 for building image using source code.


问:
Issue with CodeIgniter redirect
Here i'm creating a login system. Once the user is verified the controller redirects the page to home.php.

There are 2 pages here login_registration.php and home.php

login_registration.php consists login and registration form from here the user is redirected to home.php. both the files are in path C:\wamp\www\CI-Project_1\application\views\login

The issue is it show 404 Page Not Found when redirected.

```<code> class Login extends CI_Controller {
    public function __construct(){
        parent::__construct();
                $this->load->helper('url');
        //LOAD MODELS HERE
        $this->load->model('Login_model');
    }

    public function index(){
        $this->load->view('login/login_registration.php');
    }

    function login_user(){
        $login_btn = $this->input->post('login_btn');

        if($login_btn == TRUE){
            $arr['login'] = array(
                'username'=>$this->input->post('username'),
                'password'=>$this->input->post('password')
            );

            $query = $this->Login_model->users_login($arr);

            if($query->num_rows() > 0 && $query->num_rows() == 1){
                $this->load->library('session');
                $this->session->set_userdata($arr['login']);
                redirect('login/home.php', 'location');
            }
            else
            {
                $this->index();
            }
        }
        else
        {
            $this->index();
        }
    }
}
</code>```

THANKS IN ADVANCE

答:
Why you going to redirect if you want to call any method from a controller then you can redirect like that:

```<code>public function home(){
    $this->load->view('login/home.php');
}

redirect('login/home', 'location');
</code>```

But I think you don't need to redirect you can simply load view file just like you already load your registration view. So you just load view Instead of redirect..

```<code>$this->load->view('login/home.php');
</code>```

Title: Issue with CodeIgniter redirect

Body:
Here i'm creating a login system. Once the user is verified the controller redirects the page to home.php.

There are 2 pages here login_registration.php and home.php

login_registration.php consists login and registration form from here the user is redirected to home.php. both the files are in path C:\wamp\www\CI-Project_1\application\views\login

The issue is it show 404 Page Not Found when redirected.

 class Login extends CI_Controller {
    public function __construct(){
        parent::__construct();
                $this->load->helper('url');
        //LOAD MODELS HERE
        $this->load->model('Login_model');
    }

    public function index(){
        $this->load->view('login/login_registration.php');
    }

    function login_user(){
        $login_btn = $this->input->post('login_btn');

        if($login_btn == TRUE){
            $arr['login'] = array(
                'username'=>$this->input->post('username'),
                'password'=>$this->input->post('password')
            );

            $query = $this->Login_model->users_login($arr);

            if($query->num_rows() > 0 && $query->num_rows() == 1){
                $this->load->library('session');
                $this->session->set_userdata($arr['login']);
                redirect('login/home.php', 'location');
            }
            else
            {
                $this->index();
            }
        }
        else
        {
            $this->index();
        }
    }
}

THANKS IN ADVANCE

Body:
Why you going to redirect if you want to call any method from a controller then you can redirect like that:

public function home(){
    $this->load->view('login/home.php');
}

redirect('login/home', 'location');

But I think you don't need to redirect you can simply load view file just like you already load your registration view. So you just load view Instead of redirect..

$this->load->view('login/home.php');


问:
Force "respond_do" format
I am using RJS with Prototype. In my controller I have this code:

```<code>def method_name
    respond_to do |format|
        ...
        format.html
        format.js
    end
en
</code>```

Is it possible to force the "respond_do" to use the 'format.html' whether or no the request is HTML or JAVA? If so, how to do it?

答: Don't use respond_to.  Just let the controller action return or call render if you want to specify a particular view.</p>

Title: Force "respond_do" format

Body:
I am using RJS with Prototype. In my controller I have this code:

def method_name
    respond_to do |format|
        ...
        format.html
        format.js
    end
en

Is it possible to force the "respond_do" to use the 'format.html' whether or no the request is HTML or JAVA? If so, how to do it?


问:
Passing parameters to addTarget:action:forControlEvents
I am using addTarget:action:forControlEvents like this:

```<code>[newsButton addTarget:self
action:@selector(switchToNewsDetails)
forControlEvents:UIControlEventTouchUpInside];
```

and I would like to pass parameters to my selector "switchToNewsDetails".
The only thing I succeed in doing is to pass the (id)sender by writing:
```<code>action:@selector(switchToNewsDetails:)```

But I am trying to pass variables like integer values. Writing it this way doesn't work :

```<code>int i = 0;
[newsButton addTarget:self
action:@selector(switchToNewsDetails:i)
forControlEvents:UIControlEventTouchUpInside];
```

Writing it this way does not work either:

```<code>int i = 0;
[newsButton addTarget:self
action:@selector(switchToNewsDetails:i:)
forControlEvents:UIControlEventTouchUpInside];
```

Any help would be appreciated :)

答:
You can replace target-action with a closure (block in Objective-C) by adding a helper closure wrapper (ClosureSleeve) and adding it as an associated object to the control so it gets retained. That way you can pass any parameters.

Swift 3

```<code>class ClosureSleeve {
    let closure: () -> ()

    init(attachTo: AnyObject, closure: @escaping () -> ()) {
        self.closure = closure
        objc_setAssociatedObject(attachTo, "[\(arc4random())]", self, .OBJC_ASSOCIATION_RETAIN)
    }

    @objc func invoke() {
        closure()
    }
}

extension UIControl {
    func addAction(for controlEvents: UIControlEvents, action: @escaping () -> ()) {
        let sleeve = ClosureSleeve(attachTo: self, closure: action)
        addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
    }
}
</code>```

Usage:

```<code>button.addAction(for: .touchUpInside) {
    self.switchToNewsDetails(parameter: i)
}
</code>```

Body:
I am using addTarget:action:forControlEvents like this:

[newsButton addTarget:self
action:@selector(switchToNewsDetails)
forControlEvents:UIControlEventTouchUpInside];

and I would like to pass parameters to my selector "switchToNewsDetails".
The only thing I succeed in doing is to pass the (id)sender by writing:

action:@selector(switchToNewsDetails:)

But I am trying to pass variables like integer values. Writing it this way doesn't work :

int i = 0;
[newsButton addTarget:self
action:@selector(switchToNewsDetails:i)
forControlEvents:UIControlEventTouchUpInside];

Writing it this way does not work either:

int i = 0;
[newsButton addTarget:self
action:@selector(switchToNewsDetails:i:)
forControlEvents:UIControlEventTouchUpInside];

Any help would be appreciated :)

Body:
You can replace target-action with a closure (block in Objective-C) by adding a helper closure wrapper (ClosureSleeve) and adding it as an associated object to the control so it gets retained. That way you can pass any parameters.

Swift 3

class ClosureSleeve {
    let closure: () -> ()

    init(attachTo: AnyObject, closure: @escaping () -> ()) {
        self.closure = closure
        objc_setAssociatedObject(attachTo, "[\(arc4random())]", self, .OBJC_ASSOCIATION_RETAIN)
    }

    @objc func invoke() {
        closure()
    }
}

extension UIControl {
    func addAction(for controlEvents: UIControlEvents, action: @escaping () -> ()) {
        let sleeve = ClosureSleeve(attachTo: self, closure: action)
        addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
    }
}

Usage:

button.addAction(for: .touchUpInside) {
    self.switchToNewsDetails(parameter: i)
}


问:
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?

答:
You can either add "env" property to nodemon.json, like this:

```<code>...
"env": {
    "__DEV__": "true"
}
</code>```

Or you can prepend __DEV__="true" to start script in package.json.
Both worked for me.

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:
You can either add "env" property to nodemon.json, like this:

...
"env": {
    "__DEV__": "true"
}

Or you can prepend __DEV__="true" to start script in package.json.
Both worked for me.


问:
Use a custom comparator in a class that inherits from std::priority_queue
I've nedded to find elements in a pryority_queue so I created the class:

```<code>template < typename T >

class AStarPryorityQueue : public std::priority_queue < T, std::vector < T > >{

public:
    bool find(const T& value) {
        auto it = std::find(this->c.begin(), this->c.end(), value);
        if (it != this->c.end()){return true;}
        else {return false;}
    }
};
</code>```

But I also need to pass a functor used to sort this.The Funtor is:

```<code>    class LessThanByHeuristic{
        public:
            LessThanByHeuristic(int dest,AStarHeuristic* heuristic,int mapWidth,bool reverse):
            destTile(dest),heuristic(heuristic),tileMapWidth(mapWidth),reverse(reverse){}
            bool operator()(const std::pair<double,int> lhs,const std::pair<double,int> rhs) const{
                if(reverse){
                    return lhs.first + (*heuristic)(Vec2(lhs.second / tileMapWidth,lhs.second % tileMapWidth),
                                                Vec2(destTile / tileMapWidth,destTile % tileMapWidth)) >
                            rhs.first + (*heuristic)(Vec2(rhs.second / tileMapWidth,rhs.second % tileMapWidth),
                                                Vec2(destTile / tileMapWidth,destTile % tileMapWidth));
                }
                else{
                    return lhs.first + (*heuristic)(Vec2(lhs.second / tileMapWidth,lhs.second % tileMapWidth),
                                                Vec2(destTile / tileMapWidth,destTile % tileMapWidth)) <
                            rhs.first + (*heuristic)(Vec2(rhs.second / tileMapWidth,rhs.second % tileMapWidth),
                                                Vec2(destTile / tileMapWidth,destTile % tileMapWidth));
                }
            }

        private:
            int destTile;
            AStarHeuristic* heuristic;
            int tileMapWidth;
            bool reverse;
    };
</code>```

How do I create a AStarPryorityQueue passing the functor and his arguments?

Without inheritance I do:

```<code>typedef std::priority_queue<std::pair<double,int>,std::vector<std::pair<double,int> >,LessThanByHeuristic>  mypqType;
</code>```

and then:

```<code>mypqType processHeap(LessThanByHeuristic(destTile,heuristic,mapWidth,true));
</code>```

How can I do it now with my AStarPryorityQueue class?

答:
The comparator is part of the priority_queue's type, thus you need to specify it in your inheritance declaration:

```<code>class AStarPryorityQueue : public std::priority_queue <std::pair<double,int>, std::vector<std::pair<double,int>>, LessThanByHeuristic>
</code>```

and in your constructor, since your LessThanByHeuristic isn't default-constructible, you need to call the constructor of std::priority-queue:

```<code>AStarPryorityQueue(int destTile, AStarHeuristic* heuristic, int tileMapWidth, bool reverse) : std::priority_queue <std::pair<double,int>,std::vector < std::pair<double,int>>,LessThanByHeuristic>{LessThanByHeuristic{destTile, heuristic, tileMapWidth, reverse}}
...
</code>```

EDIT: I'm not 100% sure that's actually what you want to do - for an implementation of A*, you normally need an addressable priority queue where you can decrease the key of an already existing entry in the PQ.

Body:
I've nedded to find elements in a pryority_queue so I created the class:

template < typename T >

class AStarPryorityQueue : public std::priority_queue < T, std::vector < T > >{

public:
    bool find(const T& value) {
        auto it = std::find(this->c.begin(), this->c.end(), value);
        if (it != this->c.end()){return true;}
        else {return false;}
    }
};

But I also need to pass a functor used to sort this.The Funtor is:

    class LessThanByHeuristic{
        public:
            LessThanByHeuristic(int dest,AStarHeuristic* heuristic,int mapWidth,bool reverse):
            destTile(dest),heuristic(heuristic),tileMapWidth(mapWidth),reverse(reverse){}
            bool operator()(const std::pair<double,int> lhs,const std::pair<double,int> rhs) const{
                if(reverse){
                    return lhs.first + (*heuristic)(Vec2(lhs.second / tileMapWidth,lhs.second % tileMapWidth),
                                                Vec2(destTile / tileMapWidth,destTile % tileMapWidth)) >
                            rhs.first + (*heuristic)(Vec2(rhs.second / tileMapWidth,rhs.second % tileMapWidth),
                                                Vec2(destTile / tileMapWidth,destTile % tileMapWidth));
                }
                else{
                    return lhs.first + (*heuristic)(Vec2(lhs.second / tileMapWidth,lhs.second % tileMapWidth),
                                                Vec2(destTile / tileMapWidth,destTile % tileMapWidth)) <
                            rhs.first + (*heuristic)(Vec2(rhs.second / tileMapWidth,rhs.second % tileMapWidth),
                                                Vec2(destTile / tileMapWidth,destTile % tileMapWidth));
                }
            }

        private:
            int destTile;
            AStarHeuristic* heuristic;
            int tileMapWidth;
            bool reverse;
    };

How do I create a AStarPryorityQueue passing the functor and his arguments?

Without inheritance I do:

typedef std::priority_queue<std::pair<double,int>,std::vector<std::pair<double,int> >,LessThanByHeuristic>  mypqType;

and then:

mypqType processHeap(LessThanByHeuristic(destTile,heuristic,mapWidth,true));

How can I do it now with my AStarPryorityQueue class?

Body:
The comparator is part of the priority_queue's type, thus you need to specify it in your inheritance declaration:

class AStarPryorityQueue : public std::priority_queue <std::pair<double,int>, std::vector<std::pair<double,int>>, LessThanByHeuristic>

and in your constructor, since your LessThanByHeuristic isn't default-constructible, you need to call the constructor of std::priority-queue:

AStarPryorityQueue(int destTile, AStarHeuristic* heuristic, int tileMapWidth, bool reverse) : std::priority_queue <std::pair<double,int>,std::vector < std::pair<double,int>>,LessThanByHeuristic>{LessThanByHeuristic{destTile, heuristic, tileMapWidth, reverse}}
...

EDIT: I'm not 100% sure that's actually what you want to do - for an implementation of A*, you normally need an addressable priority queue where you can decrease the key of an already existing entry in the PQ.


问:
Is it possible to wrap a C# singleton in an interface?
I currently have a class in which I only have static members and constants, however I'd like to replace it with a singleton wrapped in an interface.

But how can I do this, bearing in mind that every singleton implementation I've seen has a static Instance method, thus breaking interface rules?

答:
A solution to consider (rather than hand-rolling your own) would be to leverage an IoC container e.g. Unity.

IoC containers commonly support registering an instance against an interface. This provides your singleton behaviour as clients resolving against the interface will receive the single instance.

```<code>  //Register instance at some starting point in your application
  container.RegisterInstance<IActiveSessionService>(new ActiveSessionService());

  //This single instance can then be resolved by clients directly, but usually it
  //will be automatically resolved as a dependency when you resolve other types.
  IActiveSessionService session = container.Resolve<IActiveSessionService>();
</code>```

You will also get the added advantage that you can vary the implementation of the singleton easily as it is registered against an interface. This can be useful for production, but perhaps more so for testing. True singletons can be quite painful in test environments.

Body:
A solution to consider (rather than hand-rolling your own) would be to leverage an IoC container e.g. Unity.

IoC containers commonly support registering an instance against an interface. This provides your singleton behaviour as clients resolving against the interface will receive the single instance.

  //Register instance at some starting point in your application
  container.RegisterInstance<IActiveSessionService>(new ActiveSessionService());

  //This single instance can then be resolved by clients directly, but usually it
  //will be automatically resolved as a dependency when you resolve other types.
  IActiveSessionService session = container.Resolve<IActiveSessionService>();

You will also get the added advantage that you can vary the implementation of the singleton easily as it is registered against an interface. This can be useful for production, but perhaps more so for testing. True singletons can be quite painful in test environments.


问:
Getting gitHub change history
I am trying, with no success, to find a way to get change history for a master branch.

I am trying to check for the top 10 files that changes have been made in, inside a defined timeline.

Any ideas?

答:
Well in the end, I extracted it to a CSV file and sorted by changed values.

This is how I solved the problem....

```<code>git diff $(git rev-list -n1 --before="1 week ago" master) --histogram --stat >file.csv
</code>```

Title: Getting gitHub change history

Body:
Well in the end, I extracted it to a CSV file and sorted by changed values.

This is how I solved the problem....

git diff $(git rev-list -n1 --before="1 week ago" master) --histogram --stat >file.csv


问:
Access value entered in input box in react
I need to create a menu in Reactjs and call an API using redux to display the data. Now I want to create a search box in the menu to display a particular category. I have tried using refs but it doesn't work. And I guess it is deprecated.

```<code>class App extends Component {
  constructor(props){
  super(props);
  this.state = { datas: []}//props.menu_items
}

componentWillMount() {
 this.setState({
  datas : require('./sample2')
 });
}

render() {
 return (
  <div className="App">
    <h2>Menu Dashboard</h2>
    <Buttons />
    <div style={{ border:'1px solid
  #E7E7E7',marginTop:'3%',width:'90%',marginLeft:'5%'}}>
     <Filters />
     <DisplayTable datas={this.state.datas}/>
    </div>
  </div>
   )
  }
  }
  class Buttons extends Component {
   constructor(props){
   super(props);
   // this.state = {searchInput: ''};
   this.search = this.search.bind(this);
  }
  search(event){
   if (event.keyCode === 13) {
   // this.setState({searchInput: event.target.value});
   console.log(this.refs.searchInput.value);
   event.preventDefault();
   }
  }
  render() {
    return (
     <div>
     <button className="button1">Categories</button>
     <button className="button2">Add Ons</button>
     <FormControl type="text" placeholder="search items"  ref="searchInput"
     className="search " onKeyDown={this.search} />
     </div>
    )
   }
  }
</code>```

How should I access the value entered in the search box so that I can display the data according to it? Also, I want to call the search function by pressing enter. I have tried the above code for both.
Thanks in advance.

答:
You can try below code, I used name for search item you can replace with it searchInput.For redux action search you need to create a search action within that you can call the api and can store that data into props.</p>

```<code>import React from "react";
import {connect} from "react-redux";
import {SearchItems} from "../actions/SearchAction";

/**
 * Search Item Class
 */
class Search extends React.Component {
  /**
   * Constructor
   * @param props
   */
  constructor(props) {
    super(props);
    this.state = {
      name: ""
    }
  }

  /**
   * Set the search text data into the state object
   * @param event
   */
  searchByText = (event) => {
    this.state[event.target.name] = event.target.value;
    this.props.SearchItems(this.state);
  }

  /**
   * Render the Search filter options.
   * @returns {XML}
   */
  render() {
    return (
       <div className="col-md-8 pull-left">
              <div className="form-group form-control-by-1">
                <input type="text" className="form-control-search search-input-box" id="name" name="name" value={this.state.name} onChange={(e) => this.searchByText(e)} placeholder="Search "/>
              </div>
            </div>
    );
  }
}

/**
 * Call the Search action function with search data.
 * @param dispatch
 * @returns {{SearchItems: (function(*=))}}
 */
const mapDispatchToProps = (dispatch) => {
  return {
    SearchItems: (inputData) => {
      dispatch(SearchItems(inputData));
    }
  };
};

/**
 * attach  both Reducer and Action into the Search component.
 */
export default connect(mapDispatchToProps)(Search);
</code>```

Body:
I need to create a menu in Reactjs and call an API using redux to display the data. Now I want to create a search box in the menu to display a particular category. I have tried using refs but it doesn't work. And I guess it is deprecated.

class App extends Component {
  constructor(props){
  super(props);
  this.state = { datas: []}//props.menu_items
}

componentWillMount() {
 this.setState({
  datas : require('./sample2')
 });
}

render() {
 return (

Menu Dashboard

    <Buttons />

     <Filters />
     <DisplayTable datas={this.state.datas}/>

   )
  }
  }
  class Buttons extends Component {
   constructor(props){
   super(props);
   // this.state = {searchInput: ''};
   this.search = this.search.bind(this);
  }
  search(event){
   if (event.keyCode === 13) {
   // this.setState({searchInput: event.target.value});
   console.log(this.refs.searchInput.value);
   event.preventDefault();
   }
  }
  render() {
    return (

     <button className="button1">Categories</button>
     <button className="button2">Add Ons</button>
     <FormControl type="text" placeholder="search items"  ref="searchInput"
     className="search " onKeyDown={this.search} />

    )
   }
  }

How should I access the value entered in the search box so that I can display the data according to it? Also, I want to call the search function by pressing enter. I have tried the above code for both.
Thanks in advance.

Body:
You can try below code, I used name for search item you can replace with it searchInput.For redux action search you need to create a search action within that you can call the api and can store that data into props.

import React from "react";
import {connect} from "react-redux";
import {SearchItems} from "../actions/SearchAction";

/**
 * Search Item Class
 */
class Search extends React.Component {
  /**
   * Constructor
   * @param props
   */
  constructor(props) {
    super(props);
    this.state = {
      name: ""
    }
  }

  /**
   * Set the search text data into the state object
   * @param event
   */
  searchByText = (event) => {
    this.state[event.target.name] = event.target.value;
    this.props.SearchItems(this.state);
  }

  /**
   * Render the Search filter options.
   * @returns {XML}
   */
  render() {
    return (
       <div className="col-md-8 pull-left">
              <div className="form-group form-control-by-1">
                <input type="text" className="form-control-search search-input-box" id="name" name="name" value={this.state.name} onChange={(e) => this.searchByText(e)} placeholder="Search "/>
              </div>
            </div>
    );
  }
}

/**
 * Call the Search action function with search data.
 * @param dispatch
 * @returns {{SearchItems: (function(*=))}}
 */
const mapDispatchToProps = (dispatch) => {
  return {
    SearchItems: (inputData) => {
      dispatch(SearchItems(inputData));
    }
  };
};

/**
 * attach  both Reducer and Action into the Search component.
 */
export default connect(mapDispatchToProps)(Search);


问:
Add attribute when new node create in JSTree
How to add attribute when creating new node in JStree?

When btnadd click that time i am adding new node.
node is created successful but now i want to add attribute.

My Html

```<code><div id="jstree">
</div>

<button id="btnadd">create node</button>

<div id="CurentNodeName"></div>
<div id="CurentNodeId"></div>
</code>```

Script

```<code><script>
    var CurrentNode;
    $(function () {
        var data = [
           { "id": "ajson1", "parent": "#", "text": "Simple root node" },
           { "id": "ajson2", "parent": "#", "text": "Root node 2" },
           { "id": "ajson3", "parent": "ajson2", "text": "Child 1" },
           { "id": "ajson4", "parent": "ajson2", "text": "Child 2" },
        ];
        $("#jstree").jstree({
            "core": {
                // so that create works
                "check_callback": true,

                "data": data
            }
        }).on('create_node.jstree', function (e, data) {
            console.log('saved');
        });

        // listen for event
        $('#jstree').on('changed.jstree', function (e, data) {
            var i, j, r = [], s = [];
            for (i = 0, j = data.selected.length; i < j; i++) {
                r.push(data.instance.get_node(data.selected[i]).text);
                CurrentNode = data.selected[0];
                console.log(data.selected[0]);

            }

            $('#CurentNodeName').html('Selected: ' + r.join(', '));
            $('#CurentNodeId').html('Selected Id: ' + CurrentNode);

        }).jstree();

        // create the New Node when Button Click
        $("#btnadd").on("click", function () {

            $('#jstree').jstree().create_node(CurrentNode, { "id": "ajson5" + CurrentNode, "text": "newly added" }, "last", function () {
           });
    });

</script>
</code>```

i also try
"attr": { title:"if",value:"expression"} } but that not help me.

答:
try this way. its work for me</p>

```<code>$('#jstree').jstree().create_node(CurrentNode, {
    li_attr: { "path": "path" },"text": "name" },
    "last", function () { }, true);
</code>```

Body:
How to add attribute when creating new node in JStree?

When btnadd click that time i am adding new node.
node is created successful but now i want to add attribute.

My Html

<button id="btnadd">create node</button>

Script

i also try
"attr": { title:"if",value:"expression"} } but that not help me.

Body:
try this way. its work for me

$('#jstree').jstree().create_node(CurrentNode, {
    li_attr: { "path": "path" },"text": "name" },
    "last", function () { }, true);


问:
Grant privileges to all users mysql?
Actually i am making  java app...and it is creating a database and table in the database on the first run..now i want it to grant select,create,insert on that table to all the users present in mysql..and even if a new user is created it should have privileges on that table too...i have tried alot of stuff from the internet heres the queries i have tried executing

```<code>grant select,create,insert on db.table to PUBLIC
grant select,create,insert on db.table to ''@'%'
grant select,create,insert on db.able to '*'@'%'
</code>```

please help me with it...
this is my javacode for the creation of database and table on the first run

```<code>st=conn.createStatement();

            ResultSet r=conn.getMetaData().getCatalogs();boolean dbe=false;
            while(r.next())
            {
                if(r.getString(1).equalsIgnoreCase("DB"))
                    {
                        st.execute("use db");
                        dbe=true;
                    }
            }
            if(!dbe)
            {
                st.execute("create database db");
                st.execute("use db");
                st.execute("create table tab(name varchar(255),address varchar(80),at datetime)");
            }
</code>```

答:
For granting privileges to all database:

```<code>GRANT ALL PRIVILEGES ON .* TO 'myuser'@'%' WITH GRANT OPTION;
</code>```

For granting privileges to a specific database:

```<code>GRANT ALL PRIVILEGES ON database_name.* TO 'myuser'@'%' WITH GRANT OPTION;
</code>```

Title: Grant privileges to all users mysql?

Body:
Actually i am making  java app...and it is creating a database and table in the database on the first run..now i want it to grant select,create,insert on that table to all the users present in mysql..and even if a new user is created it should have privileges on that table too...i have tried alot of stuff from the internet heres the queries i have tried executing

grant select,create,insert on db.table to PUBLIC
grant select,create,insert on db.table to ''@'%'
grant select,create,insert on db.able to '*'@'%'

please help me with it...
this is my javacode for the creation of database and table on the first run

st=conn.createStatement();

            ResultSet r=conn.getMetaData().getCatalogs();boolean dbe=false;
            while(r.next())
            {
                if(r.getString(1).equalsIgnoreCase("DB"))
                    {
                        st.execute("use db");
                        dbe=true;
                    }
            }
            if(!dbe)
            {
                st.execute("create database db");
                st.execute("use db");
                st.execute("create table tab(name varchar(255),address varchar(80),at datetime)");
            }

Body:
For granting privileges to all database:

GRANT ALL PRIVILEGES ON .* TO 'myuser'@'%' WITH GRANT OPTION;

For granting privileges to a specific database:

GRANT ALL PRIVILEGES ON database_name.* TO 'myuser'@'%' WITH GRANT OPTION;


问:
O(n) algorithm for two identical points

The Problem Statement

Given n points in a 2D plane having x and y coordinate. Two points are identical if one can be obtained from the other by multiplication by the same number. Example: (10,15) and (2,3) are identical whereas (10,15) and (10,20) are not. Suggest an O(n) algorithm which determines whether the input n points contains two identical points or not.

The simple approach can be just checking for each points i.e. if there are 5 points, for the first one I have 4 comparisons, for the second one I have 3 comparisons and so on. But that isn't an O(n) time complexity solution. I really can't think ahead of that. Any suggestions?

答:
One way to reduce a point to a single number is to multiply the first co-ordinate of the point by product of all the second co-ordinates of the other points.

So for e.g:

```<code>(10, 20) -> 10 * 10 * 4 = 400
(5, 10)  -> 5 * 20 * 4  = 400
(3, 4)   -> 3 * 20 * 10 = 600
</code>```

The first and second point match. For large sets of points the products would be very large, and would require using a BigNumber (which will be more than O(n)) but you could keep the numbers within a reasonable limit by taking a modulo after each multiplication. Then use a hash table as suggested in Jerry Coffin's answer.

You can easily compute the product of all the second co-ordinates by doing a single forward pass then a single backwards pass over the array and keeping running products:

e.g. in Java:

```<code>    long m = 9223372036854775783L; // largest prime less than max long
    int[][] points = {{1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 6}};
    long[] mods = new long[points.length];

    long prod = 1;
    for(int i = 0; i < points.length; i++)
    {
        mods[i] = prod;
        prod = (points[i][1] * prod) % m;
    }
    prod = 1;
    for(int i = points.length - 1; i >= 0 ; i--)
    {
        mods[i] = (mods[i] * prod) % m;
        prod = (points[i][1] * prod) % m;
    }

    HashSet<Long> set = new HashSet<Long>();
    for(int i = 0; i < points.length; i++)
    {
        prod = (mods[i] * points[i][0]) % m;
        if(set.contains(prod))
            System.out.println("Found a match");
        set.add(prod);
    }
</code>```

This algorithm assumes all the co-ordinates are integers != 0. Zeroes can be handled as special cases: all points with zero in the first place match each other, likewise for those with zero in the second place, and (0, 0) matches all points. As an optimization, the second and third pass through the array could be merged into a single pass.

Title: O(n) algorithm for two identical points

Body:
One way to reduce a point to a single number is to multiply the first co-ordinate of the point by product of all the second co-ordinates of the other points.

So for e.g:

(10, 20) -> 10 * 10 * 4 = 400
(5, 10)  -> 5 * 20 * 4  = 400
(3, 4)   -> 3 * 20 * 10 = 600

The first and second point match. For large sets of points the products would be very large, and would require using a BigNumber (which will be more than O(n)) but you could keep the numbers within a reasonable limit by taking a modulo after each multiplication. Then use a hash table as suggested in Jerry Coffin's answer.

You can easily compute the product of all the second co-ordinates by doing a single forward pass then a single backwards pass over the array and keeping running products:

e.g. in Java:

    long m = 9223372036854775783L; // largest prime less than max long
    int[][] points = {{1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 6}};
    long[] mods = new long[points.length];

    long prod = 1;
    for(int i = 0; i < points.length; i++)
    {
        mods[i] = prod;
        prod = (points[i][1] * prod) % m;
    }
    prod = 1;
    for(int i = points.length - 1; i >= 0 ; i--)
    {
        mods[i] = (mods[i] * prod) % m;
        prod = (points[i][1] * prod) % m;
    }

    HashSet<Long> set = new HashSet<Long>();
    for(int i = 0; i < points.length; i++)
    {
        prod = (mods[i] * points[i][0]) % m;
        if(set.contains(prod))
            System.out.println("Found a match");
        set.add(prod);
    }

This algorithm assumes all the co-ordinates are integers != 0. Zeroes can be handled as special cases: all points with zero in the first place match each other, likewise for those with zero in the second place, and (0, 0) matches all points. As an optimization, the second and third pass through the array could be merged into a single pass.


问:
How do I make a flat list out of a list of lists?
I have a list of lists like

```<code>[
    [1, 2, 3],
    [4, 5, 6],
    [7],
    [8, 9]
]
</code>```

How can I flatten it to get [1, 2, 3, 4, 5, 6, 7, 8, 9]?

If your list of lists comes from a nested list comprehension, the problem can be solved more simply/directly by fixing the comprehension; please see How can I get a flat result from a list comprehension instead of a nested list?.

The most popular solutions here generally only flatten one "level" of the nested list. See Flatten an irregular (arbitrarily nested) list of lists for solutions that completely flatten a deeply nested structure (recursively, in general).

答:
The following seems simplest to me:</p>
```<code>>>> import numpy as np
>>> l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> print(np.concatenate(l))
[1 2 3 4 5 6 7 8 9]
</code>```

Body:
I have a list of lists like

[
    [1, 2, 3],
    [4, 5, 6],
    [7],
    [8, 9]
]

How can I flatten it to get [1, 2, 3, 4, 5, 6, 7, 8, 9]?

If your list of lists comes from a nested list comprehension, the problem can be solved more simply/directly by fixing the comprehension; please see How can I get a flat result from a list comprehension instead of a nested list?.

The most popular solutions here generally only flatten one "level" of the nested list. See Flatten an irregular (arbitrarily nested) list of lists for solutions that completely flatten a deeply nested structure (recursively, in general).

Body:
The following seems simplest to me:

>>> import numpy as np
>>> l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> print(np.concatenate(l))
[1 2 3 4 5 6 7 8 9]


问:
How to use java mapping in mule?
i get payload in below java format:

```<code>[
      {emai:'xyz@gmail.com',id:a1},
      {emai:'xyz@gmail.com',id:a2},
      {emai:'abc@gmail.com',id:a3},
      ....
]
</code>```

the above input i is sent to java component which which need to give output in below format

```<code>[
      {emai:'xyz@gmail.com',id:[a1,a2]},
      {emai:'abc@gmail.com',id:a3},
      ....
]
</code>```

i.e i need to combine all the id of a email into single array.

can anybody share the link to write java code? or any sample code?

Thanks..,

答:
You can try following dataweave code

```<code>%dw 1.0
%output application/java
---
payload groupBy $.emai map {
    emai : $.emai[0],
    id : $.id
}
</code>```

Hope this helps.

Title: How to use java mapping in mule?

Body:
i get payload in below java format:

[
      {emai:'xyz@gmail.com',id:a1},
      {emai:'xyz@gmail.com',id:a2},
      {emai:'abc@gmail.com',id:a3},
      ....
]

the above input i is sent to java component which which need to give output in below format

[
      {emai:'xyz@gmail.com',id:[a1,a2]},
      {emai:'abc@gmail.com',id:a3},
      ....
]

i.e i need to combine all the id of a email into single array.

can anybody share the link to write java code? or any sample code?

Thanks..,

Body:
You can try following dataweave code

%dw 1.0
%output application/java
---
payload groupBy $.emai map {
    emai : $.emai[0],
    id : $.id
}

Hope this helps.


答:
The ref searchInput is the reference of FormControl component, not of the input component. The FormControl is not storing the value of input in its reference.

Instead, pass an onChange handler to the FormControl component and store the value of input in your state like this:

```<code>onChange = e => {
  this.setState({ value: e.target.value })
}
</code>```

and modify your search function to this:

```<code>  search = e => {
    if (e.keyCode === 13) {
      console.log('this.state.value..', this.state.value)
    }
  }
</code>```

Render your FormControl like this:

```<code><FormControl value={this.state.value} type="text" placeholder="search items"
                   className="search " onChange={this.onChange} onKeyDown={this.search} />
</code>```

Title: Access value entered in input box in react

Body:
The ref searchInput is the reference of FormControl component, not of the input component. The FormControl is not storing the value of input in its reference.

Instead, pass an onChange handler to the FormControl component and store the value of input in your state like this:

onChange = e => {
  this.setState({ value: e.target.value })
}

and modify your search function to this:

  search = e => {
    if (e.keyCode === 13) {
      console.log('this.state.value..', this.state.value)
    }
  }

Render your FormControl like this:

<FormControl value={this.state.value} type="text" placeholder="search items"
                   className="search " onChange={this.onChange} onKeyDown={this.search} />


答:
According to the documentation, FormControl assigns a ref to child input element, when you pass with the prop name inputRef.Also React docs suggest on using the callback approch for refs over the string refs.

See this answer for more info:

In React .js: is there any function similar like document.getElementById() in javascript ? how to select certain object?

So you can assign the ref and get the value like

```<code>class Buttons extends Component {
   constructor(props){
   super(props);
   // this.state = {searchInput: ''};
   this.search = this.search.bind(this);
  }
  search(event){
   if (event.keyCode === 13) {
   console.log(this.searchInput.value);
   event.preventDefault();
   }
  }
  render() {
    return (
     <div>
     <button className="button1">Categories</button>
     <button className="button2">Add Ons</button>
     <FormControl type="text" placeholder="search items"  inputRef={(ref) => {this.searchInput=ref}}
     className="search " onKeyDown={this.search} />
     </div>
    )
   }
  }
</code>```

Body:
According to the documentation, FormControl assigns a ref to child input element, when you pass with the prop name inputRef.Also React docs suggest on using the callback approch for refs over the string refs.

See this answer for more info:

In React .js: is there any function similar like document.getElementById() in javascript ? how to select certain object?

So you can assign the ref and get the value like

class Buttons extends Component {
   constructor(props){
   super(props);
   // this.state = {searchInput: ''};
   this.search = this.search.bind(this);
  }
  search(event){
   if (event.keyCode === 13) {
   console.log(this.searchInput.value);
   event.preventDefault();
   }
  }
  render() {
    return (
     <div>
     <button className="button1">Categories</button>
     <button className="button2">Add Ons</button>
     <FormControl type="text" placeholder="search items"  inputRef={(ref) => {this.searchInput=ref}}
     className="search " onKeyDown={this.search} />
     </div>
    )
   }
  }


问:
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>```

答: mysqli_insert_id() is the Function you are looking for.</p>

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;
}