问:
Map and lambda function
I'm currently doing a hackerrank problem.

The objective is to find the cubes of the first n Fibonacci numbers. The user inputs n. So for example, if the user inputs 5, the output should be [0, 1, 1, 8, 27], since the first five Fibonacci numbers are [0, 1, 1, 2, 3].

I've written the following code:

```<code>cube = lambda x: x**3 # complete the lambda function

def fibonacci(n):
    # return a list of fibonacci numbers
    initiallist = []
    for i in range(n):
        if i < 2:
            initiallist += [i]
        else:
            initiallist += [initiallist[-1] + initiallist[-2]]
    return initiallist
</code>```

I'm given the following code (which I cannot edit):

```<code>if __name__ == '__main__':
    n = int(input())
    print(map(cube, fibonacci(n)))
</code>```

The problem is that my code fails the test cases because it returns a map object instead of a list. How can I ensure it returns a list instead?

答:
This should give you more than you need. I added a few extra bits like looping  and input validation just in case. Hope this helps

General Formula
F(n) = F(n-1) + F(n-2)

Get User input

```<code>    def get_user_input():
        while True:
            try:
                nums_in_list = int(input("Enter the amout of numbers you want in the fibonacci list: "))

                if nums_in_list < 1:
                    print("Please enter a number greater than 0.")
                    continue

                return nums_in_list

            except ValueError:
                print ("Please enter an integer.")
</code>```

Create Fabonacci List based on user input

```<code>    def genterate_list(user_input):
        fab_list = [0]
        if user_input == 1:
            return fab_list
        elif user_input == 2:
            fab_list.append(1)
            return fab_list
        else:
            count = 1
            while user_input > count:
                if count == 2:
                    fab_list.append(1)
                elif count > 2:
                    fab_list.append(fab_list[count - 2] + fab_list[count - 3])

                count += 1
        return fab_list
</code>```

Extra Add in to loop the program

```<code>def loop_program():
    while True:
        opts = ['y', 'Y', 'N', 'n']

        loop = input("Would you like to run the program again (y/n): ")

        if loop not in opts:
            print("Please select (y/n): ")
            continue
        elif loop == 'N' or loop == 'n':
            return "N"
        else:
            return "Y"
</code>```

Main section:
Calls the functions defined above
Displays the outputs.

```<code>    if __name__ == '__main__':
        while True:
            original = genterate_list(get_user_input())
            print("Original Fabonacci")

            for x in original:
                print(x)

            cube_funtion = lambda value : value ** 3
            cube_result = map(cube_funtion, original)
            print("Cubed Values")
            list(map(print, cube_result))
            if loop_program() == "N":
                break
</code>```

Title: Map and lambda function

Body:
I'm currently doing a hackerrank problem.

The objective is to find the cubes of the first n Fibonacci numbers. The user inputs n. So for example, if the user inputs 5, the output should be [0, 1, 1, 8, 27], since the first five Fibonacci numbers are [0, 1, 1, 2, 3].

I've written the following code:

cube = lambda x: x**3 # complete the lambda function

def fibonacci(n):
    # return a list of fibonacci numbers
    initiallist = []
    for i in range(n):
        if i < 2:
            initiallist += [i]
        else:
            initiallist += [initiallist[-1] + initiallist[-2]]
    return initiallist

I'm given the following code (which I cannot edit):

if __name__ == '__main__':
    n = int(input())
    print(map(cube, fibonacci(n)))

The problem is that my code fails the test cases because it returns a map object instead of a list. How can I ensure it returns a list instead?

Body:
This should give you more than you need. I added a few extra bits like looping  and input validation just in case. Hope this helps

General Formula
F(n) = F(n-1) + F(n-2)

Get User input

    def get_user_input():
        while True:
            try:
                nums_in_list = int(input("Enter the amout of numbers you want in the fibonacci list: "))

                if nums_in_list < 1:
                    print("Please enter a number greater than 0.")
                    continue

                return nums_in_list

            except ValueError:
                print ("Please enter an integer.")

Create Fabonacci List based on user input

    def genterate_list(user_input):
        fab_list = [0]
        if user_input == 1:
            return fab_list
        elif user_input == 2:
            fab_list.append(1)
            return fab_list
        else:
            count = 1
            while user_input > count:
                if count == 2:
                    fab_list.append(1)
                elif count > 2:
                    fab_list.append(fab_list[count - 2] + fab_list[count - 3])

                count += 1
        return fab_list

Extra Add in to loop the program

def loop_program():
    while True:
        opts = ['y', 'Y', 'N', 'n']

        loop = input("Would you like to run the program again (y/n): ")

        if loop not in opts:
            print("Please select (y/n): ")
            continue
        elif loop == 'N' or loop == 'n':
            return "N"
        else:
            return "Y"

Main section:
Calls the functions defined above
Displays the outputs.

    if __name__ == '__main__':
        while True:
            original = genterate_list(get_user_input())
            print("Original Fabonacci")

            for x in original:
                print(x)

            cube_funtion = lambda value : value ** 3
            cube_result = map(cube_funtion, original)
            print("Cubed Values")
            list(map(print, cube_result))
            if loop_program() == "N":
                break


来源: stackexchange

问:
Calling StoredProcedure using JPA in Spring Boot
I am trying to call a stored procedure, which is built in mysql, in my Spring boot app using JPA. My stored procedure returns the result which cant be contain in single model as it fetches data from combination of tables.
I can do this with "call " but i guess that is not JPA's way. COuld you please let me know what is the best way to do it?</p>

答:
In case you're using plain JPA you need to do a native query call. Something like below.

```<code>Query q = em.createNativeQuery("select my_store_pro(?, ?)");
List<Object[]> results = q.getResultList();

for (Object[] a : results) {
    System.out.println("result " + a[0] + " " + a[1]);
}
</code>```

If you're using Spring Data repositories then you want something like below.

```<code>@Query(nativeQuery = true, value = "select my_store_pro(?, ?)")
Date callMyStoreProc(int val1, int val2);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In case you're using plain JPA you need to do a native query call. Something like below.

Query q = em.createNativeQuery("select my_store_pro(?, ?)");
List<Object[]> results = q.getResultList();

for (Object[] a : results) {
    System.out.println("result " + a[0] + " " + a[1]);
}

If you're using Spring Data repositories then you want something like below.

@Query(nativeQuery = true, value = "select my_store_pro(?, ?)")
Date callMyStoreProc(int val1, int val2);


问:
TypeScript Error: Property '0' is missing in type
I have my interface like this

export interface Details {
  Name: [{
    First: string;
    Last: string;
  }];
}
```

<p>I have an observable config variable:<br/></p>

<p><code>Configuration: KnockoutObservable<Details> = ko.observable<Details>();</code></p>

<p>and I would like to assign it a value in the constructor as follows: </p>

<pre class="lang-js prettyprint-override"><code>config = {
  Name: [{
    First: "ABC",
    Last: "DEF"
  },
  {
    First: "LMN",
    Last: "XYZ"
  }]
};

this.Configuration(config);
</code>```

and I am getting an error:

```<code>Types of property 'Name' is incompatible and property '0' is missing in type.
Type '{ First:string; Last:string; }[]' is not assignable to
type '[{ First: string; Last:string; }]'
</code>```

I don't have control on changing the interface as it is being used elsewhere.
 What is the correct way to initialize this config variable ?

Thanks in advance.

答:
In this type definition:

```<code>interface Details {
  Name: [{
    First: string;
    Last: string;
  }];
}
</code>```

Name is not an array at compile-time. It's a tuple with one element. Tuples in Typescript are allowed to have extra elements, but they can't have missing elements. As a 1-tuple, Name is essentially an array which must have at least one element.

However, in this value:

```<code>const config = {
  Name: [{
    First: "ABC",
    Last: "DEF"
  },
  {
    First: "LMN",
    Last: "XYZ"
  }]
};
</code>```

Since there is no explicit typing, the Name property here defaults to array type. Arrays can have any number of elements, including zero - which doesn't fit in a 1-tuple. Hence your error.

Your error can be fixed by giving the compiler a hint that your literal is actually a tuple:

```<code>const config: Details = { Name: [{...}, {...}] };
</code>```

If you do need to be able to take in an array of names, you'll have to do some casting, maybe something like this:

```<code>if (names.length > 0) {
  const config = {
    Name: names as Details['Name']
  };
  Configuration(config);
}
</code>```

(You could remove the if check if you can determine that the tuple was simply a mistake by whoever wrote the typings.)

Tuples reference:
https://www.typescriptlang.org/docs/handbook/basic-types.html

ContentLicense: CC BY-SA 4.0

Body:
I have my interface like this

export interface Details {
  Name: [{
    First: string;
    Last: string;
  }];
}

I have an observable config variable:

Configuration: KnockoutObservable = ko.observable();

and I would like to assign it a value in the constructor as follows:

config = {
  Name: [{
    First: "ABC",
    Last: "DEF"
  },
  {
    First: "LMN",
    Last: "XYZ"
  }]
};

this.Configuration(config);

and I am getting an error:

Types of property 'Name' is incompatible and property '0' is missing in type.
Type '{ First:string; Last:string; }[]' is not assignable to
type '[{ First: string; Last:string; }]'

I don't have control on changing the interface as it is being used elsewhere.
 What is the correct way to initialize this config variable ?

Thanks in advance.

Body:
In this type definition:

interface Details {
  Name: [{
    First: string;
    Last: string;
  }];
}

Name is not an array at compile-time. It's a tuple with one element. Tuples in Typescript are allowed to have extra elements, but they can't have missing elements. As a 1-tuple, Name is essentially an array which must have at least one element.

However, in this value:

const config = {
  Name: [{
    First: "ABC",
    Last: "DEF"
  },
  {
    First: "LMN",
    Last: "XYZ"
  }]
};

Since there is no explicit typing, the Name property here defaults to array type. Arrays can have any number of elements, including zero - which doesn't fit in a 1-tuple. Hence your error.

Your error can be fixed by giving the compiler a hint that your literal is actually a tuple:

const config: Details = { Name: [{...}, {...}] };

If you do need to be able to take in an array of names, you'll have to do some casting, maybe something like this:

if (names.length > 0) {
  const config = {
    Name: names as Details['Name']
  };
  Configuration(config);
}

(You could remove the if check if you can determine that the tuple was simply a mistake by whoever wrote the typings.)

Tuples reference:
https://www.typescriptlang.org/docs/handbook/basic-types.html


问:
Android RecyclerView: IndexOutOfBoundsException: Inconsistency detected
I have a problem with my RecyclerView, I learnt here that bug had been fixed and that I should make sure that I'm inserting data on main thread and calling apropriate notify. I did that, but I am still getting this exception.

onLoadFinisher method (I am using loaders to load more data)

```<code>@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data)
{
    switch (loader.getId())
    {
        case UP_LOADER_ID:
            Log.d("Adapter", "Thread: "+Thread.currentThread().getName());
            days.put(firstDate, data);
            notifyItemRangeInserted(0, data.getCount()+1);
            loadingUp = false;
            break;

        case DOWN_LOADER_ID:
            days.put(lastDate, data);
            notifyItemRangeInserted(getItemCount(), data.getCount()+1);
            loadingDown = false;
            break;

        default:
            throw new IllegalArgumentException("Unknown loader id: " + loader.getId());
    }
}
</code>```

log

```<code>I/OpenGLRenderer: Initialized EGL, version 1.4
D/Adapter: Thread: main
D/Adapter: Thread: main
D/Adapter: Thread: main
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: net.antilopa, PID: 6406
                  java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{fa4fb40 position=42 id=-1497045600000, oldPos=21, pLpos:21 scrap [attachedScrap] tmpDetached not recyclable(1) no parent}
                      at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:5220)
                      at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5402)
                      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5363)
                      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5359)
                      at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2141)
                      at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1525)
                      at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1488)
                      at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:585)
                      at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3457)
                      at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3252)
                      at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3767)
                      at android.view.View.layout(View.java:16722)
                      at android.view.ViewGroup.layout(ViewGroup.java:5438)
</code>```

答:
You can replace getItemCount() by getItemCount()-1, because getItemCount() returns number of counts but index value is getItemCount()-1.

```<code> case DOWN_LOADER_ID:
        days.put(lastDate, data);
        notifyItemRangeInserted(data.getCount()-1, data.getCount()+1);
        loadingDown = false;
        break;
</code>```

Body:
I have a problem with my RecyclerView, I learnt here that bug had been fixed and that I should make sure that I'm inserting data on main thread and calling apropriate notify. I did that, but I am still getting this exception.

onLoadFinisher method (I am using loaders to load more data)

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data)
{
    switch (loader.getId())
    {
        case UP_LOADER_ID:
            Log.d("Adapter", "Thread: "+Thread.currentThread().getName());
            days.put(firstDate, data);
            notifyItemRangeInserted(0, data.getCount()+1);
            loadingUp = false;
            break;

        case DOWN_LOADER_ID:
            days.put(lastDate, data);
            notifyItemRangeInserted(getItemCount(), data.getCount()+1);
            loadingDown = false;
            break;

        default:
            throw new IllegalArgumentException("Unknown loader id: " + loader.getId());
    }
}

log

I/OpenGLRenderer: Initialized EGL, version 1.4
D/Adapter: Thread: main
D/Adapter: Thread: main
D/Adapter: Thread: main
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: net.antilopa, PID: 6406
                  java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{fa4fb40 position=42 id=-1497045600000, oldPos=21, pLpos:21 scrap [attachedScrap] tmpDetached not recyclable(1) no parent}
                      at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:5220)
                      at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5402)
                      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5363)
                      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5359)
                      at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2141)
                      at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1525)
                      at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1488)
                      at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:585)
                      at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3457)
                      at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3252)
                      at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3767)
                      at android.view.View.layout(View.java:16722)
                      at android.view.ViewGroup.layout(ViewGroup.java:5438)

Body:
You can replace getItemCount() by getItemCount()-1, because getItemCount() returns number of counts but index value is getItemCount()-1.

 case DOWN_LOADER_ID:
        days.put(lastDate, data);
        notifyItemRangeInserted(data.getCount()-1, data.getCount()+1);
        loadingDown = false;
        break;


问:
Another annoying JavaScript click event issue
```<code>var Home = document.getElementById("home");
var Page = document.getElementById("page");

Home.onclick = function(){Page.innerHTML = "I TYPED A BUNCH OF HTML HERE";};
</code>```

Why is this not working? Nothing happens to the div id="page" when I click the div id="home" element.

Note: This is plain Javascript linked between script tags in a .js document

Edit: I tried using the Event Listener method.

```<code>Home.addEventListener("click", function(){Page.innerHTML = "

ALL THE HTML HERE

";
});
</code>```

Still, nothing happens to the div id "page" when the div id "home" is clicked.
Tried running in IE and Chrome.

答:
This is plain Javascript linked between script tags in a .js document

If it is a .js document, there is no need of  tag.

Try the below code snippet:

 var Home = document.getElementById("home");
 var Page = document.getElementById("page");

 Home.onclick = function(){
 Page.innerHTML = "I TYPED A BUNCH OF HTML HERE";
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div id="home">  Home </div>
  <div id="page">   </div></code>```

You should concatenate your text to the element's innerHTML instead of assigning.

Body:
var Home = document.getElementById("home");
var Page = document.getElementById("page");

Home.onclick = function(){Page.innerHTML = "I TYPED A BUNCH OF HTML HERE";};

Why is this not working? Nothing happens to the div id="page" when I click the div id="home" element.

Note: This is plain Javascript linked between script tags in a .js document

Edit: I tried using the Event Listener method.

Home.addEventListener("click", function(){Page.innerHTML = "

ALL THE HTML HERE

";
});

Still, nothing happens to the div id "page" when the div id "home" is clicked.
Tried running in IE and Chrome.

Body:
This is plain Javascript linked between script tags in a .js document

If it is a .js document, there is no need of <script></script> tag.

Try the below code snippet:

 var Home = document.getElementById("home");
 var Page = document.getElementById("page");

 Home.onclick = function(){
 Page.innerHTML = "I TYPED A BUNCH OF HTML HERE";
};

  <div id="home">  Home </div>
  <div id="page">   </div>

You should concatenate your text to the element's innerHTML instead of assigning.


问:
Issue with low energy bluetooth adapter for tizen
I have been able to access the default bluetooth adapter using var adapter = tizen.bluetooth.getDefaultAdapter(); and it works fine as far as now. But when I use var adapter = tizen.bluetooth.getLEAdapter(); for low energy bluetooth adapter I'm not getting the required bluetooth adapter object, i.e, they do not have any parameters like name, mac address as in the case of default adapter. And when I invoke the adapter.startScan() function of LEAdapter it does not return any results. I assume all the latest smartphones support the low energy adapter as well.

I have included the following previlages in the manifest.

<tizen:privilege name="http://tizen.org/privilege/bluetooth.gap"/>
 <tizen:privilege name="http://tizen.org/privilege/bluetooth.admin"/>
 <tizen:privilege name="http://tizen.org/privilege/bluetooth.spp"/>
 <tizen:privilege name="http://tizen.org/privilege/bluetooth.health"/>

What am I doing wrong here?

答:
getLEAdapter() Gets the default Low Energy Bluetooth adapter. You may try to Catch the exception:

```<code>try
{
   var adapter = tizen.bluetooth.getLEAdapter();
}
catch (err)
{
   console.log(err.name + ": " + err.message);
}
</code>```

Exceptions: WebAPIException thrown from getLEAdapter()

SecurityError, if the application does not have the privilege to call this method.

NotSupportedError, if the feature is not supported.

UnknownError, if any other error occurs.

To check if this method is supported or not, use tizen.systeminfo.getCapability("http://tizen.org/feature/network.bluetooth.le").

```<code>try
{
   /* Checks if a device supports bluetooth API */
   var bluetooth = tizen.systeminfo.getCapability("http://tizen.org/feature/network.bluetooth.le");
   console.log(" Bluetooth = " + bluetooth);
}
catch (error)
{
   console.log("Error name: " + error.name + ", message: " + error.message);

}
</code>```

Resource Links to see:
BluetoothManager::getLEAdapter

SystemInfo::getCapability

Body:
getLEAdapter() Gets the default Low Energy Bluetooth adapter. You may try to Catch the exception:

try
{
   var adapter = tizen.bluetooth.getLEAdapter();
}
catch (err)
{
   console.log(err.name + ": " + err.message);
}

Exceptions: WebAPIException thrown from getLEAdapter()

SecurityError, if the application does not have the privilege to call this method.

NotSupportedError, if the feature is not supported.

UnknownError, if any other error occurs.

To check if this method is supported or not, use tizen.systeminfo.getCapability("http://tizen.org/feature/network.bluetooth.le").

try
{
   /* Checks if a device supports bluetooth API */
   var bluetooth = tizen.systeminfo.getCapability("http://tizen.org/feature/network.bluetooth.le");
   console.log(" Bluetooth = " + bluetooth);
}
catch (error)
{
   console.log("Error name: " + error.name + ", message: " + error.message);

}

Resource Links to see:
BluetoothManager::getLEAdapter

SystemInfo::getCapability


问:
Check if DataGridView Contains specific word
I'm currently doing a school project and I need to know how to check if in any row of the datagridview contains a specific word in any column, and hide the rows that don't contain that word, in any column.
I have no code yet, just the datagridview and the textbox on the form.</p>

答:
You only want to filter when the textbox is NOT not null or empty string(make sure you trim the string to remove leading and trailing white space).

```<code> (dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("columnname like '%{0}%'", textBoxFilter.Text);
</code>```

Filter expressions

columnname like '%{0}%' means  columnname contains specific word/string.

columnname not like '%{0}% means NOT contains

Body:
You only want to filter when the textbox is NOT not null or empty string(make sure you trim the string to remove leading and trailing white space).

 (dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("columnname like '%{0}%'", textBoxFilter.Text);

Filter expressions

columnname like '%{0}%' means  columnname contains specific word/string.

columnname not like '%{0}% means NOT contains


问:
Loading Integer Array from xml
I have an integer array in an xml file as follows

```<code><integer-array name="myArray">
    <item>@drawable/pic1</item>
    <item>@drawable/pic2</item>
    <item>@drawable/pic3</item>
    <item>@drawable/pic4</item>
</integer-array>
</code>```

In the code, I am trying to load this array

```<code>int[] picArray = getResources().getIntArray(R.array.myArray);
</code>```

The expected result is

```<code>R.drawable.pic1, R.drawable.pic2,R.drawable.pic3
</code>```

but instead it is coming with an array with all values as zero

Can anyone tell me what is wrong?

答:
It looks like you might be talking about typed arrays?

if so a typed array should look like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="icons">
        <item>@drawable/home</item>
        <item>@drawable/settings</item>
        <item>@drawable/logout</item>
    </array>
    <array name="colors">
        <item>#FFFF0000</item>
        <item>#FF00FF00</item>
        <item>#FF0000FF</item>
    </array>
</resources>
</code>```

Can you show us your actual xml file so we can help you?

EDIT: Yeah those are not integers. make it a resource array if you want to store resources.

Title: Loading Integer Array from xml

Body:
I have an integer array in an xml file as follows

<integer-array name="myArray">
    <item>@drawable/pic1</item>
    <item>@drawable/pic2</item>
    <item>@drawable/pic3</item>
    <item>@drawable/pic4</item>
</integer-array>

In the code, I am trying to load this array

int[] picArray = getResources().getIntArray(R.array.myArray);

The expected result is

R.drawable.pic1, R.drawable.pic2,R.drawable.pic3

but instead it is coming with an array with all values as zero

Can anyone tell me what is wrong?

Body:
It looks like you might be talking about typed arrays?

if so a typed array should look like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="icons">
        <item>@drawable/home</item>
        <item>@drawable/settings</item>
        <item>@drawable/logout</item>
    </array>
    <array name="colors">
        <item>#FFFF0000</item>
        <item>#FF00FF00</item>
        <item>#FF0000FF</item>
    </array>
</resources>

Can you show us your actual xml file so we can help you?

EDIT: Yeah those are not integers. make it a resource array if you want to store resources.

ContentLicense: CC BY-SA 2.5


问:
Update bootstrap Table when Click Edit Button in Codeigniter
Here. I have codeigniter update code, it also worked but the problem is when i click the Edit button did not parsing After space data.
(After space Words did not fetch in update model).
How can I solve this problem.

vvIncome.php view

$(document).on('click','.btn_edit', function(e) {
  $("#edit").val($(this).attr('edit_id'));
  $("#in_dis").val($(this).attr("in_dis"));
  $("#in_amnt").val($(this).attr('in_amnt'));
  $("#confirm-edit").modal({show:'true'});

});

$(document).on('click', '#btn-ys', function() {
var income_id = $('#edit').val();
var in_dis = $('#in_dis').val();
var in_amnt = $('#in_amnt').val();
var result{"income_id":income_id,"in_dis":in_dis,"in_amnt":in_amnt};

 $.ajax({
data:result,
type: "POST",
url:'<?php echo base_url(); ?>admin/income/editincome/'+income_id,
success: function(data){
$("#confirm-edit").modal('hide');
viewData();
     }
 });
});```
</div>
</div>
</p>

<p><strong>View PHP Code</strong>
</p>

```

 <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

EDIT CATEGORY

<form class="form-horizontal">

 <input type="text"class="form-control" id="in_dis" placeholder="description">

 <input type="number" class="form-control" id="in_amnt" placeholder="amount">

 <input type="hidden" class="form-control"     id="edit" placeholder="income_id">

 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
 <button type="button" id="btn-ys" class="btn btn-success">SUBMIT</button>

 </form>

```

<p>`
<strong>Income_resut.php</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><thead>
<tr>
<th ><center>DESCRIPTION</center></th>
<th ><center>AMOUNT</center></th>
<th ><center>EDIT</center></th>
<th ><center>DELETE</center></th>
</tr>
</thead>
<?php foreach ($incm as $in_key) { ?>
 <tr>
<td><center><?php echo $in_key->description;?></center></td>
<td><center><?php echo $in_key->amount;?></center></td>
<td>
<center><button type="button" title="edit" data-toggle="modal" edit_id=<?php echo $in_key->income_id;?> in_dis=<?php echo $in_key->description;?> in_amnt=<?php echo $in_key->amount;?>  class="btn btn-info btn_edit"><i class="fa fa-pencil"></i></button></center>
</td>
<td>
<center><button type="button" title="delete" data-toggle="modal" del_id=<?php echo $in_key->income_id;?> class="btn btn-danger btn-delete"><i class="fa fa-trash-o"></i></button></center>
</td>
<?php } ?>
 </table></code>```

`

income.php Controller

public function editincome($income_id)
{
$udata['income_id'] = $this->input->POST('income_id');
$udata['description'] = $this->input->POST('in_dis');
$udata['amount'] = $this->input->POST('in_amnt');
$update = $this->income_model>update_income_details($udata,$income_id);
 }```
</div>
</div>
</p>

<p><strong>Income_Model.php</strong> Model</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>public function update_income_details($udata,$income_id)
 {
 $this->db->from('income', $udata);
 $this->db->where('income_id',$income_id );
 return $this->db->update('income',$udata);
 }</code>```

This on view table
enter image description here

This is edit model
enter image description here

答:
Try changing to this,

for eg, in_dis=<?php echo $in_key->description;?> to data-in_dis="<?php echo rawurlencode($in_key->description); ?>"

then
$("#in_dis").val($(this).attr("in_dis")); to $("#in_dis").val(decodeURIComponent($(this).data("in_dis")));

Use .data() instead of .attr()

Let me know if it works for you.

Body:
Here. I have codeigniter update code, it also worked but the problem is when i click the Edit button did not parsing After space data.
(After space Words did not fetch in update model).
How can I solve this problem.

vvIncome.php view

$(document).on('click','.btn_edit', function(e) {
  $("#edit").val($(this).attr('edit_id'));
  $("#in_dis").val($(this).attr("in_dis"));
  $("#in_amnt").val($(this).attr('in_amnt'));
  $("#confirm-edit").modal({show:'true'});

});

$(document).on('click', '#btn-ys', function() {
var income_id = $('#edit').val();
var in_dis = $('#in_dis').val();
var in_amnt = $('#in_amnt').val();
var result{"income_id":income_id,"in_dis":in_dis,"in_amnt":in_amnt};

 $.ajax({
data:result,
type: "POST",
url:'<?php echo base_url(); ?>admin/income/editincome/'+income_id,
success: function(data){
$("#confirm-edit").modal('hide');
viewData();
     }
 });
});

View PHP Code

 <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

EDIT CATEGORY

<form class="form-horizontal">

 <input type="text"class="form-control" id="in_dis" placeholder="description">

 <input type="number" class="form-control" id="in_amnt" placeholder="amount">

 <input type="hidden" class="form-control"     id="edit" placeholder="income_id">

 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
 <button type="button" id="btn-ys" class="btn btn-success">SUBMIT</button>

 </form>

`
Income_resut.php

DESCRIPTION
AMOUNT
EDIT
DELETE

<?php foreach ($incm as $in_key) { ?>

<?php echo $in_key->description;?>
<?php echo $in_key->amount;?>

<button type="button" title="edit" data-toggle="modal" edit_id=<?php echo $in_key->income_id;?> in_dis=<?php echo $in_key->description;?> in_amnt=<?php echo $in_key->amount;?>  class="btn btn-info btn_edit"></button>

<button type="button" title="delete" data-toggle="modal" del_id=<?php echo $in_key->income_id;?> class="btn btn-danger btn-delete"></button>

<?php } ?>

`

income.php Controller

public function editincome($income_id)
{
$udata['income_id'] = $this->input->POST('income_id');
$udata['description'] = $this->input->POST('in_dis');
$udata['amount'] = $this->input->POST('in_amnt');
$update = $this->income_model>update_income_details($udata,$income_id);
 }

Income_Model.php Model

public function update_income_details($udata,$income_id)
 {
 $this->db->from('income', $udata);
 $this->db->where('income_id',$income_id );
 return $this->db->update('income',$udata);
 }

This on view table
enter image description here

This is edit model
enter image description here


问:
Cannot send new build to testers from expired TestFlight app
I have an issue with TestFlight: I let the expiry date passed by (60 days) and just uploaded a new build. I added all testers to it, but it didn’t notify of new update.

my testers can’t open the old testflight build on device to trigger an update, because it says it expired.

my testers can’t download from the initial email invite because it says app already accepted.

And when opening TestFlight, my app is missing and does not give my testers the opportunity to update.

Therefore, how do send a new build to testers for an app that expired?

Thanks!

答: Remove your internal testers and invite them again. An email would be generated on internal testers ID's  and have to accept it. Then enter  redeem code into the TestFlight App.


问:
Memory Management in Caffe2
I am new to caffe2 and I wanted to know how does the caffe2 framework stores the models in the CPU or the GPU memory and how that is maintained. I have tried reading its github code but nothing concrete so far. Thanks for the help :) :) </p>

答:
The models are stored using protobuf. The same as Caffe.

Check these out:

https://caffe2.ai/docs/tutorial-loading-pre-trained-models.html

https://caffe2.ai/docs/zoo.html

Title: Memory Management in Caffe2


问:
slickjs always show arrows
I'm trying to config slick.js to show arrows in any circumstance.

```<code>$('.slider-for').slick({
  slidesToShow: 1,
  slidesToScroll: 1,
  arrows: false,
  fade: true,
  asNavFor: '.slider-nav'
});
$('.slider-nav').slick({
  slidesToShow: 6,
  infinite: true,
  slidesToScroll: 1,
  asNavFor: '.slider-for',
  arrows: true,
  centerMode: false,
  focusOnSelect: true
});
</code>```

The problem is when my slider hasn't enough slides do show (in my case, 6)
If the slider has less than 6 slides, the arrows don't show up.

I know the plugin  works like that, but for other reasons, i need to always show the arrows.

Anyone had to deal with something like that before ?

Thanks.

答:
You can set slidesToShow to 0 if there is less than your default count of slides:

```<code>$(function() {
  var slides_count;
  slides_count = $('.slides .slide').length <= 5 ? 0 : 5;
  $('.slides').slick({
    slidesToShow: slides_count
  });
  if ($('.slides .slide').length <= 5) {
    return $('.slides .slick-next').addClass('slick-disabled').off('click');
  }
});

$('.slides').on('afterChange', function(slick) {
  if ($('.slides .slide').length <= 5) {
    return $(this).find('.slick-next').addClass('slick-disabled');
  }
});
</code>```

Title: slickjs always show arrows

Body:
I'm trying to config slick.js to show arrows in any circumstance.

$('.slider-for').slick({
  slidesToShow: 1,
  slidesToScroll: 1,
  arrows: false,
  fade: true,
  asNavFor: '.slider-nav'
});
$('.slider-nav').slick({
  slidesToShow: 6,
  infinite: true,
  slidesToScroll: 1,
  asNavFor: '.slider-for',
  arrows: true,
  centerMode: false,
  focusOnSelect: true
});

The problem is when my slider hasn't enough slides do show (in my case, 6)
If the slider has less than 6 slides, the arrows don't show up.

I know the plugin  works like that, but for other reasons, i need to always show the arrows.

Anyone had to deal with something like that before ?

Thanks.

Body:
You can set slidesToShow to 0 if there is less than your default count of slides:

$(function() {
  var slides_count;
  slides_count = $('.slides .slide').length <= 5 ? 0 : 5;
  $('.slides').slick({
    slidesToShow: slides_count
  });
  if ($('.slides .slide').length <= 5) {
    return $('.slides .slick-next').addClass('slick-disabled').off('click');
  }
});

$('.slides').on('afterChange', function(slick) {
  if ($('.slides .slide').length <= 5) {
    return $(this).find('.slick-next').addClass('slick-disabled');
  }
});


问:
Insert into a MySQL table or update if exists
I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.

For example:

INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19);
```

Let’s say the unique key is ID, and in my Database, there is a row with ID = 1. In that case, I want to update that row with these values. Normally this gives an error.

If I use INSERT IGNORE it will ignore the error, but it still won’t update.

答:
Just because I was here looking for this solution but for updating from another identically-structured table (in my case website test DB to live DB):

```<code>INSERT  live-db.table1
SELECT  *
FROM    test-db.table1 t
ON DUPLICATE KEY UPDATE
        ColToUpdate1 = t.ColToUpdate1,
        ColToUpdate2 = t.ColToUpdate2,
        ...
</code>```

As mentioned elsewhere, only the columns you want to update need to be included  after ON DUPLICATE KEY UPDATE.

No need to list the columns in the INSERT or SELECT, though I agree it's probably better practice.

Body:
I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.

For example:

INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19);

Let’s say the unique key is ID, and in my Database, there is a row with ID = 1. In that case, I want to update that row with these values. Normally this gives an error.

If I use INSERT IGNORE it will ignore the error, but it still won’t update.

Body:
Just because I was here looking for this solution but for updating from another identically-structured table (in my case website test DB to live DB):

INSERT  live-db.table1
SELECT  *
FROM    test-db.table1 t
ON DUPLICATE KEY UPDATE
        ColToUpdate1 = t.ColToUpdate1,
        ColToUpdate2 = t.ColToUpdate2,
        ...

As mentioned elsewhere, only the columns you want to update need to be included  after ON DUPLICATE KEY UPDATE.

No need to list the columns in the INSERT or SELECT, though I agree it's probably better practice.


问:
Create table with firedac without SQL Script
Firedac library centralizes database behavior and have a lot of methods which works fine without care about the Database Type. Actually, using native drivers for most common databases, Firedac hides subtle differences on syntax allowing very flexible changes of database platform.

For example, generators and autoinc fields are easily detectable, CAST and parameters works fine allowing easy migration between databases.

How to use Firedac power to create New Table without instantiate FDQuery, which runs a SQL Script CREATE TABLE?

I hope to create any Object and, calling specific FieldByName for each Object Field, record it on database, but first I need to certify:

If Table is already created

If Field is already created

If record is already created

This is the code I have, so far:

```<code>TRecCustomer = record
  Id:integer;
  Name:String;
  Birthday:TDate;
end;

ICustomer = interface
  procedure setCustomerId(Value: Integer);
  procedure setCustomerName(Value: String);
  procedure SetBirthday(Value: TDate);
  procedure Post;
end;

TCustomer = class(TInterfacedObjet, ICustomer)
  CustomerObject=TRecCustomer;

  procedure setCustomerId(Value: Integer);
  procedure setCustomerName(Value: String);
  procedure SetBirthday(Value: TDate);
  procedure Post;
end;

procedure TCustomer.Post;
begin
  if not TableExists('Customer') then CreateTable('Customer');
  if not FieldExists('Name') then CreateField('Customer','name',ftString,[],40);
  if not FieldExists('Id') then CreateField('Customer','Id',ftInteger,[cAutoInc,cNotNull]);
  if not FieldExists('Birthday') then CreateField('Customer','birthday',ftDate);
end;
</code>```

Imagine the procedures

```<code>CreateTable(Tablename: String)
CreateField(FieldName: String; FieldType: TDataType; Constraints: TConstraints; Length: Integer = 0);
</code>```

where

```<code>TConstraints = set of (cAutoInc, cNotNull, cUnique, cEtc);
</code>```

I can do it for specific database, for example Sqlite or Firebird, but I don't know hou to do for any database using Firedac resources.

I found FireDAC.Comp.Client.TFDTable.CreateTable(ARecreate: Boolean = True;  AParts: TFDPhysCreateTableParts = [tpTable .. tpIndexes]), suggested by @Ondrej Kelle but I don't understood AParts usage. Somebody have an example? http://docwiki.embarcadero.com/Libraries/Berlin/en/FireDAC.Comp.Client.TFDTable.CreateTable

Thanks a lot.

答:
You can create a TFDTable object, describe your table at least by specifying TableName and adding field definitions in the FieldDefs collection. In practice you'll usually create also a primary key index for some field (that's what can be done by the AddIndex method). After you describe your table, call CreateTable method. A minimal example can be:

```<code>var
  Table: TFDTable;
begin
  Table := TFDTable.Create(nil);
  try
    Table.Connection := FDConnection1;
    { specify table name }
    Table.TableName := 'MyTable';
    { add some fields }
    Table.FieldDefs.Add('ID', ftInteger, 0, False);
    Table.FieldDefs.Add('Name', ftString, 50, False);
    { define primary key index }
    Table.AddIndex('pkMyTableID', 'ID', '', [soPrimary]);
    { and create it; when the first parameter is True, an existing one is dropped }
    Table.CreateTable(False);
  finally
    Table.Free;
  end;
end;
</code>```

Body:
Firedac library centralizes database behavior and have a lot of methods which works fine without care about the Database Type. Actually, using native drivers for most common databases, Firedac hides subtle differences on syntax allowing very flexible changes of database platform.

For example, generators and autoinc fields are easily detectable, CAST and parameters works fine allowing easy migration between databases.

How to use Firedac power to create New Table without instantiate FDQuery, which runs a SQL Script CREATE TABLE?

I hope to create any Object and, calling specific FieldByName for each Object Field, record it on database, but first I need to certify:

If Table is already created

If Field is already created

If record is already created

This is the code I have, so far:

TRecCustomer = record
  Id:integer;
  Name:String;
  Birthday:TDate;
end;

ICustomer = interface
  procedure setCustomerId(Value: Integer);
  procedure setCustomerName(Value: String);
  procedure SetBirthday(Value: TDate);
  procedure Post;
end;

TCustomer = class(TInterfacedObjet, ICustomer)
  CustomerObject=TRecCustomer;

  procedure setCustomerId(Value: Integer);
  procedure setCustomerName(Value: String);
  procedure SetBirthday(Value: TDate);
  procedure Post;
end;

procedure TCustomer.Post;
begin
  if not TableExists('Customer') then CreateTable('Customer');
  if not FieldExists('Name') then CreateField('Customer','name',ftString,[],40);
  if not FieldExists('Id') then CreateField('Customer','Id',ftInteger,[cAutoInc,cNotNull]);
  if not FieldExists('Birthday') then CreateField('Customer','birthday',ftDate);
end;

Imagine the procedures

CreateTable(Tablename: String)
CreateField(FieldName: String; FieldType: TDataType; Constraints: TConstraints; Length: Integer = 0);

where

TConstraints = set of (cAutoInc, cNotNull, cUnique, cEtc);

I can do it for specific database, for example Sqlite or Firebird, but I don't know hou to do for any database using Firedac resources.

I found FireDAC.Comp.Client.TFDTable.CreateTable(ARecreate: Boolean = True;  AParts: TFDPhysCreateTableParts = [tpTable .. tpIndexes]), suggested by @Ondrej Kelle but I don't understood AParts usage. Somebody have an example? http://docwiki.embarcadero.com/Libraries/Berlin/en/FireDAC.Comp.Client.TFDTable.CreateTable

Thanks a lot.

Body:
You can create a TFDTable object, describe your table at least by specifying TableName and adding field definitions in the FieldDefs collection. In practice you'll usually create also a primary key index for some field (that's what can be done by the AddIndex method). After you describe your table, call CreateTable method. A minimal example can be:

var
  Table: TFDTable;
begin
  Table := TFDTable.Create(nil);
  try
    Table.Connection := FDConnection1;
    { specify table name }
    Table.TableName := 'MyTable';
    { add some fields }
    Table.FieldDefs.Add('ID', ftInteger, 0, False);
    Table.FieldDefs.Add('Name', ftString, 50, False);
    { define primary key index }
    Table.AddIndex('pkMyTableID', 'ID', '', [soPrimary]);
    { and create it; when the first parameter is True, an existing one is dropped }
    Table.CreateTable(False);
  finally
    Table.Free;
  end;
end;


问:
Print Preview in ReportViewer display blank screen
Below is the code for the new page setting:

```<code>Dim newPageSettings As New PageSettings
newPageSettings.Margins = New Margins(20, 20, 20, 20)
newPageSettings.Landscape = True
Dim paperSize As PaperSize = New PaperSize()
paperSize.RawKind = PaperKind.A4
newPageSettings.PaperSize = paperSize
ReportViewer1.SetPageSettings(newPageSettings)
Me.ReportViewer1.RefreshReport()
</code>```

After I debug the system and click Print Preview in ReportViewer, the screen display as below:

I seriously don't know how this happen. Please help. Thanks.

答: I have already found a solution for above issue. Instead of using coding to setup setting for print preview, I change the Report Setting in rdlc. Please see below picture for more info:

Body:
Below is the code for the new page setting:

Dim newPageSettings As New PageSettings
newPageSettings.Margins = New Margins(20, 20, 20, 20)
newPageSettings.Landscape = True
Dim paperSize As PaperSize = New PaperSize()
paperSize.RawKind = PaperKind.A4
newPageSettings.PaperSize = paperSize
ReportViewer1.SetPageSettings(newPageSettings)
Me.ReportViewer1.RefreshReport()

After I debug the system and click Print Preview in ReportViewer, the screen display as below:

I seriously don't know how this happen. Please help. Thanks.


问:
jquery hover a list item and display image in another div, list is dynamic
I have a Wordpress test site and am using a plugin to list recent posts of a certain category, with thumbnails from the posts. I'd like to change it so that instead of each item in the list displaying a thumbnail next to it, only the item that is being hovered over shows its thumbnail, in a separate div.

I like one jquery solution I found at the post here by Shlomi Hassid. However, I can't adapt it, because he's using static images and the 'data-image' variable, which is not present in the list I'm working with. (His gives a fiddle example.)

It seems like I need to pass the data-image variable to the PHP to make it work, so I tried adding this to Hassid's script:

```<code>var htthumb = $(this).data('image');
    $.ajax({
        type: 'POST',
        url: 'http://testsite.humortimes.com/wp-content/plugins/recent-posts-widget-thumbs-mine/includes/widget.php',
        data: {'variable': htthumb},
    });
</code>```

...and in the PHP added $htimgsrc = $_POST['htthumb'];

Then, in the list class, added data-image=$htimgsrc before the PHP segment that creates the list:

```<code><li class="ht-menu-item" data-image=$htimgsrc <?php
</code>```

But the result just shows the data-image prefix as above with the variable name, not the source information that I need it to.

So, I guess I just need help with passing the variable from the js to the php, or an altogether different way to do this.

The page I'm working on, in a test site, is here.

Thanks for any help.

EDIT:

I've been rethinking this. I really only need the attachment image url placed it after "data-image=' for the js to find the image, so I don't need to get the variable from the js as above. So, during the 'have posts' loop in the plugin, I tried to grab the image url using wp_get_attachment_image( $thumb_id ), where $thumb_id is a variable from another PHP file in the plugin that is grabbing the thumbnail's id. This way, I figure, I can get the correct image. But that seems to return null for some reason.

Any ideas would be welcome. Thanks.

答:
Okay, gave up on trying to get the image attachment info from within the plugin (although that should be possible, since in its original form, it supplies the thumbnail next to each item on the list; but I wanted it in a separate div, and only while hovering over the list item). I decided I just needed to get the image's url with my own function. So, I found some useful code and adapted it, inserting this in the loop, and using the '$htthumb1' variable produced for the 'data-image=' url:</p>

```<code>if ( has_post_thumbnail() ) {
        the_post_thumbnail();
    } else {
        // No post thumbnail, try attachments instead.
        $attachment = get_children(
        array(
            'post_parent'    => get_the_ID(),
            'post_type'      => 'attachment',
            'post_mime_type' => 'image',
            'order'          => 'DESC',
            'numberposts'    => 1,
        )
    );
    if ( ! is_array( $attachment ) || empty( $attachment ) ) {
        return;
    }
    $attachment = current( $attachment );
    $htthumb1 = wp_get_attachment_thumb_url( $attachment->ID );
    };
</code>```

Body:
I have a Wordpress test site and am using a plugin to list recent posts of a certain category, with thumbnails from the posts. I'd like to change it so that instead of each item in the list displaying a thumbnail next to it, only the item that is being hovered over shows its thumbnail, in a separate div.

I like one jquery solution I found at the post here by Shlomi Hassid. However, I can't adapt it, because he's using static images and the 'data-image' variable, which is not present in the list I'm working with. (His gives a fiddle example.)

It seems like I need to pass the data-image variable to the PHP to make it work, so I tried adding this to Hassid's script:

var htthumb = $(this).data('image');
    $.ajax({
        type: 'POST',
        url: 'http://testsite.humortimes.com/wp-content/plugins/recent-posts-widget-thumbs-mine/includes/widget.php',
        data: {'variable': htthumb},
    });

...and in the PHP added $htimgsrc = $_POST['htthumb'];

Then, in the list class, added data-image=$htimgsrc before the PHP segment that creates the list:

<li class="ht-menu-item" data-image=$htimgsrc <?php

But the result just shows the data-image prefix as above with the variable name, not the source information that I need it to.

So, I guess I just need help with passing the variable from the js to the php, or an altogether different way to do this.

The page I'm working on, in a test site, is here.

Thanks for any help.

EDIT:

I've been rethinking this. I really only need the attachment image url placed it after "data-image=' for the js to find the image, so I don't need to get the variable from the js as above. So, during the 'have posts' loop in the plugin, I tried to grab the image url using wp_get_attachment_image( $thumb_id ), where $thumb_id is a variable from another PHP file in the plugin that is grabbing the thumbnail's id. This way, I figure, I can get the correct image. But that seems to return null for some reason.

Any ideas would be welcome. Thanks.

Body:
Okay, gave up on trying to get the image attachment info from within the plugin (although that should be possible, since in its original form, it supplies the thumbnail next to each item on the list; but I wanted it in a separate div, and only while hovering over the list item). I decided I just needed to get the image's url with my own function. So, I found some useful code and adapted it, inserting this in the loop, and using the '$htthumb1' variable produced for the 'data-image=' url:

if ( has_post_thumbnail() ) {
        the_post_thumbnail();
    } else {
        // No post thumbnail, try attachments instead.
        $attachment = get_children(
        array(
            'post_parent'    => get_the_ID(),
            'post_type'      => 'attachment',
            'post_mime_type' => 'image',
            'order'          => 'DESC',
            'numberposts'    => 1,
        )
    );
    if ( ! is_array( $attachment ) || empty( $attachment ) ) {
        return;
    }
    $attachment = current( $attachment );
    $htthumb1 = wp_get_attachment_thumb_url( $attachment->ID );
    };


问:
Join SQL tables
Suppose that in table "ab" I have the names of the students that get along from class "a" and class "b", identically I have table "ac" and "bc". What SQL query should I use in order to get all the combinations possible of students who can form groups (i.e. "get along together")? And how can i extend this to n classes?
For example: John from class a gets along with Jen from class b and Steff from class c, and Jen and Steff get along. Therefore John, Jen and Steff can form a group).</p>

答:
This query should return all students who can be in one group with John.

```<code>WITH ABC AS (SELECT AB.A, AB.B, AC.C FROM (SELECT * FROM AB
                        INNER JOIN BC
                        ON AB.B=BC.B)
         INNER JOIN AC
         ON (AC.C=BC.C AND AB.A=AC.A))
SELECT STUDENT FROM (
    SELECT AB.B STUDENT FROM ABC WHERE AB.A='John'
    UNION
    SELECT AC.C STUDENT FROM ABC WHERE AB.A='John')
GROUP BY STUDENT
</code>```

PS.: Written fast without any syntax check, hope you'll be able to bring this to work :)

Title: Join SQL tables

Body:
This query should return all students who can be in one group with John.

WITH ABC AS (SELECT AB.A, AB.B, AC.C FROM (SELECT * FROM AB
                        INNER JOIN BC
                        ON AB.B=BC.B)
         INNER JOIN AC
         ON (AC.C=BC.C AND AB.A=AC.A))
SELECT STUDENT FROM (
    SELECT AB.B STUDENT FROM ABC WHERE AB.A='John'
    UNION
    SELECT AC.C STUDENT FROM ABC WHERE AB.A='John')
GROUP BY STUDENT

PS.: Written fast without any syntax check, hope you'll be able to bring this to work :)


问:
How i can get xml node text/value from .xml document with jquery ajax() and $.when() method()
I am using the following javascript/jquery functions to get an external .xml file with getSessionId() method.

```<code>function getSessionId(){
    try{
     $.ajax({
        url: 'UrlToXmlDocument',
        data:{var1:'xxxxxx',var2:'someVal'},
        type:"POST",
        cache:false,
        success: function(r){
            return r;
        },
        error: function(xhr){
            return xhr.status;
           }
         });
      }catch(e){

      }
     }
</code>```

here i am testing that if the above function finished its execution and returned xml document, then find a value in the returned xml file by the following method:

```<code>function saveApprovedCase(){
    $.when(getSessionId()).done(function(txt){
    try{
         alert(txt.find('data').text());
            }catch(e){

                    }
                 });
        }
</code>```

but it alerts only that [Object XMLDocument], where i need to get text inside an element called Required Value.

答:
You are missing dataType.

```<code>    type: "POST",
    dataType: "text",
    cache:false,
</code>```

Body:
I am using the following javascript/jquery functions to get an external .xml file with getSessionId() method.

function getSessionId(){
    try{
     $.ajax({
        url: 'UrlToXmlDocument',
        data:{var1:'xxxxxx',var2:'someVal'},
        type:"POST",
        cache:false,
        success: function(r){
            return r;
        },
        error: function(xhr){
            return xhr.status;
           }
         });
      }catch(e){

      }
     }

here i am testing that if the above function finished its execution and returned xml document, then find a value in the returned xml file by the following method:

function saveApprovedCase(){
    $.when(getSessionId()).done(function(txt){
    try{
         alert(txt.find('data').text());
            }catch(e){

                    }
                 });
        }

but it alerts only that [Object XMLDocument], where i need to get text inside an element called Required Value.

Body:
You are missing dataType.

    type: "POST",
    dataType: "text",
    cache:false,


问:
How to execute command on linux plateform with different thread in python?
I want to execute two separate commands on command prompt and read command's output in python. My approach is, I want to execute these command on certain time interval i.e. after x seconds.

I have two commands say command1 and command2. command1 is taking maximum 30 seconds to print it's output on console. command2 is taking maximum 10 seconds to print it't output on console.

I want to execute this command1 and command2 with new thread every time (time interval) i.e. after every x seconds

program code -

```<code>import os,sys
import thread,threading
import time

def read_abc_data():

    with open("abc.txt", "a") as myfile:
        output = os.popen('command1').read()
        myfile.write(output +"\n\n")

def abc(threadName):

    while True:
        threading.Thread(target = read_abc_data).start()
        time.sleep(10)

def read_pqr_data():

    with open("pqr.txt", "a") as myfile:
        output = os.popen('command2').read()
        myfile.write(output +"\n\n")

def pqr(threadName):

    while True:
        threading.Thread(target = read_pqr_data).start()
        time.sleep(10)

if __name__ == "__main__":

    try:
        thread.start_new_thread( abc, ("Thread-1",  ) )
        thread.start_new_thread( pqr, ("Thread-2",  ) )
    except:
        print "Error: unable to start thread"

    while 1:
        pass
</code>```

Currently I have given 10 seconds sleep (delay) to execute read_abc_data() and read_pqr_data() functions. after executing this program for 1 minute I'm getting abc.txt file as empty. I think the reason is command1 didn't provide complete output in 10 seconds. right?

I want abc.txt and pqr.txt files with commands output as data in that. Is I'm missing something?

答:
As commands output while running, so you'd better get outputs streamingly. It can be done with subprocess and readline:

```<code>import subprocess

def read_abc_data():
    with open("abc.txt", "a") as myfile:
        process = subprocess.Popen('command1', stdout=subprocess.PIPE)
        for line in iter(process.stdout.readline, ''):
            myfile.write(line)
</code>```

Body:
I want to execute two separate commands on command prompt and read command's output in python. My approach is, I want to execute these command on certain time interval i.e. after x seconds.

I have two commands say command1 and command2. command1 is taking maximum 30 seconds to print it's output on console. command2 is taking maximum 10 seconds to print it't output on console.

I want to execute this command1 and command2 with new thread every time (time interval) i.e. after every x seconds

program code -

import os,sys
import thread,threading
import time

def read_abc_data():

    with open("abc.txt", "a") as myfile:
        output = os.popen('command1').read()
        myfile.write(output +"\n\n")

def abc(threadName):

    while True:
        threading.Thread(target = read_abc_data).start()
        time.sleep(10)

def read_pqr_data():

    with open("pqr.txt", "a") as myfile:
        output = os.popen('command2').read()
        myfile.write(output +"\n\n")

def pqr(threadName):

    while True:
        threading.Thread(target = read_pqr_data).start()
        time.sleep(10)

if __name__ == "__main__":

    try:
        thread.start_new_thread( abc, ("Thread-1",  ) )
        thread.start_new_thread( pqr, ("Thread-2",  ) )
    except:
        print "Error: unable to start thread"

    while 1:
        pass

Currently I have given 10 seconds sleep (delay) to execute read_abc_data() and read_pqr_data() functions. after executing this program for 1 minute I'm getting abc.txt file as empty. I think the reason is command1 didn't provide complete output in 10 seconds. right?

I want abc.txt and pqr.txt files with commands output as data in that. Is I'm missing something?

Body:
As commands output while running, so you'd better get outputs streamingly. It can be done with subprocess and readline:

import subprocess

def read_abc_data():
    with open("abc.txt", "a") as myfile:
        process = subprocess.Popen('command1', stdout=subprocess.PIPE)
        for line in iter(process.stdout.readline, ''):
            myfile.write(line)


问:
Java 8 List<V> into Map<K, V>
I want to translate a List of objects into a Map using Java 8's streams and lambdas.

This is how I would write it in Java 7 and below.

```<code>private Map<String, Choice> nameMap(List<Choice> choices) {
        final Map<String, Choice> hashMap = new HashMap<>();
        for (final Choice choice : choices) {
            hashMap.put(choice.getName(), choice);
        }
        return hashMap;
}
</code>```

I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without Guava.

In Guava:

```<code>private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, new Function<Choice, String>() {

        @Override
        public String apply(final Choice input) {
            return input.getName();
        }
    });
}
</code>```

And Guava with Java 8 lambdas.

```<code>private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}
</code>```

答:
You can create a Stream of the indices using an IntStream and then convert them to a Map :</p>

```<code>Map<Integer,Item> map =
IntStream.range(0,items.size())
         .boxed()
         .collect(Collectors.toMap (i -> i, i -> items.get(i)));
</code>```

Title: Java 8 List<V> into Map<K, V>

Body:
I want to translate a List of objects into a Map using Java 8's streams and lambdas.

This is how I would write it in Java 7 and below.

private Map<String, Choice> nameMap(List<Choice> choices) {
        final Map<String, Choice> hashMap = new HashMap<>();
        for (final Choice choice : choices) {
            hashMap.put(choice.getName(), choice);
        }
        return hashMap;
}

I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without Guava.

In Guava:

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, new Function<Choice, String>() {

        @Override
        public String apply(final Choice input) {
            return input.getName();
        }
    });
}

And Guava with Java 8 lambdas.

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}

Body:
You can create a Stream of the indices using an IntStream and then convert them to a Map :

Map<Integer,Item> map =
IntStream.range(0,items.size())
         .boxed()
         .collect(Collectors.toMap (i -> i, i -> items.get(i)));


问:
LINQ Query to check for a predicate in all columns in a table
I have a table with 30 columns,
and it contains 1000 rows.
I want a single LINQ query,  which checks for a particular value in all columns and converts the result into a list.

For example:

```<code>table.where(allcolumnvalue.contains(searchvalue)).Tolist()
</code>```

How to accomplish the above using one LINQ query. Any help is much appreciated.

答:
I got answer But Is not perfect answer  But Is Worked well

```<code>   public class GenericList<T>
{
    void Add(T input) { }

    public List<T> SerachFun(List<T> input, string search)
    {
        List<T> output = new System.Collections.Generic.List<T>();
        foreach (var aa in input)
        {
            var columns = aa.GetType().GetProperties().ToList();
            foreach (var bb in columns)
            {
                var cccc = bb.GetValue(aa);
                bool result = cccc.ToString().Contains(search);
                if (result)
                {
                    output.Add(aa);
                    continue;
                }

            }

        }
        return output;
    }
}
</code>```

The Generic Class Object Created

```<code>        public GenericList<table1> g = new GenericList<table1>();
</code>```

the Generic Class Method Called :

```<code>   var tabledetails=db.table1.ToList();
   var resultcommonsearch = g.SerachFun(tabledetails, "Dhoni");
</code>```

Body:
I have a table with 30 columns,
and it contains 1000 rows.
I want a single LINQ query,  which checks for a particular value in all columns and converts the result into a list.

For example:

table.where(allcolumnvalue.contains(searchvalue)).Tolist()

How to accomplish the above using one LINQ query. Any help is much appreciated.

Body:
I got answer But Is not perfect answer  But Is Worked well

   public class GenericList<T>
{
    void Add(T input) { }

    public List<T> SerachFun(List<T> input, string search)
    {
        List<T> output = new System.Collections.Generic.List<T>();
        foreach (var aa in input)
        {
            var columns = aa.GetType().GetProperties().ToList();
            foreach (var bb in columns)
            {
                var cccc = bb.GetValue(aa);
                bool result = cccc.ToString().Contains(search);
                if (result)
                {
                    output.Add(aa);
                    continue;
                }

            }

        }
        return output;
    }
}

The Generic Class Object Created

        public GenericList<table1> g = new GenericList<table1>();

the Generic Class Method Called :

   var tabledetails=db.table1.ToList();
   var resultcommonsearch = g.SerachFun(tabledetails, "Dhoni");


问:
Showing Response Status - Uploading Image using JQuery
What I'm trying to do is download some image from a URL then upload it to WordPress post, my form below:

```<code><form method="post" id="upload">
<?php foreach($data as $row): ?>

<label>File Name</label>
<input type="text" id="filename_<?php echo $row->id;?>" name="data[<?php echo $row->id;?>][filename]" value="<?php echo $file_name;?>" />

<label>Title</label>
<input type="text" id="title_<?php echo $row->id;?>" name="data[<?php echo $row->id;?>][title]" value="<?php echo $title;?>" />

<?php endforeach;?>
<button name="act" value="savepost">Save</button>
</form>
<!-- showing result here -->
<div id="result"></div>
</code>```

So, then when click Save button... the action will call function prc_upload()

```<code>function prc_upload() {
   $posts = $_POST['data'];
   foreach ($posts as $post) {
   $filename  = $post['filename'];
   $title     = $post['title'];
   // Process uplaoding here
   // Process uplaoding here
   // Process uplaoding here
   if (!$fileSaved) {
      $result = $filename.' Can not saved !!';
   } else {
      $result = filename' Saved Succesfuly!!';
   }
}
</code>```

How to use jquery to show response result when Save button clicked..

答:
make sure that your form has enctype="multipart/form-data" attribute.</p>

```<code>$new_post = wp_insert_post($post_array);
if (!function_exists('wp_generate_attachment_metadata')){
                require_once(ABSPATH . "wp-admin" . '/includes/image.php');
                require_once(ABSPATH . "wp-admin" . '/includes/file.php');
                require_once(ABSPATH . "wp-admin" . '/includes/media.php');
            }
             if ($_FILES) {
                foreach ($_FILES as $file => $array) {
                    if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
                        return "upload error : " . $_FILES[$file]['error'];
                    }
                    $attach_id = media_handle_upload( $file, $new_post );
                }
            }
            if ($attach_id > 0){

                update_post_meta($new_post,'_thumbnail_id',$attach_id);
            }
</code>```

Body:
What I'm trying to do is download some image from a URL then upload it to WordPress post, my form below:

<form method="post" id="upload">
<?php foreach($data as $row): ?>

File Name
<input type="text" id="filename_<?php echo $row->id;?>" name="data[<?php echo $row->id;?>][filename]" value="<?php echo $file_name;?>" />

Title
<input type="text" id="title_<?php echo $row->id;?>" name="data[<?php echo $row->id;?>][title]" value="<?php echo $title;?>" />

<?php endforeach;?>
<button name="act" value="savepost">Save</button>
</form>

So, then when click Save button... the action will call function prc_upload()

function prc_upload() {
   $posts = $_POST['data'];
   foreach ($posts as $post) {
   $filename  = $post['filename'];
   $title     = $post['title'];
   // Process uplaoding here
   // Process uplaoding here
   // Process uplaoding here
   if (!$fileSaved) {
      $result = $filename.' Can not saved !!';
   } else {
      $result = filename' Saved Succesfuly!!';
   }
}

How to use jquery to show response result when Save button clicked..

Body:
make sure that your form has enctype="multipart/form-data" attribute.

$new_post = wp_insert_post($post_array);
if (!function_exists('wp_generate_attachment_metadata')){
                require_once(ABSPATH . "wp-admin" . '/includes/image.php');
                require_once(ABSPATH . "wp-admin" . '/includes/file.php');
                require_once(ABSPATH . "wp-admin" . '/includes/media.php');
            }
             if ($_FILES) {
                foreach ($_FILES as $file => $array) {
                    if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
                        return "upload error : " . $_FILES[$file]['error'];
                    }
                    $attach_id = media_handle_upload( $file, $new_post );
                }
            }
            if ($attach_id > 0){

                update_post_meta($new_post,'_thumbnail_id',$attach_id);
            }


问:
docker pull failed. manifest invalid: manifest invalid - artifactory
docker 1.9.1 pull on centos7 is failing when pulling from private V2 registry.

```<code>$ docker -v
Docker version 1.9.1, build 78ee77d/1.9.1

$ docker pull web-docker.bin-repo.hostname.com/web-dev:latest
Trying to pull repository web-docker.bin-repo.hostname.com/web-dev ...

failed
manifest invalid: manifest invalid
</code>```

The same command works fine on osx with docker 1.10.3.  Can anyone tell me why this isn't working and how to troubleshoot further?

update:  here is the manifest it's trying to pull.  It can pull v1 manifests, but fails on v2 manifests like the one below.

```<code>{
   "schemaVersion": 2,
   "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
   "config": {
      "mediaType": "application/octet-stream",
      "size": 7503,
      "digest": "sha256:58672cb2c8c6d44c1271a5ca38e60a4ab29fb60050bc76995ce662c126509036"
   },
   "layers": [
      {
         "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
         "size": 32,
         "digest": "sha256:a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4"
      },
      {
         "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
         "size": 72038766,
         "digest": "sha256:35d9d5d11536c0c6843ecd106dc710b5c54b8198aa28710e73dba2cbe555847f"
      },
      {
         "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
         "size": 19361671,
         "digest": "sha256:f7de7971859186e93100b41fbba5513771737ba65f57c62404130646bd41b96b"
      },
      {
         "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
         "size": 108814795,
         "digest": "sha256:0041a80e34f1271571619554f6833c06e0ef75d39f152f5fe44ba75bf7e25ae2"
      },
      {
         "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
         "size": 157895786,
         "digest": "sha256:ec3cfa9c22f7e6497a0eacf85c86bf8eb5fdec35d096298f9efb43827a393472"
      }
   ]
}
</code>```

答:
For this issue what I observed is that whenever you push the same image artifact for the second time with same SHA, we will observe this issue.

To Solve this, I would recommend giving permission to override/delete the mainifest file in artifactory.

This will definitely solve this issue.

Body:
docker 1.9.1 pull on centos7 is failing when pulling from private V2 registry.

$ docker -v
Docker version 1.9.1, build 78ee77d/1.9.1

$ docker pull web-docker.bin-repo.hostname.com/web-dev:latest
Trying to pull repository web-docker.bin-repo.hostname.com/web-dev ...

failed
manifest invalid: manifest invalid

The same command works fine on osx with docker 1.10.3.  Can anyone tell me why this isn't working and how to troubleshoot further?

update:  here is the manifest it's trying to pull.  It can pull v1 manifests, but fails on v2 manifests like the one below.

{
   "schemaVersion": 2,
   "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
   "config": {
      "mediaType": "application/octet-stream",
      "size": 7503,
      "digest": "sha256:58672cb2c8c6d44c1271a5ca38e60a4ab29fb60050bc76995ce662c126509036"
   },
   "layers": [
      {
         "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
         "size": 32,
         "digest": "sha256:a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4"
      },
      {
         "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
         "size": 72038766,
         "digest": "sha256:35d9d5d11536c0c6843ecd106dc710b5c54b8198aa28710e73dba2cbe555847f"
      },
      {
         "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
         "size": 19361671,
         "digest": "sha256:f7de7971859186e93100b41fbba5513771737ba65f57c62404130646bd41b96b"
      },
      {
         "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
         "size": 108814795,
         "digest": "sha256:0041a80e34f1271571619554f6833c06e0ef75d39f152f5fe44ba75bf7e25ae2"
      },
      {
         "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
         "size": 157895786,
         "digest": "sha256:ec3cfa9c22f7e6497a0eacf85c86bf8eb5fdec35d096298f9efb43827a393472"
      }
   ]
}


问:
Java OO static ultility method help!
I recently did a method in the User class which looks like this;

```<code>  public static boolean checkUN(String username) {
  boolean check = false;
  ResultSet rs;
  String dbQuery;
  SQLController db = new SQLController();
  db.setUp();
  dbQuery = "SELECT * FROM User WHERE User_name ='" + username + "'";
  try {
   db.setUp();
   rs = db.readRequest(dbQuery);
   if (rs.next()) {
    check = true;
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  db.terminate();
  return check;
 }
</code>```

I intended it to be a validation check before the User is able to continue to the next step of registration.

When I showed it to the teacher, she said that it would be ok, as im using it as a ultility method. However, she changed her mind later on, saying that I should change this to an instance method, then creating a new User object to do the validation.

Which way is more effective?

```<code>user.checkUsername(jTextUN.getText());
</code>```

and the instance way
(assuming I changed the method, removing static and the input parameter);

```<code>User user = new User();
user.setUsername(jTextUN.getText());
user.checkUsername();
</code>```

Cheers!

答: Well, the second way is more extensible and more intuitive (in terms of if you want to change things later on), so I'd recommend it. But the first way solves the problem directly, and if the concept of a "user" won't be extended later (with new methods), then either one should be fine.</p>

Title: Java OO static ultility method help!

Body:
I recently did a method in the User class which looks like this;

  public static boolean checkUN(String username) {
  boolean check = false;
  ResultSet rs;
  String dbQuery;
  SQLController db = new SQLController();
  db.setUp();
  dbQuery = "SELECT * FROM User WHERE User_name ='" + username + "'";
  try {
   db.setUp();
   rs = db.readRequest(dbQuery);
   if (rs.next()) {
    check = true;
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  db.terminate();
  return check;
 }

I intended it to be a validation check before the User is able to continue to the next step of registration.

When I showed it to the teacher, she said that it would be ok, as im using it as a ultility method. However, she changed her mind later on, saying that I should change this to an instance method, then creating a new User object to do the validation.

Which way is more effective?

user.checkUsername(jTextUN.getText());

and the instance way
(assuming I changed the method, removing static and the input parameter);

User user = new User();
user.setUsername(jTextUN.getText());
user.checkUsername();

Cheers!


问:
bootstrap collapse content panel should be activated on mobile device
I have problem to activate collapse content panel over mobile devices and on desktop it should be de-activated. I've used bootstrap collapse feature.</p>

答:
Please use this jquery code. it will help you. working jsfiddle example</p>

```<code>$(document).ready(function(){
  if ($(window).width() < 767){
    $('.panel-collapse').removeClass('in');
    $('.panel-collapse:first').addClass('in');
    $('.collapsed').css({'pointer-events':'auto','cursor':'pointer'});
  }else{
    $('.panel-collapse').addClass('in');
    $('.collapsed').css({'pointer-events':'none','cursor':'default'});
  }
});
</code>```

Body:
Please use this jquery code. it will help you. working jsfiddle example

$(document).ready(function(){
  if ($(window).width() < 767){
    $('.panel-collapse').removeClass('in');
    $('.panel-collapse:first').addClass('in');
    $('.collapsed').css({'pointer-events':'auto','cursor':'pointer'});
  }else{
    $('.panel-collapse').addClass('in');
    $('.collapsed').css({'pointer-events':'none','cursor':'default'});
  }
});


问:
Problem with Twitter search api
working when using this in rails c

```<code>client = TwitterSearch::Client.new('campvote')

tweets = client.query('#barcampmlk2 #railsforzombies +1')
</code>```

but not when BarcampSession.update_twitter! it retune empty hash

```<code>require 'twitter_search'
class BarcampSession < ActiveRecord::Base
    validates :hash_tag , :format => {:with => /^#\w+/ } , :presence => true ,:uniqueness => true
    validates :name , :presence => true
    validates :email , :presence => true , :format => {:with => /((\S+)@(\S{3}[a-zA-z0-9)]\S*))/ }
    validates :handphone, :presence => true

    def self.update_twitter!
        client = TwitterSearch::Client.new('campvote')
        BarcampSession.all.each do |sess|
            tweets = client.query('#barcampmlk2 #{sess.hash_tag} +1')
            puts tweets.to_yaml
        end

    end
end
</code>```

it return

```<code>rb(main):014:0> BarcampSession.update_twitter!
--- !seq:TwitterSearch::Tweets []

=> [#<BarcampSession id: 1, hash_tag: "#railsforzombies", name: "wizztjh", email: "wiz123tjh@gmail.com", handphone: "1234006", since: nil, created_at: "2010-12-14 18:28:01", updated_at: "2010-12-14 18:28:01">]
</code>```

答:
String interpolation works only with double quotes, not single quotes. Change the line

```<code>tweets = client.query('#barcampmlk2 #{sess.hash_tag} +1')
</code>```

to

```<code>tweets = client.query("#barcampmlk2 #{sess.hash_tag} +1")
</code>```

Title: Problem with Twitter search api

Body:
working when using this in rails c

client = TwitterSearch::Client.new('campvote')

tweets = client.query('#barcampmlk2 #railsforzombies +1')

but not when BarcampSession.update_twitter! it retune empty hash

require 'twitter_search'
class BarcampSession < ActiveRecord::Base
    validates :hash_tag , :format => {:with => /^#\w+/ } , :presence => true ,:uniqueness => true
    validates :name , :presence => true
    validates :email , :presence => true , :format => {:with => /((\S+)@(\S{3}[a-zA-z0-9)]\S*))/ }
    validates :handphone, :presence => true

    def self.update_twitter!
        client = TwitterSearch::Client.new('campvote')
        BarcampSession.all.each do |sess|
            tweets = client.query('#barcampmlk2 #{sess.hash_tag} +1')
            puts tweets.to_yaml
        end

    end
end

it return

rb(main):014:0> BarcampSession.update_twitter!
--- !seq:TwitterSearch::Tweets []

=> [#<BarcampSession id: 1, hash_tag: "#railsforzombies", name: "wizztjh", email: "wiz123tjh@gmail.com", handphone: "1234006", since: nil, created_at: "2010-12-14 18:28:01", updated_at: "2010-12-14 18:28:01">]

Body:
String interpolation works only with double quotes, not single quotes. Change the line

tweets = client.query('#barcampmlk2 #{sess.hash_tag} +1')

to

tweets = client.query("#barcampmlk2 #{sess.hash_tag} +1")


问:
How to set text to Chinese characters in VBA for Powerpoint?
I am trying to set the text in a Powerpoint text box to Chinese characters from a .txt file encoded in UTF-8, using VBA. Currently, I have

```<code>Set TradBox = Current.Shapes.AddTextbox(msoTextOrientationHorizontal, 0, 0, 500, 250)
Set SimpBox = Current.Shapes.AddTextbox(msoTextOrientationHorizontal, 0, 250, 500, 250)
TradBox.TextFrame.TextRange.Text = DataLineTrad
SimpBox.TextFrame.TextRange.Text = DataLineSimp
</code>```

Where DataLineTrad and Simp are strings of Chinese characters. This results in gibberish, like ï»¿ç¦®è®“. How can I change the text box so its encoding matches the text I am trying to enter?

答:
The solution is to tweak the OS to use the desired language for non-unicode programs in Windows.

Follow instructions (minus the Registry hack) in How To Display Foreign Characters In Excel VBE.

I just tested on my English Windows 7 Ent x64 with Office 2010 x86, and worked like charm!

Body:
I am trying to set the text in a Powerpoint text box to Chinese characters from a .txt file encoded in UTF-8, using VBA. Currently, I have

Set TradBox = Current.Shapes.AddTextbox(msoTextOrientationHorizontal, 0, 0, 500, 250)
Set SimpBox = Current.Shapes.AddTextbox(msoTextOrientationHorizontal, 0, 250, 500, 250)
TradBox.TextFrame.TextRange.Text = DataLineTrad
SimpBox.TextFrame.TextRange.Text = DataLineSimp

Where DataLineTrad and Simp are strings of Chinese characters. This results in gibberish, like ï»¿ç¦®è®“. How can I change the text box so its encoding matches the text I am trying to enter?


问:
Get last ID after insert (always return 0)
I have an Sql class like this:

```<code>        class Sql extends PDO {
            private $connection;
            public function __construct() {
                $this->connection = new PDO("mysql:host=localhost;dbname=myDB", "root", "root");
            }

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

Then I'm trying to insert a data in my db using another class "user.php". Using the "getConection" (sql class method). Like this:

```<code>class User {
    private $iduser;
    private $deslogin;
    private $despassword;
    private $datecad;

    (getters & setters)

public function insert() { //query & select are a SQL class method
        $sql = new Sql();
        $sql->query("INSERT INTO tb_users (deslogin, despassword) VALUES (:LOGIN, :PASS))", array(
            ':LOGIN'=>$this->getDeslogin(),
            ':PASS'=>$this->getDespassword()
        ));

            echo $sql->getConnection()->lastInsertId(); //getConnection is a Sql Class method that returns the private connection.
    }
</code>```

Why my echo always returns 0?

答:
Its because you need same connection object regarding insert query to get last inserted ID but you are creating new connection for getting last inserted ID. That's why you are always getting 0 as result.

See the reference :

http://php.net/manual/en/pdo.lastinsertid.php#120618

EDIT

From your code reference its problem in your insert Have you mark there is one extra closing bracket

change your code to:

```<code>$sql->query("INSERT INTO tb_users (deslogin, despassword) VALUES (:LOGIN, :PASS)", array(
            ':LOGIN'=>$this->getDeslogin(),
            ':PASS'=>$this->getDespassword()
        )); //<------there must be only one bracket after::LOGIN, :PASS
</code>```

Body:
I have an Sql class like this:

        class Sql extends PDO {
            private $connection;
            public function __construct() {
                $this->connection = new PDO("mysql:host=localhost;dbname=myDB", "root", "root");
            }

 (...)

Then I'm trying to insert a data in my db using another class "user.php". Using the "getConection" (sql class method). Like this:

class User {
    private $iduser;
    private $deslogin;
    private $despassword;
    private $datecad;

    (getters & setters)

public function insert() { //query & select are a SQL class method
        $sql = new Sql();
        $sql->query("INSERT INTO tb_users (deslogin, despassword) VALUES (:LOGIN, :PASS))", array(
            ':LOGIN'=>$this->getDeslogin(),
            ':PASS'=>$this->getDespassword()
        ));

            echo $sql->getConnection()->lastInsertId(); //getConnection is a Sql Class method that returns the private connection.
    }

Why my echo always returns 0?

Body:
Its because you need same connection object regarding insert query to get last inserted ID but you are creating new connection for getting last inserted ID. That's why you are always getting 0 as result.

See the reference :

http://php.net/manual/en/pdo.lastinsertid.php#120618

EDIT

From your code reference its problem in your insert Have you mark there is one extra closing bracket

change your code to:

$sql->query("INSERT INTO tb_users (deslogin, despassword) VALUES (:LOGIN, :PASS)", array(
            ':LOGIN'=>$this->getDeslogin(),
            ':PASS'=>$this->getDespassword()
        )); //<------there must be only one bracket after::LOGIN, :PASS


问:
Where can one find the list of all functions available under firebase-admin? firebase-functions?
I'm testing out writing code with Firebase Cloud Functions.

with

```<code>const admin = require('firebase-admin');
const functions = require('firebase-functions');
</code>```

Where can one find the list of all functions available under admin, or functions, or any other popular or recommended firebase or Node.js sets of functions?

btw shouldn't there be a firebase-cloud-functions tag?

答:
The admin module you import is the Firebase Admin SDK for node. It is documented in this guide and this API reference.

The functions module you import is the Cloud Functions library for Firebase. It is documented in this guide and in this API reference.

Body:
I'm testing out writing code with Firebase Cloud Functions.

with

const admin = require('firebase-admin');
const functions = require('firebase-functions');

Where can one find the list of all functions available under admin, or functions, or any other popular or recommended firebase or Node.js sets of functions?

btw shouldn't there be a firebase-cloud-functions tag?


问:
ReactJS Redux Api Fetch
I just need a little help with regards to fetching of data through an api

currently I have this code in my container

```<code>    fetchAll: () => {
        Promise.resolve(token.getToken()).then( (response) => {
            let obj = {
             token_type: response.data.token_type,
             access_token: response.data.access_token
            }

            apiFetch("http://dev.apiserver.com/api/all",{
              "method": "GET",
              "headers": {
                "Authorization": `${obj.token_type} ${obj.access_token}`,
                "userId": 1
              }
            })
            .then( (res) => {
                return res.json();
            }).then( (json) => {
                dispatch({
                    type: 'FETCH_ALL',
                    payload: json
                })
            }).catch(function(err) {
                console.log(err)
            })
        })
    }
</code>```

I'm calling the above function from componentWillMount(), I can successfully log the result in my console

here is my reducer code

```<code>    const allReducer = (state: Immut = initialState, action: { type: string, payload: any }) => {
        switch (action.type) {
          case FETCH_ALL:
            let newState = state
            let payload = action.payload

            newState = Immutable.fromJS(payload)
            console.log(newState)

            return newState
        }
    }
</code>```

the problem is that it doesn't update the state or re-render the components

答:
Since your reducer is getting called, the issue is likely not in the AJAX call or the update part of the Redux cycle, but in how your component connects to the state. Changes in the state should reactively trigger a re-render of the component, but for this to happen, the props of the component need to change. First, a few steps on how you might debug this issue, before some suggestions of possible causes, and suggested best practices.

Redux Dev Tools

Install Redux Dev Tools on Chrome. DevTools allow you to view a history of actions, and the changes each action induced to the Redux state.

First, use Redux DevTools to ensure that the shape of your Redux state is what you expect, even before triggering any action / AJAX call.

Then, select your AJAX fetch success (FETCH_ALL) action in Redux DevTools and, looking at the diff, see that the state changes as you expect.

Manual debugging

Try putting a debug value in the initialState of your reducer, and ensure it renders on the component.

See that the props of the component are updated when state changes. Put a console.log for this.props and nextProps in the life-cycle method componentWillReceiveProps(nextProps).

Issues to look for

Your component may be looking for the data in a wrong place of the state. The structure of your store follows the composition of your reducers. For example, the following puts the output of myDataReducer under app.db:

```<code>const rootReducer = combineReducers({
  app: combineReducers({ db: myDataReducer }),
});
</code>```

You seem to be using Immutable.js. Vanilla Redux treats the state as a POJO. You should either A) use a JavaScript object as the root of your state, or B) use a special combineReducers from redux-immutable.

Best practices

Trigger data fetching from componentDidMount instead of componentWillMount.

Trigger all side effects with an Redux action, instead of chaining promises directly in component code. Effect those changes using Redux middleware, like redux-saga. In your case, you could use redux-promise, create an action like

```<code>const action = ({type: FETCH_DATA, payload: axios.get(ENDPOINT, params)});
</code>```

The redux-promise middleware handles the resolving, so that your reducer will only see the resolved value in the payload.

Title: ReactJS Redux Api Fetch

Body:
I just need a little help with regards to fetching of data through an api

currently I have this code in my container

    fetchAll: () => {
        Promise.resolve(token.getToken()).then( (response) => {
            let obj = {
             token_type: response.data.token_type,
             access_token: response.data.access_token
            }

            apiFetch("http://dev.apiserver.com/api/all",{
              "method": "GET",
              "headers": {
                "Authorization": `${obj.token_type} ${obj.access_token}`,
                "userId": 1
              }
            })
            .then( (res) => {
                return res.json();
            }).then( (json) => {
                dispatch({
                    type: 'FETCH_ALL',
                    payload: json
                })
            }).catch(function(err) {
                console.log(err)
            })
        })
    }

I'm calling the above function from componentWillMount(), I can successfully log the result in my console

here is my reducer code

    const allReducer = (state: Immut = initialState, action: { type: string, payload: any }) => {
        switch (action.type) {
          case FETCH_ALL:
            let newState = state
            let payload = action.payload

            newState = Immutable.fromJS(payload)
            console.log(newState)

            return newState
        }
    }

the problem is that it doesn't update the state or re-render the components

Body:
Since your reducer is getting called, the issue is likely not in the AJAX call or the update part of the Redux cycle, but in how your component connects to the state. Changes in the state should reactively trigger a re-render of the component, but for this to happen, the props of the component need to change. First, a few steps on how you might debug this issue, before some suggestions of possible causes, and suggested best practices.

Redux Dev Tools

Install Redux Dev Tools on Chrome. DevTools allow you to view a history of actions, and the changes each action induced to the Redux state.

First, use Redux DevTools to ensure that the shape of your Redux state is what you expect, even before triggering any action / AJAX call.

Then, select your AJAX fetch success (FETCH_ALL) action in Redux DevTools and, looking at the diff, see that the state changes as you expect.

Manual debugging

Try putting a debug value in the initialState of your reducer, and ensure it renders on the component.

See that the props of the component are updated when state changes. Put a console.log for this.props and nextProps in the life-cycle method componentWillReceiveProps(nextProps).

Issues to look for

Your component may be looking for the data in a wrong place of the state. The structure of your store follows the composition of your reducers. For example, the following puts the output of myDataReducer under app.db:

const rootReducer = combineReducers({
  app: combineReducers({ db: myDataReducer }),
});

You seem to be using Immutable.js. Vanilla Redux treats the state as a POJO. You should either A) use a JavaScript object as the root of your state, or B) use a special combineReducers from redux-immutable.

Best practices

Trigger data fetching from componentDidMount instead of componentWillMount.

Trigger all side effects with an Redux action, instead of chaining promises directly in component code. Effect those changes using Redux middleware, like redux-saga. In your case, you could use redux-promise, create an action like

const action = ({type: FETCH_DATA, payload: axios.get(ENDPOINT, params)});

The redux-promise middleware handles the resolving, so that your reducer will only see the resolved value in the payload.


问:
is it possible to version and deploy a configuration file to nexus via maven commands
I am working on a java project and I would like to version and store a configuration file on nexus. Lets assume the file structure of java project is as below.

```<code>src/
conf/application.config
pom.xml
</code>```

Is it possible to deploy application.config file to nexus when I run mvn clean install. After each build I expect an application artifact and a configuration artifact to be deployed to nexus. Is there any maven plugin for this purpose.

答:
I manged to deploy file with maven-deploy-plugin.

http://maven.apache.org/plugins/maven-deploy-plugin/usage.html

You can find an example below.

```<code> <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
                <executions>
                    <execution>
                        <id>deploy-file</id>
                        <!-- change to deploy-->
                        <phase>install</phase>
                        <goals>
                            <goal>deploy-file</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <file>app.properties</file>
                    <repositoryId>stack.example.release</repositoryId>
                    <url>http://nexusserver/nexus/content/repositories/releases/</url>
                    <groupId>com.stack.example.config</groupId>
                    <artifactId>app</artifactId>
                    <packaging>properties</packaging>
                    <version>1.0.0</version>
                </configuration>
            </plugin>

        </plugins>
    </build>
</code>```

Body:
I am working on a java project and I would like to version and store a configuration file on nexus. Lets assume the file structure of java project is as below.

src/
conf/application.config
pom.xml

Is it possible to deploy application.config file to nexus when I run mvn clean install. After each build I expect an application artifact and a configuration artifact to be deployed to nexus. Is there any maven plugin for this purpose.

Body:
I manged to deploy file with maven-deploy-plugin.

http://maven.apache.org/plugins/maven-deploy-plugin/usage.html

You can find an example below.

 <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
                <executions>
                    <execution>
                        <id>deploy-file</id>
                        <!-- change to deploy-->
                        <phase>install</phase>
                        <goals>
                            <goal>deploy-file</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <file>app.properties</file>
                    <repositoryId>stack.example.release</repositoryId>
                    <url>http://nexusserver/nexus/content/repositories/releases/</url>
                    <groupId>com.stack.example.config</groupId>
                    <artifactId>app</artifactId>
                    <packaging>properties</packaging>
                    <version>1.0.0</version>
                </configuration>
            </plugin>

        </plugins>
    </build>