问:
this.props.params not existing after passing parameter on react-router
I'm passing parameter from react-router's route path to component but in this.props object, 'params' not existing

```<code>const routes = (
    <Router forceRefresh={true}>
        <div>
            <Route exact path="/" component={Firstpage}/>
            <Route exact path="/projects" component={Projectslist}/>
            <Route exact path="/projects/:projectId" component={Singleproject}/>
        </div>
    </Router>
);
</code>```

And this is my component:

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

    componentWillMount(){
        window.document.title = "Wploper | Project title";
    }
    render(){
        return(
            <div>
                <Mainheader/>
                <div id="single-project-container" className="sheet-max-width">
                    <h2>{this.props.params}</h2>
                </div>
                <Mainfooter/>
            </div>
        );
    }
}
</code>```

And the object (this.props) hasn't params:
enter image description here

答: In react-router version 4 you can get the path params with this.props.match.params

Body:
I'm passing parameter from react-router's route path to component but in this.props object, 'params' not existing

const routes = (
    <Router forceRefresh={true}>

            <Route exact path="/" component={Firstpage}/>
            <Route exact path="/projects" component={Projectslist}/>
            <Route exact path="/projects/:projectId" component={Singleproject}/>

    </Router>
);

And this is my component:

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

    componentWillMount(){
        window.document.title = "Wploper | Project title";
    }
    render(){
        return(

                <Mainheader/>

{this.props.params}

                <Mainfooter/>

        );
    }
}

And the object (this.props) hasn't params:
enter image description here


来源: stackexchange

问:
How to disable forward class compiler warning (undocumented class)
I'm currently writing an iPhone application that uses a UITabBarController with more than 5 Tab Bar Items. Thus, a 'more' tab is automatically generated (like in the YouTube Application).
I found out that the corresponding view controller class is UIMoreListController, but I don't have any corresponding .h files. So, my code looks like this:

```<code>@class UIMoreListController; // can't use #import since .h file is missing

@implementation SomeUINavigationControllerDelegate

- (void)navigationController:(UINavigationController *)navigationController
        willShowViewController:(UIViewController *)viewController
        animated:(BOOL)animated
{
     if ([viewController isKindOfClass:[UIMoreListController class]])
         ... // do something if "more" view is active
</code>```

This works like a charm. However, the compiler keeps giving me

warning: receiver 'UIMoreListController' is a forward class and corresponding @interface may not exist

Is there a neat way of getting rid of this warning (and this particular warning only)? Again, I can't use #import since no .h file is available.

答: Why are you trying to do this? You should not be using any private APIs. There's no guarantee that this class will still be there in the next OS release, and if you assume it is, then that road leads to bugs or even crashes.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm currently writing an iPhone application that uses a UITabBarController with more than 5 Tab Bar Items. Thus, a 'more' tab is automatically generated (like in the YouTube Application).
I found out that the corresponding view controller class is UIMoreListController, but I don't have any corresponding .h files. So, my code looks like this:

@class UIMoreListController; // can't use #import since .h file is missing

@implementation SomeUINavigationControllerDelegate

- (void)navigationController:(UINavigationController *)navigationController
        willShowViewController:(UIViewController *)viewController
        animated:(BOOL)animated
{
     if ([viewController isKindOfClass:[UIMoreListController class]])
         ... // do something if "more" view is active

This works like a charm. However, the compiler keeps giving me

warning: receiver 'UIMoreListController' is a forward class and corresponding @interface may not exist

Is there a neat way of getting rid of this warning (and this particular warning only)? Again, I can't use #import since no .h file is available.

OwnerDisplayName: Kevin Ballard


问:
Sun (oracle) Java on new projects

Possible Duplicate:

  Are there reliable alternatives to Sun's JVM for desktop & enterprise development?

I'm considering a large long term Java project.

I'm seeing some negative signs in the Oracle takeover of Sun and concerned that this may affect the viability of using Sun (Oracle) on the project.

Should I consider using another Java implementation base?  If so, what looks good long term?

答: Developing in Java means your work will function across a number of different platforms, so there's no vendor lock-in issues.  Oracle, IBM, and others are also supporting the OpenJDK project, so you can always switch to that if you don't like the terms of the available proprietary implementations. </p>

Title: Sun (oracle) Java on new projects


问:
SOAP with two certificates file and "Could not connect to host"
I have an issue connecting PHP with an API which requires using SSL certificates. The issue is when I run my PHP code I get "Could not connect to host".

I was able to connect to the service provider using CURL like this  :

$wsdl       = 'https://example.com/Case.svc';
$certFile   = getcwd() . '/certificate.crt';
$keyFile    = getcwd() . '/key.pem';
$password   = 'password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,           $wsdl);
curl_setopt($ch, CURLOPT_SSLCERT,       $certFile);
curl_setopt($ch, CURLOPT_SSLKEYPASSWD,  $password);
curl_setopt($ch, CURLOPT_SSLKEY,        $keyFile);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$output = curl_exec($ch);

var_dump(curl_errno($ch));
var_dump(curl_error($ch));
```

<p>However, I was not able to do this using SOAP:</p>

<pre class="lang-php prettyprint-override"><code>$options=array(
            'soap_version'   => SOAP_1_2,
            'trace' => true,
            'cache_wsdl' => WSDL_CACHE_NONE,
            'exceptions' => 1,
            'encoding' => 'UTF-8',
            'stream_context'=>stream_context_create(
                          array(
                            'ssl'=>array(
                                'verify_peer'=>true
                                ,'allow_self_signed'=>false
                                ,'cafile'=>'certificate.crt'
                                ,'verify_depth'=>5
                                )
                            )
                        ),
                        'local_cert' => 'key.pem',
            'passphrase' => 'password',
        );

    $client = new SoapClient("Case.wsdl", $options);
</code>```

It results in "Could not connect to host".

The Issue might be in the certificate itself, maybe I need to merge two certificate in one file. I can see that many people having the same issue, most of them did not get an answer.

Why is the SOAP code returning "Could not connect to host", and how do I fix it?

答:
If your certificate is self signed you don't have to set cafile.
cafile is only for CA chain.
local_cert needs to have both: certificate (leaf) and private key concatenated e.g.:

```<code>-----BEGIN CERTIFICATE-----
MIIDsDCCApgCAWUwDQ....
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAsMGypi...
-----END RSA PRIVATE KEY-----
</code>```

For some reason self signed certificate don't work for me on ubuntu but works fine on mac os.

ContentLicense: CC BY-SA 3.0

Body:
I have an issue connecting PHP with an API which requires using SSL certificates. The issue is when I run my PHP code I get "Could not connect to host".

I was able to connect to the service provider using CURL like this  :

$wsdl       = 'https://example.com/Case.svc';
$certFile   = getcwd() . '/certificate.crt';
$keyFile    = getcwd() . '/key.pem';
$password   = 'password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,           $wsdl);
curl_setopt($ch, CURLOPT_SSLCERT,       $certFile);
curl_setopt($ch, CURLOPT_SSLKEYPASSWD,  $password);
curl_setopt($ch, CURLOPT_SSLKEY,        $keyFile);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$output = curl_exec($ch);

var_dump(curl_errno($ch));
var_dump(curl_error($ch));

However, I was not able to do this using SOAP:

$options=array(
            'soap_version'   => SOAP_1_2,
            'trace' => true,
            'cache_wsdl' => WSDL_CACHE_NONE,
            'exceptions' => 1,
            'encoding' => 'UTF-8',
            'stream_context'=>stream_context_create(
                          array(
                            'ssl'=>array(
                                'verify_peer'=>true
                                ,'allow_self_signed'=>false
                                ,'cafile'=>'certificate.crt'
                                ,'verify_depth'=>5
                                )
                            )
                        ),
                        'local_cert' => 'key.pem',
            'passphrase' => 'password',
        );

    $client = new SoapClient("Case.wsdl", $options);

It results in "Could not connect to host".

The Issue might be in the certificate itself, maybe I need to merge two certificate in one file. I can see that many people having the same issue, most of them did not get an answer.

Why is the SOAP code returning "Could not connect to host", and how do I fix it?

Body:
If your certificate is self signed you don't have to set cafile.
cafile is only for CA chain.
local_cert needs to have both: certificate (leaf) and private key concatenated e.g.:

-----BEGIN CERTIFICATE-----
MIIDsDCCApgCAWUwDQ....
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAsMGypi...
-----END RSA PRIVATE KEY-----

For some reason self signed certificate don't work for me on ubuntu but works fine on mac os.


问:
RxJava - counter with x of y
How can I do this? I came up with following, it allows me to calculate the x in x of y, but how can I improve that to calculate the y as well?

```<code>Observable<LoadedPhoneContact> phoneContacts = getPhoneContacts()
        .flatMapObservable(contacts -> Observable.fromIterable(contacts));

Observable<Integer> phoneContactsCounter = phoneContacts
        .cache()
        .map(contact -> 1)
        .reduce((c1, c2) -> c2 + c2)
        .toObservable();

mSimils = phoneContacts
        .zipWith(phoneContactsCounter, (contact, index) -> new Pair<>(contact, index))
        .doOnNext(data ->  {
            L.d("x / y = %d / %d", data.second, ?);
        })
        .map(data -> SimilUtil.calcSimils(data))
        ;
</code>```

Any ideas or better/alternative solutions?

I want to be able to see the progress in a format like "x of y items processed"...

I could zip with a third observable that just emits the count, but is this the correct way?

答:
How about this:</p>

```<code>Observable<?> result = Observable.defer(() -> {
    int[] counter = { 1 };
    return getPhoneContacts()
        .toObservable()
        .flatMapIterable(list -> list, (list, element) -> {
             L.d("x / y = %d / %d", counter[0]++, list.size());
             return SimilUtil.calcSimils(element);
        });
});
</code>```

Title: RxJava - counter with x of y

Body:
How can I do this? I came up with following, it allows me to calculate the x in x of y, but how can I improve that to calculate the y as well?

Observable<LoadedPhoneContact> phoneContacts = getPhoneContacts()
        .flatMapObservable(contacts -> Observable.fromIterable(contacts));

Observable<Integer> phoneContactsCounter = phoneContacts
        .cache()
        .map(contact -> 1)
        .reduce((c1, c2) -> c2 + c2)
        .toObservable();

mSimils = phoneContacts
        .zipWith(phoneContactsCounter, (contact, index) -> new Pair<>(contact, index))
        .doOnNext(data ->  {
            L.d("x / y = %d / %d", data.second, ?);
        })
        .map(data -> SimilUtil.calcSimils(data))
        ;

Any ideas or better/alternative solutions?

I want to be able to see the progress in a format like "x of y items processed"...

I could zip with a third observable that just emits the count, but is this the correct way?

Body:
How about this:

Observable<?> result = Observable.defer(() -> {
    int[] counter = { 1 };
    return getPhoneContacts()
        .toObservable()
        .flatMapIterable(list -> list, (list, element) -> {
             L.d("x / y = %d / %d", counter[0]++, list.size());
             return SimilUtil.calcSimils(element);
        });
});


问:
"Timeout while fetching" URLFetch GAE/J
I'm using the XMLReader to simply read a feed like below.

```<code>URLConnection urlConnection = url.openConnection();
XmlReader reader = new XmlReader(urlConnection);
</code>```

When this is called I receive within 5 seconds an IOException "Timeout
while fetching". So I tried to set the timeouts to the max. (10 sec) but still no luck and still an IOExeption in 5 sec.

```<code>urlConnection.setConnectTimeout(10000);
</code>```

(the max is stated in documentation: http://code.google.com/intl/nl-NL/appengine/docs/java/urlfetch/overview.html)

Seems that the size of the feed is too large. When I call a smaller feed
it works properly. Is there any workaround or solution for this? I need to be able to call larger feeds.

答:
The reason is:

If no data is available for the read timeout period, exception can be thrown. From the doc of Oracle

A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.

By the way, ReadTimeout is different with ConnectTimeout, the read timeout is the timeout to get data from the host, see different connection timeout and read timeout

So as @systempuntoout answer, need to set read timeout.

Title: "Timeout while fetching" URLFetch GAE/J

Body:
I'm using the XMLReader to simply read a feed like below.

URLConnection urlConnection = url.openConnection();
XmlReader reader = new XmlReader(urlConnection);

When this is called I receive within 5 seconds an IOException "Timeout
while fetching". So I tried to set the timeouts to the max. (10 sec) but still no luck and still an IOExeption in 5 sec.

urlConnection.setConnectTimeout(10000);

(the max is stated in documentation: http://code.google.com/intl/nl-NL/appengine/docs/java/urlfetch/overview.html)

Seems that the size of the feed is too large. When I call a smaller feed
it works properly. Is there any workaround or solution for this? I need to be able to call larger feeds.


问:
Need Get HttpPost Values in TextBox Control Unsing ASP.NET C#
I need to pass data between pages using ASP.NET C#, I need to get text value from first page to second page inside a TextBox using HttPost. My pages structure is given below
I have Two(2) pages as given below:

WebForm1.aspx

```<code><form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtData" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="btnHttpPost" runat="server" Text="HTTPPost" PostBackUrl="~/WebForm2.aspx" />
    </div>
</form>
</code>```

WebForm2.aspx

```<code><form id="form1" runat="server">
    <div>
        <h1>HttpPost</h1>
        Data is: <%=Request.Form["txtData"] %>
        <p>
            <asp:TextBox ID="txtGetValue" runat="server"></asp:TextBox>
        </p>
    </div>
</form>
</code>```

As we see in WebForm2.aspx the line below Heading 1 Tag working fine, but I need the value of the previous page (WebForm1.aspx) in TextBox named (txtGetValue)  available in second page (Webform2.aspx).

答:
That can be really easily done in code behind. Like so:</p>

```<code>public void Page_Load(object sender, EventArgs e)
{
    txtGatValue.Text = Request.Form["txtData"];
}
</code>```

Body:
I need to pass data between pages using ASP.NET C#, I need to get text value from first page to second page inside a TextBox using HttPost. My pages structure is given below
I have Two(2) pages as given below:

WebForm1.aspx

<form id="form1" runat="server">

        <asp:TextBox ID="txtData" runat="server"></asp:TextBox>

        <asp:Button ID="btnHttpPost" runat="server" Text="HTTPPost" PostBackUrl="~/WebForm2.aspx" />

</form>

WebForm2.aspx

<form id="form1" runat="server">

HttpPost

        Data is: <%=Request.Form["txtData"] %>

            <asp:TextBox ID="txtGetValue" runat="server"></asp:TextBox>

</form>

As we see in WebForm2.aspx the line below Heading 1 Tag working fine, but I need the value of the previous page (WebForm1.aspx) in TextBox named (txtGetValue)  available in second page (Webform2.aspx).

Body:
That can be really easily done in code behind. Like so:

public void Page_Load(object sender, EventArgs e)
{
    txtGatValue.Text = Request.Form["txtData"];
}


问:
Magento: Setting a custom attribute on the sales/order_shipment model
I'm trying to add an EAV attribute called "vendorping" to the sales/order_shipment model. To accomplish this, I created the following file in my module:

```<code>// app\code\local\Jb\Vendorping\sql\vendorping_setup\mysql4-install-0.1.0.php

$this->startSetup();

$sql = 'SELECT entity_type_id FROM `'.$this->getTable('eav_entity_type').'` WHERE entity_type_code = \'shipment\'';
$row = Mage::getSingleton('core/resource')
    ->getConnection('core_read')
    ->fetchRow($sql);
$entityTypeId = $row['entity_type_id'];

$c = array(
    'entity_type_id'  => $entityTypeId,
    'attribute_code'  => 'vendorping',
    'backend_type'    => 'int',
    'frontend_input'  => 'text',
    'is_global'       => '1',
    'is_visible'      => '0',
    'is_required'     => '0',
    'is_user_defined' => '0',
    'frontend_label'  => 'Vendor Confirmed',
    );
$attribute = new Mage_Eav_Model_Entity_Attribute();
$attribute->loadByCode($c['entity_type_id'], $c['attribute_code'])
    ->setStoreId(0)
    ->addData($c)
    ->save();

$this->endSetup();
</code>```

Now, this is working fine -- this attribute is successfully added:

```<code>mysql> mysql> SELECT * FROM eav_attribute WHERE attribute_code LIKE 'vendorping';
+--------------+----------------+----------------+-----------------+---------------+--------------+---------------+----------------+----------------+------------------+----------------+--------------+-------------+-----------------+---------------+-----------+------+
| attribute_id | entity_type_id | attribute_code | attribute_model | backend_model | backend_type | backend_table | frontend_model | frontend_input | frontend_label   | frontend_class | source_model | is_required | is_user_defined | default_value | is_unique | note |
+--------------+----------------+----------------+-----------------+---------------+--------------+---------------+----------------+----------------+------------------+----------------+--------------+-------------+-----------------+---------------+-----------+------+
|          127 |              8 | vendorping     | NULL            | NULL          | int          | NULL          | NULL           | text           | Vendor Confirmed | NULL           | NULL         |           0 |               0 | NULL          |         0 |      |
+--------------+----------------+----------------+-----------------+---------------+--------------+---------------+----------------+----------------+------------------+----------------+--------------+-------------+-----------------+---------------+-----------+------+
1 row in set (0.00 sec)
</code>```

But if I run this controller action, I can't seem to successfully save the new attribute:

```<code>// app\code\local\Jb\Vendorping\controllers\IndexController.php ===

class Jb_Vendorping_IndexController extends Mage_Core_Controller_Front_Action
{
    public function pingAction()
    {
        // Get shipment
        $shipmentId = 1; // Set manually for now
        $shipment = Mage::getModel('sales/order_shipment')->load($shipmentId);
        var_dump($shipment->getOrder()->getShippingDescription());
            // Outputs:
            // string(17) "Flat Rate - Fixed" [So the shipment exists]

        // Save "vendorping" field and save
        $shipment->setVendorping(1);
        $shipment->save();

        // Reload shipment from database
        $shipment = Mage::getModel('sales/order_shipment')->load($shipmentId);

        // Check "vendorping" field
        var_dump($shipment->getVendorping());
            // Outputs:
            // NULL [Why??]
    }
}
</code>```

答:
This worked:</p>

```<code>// ModuleNamespace/ModuleName/sql/vendorping_setup/mysql4-install-0.1.0.php

$this->startSetup();

if (version_compare(Mage::getVersion(), '1.4.1.0', '>=')) { // If sales data is stored flat
    $w = $this->_conn;
    $w->addColumn($this->getTable('sales_flat_shipment'), 'vendorping', 'int');
} else {
    $eav = new Mage_Eav_Model_Entity_Setup('sales_setup');
    $eav->addAttribute('shipment', 'vendorping', array('type' => 'int'));
}

$this->endSetup();
</code>```

Body:
I'm trying to add an EAV attribute called "vendorping" to the sales/order_shipment model. To accomplish this, I created the following file in my module:

// app\code\local\Jb\Vendorping\sql\vendorping_setup\mysql4-install-0.1.0.php

$this->startSetup();

$sql = 'SELECT entity_type_id FROM `'.$this->getTable('eav_entity_type').'` WHERE entity_type_code = \'shipment\'';
$row = Mage::getSingleton('core/resource')
    ->getConnection('core_read')
    ->fetchRow($sql);
$entityTypeId = $row['entity_type_id'];

$c = array(
    'entity_type_id'  => $entityTypeId,
    'attribute_code'  => 'vendorping',
    'backend_type'    => 'int',
    'frontend_input'  => 'text',
    'is_global'       => '1',
    'is_visible'      => '0',
    'is_required'     => '0',
    'is_user_defined' => '0',
    'frontend_label'  => 'Vendor Confirmed',
    );
$attribute = new Mage_Eav_Model_Entity_Attribute();
$attribute->loadByCode($c['entity_type_id'], $c['attribute_code'])
    ->setStoreId(0)
    ->addData($c)
    ->save();

$this->endSetup();

Now, this is working fine -- this attribute is successfully added:

mysql> mysql> SELECT * FROM eav_attribute WHERE attribute_code LIKE 'vendorping';
+--------------+----------------+----------------+-----------------+---------------+--------------+---------------+----------------+----------------+------------------+----------------+--------------+-------------+-----------------+---------------+-----------+------+
| attribute_id | entity_type_id | attribute_code | attribute_model | backend_model | backend_type | backend_table | frontend_model | frontend_input | frontend_label   | frontend_class | source_model | is_required | is_user_defined | default_value | is_unique | note |
+--------------+----------------+----------------+-----------------+---------------+--------------+---------------+----------------+----------------+------------------+----------------+--------------+-------------+-----------------+---------------+-----------+------+
|          127 |              8 | vendorping     | NULL            | NULL          | int          | NULL          | NULL           | text           | Vendor Confirmed | NULL           | NULL         |           0 |               0 | NULL          |         0 |      |
+--------------+----------------+----------------+-----------------+---------------+--------------+---------------+----------------+----------------+------------------+----------------+--------------+-------------+-----------------+---------------+-----------+------+
1 row in set (0.00 sec)

But if I run this controller action, I can't seem to successfully save the new attribute:

// app\code\local\Jb\Vendorping\controllers\IndexController.php ===

class Jb_Vendorping_IndexController extends Mage_Core_Controller_Front_Action
{
    public function pingAction()
    {
        // Get shipment
        $shipmentId = 1; // Set manually for now
        $shipment = Mage::getModel('sales/order_shipment')->load($shipmentId);
        var_dump($shipment->getOrder()->getShippingDescription());
            // Outputs:
            // string(17) "Flat Rate - Fixed" [So the shipment exists]

        // Save "vendorping" field and save
        $shipment->setVendorping(1);
        $shipment->save();

        // Reload shipment from database
        $shipment = Mage::getModel('sales/order_shipment')->load($shipmentId);

        // Check "vendorping" field
        var_dump($shipment->getVendorping());
            // Outputs:
            // NULL [Why??]
    }
}

Body:
This worked:

// ModuleNamespace/ModuleName/sql/vendorping_setup/mysql4-install-0.1.0.php

$this->startSetup();

if (version_compare(Mage::getVersion(), '1.4.1.0', '>=')) { // If sales data is stored flat
    $w = $this->_conn;
    $w->addColumn($this->getTable('sales_flat_shipment'), 'vendorping', 'int');
} else {
    $eav = new Mage_Eav_Model_Entity_Setup('sales_setup');
    $eav->addAttribute('shipment', 'vendorping', array('type' => 'int'));
}

$this->endSetup();


问:
Merge two Columns when specific Column starts with a Specific test
I need to change two columns in every line where "Color" column starts with a specific value "yell"

My table is:

```<code>+------+----------+----------+
| Name | Color    | Quantity |
+------+----------+----------+
| A    | <yell> U | 2        |
+------+----------+----------+
| B    | Blue     | 1        |
+------+----------+----------+
| C    | Red      | 4        |
+------+----------+----------+
| D    | <yell> A | 2        |
+------+----------+----------+
</code>```

For this, example table, I have 2 lines where column Collor starts with the string "Yell" . I need to change that field to Yellow and Put quantity = quantity-1, for the column "Quantity"

I need to match only the first 6 characters of the Collor string . What comes after this can be different from line to line.

So my table would be:

```<code>+------+--------+----------+
| Name | Color  | Quantity |
+------+--------+----------+
| A    | Yellow | 1        |
+------+--------+----------+
| B    | Blue   | 1        |
+------+--------+----------+
| C    | Red    | 4        |
+------+--------+----------+
| D    | Yellow | 1        |
+------+--------+----------+
</code>```

Can you help me? I've tried a merge but i'm not doing it right.

答:
Something like this ?</p>

```<code>   update TABLENAME a
       set a.color = 'Yellow',
           a.quantity = a.quantity - 1
     where exists (select count(*)
              from TABLENAME t
             where substr(t.color, 1, 6) = substr(a.color, 1, 6)
             group by (substr(t.color, 1, 6))
            having count(*) > 1)
</code>```

Body:
I need to change two columns in every line where "Color" column starts with a specific value "yell"

My table is:

+------+----------+----------+
| Name | Color    | Quantity |
+------+----------+----------+
| A    | <yell> U | 2        |
+------+----------+----------+
| B    | Blue     | 1        |
+------+----------+----------+
| C    | Red      | 4        |
+------+----------+----------+
| D    | <yell> A | 2        |
+------+----------+----------+

For this, example table, I have 2 lines where column Collor starts with the string "Yell" . I need to change that field to Yellow and Put quantity = quantity-1, for the column "Quantity"

I need to match only the first 6 characters of the Collor string . What comes after this can be different from line to line.

So my table would be:

+------+--------+----------+
| Name | Color  | Quantity |
+------+--------+----------+
| A    | Yellow | 1        |
+------+--------+----------+
| B    | Blue   | 1        |
+------+--------+----------+
| C    | Red    | 4        |
+------+--------+----------+
| D    | Yellow | 1        |
+------+--------+----------+

Can you help me? I've tried a merge but i'm not doing it right.

Body:
Something like this ?

   update TABLENAME a
       set a.color = 'Yellow',
           a.quantity = a.quantity - 1
     where exists (select count(*)
              from TABLENAME t
             where substr(t.color, 1, 6) = substr(a.color, 1, 6)
             group by (substr(t.color, 1, 6))
            having count(*) > 1)


问:
C macro and makefile and expressions not work as expected
In my C code, I need to check my kernel version and act according to it.
In the makefile I have the following:

```<code>KERNEL_MAJOR :=$(word 1, $(subst ., ,$(KERNEL_HEADERS)))
KERNEL_MINOR :=$(word 2, $(subst ., ,$(KERNEL_HEADERS)))
KERNEL_MICRO :=$(word 1, $(subst -, ,$(word 3, $(subst ., ,$(KERNEL_HEADERS)))))
KERNEL_PATCH_LEVEL :=$(word 1, $(subst ., ,$(word 2, $(subst -, ,$(KERNEL_HEADERS)))))
KARGS := KCPPFLAGS="-DKERNEL_MAJOR=$(KERNEL_MAJOR) -DKERNEL_MINOR=$(KERNEL_MINOR) -DKERNEL_MICRO=$(KERNEL_MICRO) -DKERNEL_PATCH_LEVEL=$(KERNEL_PATCH_LEVEL)"
</code>```

Samples:

3.0.101-0.47.71-default looks like:

```<code>KCPPFLAGS="-DKERNEL_MAJOR=3 -DKERNEL_MINOR=0 -DKERNEL_MICRO=101 -DKERNEL_PATCH_LEVEL=0"
</code>```

4.1.21.x86_64.1 (notice KERNEL_PATCH_LEVEL):

```<code>KCPPFLAGS="-DKERNEL_MAJOR=4 -DKERNEL_MINOR=1 -DKERNEL_MICRO=21 -DKERNEL_PATCH_LEVEL="
</code>```

I have macro in my code to check if kernel is 3.0.101.0 or 3.0.76.0:

```<code>#if defined(KERNEL_MAJOR) && defined(KERNEL_MINOR) && defined(KERNEL_MICRO) && defined(KERNEL_PATCH_LEVEL) && \
    (KERNEL_VERSION(KERNEL_MAJOR,KERNEL_MINOR,KERNEL_MICRO) == KERNEL_VERSION(3,0,101) || KERNEL_VERSION(KERNEL_MAJOR,KERNEL_MINOR,KERNEL_MICRO) == KERNEL_VERSION(3,0,76)) \
    && (KERNEL_PATCH_LEVEL == 0)
</code>```

There are 3 && boolean expressions, if expression #1 is ok, then i want to continue to expression #2, if expression #2 continue, i will continue to expression #3.
When i try to compile (make..) on kernel version 4.1.21.x86_64.1 i receive:

```<code>error: operator '==' has no left operand
</code>```

This is because -DKERNEL_PATCH_LEVEL="  - see the output.

I would expect the make to prevent me from getting to that && condition since expression #2 has failed (3.0.101 or 3.0.76)

答:
All the #if conditions pass because KERNEL_PATCH_LEVEL is defined.  It's just defined as an empty string.  -DKERNEL_PATCH_LEVEL= is equivalent to

```<code>#define KERNEL_PATCH_LEVEL
</code>```

Which, of course, will pass an #if (defined) test.

It's somewhat difficult to test if a macro is empty.  It might be easier to modify your makefile to define KERNEL_PATCH_LEVEL as some special value (like 0 or -1) if it isn't present in the version string.

Body:
In my C code, I need to check my kernel version and act according to it.
In the makefile I have the following:

KERNEL_MAJOR :=$(word 1, $(subst ., ,$(KERNEL_HEADERS)))
KERNEL_MINOR :=$(word 2, $(subst ., ,$(KERNEL_HEADERS)))
KERNEL_MICRO :=$(word 1, $(subst -, ,$(word 3, $(subst ., ,$(KERNEL_HEADERS)))))
KERNEL_PATCH_LEVEL :=$(word 1, $(subst ., ,$(word 2, $(subst -, ,$(KERNEL_HEADERS)))))
KARGS := KCPPFLAGS="-DKERNEL_MAJOR=$(KERNEL_MAJOR) -DKERNEL_MINOR=$(KERNEL_MINOR) -DKERNEL_MICRO=$(KERNEL_MICRO) -DKERNEL_PATCH_LEVEL=$(KERNEL_PATCH_LEVEL)"

Samples:

3.0.101-0.47.71-default looks like:

KCPPFLAGS="-DKERNEL_MAJOR=3 -DKERNEL_MINOR=0 -DKERNEL_MICRO=101 -DKERNEL_PATCH_LEVEL=0"

4.1.21.x86_64.1 (notice KERNEL_PATCH_LEVEL):

KCPPFLAGS="-DKERNEL_MAJOR=4 -DKERNEL_MINOR=1 -DKERNEL_MICRO=21 -DKERNEL_PATCH_LEVEL="

I have macro in my code to check if kernel is 3.0.101.0 or 3.0.76.0:

#if defined(KERNEL_MAJOR) && defined(KERNEL_MINOR) && defined(KERNEL_MICRO) && defined(KERNEL_PATCH_LEVEL) && \
    (KERNEL_VERSION(KERNEL_MAJOR,KERNEL_MINOR,KERNEL_MICRO) == KERNEL_VERSION(3,0,101) || KERNEL_VERSION(KERNEL_MAJOR,KERNEL_MINOR,KERNEL_MICRO) == KERNEL_VERSION(3,0,76)) \
    && (KERNEL_PATCH_LEVEL == 0)

There are 3 && boolean expressions, if expression #1 is ok, then i want to continue to expression #2, if expression #2 continue, i will continue to expression #3.
When i try to compile (make..) on kernel version 4.1.21.x86_64.1 i receive:

error: operator '==' has no left operand

This is because -DKERNEL_PATCH_LEVEL="  - see the output.

I would expect the make to prevent me from getting to that && condition since expression #2 has failed (3.0.101 or 3.0.76)

Body:
All the #if conditions pass because KERNEL_PATCH_LEVEL is defined.  It's just defined as an empty string.  -DKERNEL_PATCH_LEVEL= is equivalent to

#define KERNEL_PATCH_LEVEL

Which, of course, will pass an #if (defined) test.

It's somewhat difficult to test if a macro is empty.  It might be easier to modify your makefile to define KERNEL_PATCH_LEVEL as some special value (like 0 or -1) if it isn't present in the version string.


问:
Multiple values of the same column name in SQL
this might seem like a weird question, earlier I posted another question on ASP multiple values through a session variable, I've now figured that out and have managed to pass all three values for instance to a label. Now however I need to pass the three IDs to create a gridview for the three values... So for my SQL statement I have:

SelectCommand="SELECT [BookID], [book_title] FROM [tblBook] WHERE ([BookID] = ?)">

So I need there to be 3 BookID=?,?,? for instance, is this possible?

Or is there another way to do it in ASP?

答:
In SQL, you can use the 'IN' operator to do it. The SQL query would be </p>

```<code>SELECT [BookID], [book_title] FROM [tblBook] WHERE [BookID] IN (@Book1,@Book2,@Book3)
</code>```

<p>You will have to pass the book1,2,3 as parameters to the asp function. You might have to construct the query dynamically by appending the parameters. Something like this </p>

```<code>string query = string.Format("SELECT [BookID], [book_title] FROM [tblBook] WHERE [BookID] IN ({0},{1},{2})",book1,book2,book3)
</code>```

Body:
In SQL, you can use the 'IN' operator to do it. The SQL query would be

SELECT [BookID], [book_title] FROM [tblBook] WHERE [BookID] IN (@Book1,@Book2,@Book3)

You will have to pass the book1,2,3 as parameters to the asp function. You might have to construct the query dynamically by appending the parameters. Something like this

string query = string.Format("SELECT [BookID], [book_title] FROM [tblBook] WHERE [BookID] IN ({0},{1},{2})",book1,book2,book3)


问:
Looping over array elements, given an array of arrays' variable names in Bash Script
I have an array containing names of categories

```<code>categories=( categoryA categoryB categoryC )
</code>```

Each category contains multiple products, which is stored in different arrays.

```<code>categoryA=( productA1 productA2 productA3 )
categoryB=( productB1 productB2 productB3 )
categoryC=( productC1 productC2 productC3 )
</code>```

I want to loop over all products, so I wrote this code:

```<code>categories=( categoryA categoryB categoryC )

categoryA=( productA1 productA2 productA3 )
categoryB=( productB1 productB2 productB3 )
categoryC=( productC1 productC2 productC3 )

for category_name in "${categories[@]}"
do
    echo $category_name

    category=${!category_name}
    for product in "${category[@]}"
    do
        echo -e '\t' $product
    done

    echo -e '\n'

done
</code>```

I expected the output to be:

```<code>CategoryA
    ProductA1
    ProductA2
    ProductA3

CategoryB
    ProductB1
    ProductB2
    ProductB3

CategoryC
    ProductC1
    ProductC2
    ProductC3
</code>```

but unfortunately, the output is

```<code>CategoryA
    ProductA1

CategoryB
    ProductB1

CategoryC
    ProductC1
</code>```

How to fix this ?

答:
Absolutely do NOT use eval for this case, just use declare to create variables on the fly,

Just replace the line

```<code>category=${!category_name}
</code>```

in your original answer with

```<code>declare -n category="${category_name}"
</code>```

the above declare syntax will create a reference for category to the variable category_name which can be accessed further for expanding as an array.

declare -n is a relatively newer syntax available since introduced in Bash 4.3-alpha

Body:
I have an array containing names of categories

categories=( categoryA categoryB categoryC )

Each category contains multiple products, which is stored in different arrays.

categoryA=( productA1 productA2 productA3 )
categoryB=( productB1 productB2 productB3 )
categoryC=( productC1 productC2 productC3 )

I want to loop over all products, so I wrote this code:

categories=( categoryA categoryB categoryC )

categoryA=( productA1 productA2 productA3 )
categoryB=( productB1 productB2 productB3 )
categoryC=( productC1 productC2 productC3 )

for category_name in "${categories[@]}"
do
    echo $category_name

    category=${!category_name}
    for product in "${category[@]}"
    do
        echo -e '\t' $product
    done

    echo -e '\n'

done

I expected the output to be:

CategoryA
    ProductA1
    ProductA2
    ProductA3

CategoryB
    ProductB1
    ProductB2
    ProductB3

CategoryC
    ProductC1
    ProductC2
    ProductC3

but unfortunately, the output is

CategoryA
    ProductA1

CategoryB
    ProductB1

CategoryC
    ProductC1

How to fix this ?

Body:
Absolutely do NOT use eval for this case, just use declare to create variables on the fly,

Just replace the line

category=${!category_name}

in your original answer with

declare -n category="${category_name}"

the above declare syntax will create a reference for category to the variable category_name which can be accessed further for expanding as an array.

declare -n is a relatively newer syntax available since introduced in Bash 4.3-alpha


问:
mongoose model value and merging new object not working in node js
I am a beginner in mean stack development. I am trying to fetch records from a collection and add two more objects in the records but I can't merge the objects.

I have tried the following. Not getting the values of the "images" objects which I tried to merge with "projects" object. It's not merging.

```<code>var _ = require('lodash');
project.findOne({_id:id}).exec(function (err, projectdetails) {

  if(err){
    res.send(err);
  }

            projectimage.find({projectId: projectdetails._id}, function(err, data){
              if(err){
                res.send(err);
              }

var projects = projectdetails;

var images = [
   {
     image_id : 1,
    "image_location" : "f1.js"
   },
    {
     image_id : 2,
    "image_location" : "f2.js"
   }

];
 projects = _.extend({},projects,{images:images},{projectimage:data});

        res.send(projects);

            });

    });
</code>```

obtained output:

```<code>{
  "_id": "58da3c350a668f13f0d6dbcc",
  "name": "senthil",
  "designation": "CI",
  "berief_text": "welcome to senthil",
  "status": 1,
  "__v": 0
}
</code>```

expected output:

```<code>{
  "_id": "58da3c350a668f13f0d6dbcc",
  "name": "senthil",
  "designation": "CI",
  "berief_text": "welcome to senthil",
  "status": 1,
  "__v": 0,
  "images": [
    {
      "image_id": 1,
      "image_location": "f1.js"
    },
    {
      "image_id": 2,
      "image_location": "f2.js"
    }
  ],
  "projectimage": [
    {
      "_id": "58da3c350a668f13f0d6dbcd",
      "imageLocation": "uploads\\project_images\\1490697269435download.jpg",
      "projectId": "58da3c350a668f13f0d6dbcc",
      "__v": 0
    },
    {
      "_id": "58da3c350a668f13f0d6dbce",
      "imageLocation": "uploads\\project_images\\1490697269439download (3).jpg",
      "projectId": "58da3c350a668f13f0d6dbcc",
      "__v": 0
    }
  ]
}
</code>```

答:
try to use

```<code>JSON.parse(JSON.stringify(projects))
JSON.parse(JSON.stringify(images))
</code>```

before

```<code>projects = _.extend({},projects,{images:images},{projectimage:data});
</code>```

Body:
I am a beginner in mean stack development. I am trying to fetch records from a collection and add two more objects in the records but I can't merge the objects.

I have tried the following. Not getting the values of the "images" objects which I tried to merge with "projects" object. It's not merging.

var _ = require('lodash');
project.findOne({_id:id}).exec(function (err, projectdetails) {

  if(err){
    res.send(err);
  }

            projectimage.find({projectId: projectdetails._id}, function(err, data){
              if(err){
                res.send(err);
              }

var projects = projectdetails;

var images = [
   {
     image_id : 1,
    "image_location" : "f1.js"
   },
    {
     image_id : 2,
    "image_location" : "f2.js"
   }

];
 projects = _.extend({},projects,{images:images},{projectimage:data});

        res.send(projects);

            });

    });

obtained output:

{
  "_id": "58da3c350a668f13f0d6dbcc",
  "name": "senthil",
  "designation": "CI",
  "berief_text": "welcome to senthil",
  "status": 1,
  "__v": 0
}

expected output:

{
  "_id": "58da3c350a668f13f0d6dbcc",
  "name": "senthil",
  "designation": "CI",
  "berief_text": "welcome to senthil",
  "status": 1,
  "__v": 0,
  "images": [
    {
      "image_id": 1,
      "image_location": "f1.js"
    },
    {
      "image_id": 2,
      "image_location": "f2.js"
    }
  ],
  "projectimage": [
    {
      "_id": "58da3c350a668f13f0d6dbcd",
      "imageLocation": "uploads\\project_images\\1490697269435download.jpg",
      "projectId": "58da3c350a668f13f0d6dbcc",
      "__v": 0
    },
    {
      "_id": "58da3c350a668f13f0d6dbce",
      "imageLocation": "uploads\\project_images\\1490697269439download (3).jpg",
      "projectId": "58da3c350a668f13f0d6dbcc",
      "__v": 0
    }
  ]
}

Body:
try to use

JSON.parse(JSON.stringify(projects))
JSON.parse(JSON.stringify(images))

before

projects = _.extend({},projects,{images:images},{projectimage:data});


问:
How to compare vectors with Boost.Test?
I am using Boost Test to unit test some C++ code.

I have a vector of values that I need to compare with expected results, but I don't want to manually check the values in a loop:

```<code>BOOST_REQUIRE_EQUAL(values.size(), expected.size());

for( int i = 0; i < size; ++i )
{
    BOOST_CHECK_EQUAL(values[i], expected[i]);
}
</code>```

The main problem is that the loop check doesn't print the index, so it requires some searching to find the mismatch.

I could use std::equal or std::mismatch on the two vectors, but that will require a lot of boilerplate as well.

Is there a cleaner way to do this?

答:
Since Boost 1.59 it is much easier to compare std::vector instances. See this documentation for version 1.63 (which is nearly equal in this respect to 1.59).

For example if you have declared std::vector<int> a, b; you can write

```<code>BOOST_TEST(a == b);
</code>```

to get a very basic comparison. The downside of this is that in case of failure Boost only tells you that a and b are not the same. But you get more info by comparing element-wise which is possible in an elegant way

```<code>BOOST_TEST(a == b, boost::test_tools::per_element() );
</code>```

Or if you want a lexicographic comparison you may do

```<code>BOOST_TEST(a <= b, boost::test_tools::lexicographic() );
</code>```

Title: How to compare vectors with Boost.Test?

Body:
I am using Boost Test to unit test some C++ code.

I have a vector of values that I need to compare with expected results, but I don't want to manually check the values in a loop:

BOOST_REQUIRE_EQUAL(values.size(), expected.size());

for( int i = 0; i < size; ++i )
{
    BOOST_CHECK_EQUAL(values[i], expected[i]);
}

The main problem is that the loop check doesn't print the index, so it requires some searching to find the mismatch.

I could use std::equal or std::mismatch on the two vectors, but that will require a lot of boilerplate as well.

Is there a cleaner way to do this?

Body:
Since Boost 1.59 it is much easier to compare std::vector instances. See this documentation for version 1.63 (which is nearly equal in this respect to 1.59).

For example if you have declared std::vector<int> a, b; you can write

BOOST_TEST(a == b);

to get a very basic comparison. The downside of this is that in case of failure Boost only tells you that a and b are not the same. But you get more info by comparing element-wise which is possible in an elegant way

BOOST_TEST(a == b, boost::test_tools::per_element() );

Or if you want a lexicographic comparison you may do

BOOST_TEST(a <= b, boost::test_tools::lexicographic() );


问:
Argument error in Rails
I am trying to create a new project in Rails. But I am facing following error:

```<code>Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/path_support.rb:25:in `initialize': wrong number of arguments (given 0, expected 1) (ArgumentError)
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:329:in `new'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:329:in `paths'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:352:in `path'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:979:in `dirs'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:831:in `stubs'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:1036:in `find_by_path'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:189:in `try_activate'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:126:in `rescue in require'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:40:in `require'
from <internal:gem_prelude>:6:in `<internal:gem_prelude>'
</code>```

How can I resolve this?

答:
Command to create new rails project:</p>

```<code>rails new project_name
</code>```

ContentLicense: CC BY-SA 4.0

Title: Argument error in Rails

Body:
I am trying to create a new project in Rails. But I am facing following error:

Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/path_support.rb:25:in `initialize': wrong number of arguments (given 0, expected 1) (ArgumentError)
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:329:in `new'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:329:in `paths'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:352:in `path'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:979:in `dirs'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:831:in `stubs'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:1036:in `find_by_path'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:189:in `try_activate'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:126:in `rescue in require'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:40:in `require'
from <internal:gem_prelude>:6:in `<internal:gem_prelude>'

How can I resolve this?

Body:
Command to create new rails project:

rails new project_name


问:
How change css of disabled input checkbox tag?..because it's too light and hard to see
Guys,
I have some input checkbox tags:

They look pretty light and hard to see or print. I tried restyle the checkbox, it seems that the disabled checkbox's style can't be changed?
Do you guys have any idea?
Thanks a lot! :)</p>

答:
The trick is to not actually disable the checkbox but intercept the click action of the "disabled" textbox so it functions as if it was disabled from that point you can style it and it will look how you want.

What you will do is add this on your "disabled" checkboxes instead of disabled="disabled":

```<code>onclick="return false;"
</code>```

EDIT:  As someone noted below there is a drawback to using this method.  The value of the checkbox will still be posted back to the server since it is technically enabled whereas if you used the supported method you would lose control over the look but wouldn't have to deal with this additional data.  (Thanks Robert)

Body:
The trick is to not actually disable the checkbox but intercept the click action of the "disabled" textbox so it functions as if it was disabled from that point you can style it and it will look how you want.

What you will do is add this on your "disabled" checkboxes instead of disabled="disabled":

onclick="return false;"

EDIT:  As someone noted below there is a drawback to using this method.  The value of the checkbox will still be posted back to the server since it is technically enabled whereas if you used the supported method you would lose control over the look but wouldn't have to deal with this additional data.  (Thanks Robert)


问:
TSQL find number of correspondences
I have the following table:

```<code>SenderName  ReceiverName    NumberOfTime
Ajay          Vijay             1
Anthony       Mark              3
Anthony       John              5
David         Mark              2
David         John              5
David         John              3
David         John              1
John          David             2
John          David             2
John          Anthony           5
Mark          Anthony           1
</code>```

Test Data:

```<code>CREATE TABLE [dbo].[tblMyTempTable](
[SenderName] [varchar](20) NULL,
[ReceiverName] [varchar](10) NULL,
[NumberOfTime] [int] NULL
) ON [PRIMARY]
GO

INSERT [dbo].[tblMyTempTable]
  ([SenderName], [ReceiverName], [NumberOfTime])
VALUES
  (N'David', N'John', 1)
  ,(N'Mark', N'Anthony', 1)
  ,(N'Ajay', N'Vijay', 1)
  ,(N'John', N'David', 2)
  ,(N'Anthony', N'Mark', 3)
  ,(N'David', N'John', 5)
  ,(N'David', N'John', 3)
  ,(N'John', N'David', 2)
  ,(N'David', N'Mark', 2)
  ,(N'John', N'Anthony', 5)
  ,(N'Anthony', N'John', 5)
</code>```

I need to find out how many times correspondence has been between each pair. For example, Anthony has contacted John 5 times, John has contacted Anthony 5 times. So total correspondence between John and Anthony has been 10 times.

Similarly, David has contacted John total of 9 times, John has contacted David 4 times. So total will be 13. I have tried many things including swapping columns using substring, repalce etc. I was wondering if anyone had interesting way to achieve the wanted results. Thanks in advance.

答:
A slight variation on other answers using a sub query instead of CTE:</p>

```<code>SELECT
    LowName, HighName, SUM(NumberOfTime) TotalNumberOfTime
FROM
    (
        SELECT
            CASE
                WHEN SenderName < ReceiverName THEN SenderName
                ELSE ReceiverName
            END LowName,
            CASE
                WHEN SenderName > ReceiverName THEN SenderName
                ELSE ReceiverName
            END HighName,
            NumberOfTime
        FROM
            tblMyTempTable
    ) tblMyTempTableWithSortedNames
GROUP BY
    LowName, HighName
</code>```

Title: TSQL find number of correspondences

Body:
I have the following table:

SenderName  ReceiverName    NumberOfTime
Ajay          Vijay             1
Anthony       Mark              3
Anthony       John              5
David         Mark              2
David         John              5
David         John              3
David         John              1
John          David             2
John          David             2
John          Anthony           5
Mark          Anthony           1

Test Data:

CREATE TABLE [dbo].[tblMyTempTable](
[SenderName] [varchar](20) NULL,
[ReceiverName] [varchar](10) NULL,
[NumberOfTime] [int] NULL
) ON [PRIMARY]
GO

INSERT [dbo].[tblMyTempTable]
  ([SenderName], [ReceiverName], [NumberOfTime])
VALUES
  (N'David', N'John', 1)
  ,(N'Mark', N'Anthony', 1)
  ,(N'Ajay', N'Vijay', 1)
  ,(N'John', N'David', 2)
  ,(N'Anthony', N'Mark', 3)
  ,(N'David', N'John', 5)
  ,(N'David', N'John', 3)
  ,(N'John', N'David', 2)
  ,(N'David', N'Mark', 2)
  ,(N'John', N'Anthony', 5)
  ,(N'Anthony', N'John', 5)

I need to find out how many times correspondence has been between each pair. For example, Anthony has contacted John 5 times, John has contacted Anthony 5 times. So total correspondence between John and Anthony has been 10 times.

Similarly, David has contacted John total of 9 times, John has contacted David 4 times. So total will be 13. I have tried many things including swapping columns using substring, repalce etc. I was wondering if anyone had interesting way to achieve the wanted results. Thanks in advance.

Body:
A slight variation on other answers using a sub query instead of CTE:

SELECT
    LowName, HighName, SUM(NumberOfTime) TotalNumberOfTime
FROM
    (
        SELECT
            CASE
                WHEN SenderName < ReceiverName THEN SenderName
                ELSE ReceiverName
            END LowName,
            CASE
                WHEN SenderName > ReceiverName THEN SenderName
                ELSE ReceiverName
            END HighName,
            NumberOfTime
        FROM
            tblMyTempTable
    ) tblMyTempTableWithSortedNames
GROUP BY
    LowName, HighName


问:
Laravel get file content
```<code>Route::get('marquee', function(){
    echo  File::get('\storage\app\marquee.json');
});
</code>```

I have a json file place inside storage/app

My question is how can I read this content from controller or route?

答:
Try this code</p>

```<code>File::get(storage_path('app\marquee.json'));
</code>```

Title: Laravel get file content

Body:
Route::get('marquee', function(){
    echo  File::get('\storage\app\marquee.json');
});

I have a json file place inside storage/app

My question is how can I read this content from controller or route?

Body:
Try this code

File::get(storage_path('app\marquee.json'));


问:
android 7.0 Notification icon appearing white square
I am using the below snippet to generate notifications in my android app.

```<code>private void sendNotification(String contentText, String message) {

    Intent resultIntent = new Intent(this, MainActivity.class);
    resultIntent.putExtra("clear","clear");
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
     Intent.FLAG_ACTIVITY_CLEAR_TASK);

   PendingIntent piResult = PendingIntent.getActivity(this, 0, resultIntent,0);

    NotificationCompat.Builder builder=new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setColor(ContextCompat.getColor(getApplicationContext(),R.color.red))
            .setContentTitle("title")
            .setContentText(message)
            .setAutoCancel(true)
            .setLargeIcon(BitmapFactory.decodeResource(getResources()
            ,R.drawable.notification))
            .setContentIntent(piResult);

    NotificationCompat.InboxStyle notification = new NotificationCompat.InboxStyle(builder);

    int i;
    for(i=0; i<messageList.size();i++){
        notification.addLine(messageList.get(i));
    }
    notification.setBigContentTitle("title");
    notification.setSummaryText(contentText);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID,notification.build());
}
</code>```

It works in android 5 and 6 but for android nougat it is not working

答:
From android version lollpop onwards, they have made the changes for the notifications. When you are specifing the small icon, it should be of specific size as mentioned in this link.

The important thing is the image should be transparent and contains only white color.

You can check this question to get the answer

Body:
I am using the below snippet to generate notifications in my android app.

private void sendNotification(String contentText, String message) {

    Intent resultIntent = new Intent(this, MainActivity.class);
    resultIntent.putExtra("clear","clear");
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
     Intent.FLAG_ACTIVITY_CLEAR_TASK);

   PendingIntent piResult = PendingIntent.getActivity(this, 0, resultIntent,0);

    NotificationCompat.Builder builder=new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setColor(ContextCompat.getColor(getApplicationContext(),R.color.red))
            .setContentTitle("title")
            .setContentText(message)
            .setAutoCancel(true)
            .setLargeIcon(BitmapFactory.decodeResource(getResources()
            ,R.drawable.notification))
            .setContentIntent(piResult);

    NotificationCompat.InboxStyle notification = new NotificationCompat.InboxStyle(builder);

    int i;
    for(i=0; i<messageList.size();i++){
        notification.addLine(messageList.get(i));
    }
    notification.setBigContentTitle("title");
    notification.setSummaryText(contentText);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID,notification.build());
}

It works in android 5 and 6 but for android nougat it is not working


问:
Format SQL statements in SQL Server Management Studio 2008
I am trying to use Ctrl K + Ctrl D (format document) in SQL Server Management Studio. It gives the message

The key combination (key, key) is bound to command(command) which is not currently available.

I also tried Ctrl A + Ctrl K + Ctrl F, and that didn't work either.

Is there any update or fix that I need to install for that?

答:
I was struggling with this, Finally found this Ctrl +K, Ctrl+Y and it worked for me.
But you need to have SQL Prompt.


问:
What does `(c = *str) != 0` mean?
```<code>int equiv (char, char);
int nmatches(char *str, char comp) {
    char c;
    int n=0;
    while ((c = *str) != 0) {
       if (equiv(c,comp) != 0) n++;
      str++;
    }
    return (n);
}
</code>```

What does "(c = *str) != 0" actually mean?
Can someone please explain it to me or help give me the correct terms to search for an explanation myself?

答:
It is just sloppily written code. The intention is to copy a character from the string str into c and then check if it was the null terminator.

The idiomatic way to check for the null terminator in C is an explicit check against '\0':

```<code>if(c != '\0')
</code>```

This is so-called self-documenting code, since the de facto standard way to write the null terminator in C is by using the octal escape sequence \0.

Another mistake is to use assignment inside conditions. This was recognized as bad practice back in the 1980s and since then every compiler gives a warning against such code, "possibly incorrect assignment" or similar. This is bad practice because assignment includes a side effect and expressions with side effects should be kept as simple as possible. But it is also bad practice because it is easy to mix up = and ==.

The code could easily be rewritten as something more readable and safe:

```<code>c = *str;
while (c != '\0')
{
  if(equiv(c, comp) != 0)
  {
    n++;
  }
  str++;
  c = *str;
}
</code>```

Title: What does `(c = *str) != 0` mean?

Body:
int equiv (char, char);
int nmatches(char *str, char comp) {
    char c;
    int n=0;
    while ((c = *str) != 0) {
       if (equiv(c,comp) != 0) n++;
      str++;
    }
    return (n);
}

What does "(c = *str) != 0" actually mean?
Can someone please explain it to me or help give me the correct terms to search for an explanation myself?

Body:
It is just sloppily written code. The intention is to copy a character from the string str into c and then check if it was the null terminator.

The idiomatic way to check for the null terminator in C is an explicit check against '\0':

if(c != '\0')

This is so-called self-documenting code, since the de facto standard way to write the null terminator in C is by using the octal escape sequence \0.

Another mistake is to use assignment inside conditions. This was recognized as bad practice back in the 1980s and since then every compiler gives a warning against such code, "possibly incorrect assignment" or similar. This is bad practice because assignment includes a side effect and expressions with side effects should be kept as simple as possible. But it is also bad practice because it is easy to mix up = and ==.

The code could easily be rewritten as something more readable and safe:

c = *str;
while (c != '\0')
{
  if(equiv(c, comp) != 0)
  {
    n++;
  }
  str++;
  c = *str;
}


问:
I am getting error while working with relation in stimulsoft report
Error is : Additional information: Parent Data Source 'EmpDetails' and
Child Data Source 'SalaryDetails' is not located in one DataSet and
can't be used in relation 'EmpSal'! You can use property CacheAllData of
report to cache this Data Source to one DataSet.

```<code> public class Employeedetails
 {
    public string EmployeeName { get; set; }
    public string JoiningDate { get; set; }
    public string Designation { get; set; }
    public string Department { get; set; }
    public string Nationality { get; set; }
    public string Status { get; set; }
    public string ContractType { get; set; }
    public string LastWorkingDate { get; set; }
    public string LengthofService { get; set; }
    public string ReasonforExit { get; set; }
    public int EmployeeId { get; set; }
}

public class EmployeeSalaryDetails
{
    public int EmployeeId { get; set; }
    public string AllowanceName { get; set; }
    public string Amount { get; set; }
}

report.CacheAllData = true;
report.Load(Server.MapPath("~/Content/Reports/ReportTemplates/FinalSettlementReport - Copy.mrt"));
report.RegData("EmpDetails", EmployeeDetailsList);
report.RegData("SalaryDetails", EmployeeSalaryList);
</code>```

this is report designin in stimulsoft

答:
```<code>report.Load(Server.MapPath("~/Content/Reports/ReportTemplates/FinalSettlementReport - Copy.mrt"));
                report.RegData("EmpDetails", EmployeeDetailsList);
                report.RegData("SalaryDetails", EmployeeSalaryList);
                report.RegBusinessObject("SchoolInfoModel", schoolInfo);
                report.CacheAllData = true;
</code>```

after changing the position of report.CacheAllData = true; after the loading report done it works without error.
'

Body:
Error is : Additional information: Parent Data Source 'EmpDetails' and
Child Data Source 'SalaryDetails' is not located in one DataSet and
can't be used in relation 'EmpSal'! You can use property CacheAllData of
report to cache this Data Source to one DataSet.

 public class Employeedetails
 {
    public string EmployeeName { get; set; }
    public string JoiningDate { get; set; }
    public string Designation { get; set; }
    public string Department { get; set; }
    public string Nationality { get; set; }
    public string Status { get; set; }
    public string ContractType { get; set; }
    public string LastWorkingDate { get; set; }
    public string LengthofService { get; set; }
    public string ReasonforExit { get; set; }
    public int EmployeeId { get; set; }
}

public class EmployeeSalaryDetails
{
    public int EmployeeId { get; set; }
    public string AllowanceName { get; set; }
    public string Amount { get; set; }
}

report.CacheAllData = true;
report.Load(Server.MapPath("~/Content/Reports/ReportTemplates/FinalSettlementReport - Copy.mrt"));
report.RegData("EmpDetails", EmployeeDetailsList);
report.RegData("SalaryDetails", EmployeeSalaryList);

this is report designin in stimulsoft

Body:
report.Load(Server.MapPath("~/Content/Reports/ReportTemplates/FinalSettlementReport - Copy.mrt"));
                report.RegData("EmpDetails", EmployeeDetailsList);
                report.RegData("SalaryDetails", EmployeeSalaryList);
                report.RegBusinessObject("SchoolInfoModel", schoolInfo);
                report.CacheAllData = true;

after changing the position of report.CacheAllData = true; after the loading report done it works without error.
'


问:
Embedding MySQL Database into application in C#
I am currently looking into developing an application in C#. The application will need to use a database backend but I was wondering if it possible to embed a database into the application itself. I.e. the user would not need to install MSSQL or MySQL onto the computers separately to my own app but instead install my program and the database is installed with it. If possible I would like to use something like a MySQL Database but not needing the user to install the MySQL Server. Is there a free option to resolve this problem.

Thanks for your help

答: There is also SQL Server Compact which is more similar to Microsoft SQL Server.  It also has other threading advantages if you don't use it on network storage.</p>


问:
Powershell how to add new line after certain string
I am very new to scripting. I am trying to solve one problem and I was looking at windows batch and powershell. I have found this but I dont know, why it is not working:

I have input.txt file with this content:

```<code><a> TEXT </a>
<c> text asdrtlj </c>
<a> another text </a>
</code>```

I want to add new line before every , so I tried this:

```<code>powershell -Command "(gc input.txt) -replace '<a>', '`r`n<a>' | Out-File output.txt"
</code>```

That adding of newline doesnt work. Can you help me please?

PS: I've found a lot of complicated codes while searching the solution and I haven't understood them yet so if you recommend me some good tutorials where to start with this languages I will appreciate it.

答:
There are a couple of issues here. Executing a command via the -command switch of powershell is causing some reserved character issues due to the < > characters.

Instead, open a PowerShell.exe window (start -> run -> powershell) and execute the command directly.

You also need to use double quotes not single quotes in order for special codes like `r and `n to work. Also `n should be sufficient on its own:

```<code>(gc input.txt) -replace '<a>', "`n<a>" | Out-File output.txt
</code>```

Body:
I am very new to scripting. I am trying to solve one problem and I was looking at windows batch and powershell. I have found this but I dont know, why it is not working:

I have input.txt file with this content:

 TEXT
<c> text asdrtlj </c>
 another text

I want to add new line before every , so I tried this:

powershell -Command "(gc input.txt) -replace '', '`r`n' | Out-File output.txt"

That adding of newline doesnt work. Can you help me please?

PS: I've found a lot of complicated codes while searching the solution and I haven't understood them yet so if you recommend me some good tutorials where to start with this languages I will appreciate it.

Body:
There are a couple of issues here. Executing a command via the -command switch of powershell is causing some reserved character issues due to the < > characters.

Instead, open a PowerShell.exe window (start -> run -> powershell) and execute the command directly.

You also need to use double quotes not single quotes in order for special codes like `r and `n to work. Also `n should be sufficient on its own:

(gc input.txt) -replace '<a>', "`n<a>" | Out-File output.txt


问:
Read invalid json in PHP
I have a problem with decoding json.
Here is the screen of the json where Google Chrome and Java recognized it.

Chrome: https://ibb.co/gZ33Qa

Android Studio: https://ibb.co/kTXV5a

I can not decode it in PHP via json_decode(), error number 4 is a syntax error.
How can you fix this json?

json himself

{"rs":[["addChd",["sFCF6",[
['zul.wgt.Div','sFCFb',{sclass:'transparent table contentHolder',prolog:'\n    '},[
['zk.Native','sFCFc',{prolog:'\n

Управляющая компания',epilog:'
'},[]],
['zk.Native','sFCFd',{prolog:'\n

\n            ',epilog:'\n
'},[
['zk.Native','sFCFe',{prolog:'

\n
    \n                    ',epilog:'\n                	\n

'},[
['zul.wgt.Label','sFCFf',{id:'nameLabel',sclass:'value',style:'font-weight: bold',value:'Общество с ограниченной ответственностью Управляющая компания "Якутск"'},[]]]],
['zk.Native','sFCFg',{prolog:'\n            '},[]],
['zk.Native','sFCFh',{prolog:'

\n
    \n                    ',epilog:'\n                	\n

'},[
['zul.wgt.Label','sFCFi',{id:'addressLabel',sclass:'value',multiline:true,value:'РС (Я), г.Якутск, ул.Орджоникидзе, д.38'},[]]]],
['zk.Native','sFCFj',{prolog:'\n            '},[]],
['zk.Native','sFCFk',{prolog:'

\n
    Телефоны:	\n
    \n                    ',epilog:'\n                	\n

'},[
['zul.wgt.Label','sFCFl',{id:'phoneLabel',sclass:'value',value:'8(4112) 40-56-41'},[]]]],
['zk.Native','sFCFm',{prolog:'\n            '},[]],
['zk.Native','sFCFn',{prolog:'

\n
    Директор:	\n
    \n                    ',epilog:'\n                	\n

'},[
['zul.wgt.Label','sFCFo',{id:'directorLabel',sclass:'value',value:'Молонов Алексей Владимирович тел.: 89142946345'},[]]]],
['zk.Native','sFCFp',{prolog:'\n            '},[]],
['zk.Native','sFCFq',{prolog:'

\n
    Бухгалтер:	\n
    \n                    ',epilog:'\n                	\n

'},[
['zul.wgt.Label','sFCFr',{id:'accounterLabel',sclass:'value',value:'Антипина Русалина Николаевна тел.: 89142946345'},[]]]],
['zk.Native','sFCFs',{prolog:'\n            '},[]],
['zk.Native','sFCFt',{prolog:'

\n
    Эл. адрес:	\n
    \n                    ',epilog:'\n                	\n

'},[
['zul.wgt.Label','sFCFu',{id:'emailLabel',sclass:'value',value:'kk_centr_2013@mail.ru'},[]]]]]],
['zk.Native','sFCFv',{prolog:'\n

'},[]],
['zul.box.Vlayout','sFCFw',{id:'noteHolder',prolog:'\n        '},[]],
['zk.Native','sFCFx',{prolog:'\n

'},[]]]]]]],["script",["jq('.contentHolder').hide().fadeIn(500); select_menu_item('organization');"]]],"rid":1}```

答:
Reading the code you sent, and just in order to make it work, you could:

```<code>try {
    $decrypted = json_decode($result);
} catch(Exception $e) {
    $sane = str_replace('="', '=\"', $result);
    $healthy = str_replace('">', '\">', $sane);
    $decrypted = json_decode($healthy);
}
</code>```

This is a hack. I would recommend for our case, that is:

(non convenient) storing html code as json strings

(issue) html has lots of character "

(issue) you are using php json encoder which is a strict encoder

A solution could be to parse every single object with a prolog key in your json string:

Find first prolog tag start position (pos) with strpos() or strrpos() php methods.

Find the string start position after prolog (pos), right after the following :'
let's call it stringstart

Find the end of that string by finding the closest '}, or '} after stringstart. This will be your stringend.

Replace all occurrences of the character " by the character ' between stringstart and stringend positions in your json string.

find next prolog.

NOTE

In order to save time, you could try to persist the stuff from your remote response by parsing it differently, using a ODM on a simple local db, etc.

I hope it is useful.

Title: Read invalid json in PHP

Body:
Reading the code you sent, and just in order to make it work, you could:

try {
    $decrypted = json_decode($result);
} catch(Exception $e) {
    $sane = str_replace('="', '=\"', $result);
    $healthy = str_replace('">', '\">', $sane);
    $decrypted = json_decode($healthy);
}

This is a hack. I would recommend for our case, that is:

(non convenient) storing html code as json strings

(issue) html has lots of character "

(issue) you are using php json encoder which is a strict encoder

A solution could be to parse every single object with a prolog key in your json string:

Find first prolog tag start position (pos) with strpos() or strrpos() php methods.

Find the string start position after prolog (pos), right after the following :'
let's call it stringstart

Find the end of that string by finding the closest '}, or '} after stringstart. This will be your stringend.

Replace all occurrences of the character " by the character ' between stringstart and stringend positions in your json string.

find next prolog.

NOTE

In order to save time, you could try to persist the stuff from your remote response by parsing it differently, using a ODM on a simple local db, etc.

I hope it is useful.


问:
RadioButton.IsChecked Not Going False
I have a UWP app in C#. I have a Radio Button that the user can turn check or uncheck. It is checked by default and the user can uncheck it when they wish. However when they uncheck it the bool value for RadioButton.IsChecked never returns false making impossible for the user to then recheck the Radio Button if required. My code is below.

```<code>    private void usingmltBtn_Click(object sender, RoutedEventArgs e)
    {

        if (RadioButton.IsChecked == true)
        {
            RadioButton.IsChecked = false;
            i2cerrRec.Visibility = Visibility.Collapsed;
            i2cerrTxt.Visibility = Visibility.Collapsed;
            mltI2Cnck = 0;

        }
        else if (RadioButton.IsChecked == false)
        {
            RadioButton.IsChecked = true;
            mlttempLbl.Text = "N/C";
        }

    }
</code>```

Thanks for your help.

答:
As other's have described, RadioButtons are designed to work in a group. This means that you will have multiple RadioButtons for a user to select from but they can only have one checked.

When a RadioButton is checked, it cannot be unchecked by the user by clicking it again without using a custom behaviour that checks if the user has tapped the RadioButton but this would not be recommended.

I suggest that you use the CheckBox for this particular functionality. You can even re-template a CheckBox control to look like a RadioButton if you wish.

Title: RadioButton.IsChecked Not Going False

Body:
I have a UWP app in C#. I have a Radio Button that the user can turn check or uncheck. It is checked by default and the user can uncheck it when they wish. However when they uncheck it the bool value for RadioButton.IsChecked never returns false making impossible for the user to then recheck the Radio Button if required. My code is below.

    private void usingmltBtn_Click(object sender, RoutedEventArgs e)
    {

        if (RadioButton.IsChecked == true)
        {
            RadioButton.IsChecked = false;
            i2cerrRec.Visibility = Visibility.Collapsed;
            i2cerrTxt.Visibility = Visibility.Collapsed;
            mltI2Cnck = 0;

        }
        else if (RadioButton.IsChecked == false)
        {
            RadioButton.IsChecked = true;
            mlttempLbl.Text = "N/C";
        }

    }

Thanks for your help.


问:
How to watch and reload ts-node when TypeScript files change
I'm trying to run a dev server with TypeScript and an Angular application without transpiling ts files every time.

What I found is that I can run .ts files with ts-node but I want also to watch .ts files and reload my app/server. An example of this is the command gulp watch.

答:
Specifically for this issue I've created the tsc-watch library. you can find it on npm.

Obvious use case would be:

tsc-watch server.ts --outDir ./dist --onSuccess "node ./dist/server.js"


问:
Installing bundles from the local file system into Eclipse (via a p2 repository)
I have a few OSGI bundles that I would like to store in a local P2 repository. I have followed this guide:

https://docs.sonatype.org/display/TYCHO/How+to+make+existing+OSGi+bundles+consumable+by+Tycho

to use eclipsec.exe  to convert the folder with bundles into a p2 repository. The resulting structure is like this:

```<code>c:\test\repo
c:\test\repo\plugins
c:\test\repo\plugins\my.bundle.jar
c:\test\repo\artifacts.jar
c:\test\repo\content.jar
</code>```

Now I would like to add this repository in eclipse Helios. In the eclipse update manager  I select add an press the "Local..." button where I specify the path to the repo:

```<code>Name: testRepo
Location: file:/C:/test/repo/
</code>```

I then uncheck "Group items by category" but it just says "There are no items available".

How do I add this local repository to eclipse?

答:
You need to create a new "Feature project" (New-->other-->plug-in development-->"Feature project")
Then you need to link this to your project from its project properties.

Then you need to create a new "Update Site Project" (there is a link on feature.xml Overview).
Then you need to link this to your project and the feature from its project properties.

then add a new category, and the feature you created in it, then say build and it builds the update site for you...

Body:
I have a few OSGI bundles that I would like to store in a local P2 repository. I have followed this guide:

https://docs.sonatype.org/display/TYCHO/How+to+make+existing+OSGi+bundles+consumable+by+Tycho

to use eclipsec.exe  to convert the folder with bundles into a p2 repository. The resulting structure is like this:

c:\test\repo
c:\test\repo\plugins
c:\test\repo\plugins\my.bundle.jar
c:\test\repo\artifacts.jar
c:\test\repo\content.jar

Now I would like to add this repository in eclipse Helios. In the eclipse update manager  I select add an press the "Local..." button where I specify the path to the repo:

Name: testRepo
Location: file:/C:/test/repo/

I then uncheck "Group items by category" but it just says "There are no items available".

How do I add this local repository to eclipse?


问:
Button's text vertical align
I have got tricky problem here. I'd like to vertical align my text inside a button

```<code><button id="rock" onClick="choose(1)">Rock</button>
</code>```

And here is my CSS

```<code>button {
    font-size: 22px;
    border: 2px solid #87231C;
    border-radius: 100px;
    width: 100px;
    height: 100px;
    color: #FF5A51;
    text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}
button:active {
    font-size: 22px;
    border: 2px solid red;
    border-radius: 100px;
    width: 100px;
    height: 100px;
}
</code>```

You can check it out here http://jsfiddle.net/kA8pp/ . I want to have the text on the bottom. Thank you very much!

EDIT: I can't explain it well so here is the picture of it  :)

答:
This should work for you!</p>

```<code>```
.button{
    font-family: Arial, Helvetica, sans-serif;
    font-weight: normal;
    color: #444;
    width: 32px;
    padding: 2px;
    margin-left: 5px;
    background-color: #fdfdfd;
    border: 1px solid #cdcdcd;
    cursor: pointer;
}
```
</code>```

Title: Button's text vertical align

Body:
I have got tricky problem here. I'd like to vertical align my text inside a button

<button id="rock" onClick="choose(1)">Rock</button>

And here is my CSS

button {
    font-size: 22px;
    border: 2px solid #87231C;
    border-radius: 100px;
    width: 100px;
    height: 100px;
    color: #FF5A51;
    text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}
button:active {
    font-size: 22px;
    border: 2px solid red;
    border-radius: 100px;
    width: 100px;
    height: 100px;
}

You can check it out here http://jsfiddle.net/kA8pp/ . I want to have the text on the bottom. Thank you very much!

EDIT: I can't explain it well so here is the picture of it  :)

Body:
This should work for you!

<pre>
.button{
    font-family: Arial, Helvetica, sans-serif;
    font-weight: normal;
    color: #444;
    width: 32px;
    padding: 2px;
    margin-left: 5px;
    background-color: #fdfdfd;
    border: 1px solid #cdcdcd;
    cursor: pointer;
}
</pre>


问:
How to set an initial selection for an AJAX driven Select2 box with CakePHP?
I'm using select2 to let user choose stuff from list from ajax.
In adding to db it's working great, but I want  to edit stuff. So I can still select stuff from my select2, but user should see what is the current value of select2.

I've tried to do something with InitSelect, but it didn't work, even after I've just passed data from php.

This is my Select2:

```<code>    $(".personid").select2({
    ajax: {
        type: "post",
        url: '/' + APP_PATH + '/Projects/find_person.json',
        datatype: 'json',
        quietMillis: '100',
        data: function (term, page) {
            return {
                q: term.toUpperCase(), // wprowadzony ciag znakow - zawsze na uppercase
                page_limit: 10,
            };
        },
        results: function (data, page) {
            var dane = {results: []};
            $.each(data['data'], function (i, item) {
                dane.results.push({
                    id: item['Person']['id'],
                    text: item['Person']['displayName']
                });
            });
            return dane;
        }
    }

});
</code>```

And this is my cake form input:

```<code>echo $this->Form->input('person_id', array(
    'type' => 'text',
    'value' => $projectcontact['Person']['id'],
    'Placeholder' => 'Wybierz osobę',
    'empty' => 'Wybierz osobę ',
    'class' => 'form-control personid',
    'label' => array(
        'class' => 'col-md-4 control-label',
        'text' => 'Osoba'
    )
));
</code>```

Can anyone help to make Select.js display current Persona name data from database in this?

答:
With Select2 4.x

With Select2 4.x you're not supposed to use a text input element anymore, but a select element. Quote from the docs:

When using Select2 with remote data, the HTML required for the select is the same as any other Select2. If you need to provide default selections, you just need to include an option for each selection that contains the value and text that should be displayed.

```<code><select class="js-data-example-ajax">
    <option value="3620194" selected="selected">select2/select2</option>
</select>
</code>```

https://select2.github.io/examples.html#data-ajax

So, as described, create a proper select input with a single selected option element, something along the lines of:

```<code>echo $this->Form->input('person_id', array(
    'type' => 'select',
    'options' => array(
        $projectcontact['Person']['id'] => $projectcontact['Person']['displayName']
    ),
    'selected' => $projectcontact['Person']['id'],
    'class' => 'form-control personid',
    'label' => array(
        'class' => 'col-md-4 control-label',
        'text' => 'Osoba'
    )
));
</code>```

Additionally you'll have to ensure that $projectcontact is being filled with the person according to the possible submitted person_id value, otherwise the selected value will not remain when rendering the form after submit.

Normally when creating a select element, you'd use a complete list of options, so that the form helper could pick the appropriate option automatically, based on the submitted value. Without such a list, you'll have to read and supply the specific person instead.

Here's some dummy code that demonstrates the priniciple:

```<code>$personId = $defaultPersonId;
if($this->request->is(array('post', 'put'))) {
    $personId = $this->request->data('ModelName.person_id');
    // ...
}

$projectcontact = $this->Person->findById($personId);
$this->set('projectcontact', $projectcontact);
</code>```

See also

Cookbook > Core Libraries > Helpers > Form > Options for select, checkbox and radio inputs

Cookbook > Core Libraries > Helpers > Form > Creating form elements

Cookbook > Models > Retrieving Your Data > find(‘list’)

Body:
I'm using select2 to let user choose stuff from list from ajax.
In adding to db it's working great, but I want  to edit stuff. So I can still select stuff from my select2, but user should see what is the current value of select2.

I've tried to do something with InitSelect, but it didn't work, even after I've just passed data from php.

This is my Select2:

    $(".personid").select2({
    ajax: {
        type: "post",
        url: '/' + APP_PATH + '/Projects/find_person.json',
        datatype: 'json',
        quietMillis: '100',
        data: function (term, page) {
            return {
                q: term.toUpperCase(), // wprowadzony ciag znakow - zawsze na uppercase
                page_limit: 10,
            };
        },
        results: function (data, page) {
            var dane = {results: []};
            $.each(data['data'], function (i, item) {
                dane.results.push({
                    id: item['Person']['id'],
                    text: item['Person']['displayName']
                });
            });
            return dane;
        }
    }

});

And this is my cake form input:

echo $this->Form->input('person_id', array(
    'type' => 'text',
    'value' => $projectcontact['Person']['id'],
    'Placeholder' => 'Wybierz osobę',
    'empty' => 'Wybierz osobę ',
    'class' => 'form-control personid',
    'label' => array(
        'class' => 'col-md-4 control-label',
        'text' => 'Osoba'
    )
));

Can anyone help to make Select.js display current Persona name data from database in this?

Body:
With Select2 4.x

With Select2 4.x you're not supposed to use a text input element anymore, but a select element. Quote from the docs:

When using Select2 with remote data, the HTML required for the select is the same as any other Select2. If you need to provide default selections, you just need to include an option for each selection that contains the value and text that should be displayed.

<select class="js-data-example-ajax">
    <option value="3620194" selected="selected">select2/select2</option>
</select>

https://select2.github.io/examples.html#data-ajax

So, as described, create a proper select input with a single selected option element, something along the lines of:

echo $this->Form->input('person_id', array(
    'type' => 'select',
    'options' => array(
        $projectcontact['Person']['id'] => $projectcontact['Person']['displayName']
    ),
    'selected' => $projectcontact['Person']['id'],
    'class' => 'form-control personid',
    'label' => array(
        'class' => 'col-md-4 control-label',
        'text' => 'Osoba'
    )
));

Additionally you'll have to ensure that $projectcontact is being filled with the person according to the possible submitted person_id value, otherwise the selected value will not remain when rendering the form after submit.

Normally when creating a select element, you'd use a complete list of options, so that the form helper could pick the appropriate option automatically, based on the submitted value. Without such a list, you'll have to read and supply the specific person instead.

Here's some dummy code that demonstrates the priniciple:

$personId = $defaultPersonId;
if($this->request->is(array('post', 'put'))) {
    $personId = $this->request->data('ModelName.person_id');
    // ...
}

$projectcontact = $this->Person->findById($personId);
$this->set('projectcontact', $projectcontact);

See also

Cookbook > Core Libraries > Helpers > Form > Options for select, checkbox and radio inputs

Cookbook > Core Libraries > Helpers > Form > Creating form elements

Cookbook > Models > Retrieving Your Data > find(‘list’)


问:
High level data structures in html data attribute
I am happy that the html5 data attribute exists.

I can write a simple string into html attributes and access them via jquery.

But .... wouldn't it be nice to have more than a simple string?

Is there no way to encode JSON into these data attributes.

In my current use case I need to store a list of strings in a html5 data attribute.

答:
You can store JSON strings in data- attributes.

function onPClick(evt) {
  var special = evt.target.getAttribute('data-special');
  if (special != null) {
    try {
      console.log("JSON", JSON.parse(special));
    } catch (error) {
      console.log("STANDARD", special);
    }
  } else {
    console.log("NULL");
  }
}
var ps = document.getElementsByTagName("p");
for (var pi = 0; pi < ps.length; pi++) {
  var p = ps[pi];
  p.onclick = onPClick;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>I am special!</p>
<p data-special='YES!'>I am special!</p>
<p data-special='{"a":"bob"}'>I am special!</p></code>```

For separation of concerns, it would be prettier to hold you data in a place that doesn't have to update the HTML every time it changes:

var p = document.body.appendChild(document.createElement("p"));
p.innerHTML = "Click me!";
Object.defineProperty(p, 'mySuperSecretValue', {
  value: 37,
  writable: true,
  enumerable: true,
  configurable: true
});
p.onclick = function pclick(evt) {
  console.log(evt.target.mySuperSecretValue++, evt.target.outerHTML);
};```

Body:
You can store JSON strings in data- attributes.

function onPClick(evt) {
  var special = evt.target.getAttribute('data-special');
  if (special != null) {
    try {
      console.log("JSON", JSON.parse(special));
    } catch (error) {
      console.log("STANDARD", special);
    }
  } else {
    console.log("NULL");
  }
}
var ps = document.getElementsByTagName("p");
for (var pi = 0; pi < ps.length; pi++) {
  var p = ps[pi];
  p.onclick = onPClick;
}

<p>I am special!</p>
<p data-special='YES!'>I am special!</p>
<p data-special='{"a":"bob"}'>I am special!</p>

For separation of concerns, it would be prettier to hold you data in a place that doesn't have to update the HTML every time it changes:

var p = document.body.appendChild(document.createElement("p"));
p.innerHTML = "Click me!";
Object.defineProperty(p, 'mySuperSecretValue', {
  value: 37,
  writable: true,
  enumerable: true,
  configurable: true
});
p.onclick = function pclick(evt) {
  console.log(evt.target.mySuperSecretValue++, evt.target.outerHTML);
};


问:
Create React App - Out of the box coverage is not 100%
Create react app doens't provide 100% coverage out of the box because of an index.js file that isn't tested.

I want to add precommit / prepush git hooks that prevent commits if code coverage thresholds aren't met.

How do I ignore the index.js file?

答:
A simple solution could be to exclude the index.js file from tests by adding the following code to the package.json file.

```<code>"jest": { "coveragePathIgnorePatterns": ["<rootDir>/src/index.js"] }
</code>```

Referece: Jest - Coverage Path Ignore Patterns

Body:
A simple solution could be to exclude the index.js file from tests by adding the following code to the package.json file.

"jest": { "coveragePathIgnorePatterns": ["<rootDir>/src/index.js"] }

Referece: Jest - Coverage Path Ignore Patterns


答:
*linkId,shape is like that trip points which is given by Heremap api step1.
You just draw route by polyline function.</p>

```<code>addPolylineToMap(map,linkId);

function addPolylineToMap(map,linkId) {
    for (j = 0; j < (shape.length - 1); j = j + 2) {
        var strip = new H.geo.Strip();
        strip.pushPoint({lat: shape[j],lng: shape[j+1]});
    }
}
</code>```

Title: How do I draw line after receiving data - Route from GPS Trace

Body:
I just started using Here Maps. Before I used Google Direction, I want to try use 'Here Maps' API. This is example JSON result. After I got this result, How do I implement this into Polyline or Direction (MAP Here)?  Thanks

{
  RouteLinks: [
  {
    linkId: 25664478,
    functionalClass: 5,
    shape: "51.1017723 0.3934907 51.1018066 0.3933491 51.1018295 0.39326",
    linkLength: 15.575699313408467
  },
  {
    linkId: 25664473,
    functionalClass: 4,
    shape: "51.1018295 0.39326 51.1022491 0.39348",
    linkLength: 44.17562556306323
  },
  {
    linkId: 25664459,
    functionalClass: 4,
    shape: "51.1022491 0.39348 51.1022987 0.39351",
    linkLength: 5.305684979980019
  },
  {
    linkId: 781742854,
    functionalClass: 4,
    shape: "51.1022987 0.39351 51.1025505 0.39365",
    linkLength: 26.670487136749067
  },
  {
    linkId: 781742855,
    functionalClass: 4,
    shape: "51.1025505 0.39365 51.1027794 0.39378",
    linkLength: 24.302012297623005
  },
  {
    linkId: 25664450,
    functionalClass: 4,
    shape: "51.1027794 0.39378 51.1030807 0.39403",
    linkLength: 33.974229462422905
  },
  {
    linkId: 25664444,
    functionalClass: 4,
    shape: "51.1030807 0.39403 51.103241 0.39413",
    linkLength: 17.215963662407898
  },
  {
    linkId: 25664440,
    functionalClass: 4,
    shape: "51.103241 0.39413 51.1033783 0.39421 51.1035385 0.39433 51.1036797 0.39445",
    linkLength: 48.32839625333388
  },
  {
    linkId: 25664427,
    functionalClass: 4,
    shape: "51.1036797 0.39445 51.1038017 0.39454",
    linkLength: 13.445306290244636
  },
  {
    linkId: 860272608,
    functionalClass: 4,
    shape: "51.1038017 0.39454 51.1039391 0.39465",
    linkLength: 15.378381014646559
  },
  {
    linkId: 860272609,
    functionalClass: 4,
    shape: "51.1039391 0.39465 51.1041908 0.39484",
    linkLength: 27.85427285471891
  },
  {
    linkId: 781742870,
    functionalClass: 4,
    shape: "51.1041908 0.39484 51.1043282 0.39494 51.1045609 0.39506",
    linkLength: 39.56626207722863
  },
  {
    linkId: 781742871,
    functionalClass: 4,
    shape: "51.1045609 0.39506 51.1047287 0.39515 51.1050262 0.3953021",
    linkLength: 48.951382959921716
  }
],
TracePoints: [
  {
    confidenceValue: 1, linkIdMatched: 25664478, matchDistance: 1.46,
    routeLinkSeqNrMatched: 0, lat: 51.10177, lon: 0.39349,
    elevation: 0, speedMps: 0, headingDegreeNorthClockwise: 10000,
    latMatched: 51.10178065190155, lonMatched: 0.3934977183445852,
    timestamp: 0, headingMatched: 114.46568884011239,
    minError: 1.3027890756593314
  },
  {
    confidenceValue: 1, linkIdMatched: 25664478, matchDistance: 1.57,
    routeLinkSeqNrMatched: 0, lat: 51.10181, lon: 0.39335,
    elevation: 0, speedMps: 0, headingDegreeNorthClockwise: 10000,
    latMatched: 51.10182, lonMatched: 0.39336,
    timestamp: 0, headingMatched: -65.53429247174023,
    minError: 1000000
  },
  {
    confidenceValue: 1, linkIdMatched: 781742854, matchDistance: 1,
    routeLinkSeqNrMatched: 4, lat: 51.10255, lon: 0.39366,
    elevation: 0, speedMps: 0, headingDegreeNorthClockwise: 10000,
    latMatched: 51.102547928304084, lonMatched: 0.3936687569824506,
    timestamp: 0, headingMatched: 20.644254301899522,
    minError: 0.6541474931313044
  },
  {
    confidenceValue: 1, linkIdMatched: 860272608, matchDistance: 4.59,
    routeLinkSeqNrMatched: 10, lat: 51.10398, lon: 0.39466,
    elevation: 0, speedMps: 0, headingDegreeNorthClockwise: 10000,
    latMatched: 51.10394, lonMatched: 0.39465,
    timestamp: 0, headingMatched: 25.217234923243595,
    minError: 1.2405405512432781
  },
  {
    confidenceValue: 1, linkIdMatched: 1022687693, matchDistance: 1.33,
    routeLinkSeqNrMatched: 14, lat: 51.10501, lon: 0.39533,
    elevation: 0, speedMps: 0, headingDegreeNorthClockwise: 10000,
    latMatched: 51.105012239590245, lonMatched: 0.39531827230152644,
    timestamp: 0, headingMatched: 16.91643828307876,
    minError: 0.8568378930601925
  }
],
Warnings: [
  {
    "tracePointSeqNum": -1,
    "routeLinkSeqNum": 3,
    "category": 3,
    "text": "Entering link 781742854 into forbidden driving direction"
  }
],
MapVersion: "2013Q4" }

Body:
*linkId,shape is like that trip points which is given by Heremap api step1.
You just draw route by polyline function.

addPolylineToMap(map,linkId);

function addPolylineToMap(map,linkId) {
    for (j = 0; j < (shape.length - 1); j = j + 2) {
        var strip = new H.geo.Strip();
        strip.pushPoint({lat: shape[j],lng: shape[j+1]});
    }
}


问:
C# function that return instance with unknown generic type
I am now implementing a function Register() which invoking other function ApiReturnFactory() inside.

```<code>    public ???? Register(string username)
    {
        var result = new AccountProcess().CreateAccount(username);
        return ApiReturnFactory.CreateInstance(result);
    }
</code>```

new AccountProcess().CreateAccount(username) returns me an object like obj<WhateverType>.

ApiReturnFactory.CreateInstance(obj) returns me an object like obj2<SameTypeWithWhateverType>.

My question is the compiler have already know what type I will return in ApiReturnFactory.CreateInstance(obj) (IntelliSense do), but what should I state in the return type ???? of Register(string username)?

I don't want to specific a generic type for obj like obj<string>, this is not reasonable since the generic type may not always be a string. What I want is something like obj<T>.

Thanks in advance.

答:
```<code>public obj2<T> Register<T>(string username)
{
    var result = new AccountProcess().CreateAccount(username);
    return (obj2<T>)ApiReturnFactory.CreateInstance(result);
}
</code>```

Body:
I am now implementing a function Register() which invoking other function ApiReturnFactory() inside.

    public ???? Register(string username)
    {
        var result = new AccountProcess().CreateAccount(username);
        return ApiReturnFactory.CreateInstance(result);
    }

new AccountProcess().CreateAccount(username) returns me an object like obj<WhateverType>.

ApiReturnFactory.CreateInstance(obj) returns me an object like obj2<SameTypeWithWhateverType>.

My question is the compiler have already know what type I will return in ApiReturnFactory.CreateInstance(obj) (IntelliSense do), but what should I state in the return type ???? of Register(string username)?

I don't want to specific a generic type for obj like obj<string>, this is not reasonable since the generic type may not always be a string. What I want is something like obj<T>.

Thanks in advance.