问:
wordpress pagination ads extra slashes to url
Working with custom post types I cant seem to get the pagination to work correct. All is working but when I click to the next page the url will get a extra slash in the url, not sure why this is happening but when using the pagination a lot will add every time a new slash to the url.

// out

```<code>site.com/projects/ ,
site.com/projects//page/2,
site.com/projects///page/3,
site.com/projects////page/4

...and so on.
</code>```

// the code used

```<code>    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

    $query = new WP_Query( array(
        'post_type'      => 'projects',
        'posts_per_page' => 5,
        'paged'          => $paged

    ) );

    if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

       the_title();

    endwhile;

        $total_pages = $query->max_num_pages;

        if ($total_pages > 1){

            $current_page = max(1, get_query_var('paged'));

            echo paginate_links(array(
                'base'      => get_pagenum_link(1) . '%_%',
                'format'    => '/page/%#%',
                'current'   => $current_page,
                'total'     => $total_pages,
                'prev_text' =>  esc_html__('volgende »', 'infrafocus'),
                'next_text' =>  esc_html__('« vorige' , 'infrafocus'),
            ));
        }

    }

    wp_reset_postdata();

    endif;
</code>```

答:
User format as below

```<code>'format'             => '?paged=%#%'
</code>```

https://codex.wordpress.org/Function_Reference/paginate_links

Body:
Working with custom post types I cant seem to get the pagination to work correct. All is working but when I click to the next page the url will get a extra slash in the url, not sure why this is happening but when using the pagination a lot will add every time a new slash to the url.

// out

site.com/projects/ ,
site.com/projects//page/2,
site.com/projects///page/3,
site.com/projects////page/4

...and so on.

// the code used

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

    $query = new WP_Query( array(
        'post_type'      => 'projects',
        'posts_per_page' => 5,
        'paged'          => $paged

    ) );

    if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

       the_title();

    endwhile;

        $total_pages = $query->max_num_pages;

        if ($total_pages > 1){

            $current_page = max(1, get_query_var('paged'));

            echo paginate_links(array(
                'base'      => get_pagenum_link(1) . '%_%',
                'format'    => '/page/%#%',
                'current'   => $current_page,
                'total'     => $total_pages,
                'prev_text' =>  esc_html__('volgende »', 'infrafocus'),
                'next_text' =>  esc_html__('« vorige' , 'infrafocus'),
            ));
        }

    }

    wp_reset_postdata();

    endif;

Body:
User format as below

'format'             => '?paged=%#%'

https://codex.wordpress.org/Function_Reference/paginate_links


来源: stackexchange

问:
Bash on Ubuntu on Windows can't use `sudo apt-get install <packagename>`
I was excited to use bash on windows but quickly ran into an issue. I am trying to install build-essential, but I get a dependency issue. Upon trying to resolve with sudo apt-get install -f, I run into another error that doesn't make much sense. I've tried update and upgrade, but that didn't work either. F

```<code>barzevp@UK-LT-8356:~$ sudo apt-get install build-essential
Reading package lists... Done
Building dependency tree
Reading state information... Done
build-essential is already the newest version.
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies.
 libc6-dev : Depends: linux-libc-dev but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).
barzevp@UK-LT-8356:~$ sudo apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
  libfreetype6 os-prober
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
  linux-libc-dev
The following NEW packages will be installed
  linux-libc-dev
0 to upgrade, 1 to newly install, 0 to remove and 43 not to upgrade.
5 not fully installed or removed.
Need to get 0 B/767 kB of archives.
After this operation, 3,946 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
(Reading database ... 28660 files and directories currently installed.)
Preparing to unpack .../linux-libc-dev_3.13.0-123.172_amd64.deb ...
Unpacking linux-libc-dev:amd64 (3.13.0-123.172) ...
dpkg: error processing archive /var/cache/apt/archives/linux-libc-dev_3.13.0-123.172_amd64.deb (--unpack):
 unable to install new version of /usr/include/linux/netfilter_ipv6/ip6t_hl.h': File exists
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

Full log of what led to the error in Bash on Ubuntu on Windows terminal is here:
https://pastebin.com/dq2D2Gtz

答:
It says dependencies aren't being installed, so try:

```<code>sudo apt-get install linux-libc-dev
</code>```

If that doesn't work try:

```<code>sudo apt-get install --reinstall build-essential
</code>```

This will reinstall build-essential. Hope this helps, cheers!

ContentLicense: CC BY-SA 3.0

Body:
I was excited to use bash on windows but quickly ran into an issue. I am trying to install build-essential, but I get a dependency issue. Upon trying to resolve with sudo apt-get install -f, I run into another error that doesn't make much sense. I've tried update and upgrade, but that didn't work either. F

barzevp@UK-LT-8356:~$ sudo apt-get install build-essential
Reading package lists... Done
Building dependency tree
Reading state information... Done
build-essential is already the newest version.
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies.
 libc6-dev : Depends: linux-libc-dev but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).
barzevp@UK-LT-8356:~$ sudo apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
  libfreetype6 os-prober
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
  linux-libc-dev
The following NEW packages will be installed
  linux-libc-dev
0 to upgrade, 1 to newly install, 0 to remove and 43 not to upgrade.
5 not fully installed or removed.
Need to get 0 B/767 kB of archives.
After this operation, 3,946 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
(Reading database ... 28660 files and directories currently installed.)
Preparing to unpack .../linux-libc-dev_3.13.0-123.172_amd64.deb ...
Unpacking linux-libc-dev:amd64 (3.13.0-123.172) ...
dpkg: error processing archive /var/cache/apt/archives/linux-libc-dev_3.13.0-123.172_amd64.deb (--unpack):
 unable to install new version of /usr/include/linux/netfilter_ipv6/ip6t_hl.h': File exists
E: Sub-process /usr/bin/dpkg returned an error code (1)

Full log of what led to the error in Bash on Ubuntu on Windows terminal is here:
https://pastebin.com/dq2D2Gtz

Body:
It says dependencies aren't being installed, so try:

sudo apt-get install linux-libc-dev

If that doesn't work try:

sudo apt-get install --reinstall build-essential

This will reinstall build-essential. Hope this helps, cheers!


问:
iPad MPMoviePlayerController - Disable Fullscreen
Is there a way to disable the fullscreen button of the MPMoviePlayerController ?</p>

答:
There's a cheat:

```<code>MPMoviePlayerController *mpc = (...some instance...)
UIView *fsbutton = [[mpc view] viewWithTag:512];
[fsbutton setHidden:YES];
</code>```

The main catch is, you have to do it in viewDidAppear: or similar, because the MoviePlayer view sets itself up somewhere inside didMoveToWindow or didMoveToSuperview, which happen after viewWillAppear:. So you get a brief flash of the fullscreen button. Other obvious catches include: brittle vs. Apple changing that 512 tag value (although it works in 3.2 - 4.2); and of course Apple would rather you not do this.

The endorsed solution is to set the control style to MPMovieControlStyleNone and roll your own transport controls, which is more work.

ContentLicense: CC BY-SA 2.5

Body:
There's a cheat:

MPMoviePlayerController *mpc = (...some instance...)
UIView *fsbutton = [[mpc view] viewWithTag:512];
[fsbutton setHidden:YES];

The main catch is, you have to do it in viewDidAppear: or similar, because the MoviePlayer view sets itself up somewhere inside didMoveToWindow or didMoveToSuperview, which happen after viewWillAppear:. So you get a brief flash of the fullscreen button. Other obvious catches include: brittle vs. Apple changing that 512 tag value (although it works in 3.2 - 4.2); and of course Apple would rather you not do this.

The endorsed solution is to set the control style to MPMovieControlStyleNone and roll your own transport controls, which is more work.


问:
Updating data on rows deleted event
I have a custom page with a form and a grid. When a row from a grid is deleted, I want to update some other rows. I am therefore handling the rowdeleted event. I confirmed (through debugging) that the event is firing correctly and that the data is being updated correctly.

The only issue I have is that the screen still shows the old values. My delete row correctly disappears but the other rows do not get updated.

For each row that I change, I am calling the Update method of the Data View. However, this still does not refresh the user interface.
Interesting, if I save, all my changes get correctly updated to the database. Which confirms that this is a UI isssue.

Is there any additional step that I need to perform to refresh the user interface? Or should I just avoid doing updates in Row Deleted event?

答: To guarantee constant optimal performance level, in the end of a roundtrip grids in Acumatica only update currently selected record. This behavior is by default. In case you insert/update/delete other records in the same grid within an event handler or an action delegate, it's always necessary to call View.RequestRefresh() to force the grid to update its entire content instead of only the selected record.

Title: Updating data on rows deleted event


问:
PHP SUM IF Function with column criteria
I would like to find a formula that sums all my columns starting with surveydone. In my example I have 10 columns starting with surveydone. Could please help me to find this formula ? Thank you

Please find below the echo json_encode I have in PHP :

```<code>{"id":"7","username":"Thomas","survey1":"valide","surveytoken1":"EuLwfqJI5UYLgK2LQ7jS","surveytokenvalid1":"1","surveydone1":"1","surveytoken2":"EuLwfqJI5UYLgK2LQ7jS","surveytokenvalid2":"1","surveydone2":"1" [...] "surveytokenvalid10":"1","surveydone10":"1"}
</code>```

and here is my code in php:

```<code>   $user_username = $_SESSION['auth']->username;
   $user['username'] = $user_username;
   $req = $pdo->prepare('SELECT * FROM data WHERE (username = ?)');
   $req->execute([$user_username]);
   $surveyuser = $req->fetch();
   echo json_encode($surveyuser);
</code>```

答:
Here is the answer I have managed to found and it works.      </p>

```<code>   $user_username = $_SESSION['auth']->username;
   $user['username'] = $user_username;
   $req = $pdo->prepare('SELECT * FROM data WHERE (username = ?)');
   $req->execute([$user_username]);
   $surveyuser = $req->fetch();
   echo json_encode($surveyuser);

  $surveyuserarray = json_decode(json_encode($surveyuser), True);
  $surveyuser2 = json_encode($surveyuser);

  foreach($surveyuserarray as $key => $value){
    if (strpos($key, 'surveydone') === 0) {
        $only_point[$key] = $value;
       }
   }

  $total_points=array();
  $total_points['totalpoints']=array_sum($only_point);

   echo ($surveyuser2);
   echo json_encode($total_points);
</code>```

Body:
I would like to find a formula that sums all my columns starting with surveydone. In my example I have 10 columns starting with surveydone. Could please help me to find this formula ? Thank you

Please find below the echo json_encode I have in PHP :

{"id":"7","username":"Thomas","survey1":"valide","surveytoken1":"EuLwfqJI5UYLgK2LQ7jS","surveytokenvalid1":"1","surveydone1":"1","surveytoken2":"EuLwfqJI5UYLgK2LQ7jS","surveytokenvalid2":"1","surveydone2":"1" [...] "surveytokenvalid10":"1","surveydone10":"1"}

and here is my code in php:

   $user_username = $_SESSION['auth']->username;
   $user['username'] = $user_username;
   $req = $pdo->prepare('SELECT * FROM data WHERE (username = ?)');
   $req->execute([$user_username]);
   $surveyuser = $req->fetch();
   echo json_encode($surveyuser);

Body:
Here is the answer I have managed to found and it works.

   $user_username = $_SESSION['auth']->username;
   $user['username'] = $user_username;
   $req = $pdo->prepare('SELECT * FROM data WHERE (username = ?)');
   $req->execute([$user_username]);
   $surveyuser = $req->fetch();
   echo json_encode($surveyuser);

  $surveyuserarray = json_decode(json_encode($surveyuser), True);
  $surveyuser2 = json_encode($surveyuser);

  foreach($surveyuserarray as $key => $value){
    if (strpos($key, 'surveydone') === 0) {
        $only_point[$key] = $value;
       }
   }

  $total_points=array();
  $total_points['totalpoints']=array_sum($only_point);

   echo ($surveyuser2);
   echo json_encode($total_points);


问:
In python, how can I extract string with regex?
I want to write a simple markdown parser function that will take in a single line of markdown and be translated into the appropriate HTML. To keep it simple, I want to support only one feature of markdown in atx syntax: headers.

Headers are designated by (1-6) hashes followed by a space, followed by text. The number of hashes determines the header level of the HTML output.
Examples

```<code># Header will become <h1>Header</h1>

## Header will become <h2>Header</h2>

###### Header will become <h6>Header</h6>
</code>```

Rules are as follows

Header content should only come after the initial hashtag(s) plus a space character.

Invalid headers should just be returned as the markdown that was recieved, no translation necessary.

Spaces before and after both the header content and the hashtag(s) should be ignored in the resulting output.

This is code I made.

```<code>import re
def markdown_parser(markdown):
    results =''
    pattern = re.compile("#+\s")
    matches = pattern.search(markdown.strip())
    if (matches != None):
        tag = matches[0]
        hashTagLen = len(tag) - 1
        htmlTag = "h" + str(hashTagLen)
        content = markdown.strip()[(hashTagLen + 1):]
        results = "<" + htmlTag + ">" + content + "</" + htmlTag + ">"
    else:
        results = markdown
    return results
</code>```

When I run this code, exception has occurred as follows.

Unhandled Exception: '_sre.SRE_Match' object is not subscriptable

I'm not sure why this error has occurred.

When I run the script on my shell, it works well.
But When I run it on unittest environment (import unittest), the error has occurred.

Please help me.

答:
You don't use indexing to access a Match Object.
https://docs.python.org/2/library/re.html#match-objects</p>

Body:
I want to write a simple markdown parser function that will take in a single line of markdown and be translated into the appropriate HTML. To keep it simple, I want to support only one feature of markdown in atx syntax: headers.

Headers are designated by (1-6) hashes followed by a space, followed by text. The number of hashes determines the header level of the HTML output.
Examples

# Header will become
Header

## Header will become
Header

###### Header will become
Header

Rules are as follows

Header content should only come after the initial hashtag(s) plus a space character.

Invalid headers should just be returned as the markdown that was recieved, no translation necessary.

Spaces before and after both the header content and the hashtag(s) should be ignored in the resulting output.

This is code I made.

import re
def markdown_parser(markdown):
    results =''
    pattern = re.compile("#+\s")
    matches = pattern.search(markdown.strip())
    if (matches != None):
        tag = matches[0]
        hashTagLen = len(tag) - 1
        htmlTag = "h" + str(hashTagLen)
        content = markdown.strip()[(hashTagLen + 1):]
        results = "<" + htmlTag + ">" + content + "</" + htmlTag + ">"
    else:
        results = markdown
    return results

When I run this code, exception has occurred as follows.

Unhandled Exception: '_sre.SRE_Match' object is not subscriptable

I'm not sure why this error has occurred.

When I run the script on my shell, it works well.
But When I run it on unittest environment (import unittest), the error has occurred.

Please help me.


问:
Wrapping boost::shared_ptr in PHP using SWIG
If I use SWIG to wrap this C++ function:

```<code>boost::shared_ptr<Client> Client::create() {
    return boost::shared_ptr<Client>(new Client());
}
</code>```

And then call it in PHP:

```<code>$client = Client::create();
echo gettype($client);
</code>```

The type of $client is resource, not object, and so I cannot call Client methods.

What are my options for wrapping this function? I'm creating a PHP wrapper for someone else's C++ library, so reworking the code to not use boost::shared_ptr isn't really an option.

This is the only solution I've come up with so far:

```<code>MyClient Client::createObject() {
    return *Client::create();
}
</code>```

And calling it in PHP:

```<code>$client = Client::createObject();
echo gettype($client);
</code>```

Now the type of $client is object and I can call Client methods on it. Is this a reasonable workaround? If not, what should I be doing?

答: You should take a look to http://www.swig.org/Doc2.0/SWIGPlus.html#SWIGPlus_smart_pointers ;)</p>

Body:
If I use SWIG to wrap this C++ function:

boost::shared_ptr<Client> Client::create() {
    return boost::shared_ptr<Client>(new Client());
}

And then call it in PHP:

$client = Client::create();
echo gettype($client);

The type of $client is resource, not object, and so I cannot call Client methods.

What are my options for wrapping this function? I'm creating a PHP wrapper for someone else's C++ library, so reworking the code to not use boost::shared_ptr isn't really an option.

This is the only solution I've come up with so far:

MyClient Client::createObject() {
    return *Client::create();
}

And calling it in PHP:

$client = Client::createObject();
echo gettype($client);

Now the type of $client is object and I can call Client methods on it. Is this a reasonable workaround? If not, what should I be doing?


问:
How to know once a dynamically added script is parsed/loaded/executed?
I am trying to dynamically load a JavaScript file and, once it is loaded, run a function that is inside the file.  In my main HTML, I basically have:

```<code>function load_javascript(js_file)
{
    function load_js_callback(example)
    {
        console.log("function " + function_in_js_file + " is " + typeof(function_name));
        if (typeof(function_in_js_file) == "undefined")
        {
            window.setTimeout(load_js_callback(example), 500);
            return false;
        }
        function_in_js_file(example);
    }

    var jstag = document.createElement("script");
    document.head.appendChild(jstag);

    // Browsers:
    jstag.onload=load_js_callback("example");
    // Internet Explorer:
    jstag.onreadystatechange = function() {
        if (this.readyState == 'complete') {
            load_js_callback("example");
        }
    }
    jstag.setAttribute('src',js_file);
}

load_javascript("/js/example.js");
</code>```

From what I can find on the internet (https://stackoverflow.com/a/3248500 and https://stackoverflow.com/a/16231055) this should work, but the jstag.onload runs before the function_in_js_file is defined, so I need the window.setTimeout to check again until the function is defined.

Ideally, I would like to get rid of that timeout.  Is there any way to know when the file has been completed loaded/parsed/executed (I'm not sure which is the right term) and the function is defined, ideally without changing the dynamic file?  I have also tried putting the document.head.appendChild(jstag); after the jstag.setAttribute, but with the same results.

答:
The reason it's running before the script loads is because:

```<code>var jstag = document.createElement("script");
document.head.appendChild(jstag);

// Browsers:
jstag.onload=load_js_callback("example");
</code>```

Is assigning the return value of load_js_callback to jstag.onload. The onload handler wants a function:

```<code>var jstag = document.createElement("script");
document.head.appendChild(jstag);

// Browsers:
jstag.onload=function() { load_js_callback("example"); };
</code>```

As pointed out in the other comments, all this guarantees is that the browser has downloaded the script.

Body:
I am trying to dynamically load a JavaScript file and, once it is loaded, run a function that is inside the file.  In my main HTML, I basically have:

function load_javascript(js_file)
{
    function load_js_callback(example)
    {
        console.log("function " + function_in_js_file + " is " + typeof(function_name));
        if (typeof(function_in_js_file) == "undefined")
        {
            window.setTimeout(load_js_callback(example), 500);
            return false;
        }
        function_in_js_file(example);
    }

    var jstag = document.createElement("script");
    document.head.appendChild(jstag);

    // Browsers:
    jstag.onload=load_js_callback("example");
    // Internet Explorer:
    jstag.onreadystatechange = function() {
        if (this.readyState == 'complete') {
            load_js_callback("example");
        }
    }
    jstag.setAttribute('src',js_file);
}

load_javascript("/js/example.js");

From what I can find on the internet (https://stackoverflow.com/a/3248500 and https://stackoverflow.com/a/16231055) this should work, but the jstag.onload runs before the function_in_js_file is defined, so I need the window.setTimeout to check again until the function is defined.

Ideally, I would like to get rid of that timeout.  Is there any way to know when the file has been completed loaded/parsed/executed (I'm not sure which is the right term) and the function is defined, ideally without changing the dynamic file?  I have also tried putting the document.head.appendChild(jstag); after the jstag.setAttribute, but with the same results.

Body:
The reason it's running before the script loads is because:

var jstag = document.createElement("script");
document.head.appendChild(jstag);

// Browsers:
jstag.onload=load_js_callback("example");

Is assigning the return value of load_js_callback to jstag.onload. The onload handler wants a function:

var jstag = document.createElement("script");
document.head.appendChild(jstag);

// Browsers:
jstag.onload=function() { load_js_callback("example"); };

As pointed out in the other comments, all this guarantees is that the browser has downloaded the script.


问:
Error on importing a java external library
here is my .java file and the directory which contains the external .jar files.

Now,on compilation on terminal(Ubuntu 16.04)

I get this error:-

package uk.co.caprica.vlcj.binding does not exist

here are my two import statements

```<code>import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
</code>```

I tried entering the folder name(full path) on my import statement ,but is still doesn't work.

I successfully compiled ,buit when I try to run the file
I get main class not found error.

Compile command
javac -cp ".:./lib/jna-3.5.2.jar/:lib/platform-3.5.2.jar/:lib/vlcj-3.8.0.jar" main.java

Run Command
java -cp ".:./lib/jna-3.5.2.jar/:lib/platform-3.5.2.jar/:lib/vlcj-3.8.0.jar" main

答:
If your command is the one you commented in Andres' answer, then your path is wrong.
Try:</p>

```<code>javac -cp ".:./lib/*" main.java
</code>```

Body:
here is my .java file and the directory which contains the external .jar files.

Now,on compilation on terminal(Ubuntu 16.04)

I get this error:-

package uk.co.caprica.vlcj.binding does not exist

here are my two import statements

import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;

I tried entering the folder name(full path) on my import statement ,but is still doesn't work.

I successfully compiled ,buit when I try to run the file
I get main class not found error.

Compile command
javac -cp ".:./lib/jna-3.5.2.jar/:lib/platform-3.5.2.jar/:lib/vlcj-3.8.0.jar" main.java

Run Command
java -cp ".:./lib/jna-3.5.2.jar/:lib/platform-3.5.2.jar/:lib/vlcj-3.8.0.jar" main

Body:
If your command is the one you commented in Andres' answer, then your path is wrong.
Try:

javac -cp ".:./lib/*" main.java


问:
Not able to get all songs from a device on Android
I'm trying to learn how to develop an Android app and I found a very useful tutorial on the web which was trying to create a simple music player.

Even though I followed it, I've got a problem:
When I try to run the app, I don't get any error in the compiler, but on the emulator the app won't start with the following error message:

Unfortunately, MusicPlayer has stopped.

This is the code:

```<code>public class MainActivity extends AppCompatActivity {
private ArrayList<Song> songList;
private ListView songView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    songView = (ListView) findViewById(R.id.song_list);
    songList = new ArrayList<Song>();
    getSongList();
}

public void getSongList(){
    // retrieve song info
    ContentResolver musicResolver = getContentResolver();
    Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
    if(musicCursor!=null && musicCursor.moveToFirst()){
        //get columns

        int titleColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.TITLE);
        int idColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media._ID);
        int artistColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.ARTIST);
        //add songs to list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            songList.add(new Song(thisId, thisTitle, thisArtist));
        }
        while (musicCursor.moveToNext());
    }
}
</code>```

}

After reviewing the code a bit, I found out that the app crashes when I call the following command:

```<code>Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
</code>```

Any idea of what's the problem?

答:
Looking at the documentation here: https://developer.android.com/guide/topics/providers/content-provider-basics.html

You need to pass in more arguments than you are.  The second parameter should be a string array of column names, and it seems that without that you won't be able to select any data.

Snippet from the documentation:

```<code>// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
    UserDictionary.Words.CONTENT_URI,   // The content URI of the words table
    mProjection,                        // The columns to return for each row
    mSelectionClause                    // Selection criteria
    mSelectionArgs,                     // Selection criteria
    mSortOrder);                        // The sort order for the returned rows
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to learn how to develop an Android app and I found a very useful tutorial on the web which was trying to create a simple music player.

Even though I followed it, I've got a problem:
When I try to run the app, I don't get any error in the compiler, but on the emulator the app won't start with the following error message:

Unfortunately, MusicPlayer has stopped.

This is the code:

public class MainActivity extends AppCompatActivity {
private ArrayList<Song> songList;
private ListView songView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    songView = (ListView) findViewById(R.id.song_list);
    songList = new ArrayList<Song>();
    getSongList();
}

public void getSongList(){
    // retrieve song info
    ContentResolver musicResolver = getContentResolver();
    Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
    if(musicCursor!=null && musicCursor.moveToFirst()){
        //get columns

        int titleColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.TITLE);
        int idColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media._ID);
        int artistColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.ARTIST);
        //add songs to list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            songList.add(new Song(thisId, thisTitle, thisArtist));
        }
        while (musicCursor.moveToNext());
    }
}

}

After reviewing the code a bit, I found out that the app crashes when I call the following command:

Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);

Any idea of what's the problem?

Body:
Looking at the documentation here: https://developer.android.com/guide/topics/providers/content-provider-basics.html

You need to pass in more arguments than you are.  The second parameter should be a string array of column names, and it seems that without that you won't be able to select any data.

Snippet from the documentation:

// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
    UserDictionary.Words.CONTENT_URI,   // The content URI of the words table
    mProjection,                        // The columns to return for each row
    mSelectionClause                    // Selection criteria
    mSelectionArgs,                     // Selection criteria
    mSortOrder);                        // The sort order for the returned rows


问:
Ruby on Rails with Heroku: fatal: No configured push destination
I'm trying to deploy my app with Heroku, I'm using a tutorial from YouTube and I'm stuck on a part in the tutorial that tells you to enter in the terminal...

```<code>git push
</code>```

after many other commands. When I did enter that command, I get the following message

```<code>fatal: No configured push destination.
Either specify the URL from the command-line or configure a remote repository using

    git remote add <name> <url>

and then push using the remote name

    git push <name>
</code>```

I'm not sure what to put in, what do I have to put in?

In case you are wondering, I'm using the tutorial with the below link
https://www.youtube.com/watch?v=mabGJ-vuABc

答:
For deploy your code following command use for push your code

```<code>git push heroku master
</code>```

For your reference : tutorial

Follow all steps as in tutorial

Body:
I'm trying to deploy my app with Heroku, I'm using a tutorial from YouTube and I'm stuck on a part in the tutorial that tells you to enter in the terminal...

git push

after many other commands. When I did enter that command, I get the following message

fatal: No configured push destination.
Either specify the URL from the command-line or configure a remote repository using

    git remote add <name> <url>

and then push using the remote name

    git push <name>

I'm not sure what to put in, what do I have to put in?

In case you are wondering, I'm using the tutorial with the below link
https://www.youtube.com/watch?v=mabGJ-vuABc

Body:
For deploy your code following command use for push your code

git push heroku master

For your reference : tutorial

Follow all steps as in tutorial


问:
Build (make) lib every time, recompile project only if lib is newer
I have the following project structure:

```<code>lib/
    Makefile
    src/...
    inc/...
    build/
        inc/...
        lib/libmylib.a
subproj1/
    src/main.cpp
    Makefile
</code>```

The Makefile in the lib folder is designed to create the file libmylib.a and copy the relevant header files to the build/inc folder.

I want the Makefile in subproj1 to always call make -C ../lib, but only re-compile file if headers have changed, and re-link only if necessary (one object file or libmylib.a is newer).

I have the following (non-defined variables such as CC are defined in another file):

```<code>LIBDIR = ../lib
SRCDIR = src
OBJDIR = obj
SRCS = $(SRCDIR)/main.cpp

MAIN=myexe

OBJS = $(SRCS:$(SRCDIR)/%.cpp=$(OBJDIR)/%.o)
DEPS = $(OBJS:.o=.d)

all: $(MAIN)

debug: CFLAGS += -g -DDEBUG
debug: LFLAGS += -g
debug: $(MAIN)

$(MAIN): $(OBJS) $(LIBDIR)/build/lib/libmylib.a
    $(CC) $^ -o $@ $(LIBS) $(LFLAGS)

$(OBJDIR)/%.o: $(SRCDIR)/%.cpp $(LIBDIR)/build/lib/libmylib.a
    mkdir -p $(OBJDIR)
    $(CC) -c -o $@ $(CFLAGS) $(INCS) -MD -MF $(patsubst %.o, %.d, $@) $<

$(LIBDIR)/build/lib/libmylib.a:
    make -C $(LIBDIR)

-include $(DEPS)

.PHONY: clean $(LIBDIR)/build/lib/libmylib.a

clean:
    $(RM) obj/* $(MAIN)
</code>```

The above will re-compile main.cpp even if nothing has changed in the lib folder. If I remove $(LIBDIR)/build/lib/libmylib.a from the $(OBJDIR)/%.o rule, the .cpp file will not be re-compiled if a header changed (I would need to run make twice).

Is there a way to have the .cpp files in subproj1 being compiled only if the header files in lib have changed (or if the .cpp files themselves have changed), and to get myexe built only if one of the .cpp has been re-compiled (newer .o) or if libmylib.a is newer?

答:
With recursive makefiles you need to execute the sub-project makefiles in correct order because the dependency tree is incomplete (e.g. this makefile does not know that updating $(LIBDIR)/build/lib/libmylib.a also updates those headers). It is easy to do that with a shell script or a top-level makefile.

Alternatively, your makefile must execute the sub-makefiles unconditionally in correct order, which can be done with shell function, e.g.:

```<code>LIBDIR := ../lib
pid := $(shell ps -o ppid= $$$$)
$(shell ${MAKE} -C ${LIBDIR} >/proc/$(pid)/fd/1 2>/proc/$(pid)/fd/2)
</code>```

That $(LIBDIR)/build/lib/libmylib.a rule should be removed, the object files should not depend on the .a and it should not be marked as .PHONY.

This makes sure that building in ${LIBDIR} happens before this makefile analyzes file timestamps in ${LIBDIR}.

Now your auto-generated header dependencies should just work.

Body:
I have the following project structure:

lib/
    Makefile
    src/...
    inc/...
    build/
        inc/...
        lib/libmylib.a
subproj1/
    src/main.cpp
    Makefile

The Makefile in the lib folder is designed to create the file libmylib.a and copy the relevant header files to the build/inc folder.

I want the Makefile in subproj1 to always call make -C ../lib, but only re-compile file if headers have changed, and re-link only if necessary (one object file or libmylib.a is newer).

I have the following (non-defined variables such as CC are defined in another file):

LIBDIR = ../lib
SRCDIR = src
OBJDIR = obj
SRCS = $(SRCDIR)/main.cpp

MAIN=myexe

OBJS = $(SRCS:$(SRCDIR)/%.cpp=$(OBJDIR)/%.o)
DEPS = $(OBJS:.o=.d)

all: $(MAIN)

debug: CFLAGS += -g -DDEBUG
debug: LFLAGS += -g
debug: $(MAIN)

$(MAIN): $(OBJS) $(LIBDIR)/build/lib/libmylib.a
    $(CC) $^ -o $@ $(LIBS) $(LFLAGS)

$(OBJDIR)/%.o: $(SRCDIR)/%.cpp $(LIBDIR)/build/lib/libmylib.a
    mkdir -p $(OBJDIR)
    $(CC) -c -o $@ $(CFLAGS) $(INCS) -MD -MF $(patsubst %.o, %.d, $@) $<

$(LIBDIR)/build/lib/libmylib.a:
    make -C $(LIBDIR)

-include $(DEPS)

.PHONY: clean $(LIBDIR)/build/lib/libmylib.a

clean:
    $(RM) obj/* $(MAIN)

The above will re-compile main.cpp even if nothing has changed in the lib folder. If I remove $(LIBDIR)/build/lib/libmylib.a from the $(OBJDIR)/%.o rule, the .cpp file will not be re-compiled if a header changed (I would need to run make twice).

Is there a way to have the .cpp files in subproj1 being compiled only if the header files in lib have changed (or if the .cpp files themselves have changed), and to get myexe built only if one of the .cpp has been re-compiled (newer .o) or if libmylib.a is newer?

Body:
With recursive makefiles you need to execute the sub-project makefiles in correct order because the dependency tree is incomplete (e.g. this makefile does not know that updating $(LIBDIR)/build/lib/libmylib.a also updates those headers). It is easy to do that with a shell script or a top-level makefile.

Alternatively, your makefile must execute the sub-makefiles unconditionally in correct order, which can be done with shell function, e.g.:

LIBDIR := ../lib
pid := $(shell ps -o ppid= $$$$)
$(shell ${MAKE} -C ${LIBDIR} >/proc/$(pid)/fd/1 2>/proc/$(pid)/fd/2)

That $(LIBDIR)/build/lib/libmylib.a rule should be removed, the object files should not depend on the .a and it should not be marked as .PHONY.

This makes sure that building in ${LIBDIR} happens before this makefile analyzes file timestamps in ${LIBDIR}.

Now your auto-generated header dependencies should just work.


问:
Remove \r from string
I have some Html in string I have tried utmost to remove \r many times but fails.</p>

```<code>text.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
</code>```

答:
You need to assign the result back to text, like:

```<code>text = text.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
</code>```

Title: Remove \r from string

Body:
I have some Html in string I have tried utmost to remove \r many times but fails.

text.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");

Body:
You need to assign the result back to text, like:

text = text.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");


问:
Google Translate get synonyms and examples
Can I access word's synonyms and examples along with the translation itself, when using Google Translate API?

I checked out docs but I don't see anything like that.

答:
Pearson released their free API which includes examples, part of speech, and synonyms. Check it out: http://developer.pearson.com/apis/dictionaries

http://api.pearson.com/v2/dictionaries/lase%20/entries?headword=hola

```<code>{
  "status": 200,
  "offset": 0,
  "limit": 10,
  "count": 1,
  "total": 1,
  "url": "/v2/dictionaries/lase /entries?headword=hola",
  "results": [
    {
      "datasets": [
        "lase",
        "dictionary"
      ],
      "headword": "hola",
      "id": "ct59rx0q97",
      "part_of_speech": "interjection",
      "senses": [
</code>```

Body:
Pearson released their free API which includes examples, part of speech, and synonyms. Check it out: http://developer.pearson.com/apis/dictionaries

http://api.pearson.com/v2/dictionaries/lase%20/entries?headword=hola

{
  "status": 200,
  "offset": 0,
  "limit": 10,
  "count": 1,
  "total": 1,
  "url": "/v2/dictionaries/lase /entries?headword=hola",
  "results": [
    {
      "datasets": [
        "lase",
        "dictionary"
      ],
      "headword": "hola",
      "id": "ct59rx0q97",
      "part_of_speech": "interjection",
      "senses": [


问:
How to set teleriks WPF IsTouchEnabled property on application level?
In http://docs.telerik.com/devtools/wpf/touch-support it states that it is possible to set the IsTouchEnabled to false on application level, but where/how?

答:
For example in your App.xaml.cs file:

```<code>public partial class App : Application
{
    public App()
    {
        Telerik.Windows.Input.Touch.TouchManager.IsTouchEnabled = false;
    }
}
</code>```

Body:
For example in your App.xaml.cs file:

public partial class App : Application
{
    public App()
    {
        Telerik.Windows.Input.Touch.TouchManager.IsTouchEnabled = false;
    }
}


问:
Django render: How to instance selected items in Select2 Jquery plugin
I'm filtering some data using Raw method, it allows the user to select multiple values in a field using Select2 plugin, I get request.POST of each field, do filtering stuff, then I return the context like this:

```<code>context = {
    'form': MyForm(request.POST),
    'results': results,
}
return render(request, self.template_name, context)
</code>```

It's suppossed to show the user which fields were selected when I get back the results to show them, but when the form renders I get selected only the first value of the list (retrieved from POST). Do I have to set something else? Or am I doing something wrong?

UPDATE: Render the input widget from Django Form:

```<code>equipo = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm', 'multiple': 'multiple'}
        )
    )
</code>```

Also, I'm not saving, I'm just retrieving values to apply filters using rawmethod and giving back the rawquery result.

View:

```<code>class MedicionView(View):

    def __init__(self):
        self.template_name = "medicion/grid.html"

    def get(self, request):

        form = MedicionFiltersForm()
        odometros = Odometro.objects.all()
        equipos = Equipo.objects.all()
        results = Odometro.objects.raw('''
            select
            ....

                ''')[:100]

        contexto = {
            'form': form,
            'results': results,
        }

        return render(request, self.template_name, contexto)

    def post(self, request):
        # Retrieve data
        form = MedicionFiltersForm(request.POST)
        equipos = request.POST.getlist('equipo')
        odometros = request.POST.getlist('odometro')
        tipo = request.POST.get('tipo')

        # business stuff

        results = Odometro.objects.raw('''
           select
            ...

                ''', [odometros, tipos, equipos])

        # More business stuff

        # return request.POST in form
        contexto = {
            'form': form,
            'results': results,
        }
        return render(request, self.template_name, contexto)
</code>```

M2M does not even exist in my models, I just use multiple values to make use of SQL WHERE IN clause in raw method.

答:
I resolved this issue in a not so nice method but it works:

I passed to a list of integers the values retrieved by the component in POST method and then dumped it into a JSON

```<code>lista_equipos = request.POST.getlist('equipo')
equipos_lista = [int(item) for item in lista_equipos]
equipos_json = json.dumps(equipos_lista)
</code>```

I return the JSON in the context:

```<code>context = {
    # some extra variables
    'equipos_lista': equipos_json
}
</code>```

In the template I retrieve this json and set the values into select2 component. Don't miss about the trigger method!

```<code><script>
    var array_equipos = {{ equipos_lista }};
    $('#id_equipo').val(array_equipos);
    $('#id_equipo').trigger('change');

 </script>
</code>```

Body:
I'm filtering some data using Raw method, it allows the user to select multiple values in a field using Select2 plugin, I get request.POST of each field, do filtering stuff, then I return the context like this:

context = {
    'form': MyForm(request.POST),
    'results': results,
}
return render(request, self.template_name, context)

It's suppossed to show the user which fields were selected when I get back the results to show them, but when the form renders I get selected only the first value of the list (retrieved from POST). Do I have to set something else? Or am I doing something wrong?

UPDATE: Render the input widget from Django Form:

equipo = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm', 'multiple': 'multiple'}
        )
    )

Also, I'm not saving, I'm just retrieving values to apply filters using rawmethod and giving back the rawquery result.

View:

class MedicionView(View):

    def __init__(self):
        self.template_name = "medicion/grid.html"

    def get(self, request):

        form = MedicionFiltersForm()
        odometros = Odometro.objects.all()
        equipos = Equipo.objects.all()
        results = Odometro.objects.raw('''
            select
            ....

                ''')[:100]

        contexto = {
            'form': form,
            'results': results,
        }

        return render(request, self.template_name, contexto)

    def post(self, request):
        # Retrieve data
        form = MedicionFiltersForm(request.POST)
        equipos = request.POST.getlist('equipo')
        odometros = request.POST.getlist('odometro')
        tipo = request.POST.get('tipo')

        # business stuff

        results = Odometro.objects.raw('''
           select
            ...

                ''', [odometros, tipos, equipos])

        # More business stuff

        # return request.POST in form
        contexto = {
            'form': form,
            'results': results,
        }
        return render(request, self.template_name, contexto)

M2M does not even exist in my models, I just use multiple values to make use of SQL WHERE IN clause in raw method.

Body:
I resolved this issue in a not so nice method but it works:

I passed to a list of integers the values retrieved by the component in POST method and then dumped it into a JSON

lista_equipos = request.POST.getlist('equipo')
equipos_lista = [int(item) for item in lista_equipos]
equipos_json = json.dumps(equipos_lista)

I return the JSON in the context:

context = {
    # some extra variables
    'equipos_lista': equipos_json
}

In the template I retrieve this json and set the values into select2 component. Don't miss about the trigger method!

<script>
    var array_equipos = {{ equipos_lista }};
    $('#id_equipo').val(array_equipos);
    $('#id_equipo').trigger('change');

 </script>


问:
jsessionid cookie set in jmeter request not recognised
I would like to execute some jmeter thread group requests in parallel using the same session. To do this, I have created a setUp thread group which authenticates and writes the JSESSIONID cookie (as well as other data) to a CSV file. This file is then to be used by the subsequent thread groups to allow them to use these already authenticated sessions.
To do this, I am basically following the solution outlined here: http://theworkaholic.blogspot.co.uk/2013/03/sharing-session-ids-across-threads.html.

The setUp thread group is authenticating and generating the CSV file as expected. However, I cannot get the requests in the subsequent thread groups to use the sessions provided. I can add the JSESSIONID cookie (either by using a BeanShell PreProcessor or using a HTTP Cookie Manager, both give the same results) but this does not seem to be recognised. The request being sent is the following:

```<code>POST https://test.mydomain.com:8443/prv/p/getUploadedfiles.action

POST data:
start=0&limit=10&sort=createdDate&dir=DESC&days=6

Cookie Data:
$Version=1; JSESSIONID="D0720DD3B06B5752DF6AC83A1B245EDA"; $Path="/";
$Domain="test.mydomain.com"

Request Headers:
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 49
Host: test.mydomain.com:8443
User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_121)
</code>```

This request has a return status of 302 to re-direct to the login page. This compares to the same request executed successfully in the setUp thread group:

```<code>POST https://test.mydomain.com:8443/prv/p/getUploadedfiles.action

POST data:
start=0&limit=10&sort=createdDate&dir=DESC&days=6

Cookie Data:
JSESSIONID=D0720DD3B06B5752DF6AC83A1B245EDA

Request Headers:
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 49
Host: test.mydomain.com:8443
User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_121)
</code>```

The only difference between the requests seem to be the $Version, $Path and $Domain explicitly set on the cookie data. [Interestingly, the 'Cookie Data' in the solution from the link above seems to be correct, by which I mean does not contain the $Version, $Path or $Domain in the request output]
BeanShell PreProcessor code is:

```<code>import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;

Cookie cookie = new Cookie("JSESSIONID", vars.get("jsessionid"), "test.mydomain.com", "/", true, -1);
CookieManager manager = sampler.getCookieManager();
manager.add(cookie);
log.info("Cookie added: " + vars.get("jsessionid"));
</code>```

Does anyone know why the JSESSIONID cookie is not being recognised?

答: Cookies scope is limited to current Thread Group only. The same applies to JMeter Variables. If you need to pass objects between different Thread Groups you will have to do it via bsh.shared namespace or by converting JMeter Variables into JMeter Properties which are global for the whole JVM. See Knit One Pearl Two: How to Use Variables in Different Thread Groups article for example JMeter Variable to JMeter Property conversion. </p>

Body:
I would like to execute some jmeter thread group requests in parallel using the same session. To do this, I have created a setUp thread group which authenticates and writes the JSESSIONID cookie (as well as other data) to a CSV file. This file is then to be used by the subsequent thread groups to allow them to use these already authenticated sessions.
To do this, I am basically following the solution outlined here: http://theworkaholic.blogspot.co.uk/2013/03/sharing-session-ids-across-threads.html.

The setUp thread group is authenticating and generating the CSV file as expected. However, I cannot get the requests in the subsequent thread groups to use the sessions provided. I can add the JSESSIONID cookie (either by using a BeanShell PreProcessor or using a HTTP Cookie Manager, both give the same results) but this does not seem to be recognised. The request being sent is the following:

POST https://test.mydomain.com:8443/prv/p/getUploadedfiles.action

POST data:
start=0&limit=10&sort=createdDate&dir=DESC&days=6

Cookie Data:
$Version=1; JSESSIONID="D0720DD3B06B5752DF6AC83A1B245EDA"; $Path="/";
$Domain="test.mydomain.com"

Request Headers:
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 49
Host: test.mydomain.com:8443
User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_121)

This request has a return status of 302 to re-direct to the login page. This compares to the same request executed successfully in the setUp thread group:

POST https://test.mydomain.com:8443/prv/p/getUploadedfiles.action

POST data:
start=0&limit=10&sort=createdDate&dir=DESC&days=6

Cookie Data:
JSESSIONID=D0720DD3B06B5752DF6AC83A1B245EDA

Request Headers:
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 49
Host: test.mydomain.com:8443
User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_121)

The only difference between the requests seem to be the $Version, $Path and $Domain explicitly set on the cookie data. [Interestingly, the 'Cookie Data' in the solution from the link above seems to be correct, by which I mean does not contain the $Version, $Path or $Domain in the request output]
BeanShell PreProcessor code is:

import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;

Cookie cookie = new Cookie("JSESSIONID", vars.get("jsessionid"), "test.mydomain.com", "/", true, -1);
CookieManager manager = sampler.getCookieManager();
manager.add(cookie);
log.info("Cookie added: " + vars.get("jsessionid"));

Does anyone know why the JSESSIONID cookie is not being recognised?


问:
NodeJS json provided in request is not sent with push
I am trying to call my api for a post webservice from a Node application.
I successfully pulled data from this same api with a get method, so connexion works perfectly.
Now I want to make a push

```<code>    request({
        method: 'POST',
        url: ws.url,
        json: {"id": 78, "product" : "MyProduct"}
    }, function (error, response,body) {
        console.log('error ',error);
        console.log('body ',body);
        console.log('response ',response);
        cb(error, response)
        //console.log(error, response)
    })
</code>```

I ve got these console.log :

```<code>error  undefined
body  undefined
response  { errMsg: 'id not provided ' }
</code>```

So the response is quite explicit, API havent received my id.
However when I call manually same ws with Postman, it works normally.

So what s wrong with my json param? should I send it another way?
My webservice needs to have this content in its body and nothing else:

```<code>{"id": 78, "product" : "MyProduct"}
</code>```

答:
I found my issue, and in fact the project where I am working extended Request library, and issue is in the method that overrode Request original behaviour.
So to sum up, my code above is supposed to work, I just have to fix this dirty override.</p>

Body:
I am trying to call my api for a post webservice from a Node application.
I successfully pulled data from this same api with a get method, so connexion works perfectly.
Now I want to make a push

    request({
        method: 'POST',
        url: ws.url,
        json: {"id": 78, "product" : "MyProduct"}
    }, function (error, response,body) {
        console.log('error ',error);
        console.log('body ',body);
        console.log('response ',response);
        cb(error, response)
        //console.log(error, response)
    })

I ve got these console.log :

error  undefined
body  undefined
response  { errMsg: 'id not provided ' }

So the response is quite explicit, API havent received my id.
However when I call manually same ws with Postman, it works normally.

So what s wrong with my json param? should I send it another way?
My webservice needs to have this content in its body and nothing else:

{"id": 78, "product" : "MyProduct"}


问:
difference between mongoose js virtuals and custom setter
Could someone clarify the difference between Mongoose JS's virtuals and custom setters comparatavely?

I searched on google nothing useful came out. To me it seems they serve to the same purpose, so why to keep them both?

答: The main difference between virtuals and setters is that virtual allows to have fields that are not stored in the database and the setters actually change some field that is stored in the database. So I would say that is the matter of persistence of data in the database.</p>


问:
Redirect on success and show error on failure
I have implemented a controller to create new users. When it creates the user successfully it redirects to Index().

What I want is to get redirected when all is OK, but stay in the current page and see the error when something failed.

I'm using jQuery ajax with MVC.

My controller looks like this:

```<code>[Authorize]
public ActionResult CreateUser(string username)
{
    try
    {
        //here the logic to create the user
    }
    catch (Exception ex)
    {
        string error = string.Format("Error creating user: {0}", ex.Message);
        Response.StatusCode = 500;
        Response.Write(error);
    }
    return RedirectToAction("Index");
}
</code>```

The form submit is intercepted with jQuery, and then the call is made with ajax:

```<code>$("#new-user-form").submit(function() {
    var form = $(this);
    $.ajax({
    type: "GET",
        url: form.attr('action'),
        data: form.serialize(),
        success: function(data, textStatus, xhr) {
            //At this point I would like to redirect
        },
        error: function(xhr, textStatus, errorThrown) {
            $(".error-summary").html(xhr.responseText);
        }
    });

    //cancel the event
    return false;
});
</code>```

It works fine when an error occurs, but I don't know how to implement the success case.

I'm opened to other alternatives.

答:
```<code> window.location.href="url here"
</code>```

Moz Doc

Body:
I have implemented a controller to create new users. When it creates the user successfully it redirects to Index().

What I want is to get redirected when all is OK, but stay in the current page and see the error when something failed.

I'm using jQuery ajax with MVC.

My controller looks like this:

[Authorize]
public ActionResult CreateUser(string username)
{
    try
    {
        //here the logic to create the user
    }
    catch (Exception ex)
    {
        string error = string.Format("Error creating user: {0}", ex.Message);
        Response.StatusCode = 500;
        Response.Write(error);
    }
    return RedirectToAction("Index");
}

The form submit is intercepted with jQuery, and then the call is made with ajax:

$("#new-user-form").submit(function() {
    var form = $(this);
    $.ajax({
    type: "GET",
        url: form.attr('action'),
        data: form.serialize(),
        success: function(data, textStatus, xhr) {
            //At this point I would like to redirect
        },
        error: function(xhr, textStatus, errorThrown) {
            $(".error-summary").html(xhr.responseText);
        }
    });

    //cancel the event
    return false;
});

It works fine when an error occurs, but I don't know how to implement the success case.

I'm opened to other alternatives.

Body:
 window.location.href="url here"

Moz Doc


问:
LibGDX how to catch touch event outside of the actor bounds
I have a stage and the actor on it with size 200x200. I need the actor catch touch events to make some calculations. But the problem is that touch events triggers only when touched over the actors bound. How can i get the event of touching any area of the screen, but handled inside the actor`s class?</p>

```<code>public class MyActor extends Actor {

public MyActor() {

    setBounds(100f, 100f, 200f, 200f);

    addListener(new InputListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            return super.touchDown(event, x, y, pointer, button);
        }

        @Override
        public void touchDragged(InputEvent event, float x, float y, int pointer) {
            super.touchDragged(event, x, y, pointer);
        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            super.touchUp(event, x, y, pointer, button);
        }
    });
}
</code>```

答:
Add listener on stage instead of any particular Actor

```<code>stage.addListener(new InputListener(){

            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

                Gdx.app.log("Stage Listener","inside touch down");
                return super.touchDown(event, x, y, pointer, button);
            }

            @Override
            public void touchDragged(InputEvent event, float x, float y, int pointer) {

                super.touchDragged(event, x, y, pointer);
            }

            @Override
            public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
                super.touchUp(event, x, y, pointer, button);
            }
        });
</code>```

EDIT

Fire event on all required Actor and handle in MyActor listener tocuhDown(..) method

```<code>stage.addListener(new InputListener(){

        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

            for(Actor actor:stage.getActors()){
                if(actor.getName().equals("MyActor")) {

                    InputEvent myEvent=new InputEvent();
                    myEvent.setType(InputEvent.Type.touchDown);
                    myEvent.setStage(stage);
                    myEvent.setPointer(pointer);
                    myEvent.setButton(button);
                    myEvent.setStageX(x);
                    myEvent.setStageY(y);
                    actor.fire(myEvent);
                }
            }
            return super.touchDown(event,x,y,pointer,button);
        }
    });
</code>```

MyActor class

```<code>public class MyActor extends Actor {

  public MyActor(){
    setBounds(100f, 100f, 200f, 200f);
    setName("MyActor");

    addListener(new InputListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

            Gdx.app.log("MyActor","touched");
            event.stop();
            return false;
        }
    });
  }
}
</code>```

Body:
I have a stage and the actor on it with size 200x200. I need the actor catch touch events to make some calculations. But the problem is that touch events triggers only when touched over the actors bound. How can i get the event of touching any area of the screen, but handled inside the actor`s class?

public class MyActor extends Actor {

public MyActor() {

    setBounds(100f, 100f, 200f, 200f);

    addListener(new InputListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            return super.touchDown(event, x, y, pointer, button);
        }

        @Override
        public void touchDragged(InputEvent event, float x, float y, int pointer) {
            super.touchDragged(event, x, y, pointer);
        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            super.touchUp(event, x, y, pointer, button);
        }
    });
}

Body:
Add listener on stage instead of any particular Actor

stage.addListener(new InputListener(){

            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

                Gdx.app.log("Stage Listener","inside touch down");
                return super.touchDown(event, x, y, pointer, button);
            }

            @Override
            public void touchDragged(InputEvent event, float x, float y, int pointer) {

                super.touchDragged(event, x, y, pointer);
            }

            @Override
            public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
                super.touchUp(event, x, y, pointer, button);
            }
        });

EDIT

Fire event on all required Actor and handle in MyActor listener tocuhDown(..) method

stage.addListener(new InputListener(){

        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

            for(Actor actor:stage.getActors()){
                if(actor.getName().equals("MyActor")) {

                    InputEvent myEvent=new InputEvent();
                    myEvent.setType(InputEvent.Type.touchDown);
                    myEvent.setStage(stage);
                    myEvent.setPointer(pointer);
                    myEvent.setButton(button);
                    myEvent.setStageX(x);
                    myEvent.setStageY(y);
                    actor.fire(myEvent);
                }
            }
            return super.touchDown(event,x,y,pointer,button);
        }
    });

MyActor class

public class MyActor extends Actor {

  public MyActor(){
    setBounds(100f, 100f, 200f, 200f);
    setName("MyActor");

    addListener(new InputListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

            Gdx.app.log("MyActor","touched");
            event.stop();
            return false;
        }
    });
  }
}


问:
Functional Programming style growing array loop
What is the smartest way to iterate over an array that grows during iteration in javascript? I want to iterate over all added elemets, even elements added during iterations. I'd like do to it in functional programming style.

For example see this code

let a = [
 'x',
  'y'
]

let limit = 4  // limit the test

for (let i=0; i0){
      a.push(a[i]+'-')
    }
}

console.log(a)```
</div>
</div>
</p>

<p>After execution got </p>

```[
  "x",
  "y",
  "x-",
  "y-",
  "x--"
]
```

<p>But if I try with an alternative "funcional" mode like forEach the new added elements are not printed</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-js lang-js prettyprint-override"><code>let a = [
 'x',
  'y'
]

let limit = 4  // limit the test

a.forEach( (e) => {
    console.log(e)
    limit--
    if(limit>0){
      a.push(e+'-')
    }
})

console.log(a)</code>```

答:
I'd like do to it in functional programming style.

In functional programming, arrays don't grow. Using lazyness, you could however iterate over elements that don't yet exist, basically an infinite stream. For example, in Haskell:

> let a = ["x", "y"] ++ map (++"-") a
> --                                ^ reference to the list itself
> take 5 a
["x","y","x-","y-","x--"
```

<blockquote>
  <p>What is the smartest way to iterate over an array that grows during iteration in javascript?</p>
</blockquote>

<p>I would use a similar approach, though of course you need a helper function that mutates the array:</p>

```function takeMapPrev(fn, arr, limit) {
    if (!arr.length) throw new RangeError("must start with something");
    var i = 0;
    while (arr.length < limit)
        arr.push(fn(arr[i++]));
    return arr;
}

console.log(takeMapPrev(e => e+'-', ['x','y'], 5)); // ["x","y","x-","y-","x--"]
```

Body:
What is the smartest way to iterate over an array that grows during iteration in javascript? I want to iterate over all added elemets, even elements added during iterations. I'd like do to it in functional programming style.

For example see this code

let a = [
 'x',
  'y'
]

let limit = 4  // limit the test

for (let i=0; i0){
      a.push(a[i]+'-')
    }
}

console.log(a)

After execution got

[
  "x",
  "y",
  "x-",
  "y-",
  "x--"
]

But if I try with an alternative "funcional" mode like forEach the new added elements are not printed

let a = [
 'x',
  'y'
]

let limit = 4  // limit the test

a.forEach( (e) => {
    console.log(e)
    limit--
    if(limit>0){
      a.push(e+'-')
    }
})

console.log(a)

Body:
I'd like do to it in functional programming style.

In functional programming, arrays don't grow. Using lazyness, you could however iterate over elements that don't yet exist, basically an infinite stream. For example, in Haskell:

> let a = ["x", "y"] ++ map (++"-") a
> --                                ^ reference to the list itself
> take 5 a
["x","y","x-","y-","x--"

What is the smartest way to iterate over an array that grows during iteration in javascript?

I would use a similar approach, though of course you need a helper function that mutates the array:

function takeMapPrev(fn, arr, limit) {
    if (!arr.length) throw new RangeError("must start with something");
    var i = 0;
    while (arr.length < limit)
        arr.push(fn(arr[i++]));
    return arr;
}

console.log(takeMapPrev(e => e+'-', ['x','y'], 5)); // ["x","y","x-","y-","x--"]


问:
Opengl ES Android - Rotate camera around itself
I am developing a terrain generation app on android with Opengl ES, and I am having problems rotating the camera around itself ( the FPS effect to make it clear).
what I am doing is to move the view with Matrix.setLookAtMand then rotating the view after translating it to the origin.This is a snippet of the code:

```<code>    Matrix.setLookAtM(mViewMatrix, 0, xrot, eyeY, yrot, xrot, lookY, yrot,0.0f, 1.0f, 0.0f);

    Matrix.translateM(mViewMatrix,0,-xrot,0f,-yrot);
    Matrix.rotateM(mViewMatrix, 0, mAngleX+mAngleY, 0.0f, 1.0f,0.0f);
    Matrix.translateM(mViewMatrix,0,xrot,0f,yrot);
</code>```

where xrot,yrot,mAngleX+mAngleY are input from the touchscreen.
This code works only in the origin, but when you move it rotates around the y axis of the world and not the camera one. I guess I am not doing it right but I didn't find a way to do it that works anywhere.

答:
I found a way to do it:

```<code>    Matrix.setIdentityM(mCurrentRotation, 0);
    Matrix.rotateM(mCurrentRotation, 0, mAngleY+mAngleX, 0.0f,1.0f, 0.0f);
    Matrix.rotateM(mCurrentRotation, 0, mAngleX, 0.0f,0.0f, 1.0f);
    mAngleX = 0.0f;
    mAngleY = 0.0f;

    Matrix.multiplyMM(mTemporaryMatrix, 0, mCurrentRotation, 0, mAccumulatedRotation, 0);

    System.arraycopy(mTemporaryMatrix, 0, mAccumulatedRotation, 0, 16);
    Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);
    // multiply the rotation just for model*view
    Matrix.multiplyMM(mMVPMatrix, 0, mTemporaryMatrix, 0, mMVPMatrix, 0);
    //than add projection as usual
    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);
</code>```

Where mTemporaryMatrix, mCurrentRotation,mAccumulatedRotation, are matrices to calculate total rotation, keep frame rotation and store the whole rotation of the camera, respectively. This solution works for rotation but it doesn't make the camera move in the direction it is pointing.

Body:
I am developing a terrain generation app on android with Opengl ES, and I am having problems rotating the camera around itself ( the FPS effect to make it clear).
what I am doing is to move the view with Matrix.setLookAtMand then rotating the view after translating it to the origin.This is a snippet of the code:

    Matrix.setLookAtM(mViewMatrix, 0, xrot, eyeY, yrot, xrot, lookY, yrot,0.0f, 1.0f, 0.0f);

    Matrix.translateM(mViewMatrix,0,-xrot,0f,-yrot);
    Matrix.rotateM(mViewMatrix, 0, mAngleX+mAngleY, 0.0f, 1.0f,0.0f);
    Matrix.translateM(mViewMatrix,0,xrot,0f,yrot);

where xrot,yrot,mAngleX+mAngleY are input from the touchscreen.
This code works only in the origin, but when you move it rotates around the y axis of the world and not the camera one. I guess I am not doing it right but I didn't find a way to do it that works anywhere.

Body:
I found a way to do it:

    Matrix.setIdentityM(mCurrentRotation, 0);
    Matrix.rotateM(mCurrentRotation, 0, mAngleY+mAngleX, 0.0f,1.0f, 0.0f);
    Matrix.rotateM(mCurrentRotation, 0, mAngleX, 0.0f,0.0f, 1.0f);
    mAngleX = 0.0f;
    mAngleY = 0.0f;

    Matrix.multiplyMM(mTemporaryMatrix, 0, mCurrentRotation, 0, mAccumulatedRotation, 0);

    System.arraycopy(mTemporaryMatrix, 0, mAccumulatedRotation, 0, 16);
    Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);
    // multiply the rotation just for model*view
    Matrix.multiplyMM(mMVPMatrix, 0, mTemporaryMatrix, 0, mMVPMatrix, 0);
    //than add projection as usual
    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);

Where mTemporaryMatrix, mCurrentRotation,mAccumulatedRotation, are matrices to calculate total rotation, keep frame rotation and store the whole rotation of the camera, respectively. This solution works for rotation but it doesn't make the camera move in the direction it is pointing.


问:
Specifying how script should be executed in PyCharm
I'm working on Django project and I want to run a script that I wrote for quick prototyping. Say the script is named 'prototype.py'.

In terminal I can execute it by doing python manage.py shell < prototype.py

However, I would like to do this not through terminal, but directly through my IDE (PyCharm), is it possible?

I.e. run python manage.py shell < some_script.py when I press Ctrl + Shift + F10 .

答:
I think you should look into PyCharm External Tools

Essentially you can have PyCharm kick things off in its console. File | Settings | Tools | External Tools | '+'. You can play around with the top bit, but for the sake of this lets just say Name = foo, Group = bar, Description = foobar, and check all the boxes. For Program put python. In Parameters put manage.py shell < some_script.py. For Working directory:, depends on what you want. The Insert macro... button is pretty useful though.

I'm not sure if it will handle the < or shell, but worth a try. If they don't work there may be some way of restructuring your command to get it to work. For instance maybe adding that line to a "shell script" and kicking the shell script off from PyCharm.

You can run it from the Tools | bar | foo drop down menu. By just using it a couple times in a row PyCharm will ask if you want to make it a Keymap. Or you could do it manually File | Settings | Keymap | External Tools


问:
Android Fragments are Duplicating/Recreating on Orientation Change
I'm trying to show two Fragments in a FrameLayout container. I only show one at a time and hide another one based on my application logic. I believe every time I change my device orientation, they recreate! I can see duplicates of fragments overlapping each other! How to fix it? Thanks in advance.

```<code>public class MainActivity extends AppCompatActivity {

   final Fragment oneFragment = oneFragment.newInstance();
   final Fragment twoFragment = twoFragment.newInstance();
   Fragment active = oneFragment;

   final FragmentManager fm = getSupportFragmentManager();

@Override
   protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       // some other code

        fm.beginTransaction().add(R.id.container, oneFragment, "1").commit();
        fm.beginTransaction().add(R.id.container, twoFragment, "2").commit();

        // onclick listener
        if(condition) {
            fm.beginTransaction().hide(active)
            .show(oneFragment).commit();
        } else {
            fm.beginTransaction().hide(active)
            .show(twoFragment).commit();
        }

      // some other code
</code>```

答:
try this:</p>

```<code> if (condition) {
    replaceFragment(oneFragment, "1")
 } else {
    replaceFragment(twoFragment, "2")
 }

 private void replaceFragment(Fragment fragment, String tag) {
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    transaction.addToBackStack(tag);
    transaction.replace(R.id.container, fragment, tag);
    transaction.commit();
}
</code>```

Body:
I'm trying to show two Fragments in a FrameLayout container. I only show one at a time and hide another one based on my application logic. I believe every time I change my device orientation, they recreate! I can see duplicates of fragments overlapping each other! How to fix it? Thanks in advance.

public class MainActivity extends AppCompatActivity {

   final Fragment oneFragment = oneFragment.newInstance();
   final Fragment twoFragment = twoFragment.newInstance();
   Fragment active = oneFragment;

   final FragmentManager fm = getSupportFragmentManager();

@Override
   protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       // some other code

        fm.beginTransaction().add(R.id.container, oneFragment, "1").commit();
        fm.beginTransaction().add(R.id.container, twoFragment, "2").commit();

        // onclick listener
        if(condition) {
            fm.beginTransaction().hide(active)
            .show(oneFragment).commit();
        } else {
            fm.beginTransaction().hide(active)
            .show(twoFragment).commit();
        }

      // some other code

Body:
try this:

 if (condition) {
    replaceFragment(oneFragment, "1")
 } else {
    replaceFragment(twoFragment, "2")
 }

 private void replaceFragment(Fragment fragment, String tag) {
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    transaction.addToBackStack(tag);
    transaction.replace(R.id.container, fragment, tag);
    transaction.commit();
}


问:
SQL error (ERROR: Could not able to execute INSERT INTO)
I have a database that I have made on phpmyAdmin that consists of three columns: id, name and number.
I have added 3 rows of data to the database through phpmyadmin.
I now wish to add data to this database through my php file. This is the code that I use to add in the data and display the data on the browser: </p>

```<code><?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myfirstsite";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}

$sql = "INSERT INTO hi (id, name, number)
VALUES ('99', 'Doe', '999999')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

//displaying data
$sql = "SELECT id, name, number FROM hi";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " .                    $row["number"]. "<br>";
}
} else {
echo "0 results";
}

$conn->close();
?>
</code>```

<p>The thing is that I don't understand why the new data isn't placed into the database but the current data is displayed onscreen.  </p>

答:
In your code you are making reference to $link which doesnt exists, it should be $conn

Chaneg this:

```<code>if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
</code>```

To:

```<code>if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
</code>```

Body:
I have a database that I have made on phpmyAdmin that consists of three columns: id, name and number.
I have added 3 rows of data to the database through phpmyadmin.
I now wish to add data to this database through my php file. This is the code that I use to add in the data and display the data on the browser:

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myfirstsite";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}

$sql = "INSERT INTO hi (id, name, number)
VALUES ('99', 'Doe', '999999')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

//displaying data
$sql = "SELECT id, name, number FROM hi";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " .                    $row["number"]. "
";
}
} else {
echo "0 results";
}

$conn->close();
?>

The thing is that I don't understand why the new data isn't placed into the database but the current data is displayed onscreen.

Body:
In your code you are making reference to $link which doesnt exists, it should be $conn

Chaneg this:

if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

To:

if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}


问:
Drupal 8 override Theme Hook Page file suggestion
I know there are some tutorials online about how to do this, but for some reason I doesn't work.

I would like to add a file theme suggestion on the "Theme Hook: Page" level of the template with the name of the content type (this way I can let all items of this content type use this template).

So, I add this to my MYTHEME.theme.php file:

```<code>function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
   if ($node = \Drupal::request()->attributes->get('node')) {
       array_splice($suggestions, 1, 0, 'page__node__' . $node->getType());
    }
}
</code>```

So you would expect the following output:

page--node--19.html.twig

page--node--%.html.twig

page--node--dish.html.twig // Gets not added

page--node.html.twig

page.html.twig

I already tried clearing the cache. I'm using Drupal 8.1

What am I missing here?

答:
I was able to achieve this by the following code, which seems somewhat same as your code</p>

```<code>if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $suggestions[] = 'page__node__'.$node->bundle();
}
</code>```

Body:
I know there are some tutorials online about how to do this, but for some reason I doesn't work.

I would like to add a file theme suggestion on the "Theme Hook: Page" level of the template with the name of the content type (this way I can let all items of this content type use this template).

So, I add this to my MYTHEME.theme.php file:

function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
   if ($node = \Drupal::request()->attributes->get('node')) {
       array_splice($suggestions, 1, 0, 'page__node__' . $node->getType());
    }
}

So you would expect the following output:

page--node--19.html.twig

page--node--%.html.twig

page--node--dish.html.twig // Gets not added

page--node.html.twig

page.html.twig

I already tried clearing the cache. I'm using Drupal 8.1

What am I missing here?

Body:
I was able to achieve this by the following code, which seems somewhat same as your code

if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $suggestions[] = 'page__node__'.$node->bundle();
}


问:
Microsoft.AspNetCore.Hosting.Abstractions manifest definition does not match the assembly reference
When I run the Entitfy framework core command add-migration MyMigrationName in a class library I get the following error

Could not load file or assembly
  'Microsoft.AspNetCore.Hosting.Abstractions, Version=1.1.1.0,
  Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its
  dependencies. The located assembly's manifest definition does not
  match the assembly reference. (Exception from HRESULT: 0x80131040)

Funny thing there is no reference in my application to Abstractions.

Here is my csproj

```<code>  <Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup Label="Globals">
      <SccProjectName>SAK</SccProjectName>
      <SccProvider>SAK</SccProvider>
      <SccAuxPath>SAK</SccAuxPath>
      <SccLocalPath>SAK</SccLocalPath>
    </PropertyGroup>

    <PropertyGroup>
      <TargetFramework>net452</TargetFramework>
      <AssemblyName>MyProjectName</AssemblyName>
      <OutputType>Library</OutputType>
      <PackageId>MyProjectName</PackageId>
      <NetStandardImplicitPackageVersion>1.6.0</NetStandardImplicitPackageVersion>
      <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
      <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
      <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
      <RootNamespace>MyProjectName</RootNamespace>
    </PropertyGroup>
    <ItemGroup>
      <None Update="appsettings.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>
    </ItemGroup>
    <ItemGroup>
      <PackageReference Include="DocumentFormat.OpenXml" Version="2.5.0" />
      <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.2" />
      <PackageReference Include="Microsoft.CSharp" Version="4.3.0" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.1" />
      <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
      <PackageReference Include="System.Collections" Version="4.3.0" />
      <PackageReference Include="System.Linq" Version="4.3.0" />
      <PackageReference Include="System.Runtime" Version="4.3.0" />
      <PackageReference Include="System.Threading" Version="4.3.0" />
    </ItemGroup>
  <ItemGroup Condition=" '$(TargetFramework)' == 'net452' ">
    <Reference Include="System" />
    <Reference Include="Microsoft.CSharp" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
  </ItemGroup>
</Project>
</code>```

答:
In order to get NuGet to add the appropriate binding redirects to class library projects, you need to add the following to your *.csproj file.

<PropertyGroup>
  <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>
```

Body:
When I run the Entitfy framework core command add-migration MyMigrationName in a class library I get the following error

Could not load file or assembly
  'Microsoft.AspNetCore.Hosting.Abstractions, Version=1.1.1.0,
  Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its
  dependencies. The located assembly's manifest definition does not
  match the assembly reference. (Exception from HRESULT: 0x80131040)

Funny thing there is no reference in my application to Abstractions.

Here is my csproj

  <Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup Label="Globals">
      <SccProjectName>SAK</SccProjectName>
      <SccProvider>SAK</SccProvider>
      <SccAuxPath>SAK</SccAuxPath>
      <SccLocalPath>SAK</SccLocalPath>
    </PropertyGroup>

    <PropertyGroup>
      <TargetFramework>net452</TargetFramework>
      <AssemblyName>MyProjectName</AssemblyName>
      <OutputType>Library</OutputType>
      <PackageId>MyProjectName</PackageId>
      <NetStandardImplicitPackageVersion>1.6.0</NetStandardImplicitPackageVersion>
      <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
      <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
      <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
      <RootNamespace>MyProjectName</RootNamespace>
    </PropertyGroup>
    <ItemGroup>
      <None Update="appsettings.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>
    </ItemGroup>
    <ItemGroup>
      <PackageReference Include="DocumentFormat.OpenXml" Version="2.5.0" />
      <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.2" />
      <PackageReference Include="Microsoft.CSharp" Version="4.3.0" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.1" />
      <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
      <PackageReference Include="System.Collections" Version="4.3.0" />
      <PackageReference Include="System.Linq" Version="4.3.0" />
      <PackageReference Include="System.Runtime" Version="4.3.0" />
      <PackageReference Include="System.Threading" Version="4.3.0" />
    </ItemGroup>
  <ItemGroup Condition=" '$(TargetFramework)' == 'net452' ">
    <Reference Include="System" />
    <Reference Include="Microsoft.CSharp" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
  </ItemGroup>
</Project>