问:
IndexError: tuple index out of range with psycopg2
This code has no issues:

```<code>cursor.execute("select message from snippets where keyword=%s", (name,))
</code>```

However, with this I get an IndexError: tuple index out of range

```<code>cursor.execute("select * from table where prescription like '\"%\"%s%'", (string,))
</code>```

Where am I going wrong?

答:
The second snippet puts the variable inside a string literal (as it's surrounded by single quotes), so psycopg doesn't handle it. One way to solve this is to keep the placeholder form and perform the string manipulation in your Python code before binding it:</p>

```<code>name = '%%%s%%' % name
cursor.execute("select * from table where prescription like %s", (name,))
</code>```

Body:
This code has no issues:

cursor.execute("select message from snippets where keyword=%s", (name,))

However, with this I get an IndexError: tuple index out of range

cursor.execute("select * from table where prescription like '\"%\"%s%'", (string,))

Where am I going wrong?

Body:
The second snippet puts the variable inside a string literal (as it's surrounded by single quotes), so psycopg doesn't handle it. One way to solve this is to keep the placeholder form and perform the string manipulation in your Python code before binding it:

name = '%%%s%%' % name
cursor.execute("select * from table where prescription like %s", (name,))


来源: stackexchange

问:
Couldn't build android gradle with Crashlytics 2.6.7 and io.branch.sdk.android.library:2+ while proguard enable?
My Gradle Settings:

```<code>compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
    transitive = true;
}

compile('io.branch.sdk.android:library:2.+') {
    transitive = true;
}
</code>```

with above crashlytics & branch.io try to build gradle with proguard enabled. I am getting below error.

Warning:Exception while processing task java.io.IOException: Can't write [/Users/Documents/test/andriod-test/app/build/intermediates/transforms/proguard/production/release/jars/3/1f/main.jar] (Can't read [/Users/Documents/test/andriod-test/app/build/intermediates/classes/production/release(;;;;;;**.class)] (Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))))))
Error:java.lang.RuntimeException: Job failed, see logs for details
Error:java.io.IOException: Can't write [/Users/Documents/test/andriod-test/app/build/intermediates/transforms/proguard/production/release/jars/3/1f/main.jar] (Can't read [/Users/Documents/test/andriod-test/app/build/intermediates/classes/production/release(;;;;;;**.class)] (Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))))))
Error:java.io.IOException: Can't read [/Users/Documents/test/andriod-test/app/build/intermediates/classes/production/release(;;;;;;**.class)] (Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class])))))))
Error:java.io.IOException: Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))))
Error:java.io.IOException: Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class])))))
Error:java.io.IOException: Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))
Error:java.io.IOException: Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class])))
Error:java.io.IOException: Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))
Error:java.io.IOException: Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class])
Error:java.io.IOException: Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]

答:
since the error message is indicating that some of the 'answers-shim' classes duplicate, one is from crashlytics and another one from io.branch itself, What I have done is, exclude the io.branch module 'answers-shim' by editting the gradle file below.

```<code>compile('io.branch.sdk.android:library:2.+') {
    transitive = true;
    exclude module: 'answers-shim'
}
</code>```

Exclude  'answer-shim' module to the io.branch.sdk.library gradle settings as shown above.

After that in your proguard file add the below line as well to ignore the warnings:

```<code>-dontwarn com.crashlytics.android.answers.shim.**
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My Gradle Settings:

compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
    transitive = true;
}

compile('io.branch.sdk.android:library:2.+') {
    transitive = true;
}

with above crashlytics & branch.io try to build gradle with proguard enabled. I am getting below error.

Warning:Exception while processing task java.io.IOException: Can't write [/Users/Documents/test/andriod-test/app/build/intermediates/transforms/proguard/production/release/jars/3/1f/main.jar] (Can't read [/Users/Documents/test/andriod-test/app/build/intermediates/classes/production/release(;;;;;;**.class)] (Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))))))
Error:java.lang.RuntimeException: Job failed, see logs for details
Error:java.io.IOException: Can't write [/Users/Documents/test/andriod-test/app/build/intermediates/transforms/proguard/production/release/jars/3/1f/main.jar] (Can't read [/Users/Documents/test/andriod-test/app/build/intermediates/classes/production/release(;;;;;;**.class)] (Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))))))
Error:java.io.IOException: Can't read [/Users/Documents/test/andriod-test/app/build/intermediates/classes/production/release(;;;;;;**.class)] (Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class])))))))
Error:java.io.IOException: Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))))
Error:java.io.IOException: Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class])))))
Error:java.io.IOException: Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))
Error:java.io.IOException: Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class])))
Error:java.io.IOException: Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))
Error:java.io.IOException: Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class])
Error:java.io.IOException: Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]

Body:
since the error message is indicating that some of the 'answers-shim' classes duplicate, one is from crashlytics and another one from io.branch itself, What I have done is, exclude the io.branch module 'answers-shim' by editting the gradle file below.

compile('io.branch.sdk.android:library:2.+') {
    transitive = true;
    exclude module: 'answers-shim'
}

Exclude  'answer-shim' module to the io.branch.sdk.library gradle settings as shown above.

After that in your proguard file add the below line as well to ignore the warnings:

-dontwarn com.crashlytics.android.answers.shim.**


问:
pthread_join - multiple threads waiting
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.

If I have multiple threads waiting to insert using pthread_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads.

```<code>/* --- GLOBAL --- */
pthread_t insertThread;

/* --- DIFFERENT THREADS --- */
// Wait for Current insert to finish
pthread_join(insertThread, NULL);

// Done start a new one
pthread_create(&insertThread, NULL, Insert, Data);
</code>```

Thank you for the replies

The program is basically a huge hash table which takes requests from clients through Sockets.

Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible.

But now that i know it's not safe the way i first thought I should be able to cobble something together

Thanks

答:
According to the Single Unix Specifcation: "The results of multiple simultaneous calls to pthread_join() specifying the same target thread are undefined."

The "normal way" of achieving a single thread to get the task would be to set up a condition variable (don't forget the related mutex): idle threads wait in pthread_cond_wait() (or pthread_cond_timedwait()), and when the thread doing the work has finished, it wakes up one of the idle ones with pthread_cond_signal().

Title: pthread_join - multiple threads waiting

Body:
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.

If I have multiple threads waiting to insert using pthread_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads.

/* --- GLOBAL --- */
pthread_t insertThread;

/* --- DIFFERENT THREADS --- */
// Wait for Current insert to finish
pthread_join(insertThread, NULL);

// Done start a new one
pthread_create(&insertThread, NULL, Insert, Data);

Thank you for the replies

The program is basically a huge hash table which takes requests from clients through Sockets.

Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible.

But now that i know it's not safe the way i first thought I should be able to cobble something together

Thanks

LastEditorDisplayName: Hosam Aly

OwnerDisplayName: Timo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Timo


问:
strtotime function giving wrong output, How to solve?
I used php strtotime function in my project and it was working fine, but today a user reported an issue, i checked and found strtotime function not giving correct output.
My Code is:

```<code>echo date('M Y', strtotime('-1 month'));
</code>```

It is giving output:

```<code>Mar 2017 instead of Feb 2017
</code>```

I checked above code at code online tools and it is giving same output there, So is it php core function issue or i did some mistake?
Note: I checked following code online

```<code>echo date('Y-m-d', strtotime('-1 month'));
</code>```

Its output strange me which is

```<code>2017-03-02
</code>```

答:
```<code>date("M Y", strtotime("-1 months"));
</code>```

This is true but today is 30th March that's why you are not getting exact result which you want. So, we should use 1st day of month and then apply substraction.

Body:
I used php strtotime function in my project and it was working fine, but today a user reported an issue, i checked and found strtotime function not giving correct output.
My Code is:

echo date('M Y', strtotime('-1 month'));

It is giving output:

Mar 2017 instead of Feb 2017

I checked above code at code online tools and it is giving same output there, So is it php core function issue or i did some mistake?
Note: I checked following code online

echo date('Y-m-d', strtotime('-1 month'));

Its output strange me which is

2017-03-02

Body:
date("M Y", strtotime("-1 months"));

This is true but today is 30th March that's why you are not getting exact result which you want. So, we should use 1st day of month and then apply substraction.


问:
How can I add class active when a link clicked and redirect?
My vue component is like this:

<template>

        ...

                Message

                Review

                Resolution

        ...

</template>

```

When the link is clicked, it will call the url, I want to add class active on the clicked link after reloading the page.

But, I'm still confused, How can I do it?

答:
Adding to Leo's answer, it's a good idea to introduce a component which will auto detect is active or not, so you don't need to write a bunch of  elements and many duplicate attributes.

For example a <custom-link> component:

```<code><custom-link href="/message/inbox" class="list-group-item">
  Message
</custom-link>
<custom-link href="/message/review" class="list-group-item">
  Review
</custom-link>
<custom-link href="/message/resolution" class="list-group-item">
  Resolution
</custom-link>
</code>```

If you don't need to reuse this component in other components or the list-group-item class is always necessary, you can also encapsulate this class to the <custom-link>. It will look even cleaner:

```<code><custom-link href="/message/inbox">Message</custom-link>
<custom-link href="/message/review">Review</custom-link>
<custom-link href="/message/resolution">Resolution</custom-link>
</code>```

the code of custom-link looks like:

```<code><a
  :href="baseUrl + href"
  :class="{ active: isActive }"
  class="list-group-item"
>
  <slot></slot>
</a>

{
  props: ['href'],
  data: () => ({ baseUrl: window.Laravel.baseUrl }),
  computed: {
    isActive () {
      return location.href === this.baseUrl + this.href
    }
  }
}
</code>```

I use location.href here directly, you can also use a computed property like Leo's example if you need some computations to get the current URL.

Body:
My vue component is like this:

<template>

        ...

                Message

                Review

                Resolution

        ...

</template>

When the link is clicked, it will call the url, I want to add class active on the clicked link after reloading the page.

But, I'm still confused, How can I do it?

Body:
Adding to Leo's answer, it's a good idea to introduce a component which will auto detect is active or not, so you don't need to write a bunch of <a> elements and many duplicate attributes.

For example a <custom-link> component:

<custom-link href="/message/inbox" class="list-group-item">
  Message
</custom-link>
<custom-link href="/message/review" class="list-group-item">
  Review
</custom-link>
<custom-link href="/message/resolution" class="list-group-item">
  Resolution
</custom-link>

If you don't need to reuse this component in other components or the list-group-item class is always necessary, you can also encapsulate this class to the <custom-link>. It will look even cleaner:

<custom-link href="/message/inbox">Message</custom-link>
<custom-link href="/message/review">Review</custom-link>
<custom-link href="/message/resolution">Resolution</custom-link>

the code of custom-link looks like:

<a
  :href="baseUrl + href"
  :class="{ active: isActive }"
  class="list-group-item"
>
  <slot></slot>
</a>

{
  props: ['href'],
  data: () => ({ baseUrl: window.Laravel.baseUrl }),
  computed: {
    isActive () {
      return location.href === this.baseUrl + this.href
    }
  }
}

I use location.href here directly, you can also use a computed property like Leo's example if you need some computations to get the current URL.


问:
Java android FloatingActionButton API 19 doesn't see
On samsung galaxy s4 mini I don't see a FloatingActionButton but on samsung galaxy s6 (API 23) I see this buttons. This is how I add this buttons :

```<code>  <android.support.design.widget.FloatingActionButton
        android:id="@+id/qick_menu_bt"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_margin="20dp"
        android:src="@drawable/quick_menu"
        app:layout_anchor="@id/mapview"
        app:layout_anchorGravity="bottom|right|end" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_margin="20dp"
        android:src="@drawable/lista"
        app:layout_anchor="@id/mapview"
        app:layout_anchorGravity="bottom|left|end" />
</code>```

In Android Studio Preview I see this buttons , but on phone I don't see . And this I add in build.gradle :

```<code>compile 'com.android.support:design:23.0.1'
</code>```

答:
https://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html

As mentioned in the android documentation FAB is added in API 21 and above, So you have to made it customized for API 19 but that is not the recommended way

Use this might be it will works

```<code>compile 'com.android.support:design:22.2.0'
</code>```

Body:
On samsung galaxy s4 mini I don't see a FloatingActionButton but on samsung galaxy s6 (API 23) I see this buttons. This is how I add this buttons :

  <android.support.design.widget.FloatingActionButton
        android:id="@+id/qick_menu_bt"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_margin="20dp"
        android:src="@drawable/quick_menu"
        app:layout_anchor="@id/mapview"
        app:layout_anchorGravity="bottom|right|end" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_margin="20dp"
        android:src="@drawable/lista"
        app:layout_anchor="@id/mapview"
        app:layout_anchorGravity="bottom|left|end" />

In Android Studio Preview I see this buttons , but on phone I don't see . And this I add in build.gradle :

compile 'com.android.support:design:23.0.1'

Body:
https://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html

As mentioned in the android documentation FAB is added in API 21 and above, So you have to made it customized for API 19 but that is not the recommended way

Use this might be it will works

compile 'com.android.support:design:22.2.0'


问:
Default Methods and the Compile Time error: The inherited method Horse.identifyMyself() cannot hide the public abstract method in Flyer
The following query is based on this official Oracle documentation. In this document under the heading "Interface Methods", under sub-section "Instance methods are preferred over interface default methods.", there are a few classes defined as follows:

```<code>public class Horse {
    public String identifyMyself() {
        return "I am a horse.";
    }
}

public interface Flyer {
    default public String identifyMyself() {
        return "I am able to fly.";
    }
}

public interface Mythical {
    default public String identifyMyself() {
        return "I am a mythical creature.";
    }
}

public class Pegasus extends Horse implements Flyer, Mythical {
    public static void main(String... args) {
        Pegasus myApp = new Pegasus();
        System.out.println(myApp.identifyMyself());
    }
}
</code>```

Everything is fine and the rule holds that inherited instance methods from super class are preferred over inherited default methods from super interfaces; however, whenever I drop the public access modifier from the method Horse.identifyMyself(), I get the following compile time error:

```<code>The inherited method Horse.identifyMyself() cannot hide the public abstract method in Mythical
</code>```

Honestly, I am not able to fully reason out this compilation error. The possible explanation I am able to think is that since we are reducing the visibility of Horse.identifyMyself() from public to package-private it is failing in hiding public method inherited from the interface(s). If this is correct, then why compiler is giving a new error message, it could have simply retained the old, well-known message: "Cannot reduce the visibility of the inherited method..."

Another query is that why compiler is referring to Mythical.identifyMyself() as "abstract method" when it is declared as default method given especially when abstract and default are mutually exclusive key words!

Thanks in advance for your patience and inputs.

Sincerely,
Nawazish

答:
The inherited method Horse.identifyMyself() cannot hide the public abstract method in Mythical

All methods declared in an interface are implicitly public.

All abstract, default, and static methods in an interface are implicitly
public, so you can omit the public modifier.

Your class Pegasus is extending Horse and implementing Flyer, Mythical which
has same method identifyMyself() so method from class Horse will be preferred
but you are reducing the visibility of Horse.identifyMyself() to default when
you removing public from it, due which you are getting above compilation
error and it will be removed once you make Horse.identifyMyself() method
public too.

since we are reducing the visibility of Horse.identifyMyself() from public to package-private it is failing in hiding public method inherited from the interface(s)

When you will make it private then your class Pegasus  will not have access
to it.

Another query is that why compiler is referring to Mythical.identifyMyself() as "abstract method" when it is declared as default method given especially when abstract and default are mutually exclusive key words!

When compiler is referring to Mythical.identifyMyself() as "abstract method",
it is just overriding.

Body:
The following query is based on this official Oracle documentation. In this document under the heading "Interface Methods", under sub-section "Instance methods are preferred over interface default methods.", there are a few classes defined as follows:

public class Horse {
    public String identifyMyself() {
        return "I am a horse.";
    }
}

public interface Flyer {
    default public String identifyMyself() {
        return "I am able to fly.";
    }
}

public interface Mythical {
    default public String identifyMyself() {
        return "I am a mythical creature.";
    }
}

public class Pegasus extends Horse implements Flyer, Mythical {
    public static void main(String... args) {
        Pegasus myApp = new Pegasus();
        System.out.println(myApp.identifyMyself());
    }
}

Everything is fine and the rule holds that inherited instance methods from super class are preferred over inherited default methods from super interfaces; however, whenever I drop the public access modifier from the method Horse.identifyMyself(), I get the following compile time error:

The inherited method Horse.identifyMyself() cannot hide the public abstract method in Mythical

Honestly, I am not able to fully reason out this compilation error. The possible explanation I am able to think is that since we are reducing the visibility of Horse.identifyMyself() from public to package-private it is failing in hiding public method inherited from the interface(s). If this is correct, then why compiler is giving a new error message, it could have simply retained the old, well-known message: "Cannot reduce the visibility of the inherited method..."

Another query is that why compiler is referring to Mythical.identifyMyself() as "abstract method" when it is declared as default method given especially when abstract and default are mutually exclusive key words!

Thanks in advance for your patience and inputs.

Sincerely,
Nawazish


问:
Table or gridlayout in J2ME
I want to display 3 rows on the screen for which table or gridlayout is needed.
Is it possible without using frameworks?
How should I implement for displaying 3 rows on the screen?</p>

答:
If you want to use Table or gridlayout in J2ME you should create your own item with the help of CustomItem (javax.microedition.lcdui.CustomItem). You should code for drawing lines for rows and columns.

If you use NetBeans then in NetBeans Mobility Pack there is library used for displaying a table. If you use NetBeans then you use the "org.netbeans.microedition.lcdui.TableItem" for the table.

Title: Table or gridlayout in J2ME


问:
Yii2 basic gridview just header and values
I would like to show data of a joined query... (Controller):

```<code>$znw_a = Znw::find()->withA()->where(['znw.id' => $zg_id])->one();
...
return $this->render('create', [
    ...
    'znw_a' => $znw_a,
</code>```

...like a very basic gridview, without pager, summary, etc, only the pure header with the data. The main idea is to show it like if it was a detailview simply transposed, so that I see data from left to right instead of top to bottom, so like a simple Excel table for example.

Is there such a simple widget like this in yii? Because GridView is not working like this, and before I'm trying to adjust my query in order to match the criteria of Gridview, maybe someone can give me a tip and I can achieve what I want easier. Can you please point me to the right direction? Many thanks!

答:
Extend DetailView for this one and use your class instead. Something like (assuming basic project template):

```<code>namespace app\widgets;

use yii\widgets\DetailView;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;

class MyDetailView extends DetailView
{
    public $template = '<td>{value}</td>';
    public $headerTemplate = '<th>{label}</th>';

    public function run()
    {
        $rows = [];
        $headers = [];
        $i = 0;
        foreach ($this->attributes as $attribute) {
            list($row, $header) = $this->renderAttribute($attribute, $i++);
            $rows[] = $row;
            $headers[] = $header;
        }

        $options = $this->options;
        $tag = ArrayHelper::remove($options, 'tag', 'table');
        $topRow = Html::tag('tr', implode("\n", $headers));
        $dataRow = Html::tag('tr', implode("\n", $rows));
        echo Html::tag($tag, $topRow . $dataRow, $options);
    }

    protected function renderAttribute($attribute, $index)
    {
        if (is_string($this->template)) {
            $row = strtr($this->template, [
                '{value}' => $this->formatter->format($attribute['value'], $attribute['format']),
            ]);
        } else {
            $row = call_user_func($this->template, $attribute, $index, $this);
        }
        if (is_string($this->headerTemplate)) {
            $header = strtr($this->headerTemplate, [
                '{label}' => $attribute['label'],
            ]);
        } else {
            $header = call_user_func($this->headerTemplate, $attribute, $index, $this);
        }
        return [$row, $header];
    }
}
</code>```

save it to /widgets/MyDetailView.php

Use it with

```<code>use app\widgets\MyDetailView;

<?= MyDetailView::widget([
    // ...
]) ?>
</code>```

Body:
I would like to show data of a joined query... (Controller):

$znw_a = Znw::find()->withA()->where(['znw.id' => $zg_id])->one();
...
return $this->render('create', [
    ...
    'znw_a' => $znw_a,

...like a very basic gridview, without pager, summary, etc, only the pure header with the data. The main idea is to show it like if it was a detailview simply transposed, so that I see data from left to right instead of top to bottom, so like a simple Excel table for example.

Is there such a simple widget like this in yii? Because GridView is not working like this, and before I'm trying to adjust my query in order to match the criteria of Gridview, maybe someone can give me a tip and I can achieve what I want easier. Can you please point me to the right direction? Many thanks!

Body:
Extend DetailView for this one and use your class instead. Something like (assuming basic project template):

namespace app\widgets;

use yii\widgets\DetailView;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;

class MyDetailView extends DetailView
{
    public $template = '<td>{value}</td>';
    public $headerTemplate = '<th>{label}</th>';

    public function run()
    {
        $rows = [];
        $headers = [];
        $i = 0;
        foreach ($this->attributes as $attribute) {
            list($row, $header) = $this->renderAttribute($attribute, $i++);
            $rows[] = $row;
            $headers[] = $header;
        }

        $options = $this->options;
        $tag = ArrayHelper::remove($options, 'tag', 'table');
        $topRow = Html::tag('tr', implode("\n", $headers));
        $dataRow = Html::tag('tr', implode("\n", $rows));
        echo Html::tag($tag, $topRow . $dataRow, $options);
    }

    protected function renderAttribute($attribute, $index)
    {
        if (is_string($this->template)) {
            $row = strtr($this->template, [
                '{value}' => $this->formatter->format($attribute['value'], $attribute['format']),
            ]);
        } else {
            $row = call_user_func($this->template, $attribute, $index, $this);
        }
        if (is_string($this->headerTemplate)) {
            $header = strtr($this->headerTemplate, [
                '{label}' => $attribute['label'],
            ]);
        } else {
            $header = call_user_func($this->headerTemplate, $attribute, $index, $this);
        }
        return [$row, $header];
    }
}

save it to /widgets/MyDetailView.php

Use it with

use app\widgets\MyDetailView;

<?= MyDetailView::widget([
    // ...
]) ?>


问:
Eclipse (on Ubuntu) do not have jsp, html and other web-files template
I installed Eclipse using Synaptic Package Manager (Ubuntu 9.10).
However, my Eclipse does not have any HTML template (in New dialog) or JSP template.
How can I fix it so that I will have some HTML and JSP templates overthere?</p>

答: You can install eclipse-wtp-webtools package for static html files. I can't find one for jsp though.


问:
Need simple working pom.xml file for wsconsume
I am using Java8 and I am trying to consume webservice using jboss plugin.

I have tried https://docs.jboss.org/author/display/JBWS/wsconsume  and ran into lot of compatibility issues

The problem is I am having lot of  dependency error all the time and I am now fed up. The current error is Failure to find com.sun.istack:istack-commons-runtime:jar:1.1. My concern is do i need these many dependency to run simple wsconsume?

```<code><pluginRepositories>
  <pluginRepository>
   <id>JBOSS</id>
   <name>JBoss Repository</name>
   <url>https://repository.jboss.org/nexus/content/groups/public/</url>
  </pluginRepository>
</pluginRepositories>

<dependencies>
  <dependency>
   <groupId>org.jboss.jbossas</groupId>
   <artifactId>jboss-as-client</artifactId>
   <version>6.1.0.Final</version>
   <type>pom</type>
   <scope>provided</scope>
  </dependency>
</dependencies>

<build>
    <plugins>

   <plugin>
   <groupId>org.jboss.ws.plugins</groupId>
   <artifactId>maven-jaxws-tools-plugin</artifactId>
   <version>1.1.1.Final</version>
   <executions>
   <execution>
   <id>My execution</id>
   <goals>
   <goal>wsconsume</goal>
   </goals>
   <configuration>
   <wsdls>
   <wsdl>mylocation?wsdl</wsdl>
   </wsdls>
   <targetPackage>src</targetPackage>
   </configuration>
   </execution>
   </executions>
   <dependencies>

   <dependency>
   <groupId>org.jboss.ws.native</groupId>
   <artifactId>jbossws-native-client</artifactId>
   <version>3.3.1.GA</version>
   <type>jar</type>
   <scope>compile</scope>
   </dependency>

   <dependency>
   <groupId>javax.xml.ws</groupId>
   <artifactId>jaxws-api</artifactId>
   <version>2.2.1</version>
   <type>jar</type>
   <scope>compile</scope>
   </dependency>

   <dependency>
   <groupId>org.jboss.ws</groupId>
   <artifactId>jbossws-spi</artifactId>
   <version>3.1.4.Final</version>
   <type>jar</type>
   <scope>compile</scope>
   </dependency>

   </dependencies>
   </plugin>
</code>```

答:
Resolved by executed the wsconsume.bat with exec-maven-plugin instead of CRAPY JBoss plugin

```<code><plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2</version>
        <executions>
          <execution>
            <id>runbatchfile</id>
            <phase>package</phase>
            <goals>
              <goal>exec</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <executable>${env.RH-SSO}/bin/wsconsume.bat</executable>
          <arguments>
            <argument>-o</argument>
            <argument>${project.build.directory}\classes</argument>
            <argument>C:\my.wsdl</argument>
          </arguments>
        </configuration>
      </plugin>
</code>```

Body:
I am using Java8 and I am trying to consume webservice using jboss plugin.

I have tried https://docs.jboss.org/author/display/JBWS/wsconsume  and ran into lot of compatibility issues

The problem is I am having lot of  dependency error all the time and I am now fed up. The current error is Failure to find com.sun.istack:istack-commons-runtime:jar:1.1. My concern is do i need these many dependency to run simple wsconsume?

<pluginRepositories>
  <pluginRepository>
   <id>JBOSS</id>
   <name>JBoss Repository</name>
   <url>https://repository.jboss.org/nexus/content/groups/public/</url>
  </pluginRepository>
</pluginRepositories>

<dependencies>
  <dependency>
   <groupId>org.jboss.jbossas</groupId>
   <artifactId>jboss-as-client</artifactId>
   <version>6.1.0.Final</version>
   <type>pom</type>
   <scope>provided</scope>
  </dependency>
</dependencies>

<build>
    <plugins>

   <plugin>
   <groupId>org.jboss.ws.plugins</groupId>
   <artifactId>maven-jaxws-tools-plugin</artifactId>
   <version>1.1.1.Final</version>
   <executions>
   <execution>
   <id>My execution</id>
   <goals>
   <goal>wsconsume</goal>
   </goals>
   <configuration>
   <wsdls>
   <wsdl>mylocation?wsdl</wsdl>
   </wsdls>
   <targetPackage>src</targetPackage>
   </configuration>
   </execution>
   </executions>
   <dependencies>

   <dependency>
   <groupId>org.jboss.ws.native</groupId>
   <artifactId>jbossws-native-client</artifactId>
   <version>3.3.1.GA</version>
   <type>jar</type>
   <scope>compile</scope>
   </dependency>

   <dependency>
   <groupId>javax.xml.ws</groupId>
   <artifactId>jaxws-api</artifactId>
   <version>2.2.1</version>
   <type>jar</type>
   <scope>compile</scope>
   </dependency>

   <dependency>
   <groupId>org.jboss.ws</groupId>
   <artifactId>jbossws-spi</artifactId>
   <version>3.1.4.Final</version>
   <type>jar</type>
   <scope>compile</scope>
   </dependency>

   </dependencies>
   </plugin>

Body:
Resolved by executed the wsconsume.bat with exec-maven-plugin instead of CRAPY JBoss plugin

<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2</version>
        <executions>
          <execution>
            <id>runbatchfile</id>
            <phase>package</phase>
            <goals>
              <goal>exec</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <executable>${env.RH-SSO}/bin/wsconsume.bat</executable>
          <arguments>
            <argument>-o</argument>
            <argument>${project.build.directory}\classes</argument>
            <argument>C:\my.wsdl</argument>
          </arguments>
        </configuration>
      </plugin>


问:
Print XML on Zebra printer using Python
In my work place, we have a Dymo printer that picks up data from a database and place it in a template label that I made, it prints with python automatically with a program.
Recently we bought a Zebra Thermal Printer, and I need to update the program to do the same thing, but with the Zebra printer.
I was looking around, and I found the ZebraDesigner for XML and I design a few labels like the ones I need it, but the zebra package for python is not able to print XML format, and I tried to print .lbl format but I wasn't able.
Note that .lbl files can't be edit as a text... And I need to do this...
Is there any solution?</p>

答:
Finally I found a way to make this.
With ZebraDesigner (not pro) I design the label template to my automated labels and I export to a file changing the route of the printer in Windows Preferences.
With the Online ZPL viewer of Labelary and minimum knowledges of ZPL (always with the manual near) I modified the label to make it editable on python with the use of .format() and {0},{1}, etc.
And finally done this, I call a batch with the command PRINT 'FILE' 'ZEBRAPORT' like PRINT C:\FILE.ZPL USB003 to print the specific modified label.
If someone want specific code of how I do this please, just ask me.

Title: Print XML on Zebra printer using Python


问:
how can I show news one by one horizontally?
code:

```<code><?php
   $query = "select * from latest_news limit 0,10";
   $fet = mysqli_query($link,$query);
   while ($fetch = mysqli_fetch_array($fet))
    {
      $news_title = $fetch['news_title'];
    }
?>
</code>```

html code:

```<code><marquee onmouseover="this.stop();" onmouseout="this.start();">
    <h3 id="news-h3"><?php echo $news_title; ?></h3>
</marquee>
</code>```

I am diplaying news_title using marquee but here only one data are showing. I want to display all news_title one by one. So, how can I do this.

Thank You

答:
Here is what you want.

```<code><marquee onmouseover="this.stop();" onmouseout="this.start();">
    <?php
        $query = "select * from latest_news limit 0,10";
        $fet = mysqli_query($link,$query);
        while ($fetch = mysqli_fetch_array($fet))
        {
          $news_title = $fetch['news_title'];
          ?>
            <span id="news-h3"><?php echo htmlspecialchars($news_title); ?></span>
          <?php
        }
    ?>
</marquee>
</code>```

Use CSS to style news span. If you want to use h3 tag then style it also like:

```<code><style>
h3 {
   display: inline;
}
</style>
</code>```

Body:
code:

<?php
   $query = "select * from latest_news limit 0,10";
   $fet = mysqli_query($link,$query);
   while ($fetch = mysqli_fetch_array($fet))
    {
      $news_title = $fetch['news_title'];
    }
?>

html code:

<marquee onmouseover="this.stop();" onmouseout="this.start();">

<?php echo $news_title; ?>

</marquee>

I am diplaying news_title using marquee but here only one data are showing. I want to display all news_title one by one. So, how can I do this.

Thank You

Body:
Here is what you want.

<marquee onmouseover="this.stop();" onmouseout="this.start();">
    <?php
        $query = "select * from latest_news limit 0,10";
        $fet = mysqli_query($link,$query);
        while ($fetch = mysqli_fetch_array($fet))
        {
          $news_title = $fetch['news_title'];
          ?>
            <span id="news-h3"><?php echo htmlspecialchars($news_title); ?></span>
          <?php
        }
    ?>
</marquee>

Use CSS to style news span. If you want to use h3 tag then style it also like:

<style>
h3 {
   display: inline;
}
</style>


问:
Load external nav and update links
I have been googling for an hour on this and thought I would see if someone had a quick answer.

I have a site running on a hosted cms and have just created a wordpress blog running on a subdomain on a new server. I do not have access to source code of hosted (business catalyst) CMS.

I would like to load the CMS navigation in to my wordpress theme and was considering using jQuery but ajax seems to have a same domain policy for loading content. From what I have read so far the way around this is with a php proxy loading the external content. Without diving in to this I can see there being a problem with the navigation links having relative urls to the original domain so they will not work on blog.domain.com. I do not want to have to create redirects for all of the possible urls on the new server as the CMS navigation will be updating regularly.

How can I load the navigation contents using php to create the proxy but automatically change the relative url's to absolute urls to the original domain? + there will be one url in the navigation that will need to stay the same and that is the one pointing to the subdomain blog.domain.com

Thanks in advance for your help.

答:
Hi Found this great article on HTML Parsing and Screen Scraping with the Simple HTML DOM Library:

http://net.tutsplus.com/tutorials/php/html-parsing-and-screen-scraping-with-the-simple-html-dom-library/

I have managed to parse the navigation by targeting the div id.

Now I have 1 last issue. The urls are realtive to the other server. How can I add the full absolute url: www.domain.com in front of all relative urls? Here's my code so far:

```<code><?php
include_once('simple_html_dom.php');

$html = file_get_html('http://www.domain.com/');

foreach($html->find('div#cat_514340_divs') as $e)
    echo $e->innertext . '<br>';

?>
</code>```

Title: Load external nav and update links

Body:
Hi Found this great article on HTML Parsing and Screen Scraping with the Simple HTML DOM Library:

http://net.tutsplus.com/tutorials/php/html-parsing-and-screen-scraping-with-the-simple-html-dom-library/

I have managed to parse the navigation by targeting the div id.

Now I have 1 last issue. The urls are realtive to the other server. How can I add the full absolute url: www.domain.com in front of all relative urls? Here's my code so far:

<?php
include_once('simple_html_dom.php');

$html = file_get_html('http://www.domain.com/');

foreach($html->find('div#cat_514340_divs') as $e)
    echo $e->innertext . '<br>';

?>


问:
java mail API forwarding the mail functionality
I am developing a standalone java utility which will connect to a existing mailbox of any organization and will read/check  the mails from Inbox that if any mail’s address field (“TO and CC” ) is crossing the character limits of 2000 characters or not….if it is crossing the limits then it will forward the same mail an email id else will do nothing….i have written the code for forwarding the mail functionality given below... it is working good...mail is getting forwarded but it is showing an exception ….
please suggest where I am lacking….

```<code>public class ForwardMail {

    public static void main(String[] args){
        Properties properties = new Properties();
          properties.put("mail.store.protocol", "pop3");
          properties.put("mail.pop3s.host", "mailcluster.mycompany.com");
          properties.put("mail.pop3s.port", "995");
          properties.put("mail.pop3.starttls.enable", "true");
          properties.put("mail.smtp.auth", "true"); /* may be commented later*/
          properties.put("smtp.starttls.enable", "true");
          properties.put("mail.smtp.host", "mailcluster.mycompany.com");
          properties.put("mail.smtp.port", "25");

        //  Session session = Session.getDefaultInstance(properties);
          Session session = Session.getInstance(properties,new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("myname@mycompany.com","mypassword@123");
                }
              });
     try{
         // session.setDebug(true);
         // Get a Store object and connect to the current host
         Store store = session.getStore("pop3s");
         store.connect("mailcluster.mycompany.com", "myname@mycompany.com","mypassword@123");

         // Create a Folder object and open the folder
         Folder folder = store.getFolder("inbox");
         folder.open(Folder.READ_ONLY);
         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
         Message[] messages = folder.getMessages();
         if (messages.length != 0) {

         for (int i = 0, n = messages.length; i < n; i++) {
            Message message = messages[i];
            // Get all the information from the message
           // String from = InternetAddress.toString(message.getFrom());
            String from = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
            if (from != null) {
               System.out.println("From:"  + from);
            }
            /*String replyTo = InternetAddress.toString(message.getReplyTo());
            if (replyTo != null) {
               System.out.println("Reply-to: " + replyTo);
            }*/
            String to = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
            if (to != null) {
               System.out.println("To: " + to);
            }

            String subject = message.getSubject();
            if (subject != null) {
               System.out.println("Subject: " + subject);
            }
            /*Date sent = message.getSentDate();
            if (sent != null) {
               System.out.println("Sent: " + sent);
            }*/
            System.out.print("Do you want to reply [y/n] : ");
            String ans = reader.readLine();
            if ("Y".equals(ans) || "y".equals(ans)) {
               Message forward = new MimeMessage(session);
               // Fill in header
               forward.setRecipients(Message.RecipientType.TO,InternetAddress.parse(from));
               forward.setSubject("Fwd: " + message.getSubject());
               forward.setFrom(new InternetAddress(to));

               // Create the message part
               MimeBodyPart messageBodyPart = new MimeBodyPart();
               // Create a multipart message
               Multipart multipart = new MimeMultipart();
               // set content
               messageBodyPart.setContent(message, "message/rfc822");
               // Add part to multi part
               multipart.addBodyPart(messageBodyPart);
               // Associate multi-part with message
               forward.setContent(multipart);
               forward.saveChanges();
               // Transport.send(forward);
               // Send the message by authenticating the SMTP server
               // Create a Transport instance and call the sendMessage
               Transport t = session.getTransport("smtp");
               try {
                  //connect to the smpt server using transport instance
                  t.connect("myname@mycompany.com", "mypassword@123");
                  t.sendMessage(forward, forward.getAllRecipients());

               } finally {
                  t.close();
               }

               System.out.println("message forwarded successfully....");

            // close the store and folder objects
            folder.close(false);
            store.close();
            }// end if

         }// end for
   }// end if
     }   catch(Exception e) {
          e.printStackTrace();
    }
        }
    }
</code>```

following is exception i am getting..

```<code>java.lang.IllegalStateException: Folder is not Open
at com.sun.mail.pop3.POP3Folder.checkOpen(POP3Folder.java:551)
at com.sun.mail.pop3.POP3Folder.getProtocol(POP3Folder.java:581)
at com.sun.mail.pop3.POP3Message.loadHeaders(POP3Message.java:606)
at com.sun.mail.pop3.POP3Message.getHeader(POP3Message.java:383)
at javax.mail.internet.MimeMessage.getAddressHeader(MimeMessage.java:701)
at javax.mail.internet.MimeMessage.getRecipients(MimeMessage.java:534)
at servion.ForwardMail.main(ForwardMail.java:56)
</code>```

How to remove this exception ???

答:
You're closing the folder after processing one message, which means it's closed while you're accessing the Message object for the second message, so JavaMail can't get the message data from the server.

And while you're fixing that, be sure to fix these common JavaMail mistakes.

Finally, the "smtp.starttls.enable" property should be "mail.smtp.starttls.enable".

Body:
I am developing a standalone java utility which will connect to a existing mailbox of any organization and will read/check  the mails from Inbox that if any mail’s address field (“TO and CC” ) is crossing the character limits of 2000 characters or not….if it is crossing the limits then it will forward the same mail an email id else will do nothing….i have written the code for forwarding the mail functionality given below... it is working good...mail is getting forwarded but it is showing an exception ….
please suggest where I am lacking….

public class ForwardMail {

    public static void main(String[] args){
        Properties properties = new Properties();
          properties.put("mail.store.protocol", "pop3");
          properties.put("mail.pop3s.host", "mailcluster.mycompany.com");
          properties.put("mail.pop3s.port", "995");
          properties.put("mail.pop3.starttls.enable", "true");
          properties.put("mail.smtp.auth", "true"); /* may be commented later*/
          properties.put("smtp.starttls.enable", "true");
          properties.put("mail.smtp.host", "mailcluster.mycompany.com");
          properties.put("mail.smtp.port", "25");

        //  Session session = Session.getDefaultInstance(properties);
          Session session = Session.getInstance(properties,new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("myname@mycompany.com","mypassword@123");
                }
              });
     try{
         // session.setDebug(true);
         // Get a Store object and connect to the current host
         Store store = session.getStore("pop3s");
         store.connect("mailcluster.mycompany.com", "myname@mycompany.com","mypassword@123");

         // Create a Folder object and open the folder
         Folder folder = store.getFolder("inbox");
         folder.open(Folder.READ_ONLY);
         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
         Message[] messages = folder.getMessages();
         if (messages.length != 0) {

         for (int i = 0, n = messages.length; i < n; i++) {
            Message message = messages[i];
            // Get all the information from the message
           // String from = InternetAddress.toString(message.getFrom());
            String from = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
            if (from != null) {
               System.out.println("From:"  + from);
            }
            /*String replyTo = InternetAddress.toString(message.getReplyTo());
            if (replyTo != null) {
               System.out.println("Reply-to: " + replyTo);
            }*/
            String to = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
            if (to != null) {
               System.out.println("To: " + to);
            }

            String subject = message.getSubject();
            if (subject != null) {
               System.out.println("Subject: " + subject);
            }
            /*Date sent = message.getSentDate();
            if (sent != null) {
               System.out.println("Sent: " + sent);
            }*/
            System.out.print("Do you want to reply [y/n] : ");
            String ans = reader.readLine();
            if ("Y".equals(ans) || "y".equals(ans)) {
               Message forward = new MimeMessage(session);
               // Fill in header
               forward.setRecipients(Message.RecipientType.TO,InternetAddress.parse(from));
               forward.setSubject("Fwd: " + message.getSubject());
               forward.setFrom(new InternetAddress(to));

               // Create the message part
               MimeBodyPart messageBodyPart = new MimeBodyPart();
               // Create a multipart message
               Multipart multipart = new MimeMultipart();
               // set content
               messageBodyPart.setContent(message, "message/rfc822");
               // Add part to multi part
               multipart.addBodyPart(messageBodyPart);
               // Associate multi-part with message
               forward.setContent(multipart);
               forward.saveChanges();
               // Transport.send(forward);
               // Send the message by authenticating the SMTP server
               // Create a Transport instance and call the sendMessage
               Transport t = session.getTransport("smtp");
               try {
                  //connect to the smpt server using transport instance
                  t.connect("myname@mycompany.com", "mypassword@123");
                  t.sendMessage(forward, forward.getAllRecipients());

               } finally {
                  t.close();
               }

               System.out.println("message forwarded successfully....");

            // close the store and folder objects
            folder.close(false);
            store.close();
            }// end if

         }// end for
   }// end if
     }   catch(Exception e) {
          e.printStackTrace();
    }
        }
    }

following is exception i am getting..

java.lang.IllegalStateException: Folder is not Open
at com.sun.mail.pop3.POP3Folder.checkOpen(POP3Folder.java:551)
at com.sun.mail.pop3.POP3Folder.getProtocol(POP3Folder.java:581)
at com.sun.mail.pop3.POP3Message.loadHeaders(POP3Message.java:606)
at com.sun.mail.pop3.POP3Message.getHeader(POP3Message.java:383)
at javax.mail.internet.MimeMessage.getAddressHeader(MimeMessage.java:701)
at javax.mail.internet.MimeMessage.getRecipients(MimeMessage.java:534)
at servion.ForwardMail.main(ForwardMail.java:56)

How to remove this exception ???


问:
Get Data from url()
I am trying to get id and val from this url()  and assign it to a text box
http://localhost:59113/Project/ProjectAllocation/?id=9%20&val=%20dgds

 I tried this code but am getting text box value like thisval=%20dgds,%20dgds

```<code>  var url = document.URL;
var id = /id=([^&]+)/.exec(url);
var val = /val=([^&]+)/.exec(url);
var result = id ? id : ' ';
var result = getId()
 $('.currentProjectName').val(val)
</code>```

答:
I got solution from this</p>

```<code>function a() {debugger
    var url = document.URL;
    var param = getUrlParam("id");
    var param = getUrlParam("val");
    $('.currentProjectName').val(param)
}

function getUrlParam(param) {
    param = param.replace(/([\[\](){}*?+^$.\\|])/g, "\\$1");
    var regex = new RegExp("[?&]" + param + "=([^&#]*)");
    var url = decodeURIComponent(window.location.href);
    var match = regex.exec(url);
    return match ? match[1] : "";
}
</code>```

Title: Get Data from url()

Body:
I am trying to get id and val from this url()  and assign it to a text box
http://localhost:59113/Project/ProjectAllocation/?id=9%20&val=%20dgds

 I tried this code but am getting text box value like thisval=%20dgds,%20dgds

  var url = document.URL;
var id = /id=([^&]+)/.exec(url);
var val = /val=([^&]+)/.exec(url);
var result = id ? id : ' ';
var result = getId()
 $('.currentProjectName').val(val)

Body:
I got solution from this

function a() {debugger
    var url = document.URL;
    var param = getUrlParam("id");
    var param = getUrlParam("val");
    $('.currentProjectName').val(param)
}

function getUrlParam(param) {
    param = param.replace(/([\[\](){}*?+^$.\\|])/g, "\\$1");
    var regex = new RegExp("[?&]" + param + "=([^&#]*)");
    var url = decodeURIComponent(window.location.href);
    var match = regex.exec(url);
    return match ? match[1] : "";
}


答:
You need to decode the URI

var url = 'http://localhost:59113/Project/ProjectAllocation/?id=9%20&val=%20dgds;'
var id = decodeURI(/id=([^&]+)/.exec(url)[1]);
var val = decodeURI(/val=([^&]+)/.exec(url)[1]);
$('#txtid').val(id);
$('#txtval').val(val);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="txtid" value="">
<input type="text" id="txtval" value=""></code>```

Title: Get Data from url()

Body:
You need to decode the URI

var url = 'http://localhost:59113/Project/ProjectAllocation/?id=9%20&val=%20dgds;'
var id = decodeURI(/id=([^&]+)/.exec(url)[1]);
var val = decodeURI(/val=([^&]+)/.exec(url)[1]);
$('#txtid').val(id);
$('#txtval').val(val);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="txtid" value="">
<input type="text" id="txtval" value="">


问:
CakePHP 3 - Compare passwords
I have two field "password" (This field is in the database) and confirm_password (This field is not in the database)

Well, I need to compare if password == confirm_password.. but I'm not knowing create a custom validation to "confirm_password"... Would need to have this field in the database?

How do I do?

答:
Now there has a method call sameAs in validator class, for version 3.2 or grater.

```<code> $validator -> sameAs('password_match','password','Passwords not equal.');
</code>```

see API

Title: CakePHP 3 - Compare passwords

Body:
Now there has a method call sameAs in validator class, for version 3.2 or grater.

 $validator -> sameAs('password_match','password','Passwords not equal.');

see API


问:
Filter the query and refresh the recycler view using firebase in android
```<code>@Override
protected void onStart() {
    super.onStart();

    mAuth.addAuthStateListener(mAuthListener);

    FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

            Product.class,
            R.layout.product_row,
            ProductViewHolder.class,
            mDatabase

    ) {
        @Override
        protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {

            Log.d(TAG, "loading view " + position);
            final String product_id = getRef(position).getKey();
            viewHolder.setTitle(model.getName());
            viewHolder.setDesc(model.getDesc());
            viewHolder.setImage(getApplicationContext(), model.getImage());
            viewHolder.setUsername(model.getUsername());

            viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent productDetailIntent = new Intent();
                    productDetailIntent.setClass(MainActivity.this, ProductDetailActivity.class);
                    productDetailIntent.putExtra("product_id", product_id);
                    Log.d(TAG + " product_id", product_id);
                    startActivity(productDetailIntent);
                }
            });

            Log.d(TAG, "finish loading view");
        }
    };

    mProductList.setAdapter(firebaseRecyclerAdapter);
}
</code>```

The above is the code that I use to get the data from the firebase realtime database. How can I change the query (mDatabase in my code) and refresh the recyclerview to filter the data? How to set a new adapter? Please give me some helps.Thank you.

答:
Set query in your database...</p>

```<code>FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

            Product.class,
            R.layout.product_row,
            ProductViewHolder.class,
            mDatabase.orderByChild("KeyName").equalTo("Value")

    )
</code>```

Body:
@Override
protected void onStart() {
    super.onStart();

    mAuth.addAuthStateListener(mAuthListener);

    FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

            Product.class,
            R.layout.product_row,
            ProductViewHolder.class,
            mDatabase

    ) {
        @Override
        protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {

            Log.d(TAG, "loading view " + position);
            final String product_id = getRef(position).getKey();
            viewHolder.setTitle(model.getName());
            viewHolder.setDesc(model.getDesc());
            viewHolder.setImage(getApplicationContext(), model.getImage());
            viewHolder.setUsername(model.getUsername());

            viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent productDetailIntent = new Intent();
                    productDetailIntent.setClass(MainActivity.this, ProductDetailActivity.class);
                    productDetailIntent.putExtra("product_id", product_id);
                    Log.d(TAG + " product_id", product_id);
                    startActivity(productDetailIntent);
                }
            });

            Log.d(TAG, "finish loading view");
        }
    };

    mProductList.setAdapter(firebaseRecyclerAdapter);
}

The above is the code that I use to get the data from the firebase realtime database. How can I change the query (mDatabase in my code) and refresh the recyclerview to filter the data? How to set a new adapter? Please give me some helps.Thank you.

Body:
Set query in your database...

FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

            Product.class,
            R.layout.product_row,
            ProductViewHolder.class,
            mDatabase.orderByChild("KeyName").equalTo("Value")

    )


问:
Separate Potential Duplicates Into Different Rows
I am trying to identify potential duplicate customers in my database based on the last 4 of the SSN, last name and DOB. The stored procedure I have written does identify potential duplicates but it lists them in one row - I am trying to split into separate rows for reporting reasons.

My T-SQL looks like:

```<code>DECLARE
@StartDate DATE = '1/1/2017',
@EndDate DATE = '3/1/2017';

SELECT  DENSE_RANK() OVER (ORDER BY c.socialSecurityNumber) AS [SSNRanking] ,
    ROW_NUMBER() OVER (PARTITION BY c.socialSecurityNumber ORDER BY c.socialSecurityNumber) AS [RowNumb] ,
    c.socialSecurityNumber AS [SSN],
    c.id AS [CustomerID]  ,
    c.firstName AS [FirstName] ,
    c.lastName AS [lastName] ,
    c.birthDate [birthdate] ,
    c.createDate AS [CreateDate] ,
    c2.socialSecurityNumber AS [DupSSN] ,
    c2.id AS [DupCustomerID] ,
    c2.firstName AS [DupFirstName] ,
    c2.lastName AS [DupLastName] ,
    c2.birthDate AS [DupBirthDate] ,
    c2.createDate AS [DupCreateDate]
FROM    dbo.Customers AS [c]
    INNER JOIN dbo.Customers AS [c2] ON ( SUBSTRING(c.socialSecurityNumber,6,4) = SUBSTRING(c2.socialSecurityNumber,6,4) AND c.birthDate = c2.birthDate AND c.lastName = c2.lastName AND c.id <> c2.id )
    LEFT JOIN dbo.CustomerAddresses AS [CA] ON c.id = CA.customerID
    LEFT OUTER JOIN dbo.Common_Orders AS [co] ON co.customerID = c.id
WHERE
    c.customerStatusTypeID <> 'M'
    AND C2.customerStatusTypeID <> 'M'
    AND c.mergedTo IS NULL
    AND c2.mergedTo IS NULL
    AND CAST(co.orderDate AS DATE) >= @StartDate
    AND CAST(co.orderDate AS DATE) <= @EndDate
    AND c.id = 1234439
GROUP BY c.socialSecurityNumber ,
    c.id ,
    c.firstName ,
    c.lastName ,
    c.birthDate ,
    c.createDate ,
    c2.socialSecurityNumber ,
    c2.id ,
    c2.firstName ,
    c2.lastName ,
    c2.birthDate ,
    c2.createDate
ORDER BY CAST(c.socialSecurityNumber AS INT) ASC;
</code>```

And my data set looks like:

```<code>SSNRanking  RowNumb  SSN        CustomerID  FirstName  lastName  birthdate  CreateDate  DupSSN     DupCustomerID  DupFirstName  DupLastName  DupBirthDate  DupCreateDate
1           1        000009915  1234439     GREG       GARRETT  1900-01-01  2014-02-25  000009915  1166084        ADAM          GARRETT      1900-01-01    2013-08-29
</code>```

In this particular instance, I have two users with the same last 4 of the SSN, same last name and same DOB - but different first names.

How can I make these two records appear on separate lines?  Ideally, I would like to see:

```<code>SSNRanking  RowNumb  SSN        CustomerID  FirstName  lastName  birthdate   CreateDate
1           1        000009915  1234439     GREG       GARRETT   1900-01-01  2014-02-25
1           2        000009915  1166084     ADAM       GARRETT   1900-01-01  2013-08-29
</code>```

But I am not sure how I can accomplish this when joining to the same table.  Suggestions?

I'm linking to a script that creates the two tables in question and inserts sample data. Hopefully that is acceptable: SQL Script

答:
This is called "unpivot". You can use UNPIVOT operator, but I prefer to use CROSS APPLY ... VALUES.

I'll wrap your query into CTE without looking at it in details and split each row into two using CROSS APPLY.

```<code>DECLARE
@StartDate DATE = '1/1/2017',
@EndDate DATE = '3/1/2017';

WITH
CTE
AS
(
    SELECT
        DENSE_RANK() OVER (ORDER BY c.socialSecurityNumber) AS [SSNRanking] ,
        ROW_NUMBER() OVER (PARTITION BY c.socialSecurityNumber ORDER BY c.socialSecurityNumber) AS [RowNumb] ,
        c.socialSecurityNumber AS [SSN],
        c.id AS [CustomerID]  ,
        c.firstName AS [FirstName] ,
        c.lastName AS [lastName] ,
        c.birthDate [birthdate] ,
        c.createDate AS [CreateDate] ,
        c2.socialSecurityNumber AS [DupSSN] ,
        c2.id AS [DupCustomerID] ,
        c2.firstName AS [DupFirstName] ,
        c2.lastName AS [DupLastName] ,
        c2.birthDate AS [DupBirthDate] ,
        c2.createDate AS [DupCreateDate]
    FROM
        dbo.Customers AS [c]
        INNER JOIN dbo.Customers AS [c2] ON ( SUBSTRING(c.socialSecurityNumber,6,4) = SUBSTRING(c2.socialSecurityNumber,6,4) AND c.birthDate = c2.birthDate AND c.lastName = c2.lastName AND c.id <> c2.id )
        LEFT JOIN dbo.CustomerAddresses AS [CA] ON c.id = CA.customerID
        LEFT JOIN dbo.Common_Orders AS [co] ON co.customerID = c.id
    WHERE
        c.customerStatusTypeID <> 'M'
        AND C2.customerStatusTypeID <> 'M'
        AND c.mergedTo IS NULL
        AND c2.mergedTo IS NULL
        AND CAST(co.orderDate AS DATE) >= @StartDate
        AND CAST(co.orderDate AS DATE) <= @EndDate
        AND c.id = 1234439
    GROUP BY
        c.socialSecurityNumber ,
        c.id ,
        c.firstName ,
        c.lastName ,
        c.birthDate ,
        c.createDate ,
        c2.socialSecurityNumber ,
        c2.id ,
        c2.firstName ,
        c2.lastName ,
        c2.birthDate ,
        c2.createDate
)
SELECT
    CA.SSNRanking
    ,CA.RowNumb
    ,CA.SSN
    ,CA.CustomerID
    ,CA.FirstName
    ,CA.lastName
    ,CA.birthdate
    ,CA.CreateDate
FROM
    CTE
    CROSS APPLY
    (
        VALUES
        (CTE.SSNRanking, CTE.RowNumb, CTE.SSN, CTE.CustomerID, CTE.FirstName, CTE.lastName, CTE.birthdate, CTE.CreateDate),
        (CTE.SSNRanking, CTE.RowNumb, CTE.DupSSN, CTE.DupCustomerID, CTE.DupFirstName, CTE.DuplastName, CTE.Dupbirthdate, CTE.DupCreateDate)
    ) AS CA(SSNRanking, RowNumb, SSN, CustomerID, FirstName, lastName, birthdate, CreateDate)
ORDER BY CAST(CA.SSN AS INT) ASC;
</code>```

By the way,

```<code>ROW_NUMBER() OVER (PARTITION BY ColumnA ORDER BY ColumnA)
</code>```

doesn't make sense when you partition and order by the same column. I'm not sure what you want to achieve there.

Body:
I am trying to identify potential duplicate customers in my database based on the last 4 of the SSN, last name and DOB. The stored procedure I have written does identify potential duplicates but it lists them in one row - I am trying to split into separate rows for reporting reasons.

My T-SQL looks like:

DECLARE
@StartDate DATE = '1/1/2017',
@EndDate DATE = '3/1/2017';

SELECT  DENSE_RANK() OVER (ORDER BY c.socialSecurityNumber) AS [SSNRanking] ,
    ROW_NUMBER() OVER (PARTITION BY c.socialSecurityNumber ORDER BY c.socialSecurityNumber) AS [RowNumb] ,
    c.socialSecurityNumber AS [SSN],
    c.id AS [CustomerID]  ,
    c.firstName AS [FirstName] ,
    c.lastName AS [lastName] ,
    c.birthDate [birthdate] ,
    c.createDate AS [CreateDate] ,
    c2.socialSecurityNumber AS [DupSSN] ,
    c2.id AS [DupCustomerID] ,
    c2.firstName AS [DupFirstName] ,
    c2.lastName AS [DupLastName] ,
    c2.birthDate AS [DupBirthDate] ,
    c2.createDate AS [DupCreateDate]
FROM    dbo.Customers AS [c]
    INNER JOIN dbo.Customers AS [c2] ON ( SUBSTRING(c.socialSecurityNumber,6,4) = SUBSTRING(c2.socialSecurityNumber,6,4) AND c.birthDate = c2.birthDate AND c.lastName = c2.lastName AND c.id <> c2.id )
    LEFT JOIN dbo.CustomerAddresses AS [CA] ON c.id = CA.customerID
    LEFT OUTER JOIN dbo.Common_Orders AS [co] ON co.customerID = c.id
WHERE
    c.customerStatusTypeID <> 'M'
    AND C2.customerStatusTypeID <> 'M'
    AND c.mergedTo IS NULL
    AND c2.mergedTo IS NULL
    AND CAST(co.orderDate AS DATE) >= @StartDate
    AND CAST(co.orderDate AS DATE) <= @EndDate
    AND c.id = 1234439
GROUP BY c.socialSecurityNumber ,
    c.id ,
    c.firstName ,
    c.lastName ,
    c.birthDate ,
    c.createDate ,
    c2.socialSecurityNumber ,
    c2.id ,
    c2.firstName ,
    c2.lastName ,
    c2.birthDate ,
    c2.createDate
ORDER BY CAST(c.socialSecurityNumber AS INT) ASC;

And my data set looks like:

SSNRanking  RowNumb  SSN        CustomerID  FirstName  lastName  birthdate  CreateDate  DupSSN     DupCustomerID  DupFirstName  DupLastName  DupBirthDate  DupCreateDate
1           1        000009915  1234439     GREG       GARRETT  1900-01-01  2014-02-25  000009915  1166084        ADAM          GARRETT      1900-01-01    2013-08-29

In this particular instance, I have two users with the same last 4 of the SSN, same last name and same DOB - but different first names.

How can I make these two records appear on separate lines?  Ideally, I would like to see:

SSNRanking  RowNumb  SSN        CustomerID  FirstName  lastName  birthdate   CreateDate
1           1        000009915  1234439     GREG       GARRETT   1900-01-01  2014-02-25
1           2        000009915  1166084     ADAM       GARRETT   1900-01-01  2013-08-29

But I am not sure how I can accomplish this when joining to the same table.  Suggestions?

I'm linking to a script that creates the two tables in question and inserts sample data. Hopefully that is acceptable: SQL Script

Body:
This is called "unpivot". You can use UNPIVOT operator, but I prefer to use CROSS APPLY ... VALUES.

I'll wrap your query into CTE without looking at it in details and split each row into two using CROSS APPLY.

DECLARE
@StartDate DATE = '1/1/2017',
@EndDate DATE = '3/1/2017';

WITH
CTE
AS
(
    SELECT
        DENSE_RANK() OVER (ORDER BY c.socialSecurityNumber) AS [SSNRanking] ,
        ROW_NUMBER() OVER (PARTITION BY c.socialSecurityNumber ORDER BY c.socialSecurityNumber) AS [RowNumb] ,
        c.socialSecurityNumber AS [SSN],
        c.id AS [CustomerID]  ,
        c.firstName AS [FirstName] ,
        c.lastName AS [lastName] ,
        c.birthDate [birthdate] ,
        c.createDate AS [CreateDate] ,
        c2.socialSecurityNumber AS [DupSSN] ,
        c2.id AS [DupCustomerID] ,
        c2.firstName AS [DupFirstName] ,
        c2.lastName AS [DupLastName] ,
        c2.birthDate AS [DupBirthDate] ,
        c2.createDate AS [DupCreateDate]
    FROM
        dbo.Customers AS [c]
        INNER JOIN dbo.Customers AS [c2] ON ( SUBSTRING(c.socialSecurityNumber,6,4) = SUBSTRING(c2.socialSecurityNumber,6,4) AND c.birthDate = c2.birthDate AND c.lastName = c2.lastName AND c.id <> c2.id )
        LEFT JOIN dbo.CustomerAddresses AS [CA] ON c.id = CA.customerID
        LEFT JOIN dbo.Common_Orders AS [co] ON co.customerID = c.id
    WHERE
        c.customerStatusTypeID <> 'M'
        AND C2.customerStatusTypeID <> 'M'
        AND c.mergedTo IS NULL
        AND c2.mergedTo IS NULL
        AND CAST(co.orderDate AS DATE) >= @StartDate
        AND CAST(co.orderDate AS DATE) <= @EndDate
        AND c.id = 1234439
    GROUP BY
        c.socialSecurityNumber ,
        c.id ,
        c.firstName ,
        c.lastName ,
        c.birthDate ,
        c.createDate ,
        c2.socialSecurityNumber ,
        c2.id ,
        c2.firstName ,
        c2.lastName ,
        c2.birthDate ,
        c2.createDate
)
SELECT
    CA.SSNRanking
    ,CA.RowNumb
    ,CA.SSN
    ,CA.CustomerID
    ,CA.FirstName
    ,CA.lastName
    ,CA.birthdate
    ,CA.CreateDate
FROM
    CTE
    CROSS APPLY
    (
        VALUES
        (CTE.SSNRanking, CTE.RowNumb, CTE.SSN, CTE.CustomerID, CTE.FirstName, CTE.lastName, CTE.birthdate, CTE.CreateDate),
        (CTE.SSNRanking, CTE.RowNumb, CTE.DupSSN, CTE.DupCustomerID, CTE.DupFirstName, CTE.DuplastName, CTE.Dupbirthdate, CTE.DupCreateDate)
    ) AS CA(SSNRanking, RowNumb, SSN, CustomerID, FirstName, lastName, birthdate, CreateDate)
ORDER BY CAST(CA.SSN AS INT) ASC;

By the way,

ROW_NUMBER() OVER (PARTITION BY ColumnA ORDER BY ColumnA)

doesn't make sense when you partition and order by the same column. I'm not sure what you want to achieve there.


问:
Change data-url via jquery
I am trying to use jquery to change the data-url attribute used by a file upload. But it doesn't seems to be working. The file upload takes the old value.

$('#fileupload').attr('data-url', "https://api.mysite.com/optimizeonly");

HTML

```<code><input id="fileupload" class="fileupload" type="file" name="file[]" data-url="https://api.mysite.com/upload" multiple="">`
</code>```

Snippet:

$('#fileupload').attr('data-url', "https://api.mysite.com/optimizeonly");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="fileupload" class="fileupload" type="file" name="file[]" data-url="https://api.mysite.com/upload" multiple=""></code>```

Edit : 1

I am using jquery file upload module , i though this was evident from the tags.
The whole code is available from the live demo (just inspect element)

答:
The data-url attribute of the input is read by the plugin when initializing. It is not automatically read afterwards. Have you tried updating the URL as follows?

```<code>var fu = $('#fileupload');
fu.fileupload('option', 'url', fu.data('url'));
</code>```

Of course, this would be done after updating the data-url attribute of the element using

```<code>fu.data('url', 'new-url-you-want-here');
</code>```

and you could, I think, skip updating the attribute altogether and only change the option of the plugin.

```<code>fu.fileupload('option', 'url', 'new-url-you-want-here');
</code>```

Title: Change data-url via jquery

Body:
I am trying to use jquery to change the data-url attribute used by a file upload. But it doesn't seems to be working. The file upload takes the old value.

$('#fileupload').attr('data-url', "https://api.mysite.com/optimizeonly");

HTML

<input id="fileupload" class="fileupload" type="file" name="file[]" data-url="https://api.mysite.com/upload" multiple="">`

Snippet:

$('#fileupload').attr('data-url', "https://api.mysite.com/optimizeonly");

<input id="fileupload" class="fileupload" type="file" name="file[]" data-url="https://api.mysite.com/upload" multiple="">

Edit : 1

I am using jquery file upload module , i though this was evident from the tags.
The whole code is available from the live demo (just inspect element)

Body:
The data-url attribute of the input is read by the plugin when initializing. It is not automatically read afterwards. Have you tried updating the URL as follows?

var fu = $('#fileupload');
fu.fileupload('option', 'url', fu.data('url'));

Of course, this would be done after updating the data-url attribute of the element using

fu.data('url', 'new-url-you-want-here');

and you could, I think, skip updating the attribute altogether and only change the option of the plugin.

fu.fileupload('option', 'url', 'new-url-you-want-here');


问:
How to include my nodejs libraries with Google Cloud Functions
I've just made my first decent Google Cloud Function and now I'd like to refactor it into libraries.

Example, I've got my Cloud Function and I'd like to require a library I've created, not something installed from NPM.

How do I deploy these libraries to Google Cloud Functions?

答:
If I understand your question correctly, you want to create a module out of your common.js file.

If that is the case, in common.js, export it like so:

```<code>export default function(){
  // Here is your common code
}
</code>```

and then just import it into your function file:

```<code>import common from './common.js';
</code>```

Body:
If I understand your question correctly, you want to create a module out of your common.js file.

If that is the case, in common.js, export it like so:

export default function(){
  // Here is your common code
}

and then just import it into your function file:

import common from './common.js';


问:
Codeigniter : how to update mulitiple record where id
I have been looking for ways but find suitable speckle. so, i have table product and I show along with his ID. and I put in a form. and when I press the update button then what had been updated in the form of their corresponding id.

my view :

```<code><?php echo form_open('stock/updating_stock');?>
  <div class="panel-body scroll-menu" style="margin-top:0px;height:170px;padding-top:5px;">
    <?php foreach($critical_plus_warning as $data){?>
      <input type="hidden" name="id_product[]" value="<?php echo $data->id_product;?>">
      <h5 class="hidden-xs"><b><?php echo $data->product_name;?></b> <input type="text" class="pull-right" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stock?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
      }else{
        echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
      }
      ?>
      </h5>
      <h5 class="hidden-lg"><b><?php $limited_word = word_limiter($data->product_name,3); echo $limited_word; ?></b> <input class="pull-right" type="text" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stocks?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
      }else{
        echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
      }
      ?>
      </h5>
    <?php }?>
  </div>
  <div class="col-xs-12" style="margin-top:-5px;background-color:white;padding:6px;background-color:white;box-shadow:0px 0px 8px 0px #bababa;"><button type="submit" name="submit" class="btn btn-success">Save data</button></div>
  <?php echo form_close();?>
</code>```

and my controller :

```<code>function updating_stock(){

    $id = $this->input->post('id_product');
    $stok = $this->input->post('update_stock');
    $user = $this->data['id'];

    for($i=0;$i<count($id);$i++){
    $data = array(
       array(
        'id'        => $id,
        'stok'      => $stok,
        'diubah'    => $user,
        'tgl_diubah'=> date('Y:m:d H:i:s'),
        ),
    );
    }
    //print_r($data);
    $this->stok_adm->update_stok($data);
}
</code>```

and my models :

```<code>function update_stok($data){
    $this->db->update_batch($this->table, $data,'id_product');
    return $this->db->affected_rows();
}
</code>```

答:
I think in your example update_batch will generate incorrect query beacues you need to update each record in db instead of updating them together - update_batch replaces values in multiple rows which fulfills conditions so there is possibility to update also incorrect rows (check example in documentation). So better idea is to update each single product using it's ID. It could look like that:

Model

```<code>function update_stok($data, $id_product){
    $this->db->where('id_product', $id_product);
    return $this->db->update($this->table, $data);
}
</code>```

Controller

```<code>function updating_stock(){
    $ids = $this->input->post('id_product');
    $stok = $this->input->post('update_stock');
    $user = $this->data['id'];

    foreach($ids as $key => $id_product) {
        $data = array(
            'stok'      => $stok[$key],
            'diubah'    => $user,
            'tgl_diubah'=> date('Y:m:d H:i:s'),
        );
        $this->stok_adm->update_stok($data, $id_product);
    }
}
</code>```

Body:
I have been looking for ways but find suitable speckle. so, i have table product and I show along with his ID. and I put in a form. and when I press the update button then what had been updated in the form of their corresponding id.

my view :

<?php echo form_open('stock/updating_stock');?>

    <?php foreach($critical_plus_warning as $data){?>
      <input type="hidden" name="id_product[]" value="<?php echo $data->id_product;?>">

<?php echo $data->product_name;?> <input type="text" class="pull-right" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stock?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "$stock";
      }else{
        echo "$stock";
      }
      ?>

<?php $limited_word = word_limiter($data->product_name,3); echo $limited_word; ?> <input class="pull-right" type="text" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stocks?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "$stock";
      }else{
        echo "$stock";
      }
      ?>

    <?php }?>

<button type="submit" name="submit" class="btn btn-success">Save data</button>

  <?php echo form_close();?>

and my controller :

function updating_stock(){

    $id = $this->input->post('id_product');
    $stok = $this->input->post('update_stock');
    $user = $this->data['id'];

    for($i=0;$i<count($id);$i++){
    $data = array(
       array(
        'id'        => $id,
        'stok'      => $stok,
        'diubah'    => $user,
        'tgl_diubah'=> date('Y:m:d H:i:s'),
        ),
    );
    }
    //print_r($data);
    $this->stok_adm->update_stok($data);
}

and my models :

function update_stok($data){
    $this->db->update_batch($this->table, $data,'id_product');
    return $this->db->affected_rows();
}

Body:
I think in your example update_batch will generate incorrect query beacues you need to update each record in db instead of updating them together - update_batch replaces values in multiple rows which fulfills conditions so there is possibility to update also incorrect rows (check example in documentation). So better idea is to update each single product using it's ID. It could look like that:

Model

function update_stok($data, $id_product){
    $this->db->where('id_product', $id_product);
    return $this->db->update($this->table, $data);
}

Controller

function updating_stock(){
    $ids = $this->input->post('id_product');
    $stok = $this->input->post('update_stock');
    $user = $this->data['id'];

    foreach($ids as $key => $id_product) {
        $data = array(
            'stok'      => $stok[$key],
            'diubah'    => $user,
            'tgl_diubah'=> date('Y:m:d H:i:s'),
        );
        $this->stok_adm->update_stok($data, $id_product);
    }
}


问:
Find remaining outer rectangles from Rectangle.Intersection
I have an outer rectangle and a rectangle inside. How can I return all remaining rectangle after cut of intersecting rectangle?</p>

答:
I have created this function that return a List excluding the intersecting one.</p>

```<code> private IEnumerable<Rectangle> GetExternalRectangles(Rectangle surface, Rectangle test)
    {
        var result = new List<Rectangle>();

        if (!test.IntersectsWith(surface)) return new List<Rectangle> { surface };
        #region Top and Bottom

        if (test.Top>surface.Top && test.Bottom < surface.Bottom) // test inside surface vertically
        {
            result.Add(new Rectangle(surface.Location, new Size(surface.Width, test.Top - surface.Top)));
            result.Add(new Rectangle(new Point(surface.Left,test.Bottom), new Size(surface.Width, surface.Bottom-test.Bottom)));
        }
        if (test.Top > surface.Top && test.Bottom > surface.Bottom) // test inside surface vertically, overflow bottom
        {
            result.Add(new Rectangle(surface.Location, new Size(surface.Width, test.Top - surface.Top)));
            //result.Add(new Rectangle(new Point(surface.Left,test.Bottom), new Size(surface.Width, surface.Bottom-test.Bottom)));
        }
        if (test.Top < surface.Top && test.Bottom < surface.Bottom) // test inside surface vertically, overflow top
        {
            //result.Add(new Rectangle(surface.Location, new Size(surface.Width, test.Top - surface.Top)));
            result.Add(new Rectangle(new Point(surface.Left, test.Bottom), new Size(surface.Width, surface.Bottom - test.Bottom)));
        }

        #endregion

        #region Lateral
        if (test.Left > surface.Left && test.Right < surface.Right) // test inside surface horizontally
        {
            result.Add(new Rectangle(new Point(surface.Left,Math.Max(surface.Top,test.Top)), new Size(test.Left-surface.Left, Math.Min(surface.Bottom, test.Bottom)- Math.Max(surface.Top, test.Top))));
            result.Add(new Rectangle(new Point(test.Right, Math.Max(surface.Top, test.Top)), new Size(surface.Right - test.Right, Math.Min(surface.Bottom, test.Bottom) - Math.Max(surface.Top, test.Top))));
        }
        if (test.Left > surface.Left && test.Right > surface.Right) // test inside surface horizontally, overflow right
        {
            result.Add(new Rectangle(new Point(surface.Left, Math.Max(surface.Top, test.Top)), new Size(test.Left - surface.Left, Math.Min(surface.Bottom, test.Bottom) - Math.Max(surface.Top, test.Top))));
            //result.Add(new Rectangle(new Point(test.Right, Math.Max(surface.Top, test.Top)), new Size(surface.Right - test.Right, Math.Min(surface.Bottom, test.Bottom) - Math.Max(surface.Top, test.Top))));
        }
        if (test.Left < surface.Left && test.Right < surface.Right) // test inside surface horizontally, overflow left
        {
            //result.Add(new Rectangle(new Point(surface.Left, Math.Max(surface.Top, test.Top)), new Size(test.Left - surface.Left, Math.Min(surface.Bottom, test.Bottom) - Math.Max(surface.Top, test.Top))));
            result.Add(new Rectangle(new Point(test.Right, Math.Max(surface.Top, test.Top)), new Size(surface.Right - test.Right, Math.Min(surface.Bottom, test.Bottom) - Math.Max(surface.Top, test.Top))));
        }
        #endregion
        return result;
    }
</code>```

Body:
I have created this function that return a List excluding the intersecting one.

 private IEnumerable<Rectangle> GetExternalRectangles(Rectangle surface, Rectangle test)
    {
        var result = new List<Rectangle>();

        if (!test.IntersectsWith(surface)) return new List<Rectangle> { surface };
        #region Top and Bottom

        if (test.Top>surface.Top && test.Bottom < surface.Bottom) // test inside surface vertically
        {
            result.Add(new Rectangle(surface.Location, new Size(surface.Width, test.Top - surface.Top)));
            result.Add(new Rectangle(new Point(surface.Left,test.Bottom), new Size(surface.Width, surface.Bottom-test.Bottom)));
        }
        if (test.Top > surface.Top && test.Bottom > surface.Bottom) // test inside surface vertically, overflow bottom
        {
            result.Add(new Rectangle(surface.Location, new Size(surface.Width, test.Top - surface.Top)));
            //result.Add(new Rectangle(new Point(surface.Left,test.Bottom), new Size(surface.Width, surface.Bottom-test.Bottom)));
        }
        if (test.Top < surface.Top && test.Bottom < surface.Bottom) // test inside surface vertically, overflow top
        {
            //result.Add(new Rectangle(surface.Location, new Size(surface.Width, test.Top - surface.Top)));
            result.Add(new Rectangle(new Point(surface.Left, test.Bottom), new Size(surface.Width, surface.Bottom - test.Bottom)));
        }

        #endregion

        #region Lateral
        if (test.Left > surface.Left && test.Right < surface.Right) // test inside surface horizontally
        {
            result.Add(new Rectangle(new Point(surface.Left,Math.Max(surface.Top,test.Top)), new Size(test.Left-surface.Left, Math.Min(surface.Bottom, test.Bottom)- Math.Max(surface.Top, test.Top))));
            result.Add(new Rectangle(new Point(test.Right, Math.Max(surface.Top, test.Top)), new Size(surface.Right - test.Right, Math.Min(surface.Bottom, test.Bottom) - Math.Max(surface.Top, test.Top))));
        }
        if (test.Left > surface.Left && test.Right > surface.Right) // test inside surface horizontally, overflow right
        {
            result.Add(new Rectangle(new Point(surface.Left, Math.Max(surface.Top, test.Top)), new Size(test.Left - surface.Left, Math.Min(surface.Bottom, test.Bottom) - Math.Max(surface.Top, test.Top))));
            //result.Add(new Rectangle(new Point(test.Right, Math.Max(surface.Top, test.Top)), new Size(surface.Right - test.Right, Math.Min(surface.Bottom, test.Bottom) - Math.Max(surface.Top, test.Top))));
        }
        if (test.Left < surface.Left && test.Right < surface.Right) // test inside surface horizontally, overflow left
        {
            //result.Add(new Rectangle(new Point(surface.Left, Math.Max(surface.Top, test.Top)), new Size(test.Left - surface.Left, Math.Min(surface.Bottom, test.Bottom) - Math.Max(surface.Top, test.Top))));
            result.Add(new Rectangle(new Point(test.Right, Math.Max(surface.Top, test.Top)), new Size(surface.Right - test.Right, Math.Min(surface.Bottom, test.Bottom) - Math.Max(surface.Top, test.Top))));
        }
        #endregion
        return result;
    }


问:
Start Async Task within a worker thread
I have two questions:

Can we start/execute an Async Task within a worker thread?

If yes, the methods onPreExecute(), onProgressUpdate(Progress...) and onPostExecute(Result) are invoked on the UI thread?

I wanna know that because I have a TCP connection running on a worker thread and when a packet is received I wanna start a new thread to make the parse of this packet and after that refresh some data structures on the UI thread.

Thanks in advance!

答:
In simple, we can start AsyncTask in a worker. You can just execute a AsyncTask in a new Thread, very simple.
The reason is in the Android source code:
[clike here]</p>

```<code>private static class InternalHandler extends Handler {
    public InternalHandler() {
        super(Looper.getMainLooper());
    }
}
</code>```

Title: Start Async Task within a worker thread

Body:
In simple, we can start AsyncTask in a worker. You can just execute a AsyncTask in a new Thread, very simple.
The reason is in the Android source code:
[clike here]

private static class InternalHandler extends Handler {
    public InternalHandler() {
        super(Looper.getMainLooper());
    }
}


问:
What is cURL in PHP?
In PHP, I see the word cURL in many PHP projects.  What is it?  How does it work?

Reference Link: cURL

答:
cURL

cURL is a way you can hit a URL from your code to get a HTML response from it.

It's used for command line cURL from the PHP language.

cURL is a library that lets you make HTTP requests in PHP.

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close().

Sample Code

```<code>// error reporting
error_reporting(E_ALL);
ini_set("display_errors", 1);

//setting url
$url = 'http://example.com/api';

//data
$data = array("message" => "Hello World!!!");

try {
    $ch = curl_init($url);
    $data_string = json_encode($data);

    if (FALSE === $ch)
        throw new Exception('failed to initialize');

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

        $output = curl_exec($ch);

    if (FALSE === $output)
        throw new Exception(curl_error($ch), curl_errno($ch));

    // ...process $output now
} catch(Exception $e) {

    trigger_error(sprintf(
        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage()),
        E_USER_ERROR);
}
</code>```

For more information, please check -

cURL

cURL Functions

ContentLicense: CC BY-SA 4.0

Title: What is cURL in PHP?

Body:
cURL

cURL is a way you can hit a URL from your code to get a HTML response from it.

It's used for command line cURL from the PHP language.

cURL is a library that lets you make HTTP requests in PHP.

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close().

Sample Code

// error reporting
error_reporting(E_ALL);
ini_set("display_errors", 1);

//setting url
$url = 'http://example.com/api';

//data
$data = array("message" => "Hello World!!!");

try {
    $ch = curl_init($url);
    $data_string = json_encode($data);

    if (FALSE === $ch)
        throw new Exception('failed to initialize');

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

        $output = curl_exec($ch);

    if (FALSE === $output)
        throw new Exception(curl_error($ch), curl_errno($ch));

    // ...process $output now
} catch(Exception $e) {

    trigger_error(sprintf(
        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage()),
        E_USER_ERROR);
}

For more information, please check -

cURL

cURL Functions