问:
Slick Carousel - Pause the slider's autoplay when a YouTube video is playing
With slick.js, I am able to pause a playing YouTube video after advancing to the next slide.

However, I can't figure out how to pause the slider's autoplay function (slickPause) on the slider itself while the video is playing.

Then, resume autoplay on the slider only after the video has finished or when the user advances to a different slide.

Please help!

```<code>(function($) {
    jQuery(document).ready(function($) {
        $(".hero-slider").on("beforeChange", function(event, slick) {
            var currentSlide, slideType, player, command;
            currentSlide = $(slick.$slider).find(".slick-current");
            slideType = currentSlide.attr("class").split(" ")[1];

            player = currentSlide.find("iframe").get(0);
            if (slideType == "vimeo") {
                command = {
                    "method": "pause",
                    "value": "true"
                };
            } else {
                command = {
                    "event": "command",
                    "func": "pauseVideo",
                    "args": ""
                };
            }
            if (player != undefined) {
                player.contentWindow.postMessage(JSON.stringify(command), "*");
            }
        });
        $(".hero-slider").slick({
            infinite: true,
            arrows: true,
            dots: false,
            fade: true,
            cssEase: 'linear',
            autoplay: true,
            autoplaySpeed: 5000,
            focusOnSelect: true
        });
    });
})(jQuery);
</code>```

答:
You may refer with this sample code. You can use slickPause like this:

```<code>$('.hero-slider').click(function() {
  $('.hero-slider').slick('slickPause');
});
</code>```

Also, here are some references which might help:

Slick-carousel - How To Pause and Play embedded Youtube videos on slide Change?

Slick-carousel how to stop autoplay when video is on via youtube api

Body:
With slick.js, I am able to pause a playing YouTube video after advancing to the next slide.

However, I can't figure out how to pause the slider's autoplay function (slickPause) on the slider itself while the video is playing.

Then, resume autoplay on the slider only after the video has finished or when the user advances to a different slide.

Please help!

(function($) {
    jQuery(document).ready(function($) {
        $(".hero-slider").on("beforeChange", function(event, slick) {
            var currentSlide, slideType, player, command;
            currentSlide = $(slick.$slider).find(".slick-current");
            slideType = currentSlide.attr("class").split(" ")[1];

            player = currentSlide.find("iframe").get(0);
            if (slideType == "vimeo") {
                command = {
                    "method": "pause",
                    "value": "true"
                };
            } else {
                command = {
                    "event": "command",
                    "func": "pauseVideo",
                    "args": ""
                };
            }
            if (player != undefined) {
                player.contentWindow.postMessage(JSON.stringify(command), "*");
            }
        });
        $(".hero-slider").slick({
            infinite: true,
            arrows: true,
            dots: false,
            fade: true,
            cssEase: 'linear',
            autoplay: true,
            autoplaySpeed: 5000,
            focusOnSelect: true
        });
    });
})(jQuery);

Body:
You may refer with this sample code. You can use slickPause like this:

$('.hero-slider').click(function() {
  $('.hero-slider').slick('slickPause');
});

Also, here are some references which might help:

Slick-carousel - How To Pause and Play embedded Youtube videos on slide Change?

Slick-carousel how to stop autoplay when video is on via youtube api


来源: stackexchange

问:
ViewData.ModelState.IsValid check firing for all (partial) forms contained in one razor view
I have two forms on my homepage (a contact form and a competition form which are both partials), both have separate controllers and models.

In both partials i have the following code which displays an error message if the email fails to send.

```<code>if (!ViewData.ModelState.IsValid)
{
    <div class="form-failure">
        <h4><i class="fa fa-close"></i>@Model.FailureTitle</h4>
        @Html.Raw(Model.FailureContent)
    </div>
</code>```

Email error code in both controllers

```<code>            if (emailService.Send(EmailMessageBuilder.BuildUserEmail(model.FullName, model.EmailAddress, model.PhoneNumber)) != EmailState.Success)
            {
                ModelState.AddModelError("Email", "There was a problem sending the Email. Please try again later, or call us.");
                return CurrentUmbracoPage();
            }
</code>```

The problem is the error displays on both forms because the !ViewData.ModelState.IsValid returns the same result for both. How can I ensure that the error only displays on the form which the request has been submitted from?

```<code>}
</code>```

答:
You can store which form it is in ViewData

```<code>if (emailService.Send(EmailMessageBuilder.BuildUserEmail(model.FullName, model.EmailAddress, model.PhoneNumber)) != EmailState.Success)
{
    ViewData["Form"] = "Form1";
    ModelState.AddModelError("Email", "There was a problem sending the Email. Please try again later, or call us.");
    return CurrentUmbracoPage();
}
</code>```

Then check in the html to see which form is invalid

```<code>if (!ViewData.ModelState.IsValid && ViewData["Form"] == "Form1" )
{
     ....
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two forms on my homepage (a contact form and a competition form which are both partials), both have separate controllers and models.

In both partials i have the following code which displays an error message if the email fails to send.

if (!ViewData.ModelState.IsValid)
{

@Model.FailureTitle

        @Html.Raw(Model.FailureContent)

Email error code in both controllers

            if (emailService.Send(EmailMessageBuilder.BuildUserEmail(model.FullName, model.EmailAddress, model.PhoneNumber)) != EmailState.Success)
            {
                ModelState.AddModelError("Email", "There was a problem sending the Email. Please try again later, or call us.");
                return CurrentUmbracoPage();
            }

The problem is the error displays on both forms because the !ViewData.ModelState.IsValid returns the same result for both. How can I ensure that the error only displays on the form which the request has been submitted from?

}

Body:
You can store which form it is in ViewData

if (emailService.Send(EmailMessageBuilder.BuildUserEmail(model.FullName, model.EmailAddress, model.PhoneNumber)) != EmailState.Success)
{
    ViewData["Form"] = "Form1";
    ModelState.AddModelError("Email", "There was a problem sending the Email. Please try again later, or call us.");
    return CurrentUmbracoPage();
}

Then check in the html to see which form is invalid

if (!ViewData.ModelState.IsValid && ViewData["Form"] == "Form1" )
{
     ....
}


问:
Windows batch: sleep
How do I get a Windows batch script to wait a few seconds?

sleep and wait don't seem to work (unrecognized command).

答:
Heh, Windows is uhm... interesting. This works:

```<code>choice /T 1 /d y > NUL
</code>```

choice presents a prompt asking you yes or no. /d y makes it choose yes. /t 1 makes it wait a second before typing it. > NUL squashes output.

Title: Windows batch: sleep

Body:
Heh, Windows is uhm... interesting. This works:

choice /T 1 /d y > NUL

choice presents a prompt asking you yes or no. /d y makes it choose yes. /t 1 makes it wait a second before typing it. > NUL squashes output.


问:
Appending JSON values to search results div
I'm attempting to append the results of a search query to a div, but getting the [object Object] result. How can I parse this this json object and retrieve/display only the title and permalink from the result?

json request

```<code>$("#searchterm").keyup(function(e) {
 var q = $("#searchterm").val();
 //Only begin search with at least 3 characters.
 if(q.length > 3){
    ajax_search();
 }
 //Send search query
 function ajax_search(){
 $.getJSON("http://url-to-search?q=" + q, {
          dataType:'jsonp'
   },
 //Get results and make 'em look good
 function(data) {
   console.log(data);
   $("#results").empty();
   $("#results").append("Results for <b> " + q + "</b>");
     $.each(data.query.search, function(i, data) {
         $("#results").append(data);
     });
  });
 }
});
</code>```

sample json

```<code>{
    "count": 50,
    "data": [{
        "id": "/folder/bob-jones/",
        "image": "https://image-url.jpg",
        "permalink": "/folder/bob-jones/",
        "text": "lots of text description here",
        "title": "Bob Jones",
        "type": "Employee"
    }]
}
</code>```

答:
data.query.search,
I think it should be data.data and inside function data.title some think like... $.each(data.data, function(i, data) {
  $("#results").append(data.title+" "+data.permalink);
});

Body:
I'm attempting to append the results of a search query to a div, but getting the [object Object] result. How can I parse this this json object and retrieve/display only the title and permalink from the result?

json request

$("#searchterm").keyup(function(e) {
 var q = $("#searchterm").val();
 //Only begin search with at least 3 characters.
 if(q.length > 3){
    ajax_search();
 }
 //Send search query
 function ajax_search(){
 $.getJSON("http://url-to-search?q=" + q, {
          dataType:'jsonp'
   },
 //Get results and make 'em look good
 function(data) {
   console.log(data);
   $("#results").empty();
   $("#results").append("Results for  " + q + "");
     $.each(data.query.search, function(i, data) {
         $("#results").append(data);
     });
  });
 }
});

sample json

{
    "count": 50,
    "data": [{
        "id": "/folder/bob-jones/",
        "image": "https://image-url.jpg",
        "permalink": "/folder/bob-jones/",
        "text": "lots of text description here",
        "title": "Bob Jones",
        "type": "Employee"
    }]
}


问:
Why can't I find my new Chrome Extension?
I recently published a Google Chrome extension on the Google Web Store: https://chrome.google.com/webstore/detail/mofoquotes/llgbcepdhpgncgifhngonfebjnclcebk

It's published successfully, even my friends can view it, but I, nor my friends, can find it when we search for it in the Web Store searchbar. Any help would be much appreciated, thank you.

答: As @Webbanditten stated, it usually takes some time (more than a day or so) for the Chrome web store to index newly accepted extensions. Unless there's a specific outage, it should show up soon. You can check it here. If you don't see start seeing it within in a few days of release you can post an issue about this.</p>


问:
How to prevent the exoplayer from reloading in case of seek backward?
I am using exoplayer to play mp3 tracks. All good. If the track is completely buffered then in case of seek forward it does not reload as expected. However, in case of seek backward it reloads.
How do i prevent that?
Is it a bug in exo?</p>

答: Not really a solution, but you can use a library that acts as a proxy between ExoPlayer and the video URL like AndroidVideoCache. It downloads the video to disk and supplies ExoPlayer with the local file URL so re-buffering is much faster.</p>


问:
SupportMapFragment#getMapAsync() on Null object reference
I've been trying to nest my SupportMapFragment into another Fragment but I keep getting a nullPointerException when trying to call getMapAsync() on my SupportMapFragment object.  I have no idea how to solve this, I've been trying for a while now :/

Here is my onCreateView method from the enclosing Fragment which is supposed to contain the Map.

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.activity_main, container, false);

    CustomMap mapFrag = new CustomMap();
    FragmentTransaction transaction = this.getChildFragmentManager().beginTransaction();
    transaction.add(R.id.map_container, mapFrag).commit();

    SupportMapFragment smf = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
    smf.getMapAsync(this);

    return rootView;

}
</code>```

Below is the activity_main.xml file:

```<code><android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".Activities.MainActivity"
    android:focusableInTouchMode="true">

    <FrameLayout
        android:layout_alignParentTop="true"
        android:layout_marginTop="0dp"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        app:layout_widthPercent="100%"
        android:layout_marginBottom="250dp"
        android:layout_centerInParent="true"
        android:id="@+id/map_container" />

    <EditText
        app:layout_widthPercent="90%"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_alignParentBottom="true"
        android:layout_alignLeft="@+id/map_container"
        android:layout_alignStart="@+id/map_container"
        android:layout_marginBottom="194dp"
        android:id="@+id/editTextCode"
        android:layout_toLeftOf="@+id/buttonCode"
        android:layout_toStartOf="@+id/buttonCode"
        android:hint="Enter Unique Code" />

    <Button
        android:text="Submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/editTextCode"
        android:layout_alignRight="@+id/map"
        android:layout_alignEnd="@+id/map"
        android:id="@+id/buttonCode" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/buttonCode"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="15dp"
        android:id="@+id/myListView" />
</code>```

And here is the map_fragment.xml file used by my CustomMap Fragment:

```<code> <fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/map" />
</code>```

答:
Try using .newInstance to create a new Map Fragment. Here's how I've gotten it to work:

```<code>    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    String MAP_FRAGMENT = "map_fragment";

    FragmentManager fragmentManager = getChildFragmentManager();
    SupportMapFragment mapFragment = (SupportMapFragment) fragmentManager
            .findFragmentByTag(MAP_FRAGMENT); // Check if map already exists

    if(mapFragment == null){
        // Create new Map instance if it doesn't exist
        mapFragment = SupportMapFragment.newInstance();
        fragmentManager.beginTransaction()
                .replace(R.id.map_container, mapFragment, MAP_FRAGMENT)
                .commit();
    }
    mapFragment.getMapAsync(this);
</code>```

Body:
I've been trying to nest my SupportMapFragment into another Fragment but I keep getting a nullPointerException when trying to call getMapAsync() on my SupportMapFragment object.  I have no idea how to solve this, I've been trying for a while now :/

Here is my onCreateView method from the enclosing Fragment which is supposed to contain the Map.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.activity_main, container, false);

    CustomMap mapFrag = new CustomMap();
    FragmentTransaction transaction = this.getChildFragmentManager().beginTransaction();
    transaction.add(R.id.map_container, mapFrag).commit();

    SupportMapFragment smf = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
    smf.getMapAsync(this);

    return rootView;

}

Below is the activity_main.xml file:

<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".Activities.MainActivity"
    android:focusableInTouchMode="true">

    <FrameLayout
        android:layout_alignParentTop="true"
        android:layout_marginTop="0dp"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        app:layout_widthPercent="100%"
        android:layout_marginBottom="250dp"
        android:layout_centerInParent="true"
        android:id="@+id/map_container" />

    <EditText
        app:layout_widthPercent="90%"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_alignParentBottom="true"
        android:layout_alignLeft="@+id/map_container"
        android:layout_alignStart="@+id/map_container"
        android:layout_marginBottom="194dp"
        android:id="@+id/editTextCode"
        android:layout_toLeftOf="@+id/buttonCode"
        android:layout_toStartOf="@+id/buttonCode"
        android:hint="Enter Unique Code" />

    <Button
        android:text="Submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/editTextCode"
        android:layout_alignRight="@+id/map"
        android:layout_alignEnd="@+id/map"
        android:id="@+id/buttonCode" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/buttonCode"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="15dp"
        android:id="@+id/myListView" />

And here is the map_fragment.xml file used by my CustomMap Fragment:

 <fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/map" />

Body:
Try using .newInstance to create a new Map Fragment. Here's how I've gotten it to work:

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    String MAP_FRAGMENT = "map_fragment";

    FragmentManager fragmentManager = getChildFragmentManager();
    SupportMapFragment mapFragment = (SupportMapFragment) fragmentManager
            .findFragmentByTag(MAP_FRAGMENT); // Check if map already exists

    if(mapFragment == null){
        // Create new Map instance if it doesn't exist
        mapFragment = SupportMapFragment.newInstance();
        fragmentManager.beginTransaction()
                .replace(R.id.map_container, mapFragment, MAP_FRAGMENT)
                .commit();
    }
    mapFragment.getMapAsync(this);


问:
How to test with DefinitelyTyped UrlFetchApp
I want to test UrlFetchApp using @types/google-apps-script in DefinitelyTyped.

Underscore.js passed from compilation to testing, but UrlFetchApp does not work.

Source

Github: https://github.com/ina6ra/tsdt-sample

package.json

```<code>{
  "dependencies": {
    "mocha": "^3.2.0",
    "power-assert": "^1.4.2",
    "ts-node": "^3.0.2",
    "underscore": "^1.8.3"
  },
  "scripts": {
    "init": "yarn install;typings install",
    "tsc": "tsc --noEmit true",
    "test": "mocha --compilers ts:ts-node/register test/**/*.ts"
  }
}
</code>```

typings.json

```<code>{
  "dependencies": {},
  "globalDependencies": {
    "google-apps-script/google-apps-script.base": "registry:dt/google-apps-script/google-apps-script.base#0.0.0+20160510192225",
    "google-apps-script/google-apps-script.types": "registry:dt/google-apps-script/google-apps-script.types#0.0.0+20160316171810",
    "google-apps-script/google-apps-script.url-fetch": "registry:dt/google-apps-script/google-apps-script.url-fetch#0.0.0+20160510192225",
    "mocha": "registry:dt/mocha#2.2.5+20170311011848",
    "underscore": "registry:dt/underscore#1.8.3+20161123125004"
  }
}
</code>```

src/urlfetchapp.ts

```<code>var UrlFetchApp: GoogleAppsScript.URL_Fetch.UrlFetchApp;

export function gasFetch(url:string) {
  var res:GoogleAppsScript.URL_Fetch.HTTPResponse = UrlFetchApp.fetch(url);
  return true;
}
</code>```

test/ufa-test.ts

```<code>import * as assert from 'power-assert';
import * as gas from '../src/urlfetchapp';

describe('UrlFetchApp', () => {
    it('test for fetch', () => {
        assert.equal(gas.gasFetch('http://www.google.com'), true);
    });
});
</code>```

Config

tsconfig.json

```<code>{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": false
    },
    "files": [
        "typings/index.d.ts",
        "src/underscore.ts",
        "src/urlfetchapp.ts"
    ],
    "exclude": [
        "node_modules/"
    ]
}
</code>```

Compile

```<code>$ yarn run tsc
yarn run v0.21.3
$ tsc --noEmit true
✨  Done in 2.94s.
</code>```

Compilation passes without error.

Test

```<code>$ yarn run test
yarn run v0.21.3
$ mocha --compilers ts:ts-node/register test/**/*.ts

  UrlFetchApp
    1) test for fetch

  Underscore.js
    ✓ test for maxList

  1 passing (29ms)
  1 failing

  1) UrlFetchApp test for fetch:
     TypeError: Cannot read property 'fetch' of undefined
      at Object.gasFetch (src/urlfetchapp.ts:4:64)
      at Context.<anonymous> (test/ufa-test.ts:6:26)

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

The test fails.

How can I solve it?

答:
Your test is running on your local machine and you don't have a global UrlFetchApp object on your local environment.

```<code>var UrlFetchApp: GoogleAppsScript.URL_Fetch.UrlFetchApp; // <-- this object has not been initialized

export function gasFetch(url:string) {
  var res:GoogleAppsScript.URL_Fetch.HTTPResponse = UrlFetchApp.fetch(url); // <-- `UrlFetchApp` is undefined for your local environment
  return true;
}
</code>```

See here for more details how to unit test google apps scripts?

Body:
I want to test UrlFetchApp using @types/google-apps-script in DefinitelyTyped.

Underscore.js passed from compilation to testing, but UrlFetchApp does not work.

Source

Github: https://github.com/ina6ra/tsdt-sample

package.json

{
  "dependencies": {
    "mocha": "^3.2.0",
    "power-assert": "^1.4.2",
    "ts-node": "^3.0.2",
    "underscore": "^1.8.3"
  },
  "scripts": {
    "init": "yarn install;typings install",
    "tsc": "tsc --noEmit true",
    "test": "mocha --compilers ts:ts-node/register test/**/*.ts"
  }
}

typings.json

{
  "dependencies": {},
  "globalDependencies": {
    "google-apps-script/google-apps-script.base": "registry:dt/google-apps-script/google-apps-script.base#0.0.0+20160510192225",
    "google-apps-script/google-apps-script.types": "registry:dt/google-apps-script/google-apps-script.types#0.0.0+20160316171810",
    "google-apps-script/google-apps-script.url-fetch": "registry:dt/google-apps-script/google-apps-script.url-fetch#0.0.0+20160510192225",
    "mocha": "registry:dt/mocha#2.2.5+20170311011848",
    "underscore": "registry:dt/underscore#1.8.3+20161123125004"
  }
}

src/urlfetchapp.ts

var UrlFetchApp: GoogleAppsScript.URL_Fetch.UrlFetchApp;

export function gasFetch(url:string) {
  var res:GoogleAppsScript.URL_Fetch.HTTPResponse = UrlFetchApp.fetch(url);
  return true;
}

test/ufa-test.ts

import * as assert from 'power-assert';
import * as gas from '../src/urlfetchapp';

describe('UrlFetchApp', () => {
    it('test for fetch', () => {
        assert.equal(gas.gasFetch('http://www.google.com'), true);
    });
});

Config

tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": false
    },
    "files": [
        "typings/index.d.ts",
        "src/underscore.ts",
        "src/urlfetchapp.ts"
    ],
    "exclude": [
        "node_modules/"
    ]
}

Compile

$ yarn run tsc
yarn run v0.21.3
$ tsc --noEmit true
✨  Done in 2.94s.

Compilation passes without error.

Test

$ yarn run test
yarn run v0.21.3
$ mocha --compilers ts:ts-node/register test/**/*.ts

  UrlFetchApp
    1) test for fetch

  Underscore.js
    ✓ test for maxList

  1 passing (29ms)
  1 failing

  1) UrlFetchApp test for fetch:
     TypeError: Cannot read property 'fetch' of undefined
      at Object.gasFetch (src/urlfetchapp.ts:4:64)
      at Context.<anonymous> (test/ufa-test.ts:6:26)

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

The test fails.

How can I solve it?

Body:
Your test is running on your local machine and you don't have a global UrlFetchApp object on your local environment.

var UrlFetchApp: GoogleAppsScript.URL_Fetch.UrlFetchApp; // <-- this object has not been initialized

export function gasFetch(url:string) {
  var res:GoogleAppsScript.URL_Fetch.HTTPResponse = UrlFetchApp.fetch(url); // <-- `UrlFetchApp` is undefined for your local environment
  return true;
}

See here for more details how to unit test google apps scripts?


答:
The Windows 2003 Resource Kit has a sleep batch file. If you ever move up to PowerShell, you can use:

```<code>Start-Sleep -s <time to sleep>
</code>```

Or something like that.

Title: Windows batch: sleep

Body:
How do I get a Windows batch script to wait a few seconds?

sleep and wait don't seem to work (unrecognized command).

Body:
The Windows 2003 Resource Kit has a sleep batch file. If you ever move up to PowerShell, you can use:

Start-Sleep -s <time to sleep>

Or something like that.


问:
python replace special character
I want to copy the file to a new place in windows7 64bit. But I found some special characters in the file name can cause error 22 when using shutil.copy2 (but this file is legal in windows GUI and can be copied with a mouse). I believe the error22 means the source file can't be found by citing this file name. So my workaround would be to remove or replace the special characters in any file name which causes this problem in windows7 64bit. In general user keep copying files from other folders to this folder so the file name must be handled by some varables rather than constants. But as an example, I just put two files names in the example code. I put the code shown in the picture:

```<code># -*- coding: gbk*-
#!/usr/bin/python
#Filename:ae.py
import os,shutil,time,re,string,sys  #re is regular expression
from nt import chdir
import win32api,win32file
import unicodedata,codecs
scr=r"C:\Users\Administrator\Desktop\« How-To Geek Forums.pdf"
des="C:\\Users\\Administrator\\Desktop\\How-To Geek Forums.pdf"
#chdir(os.path.dirname(scr))
os.rename(scr,des)
</code>```

and I got

```<code>WindowsError:[Error 123]
</code>```

I think that means I can't even rename it using python script once there are some special characters like «

答:
So, it looks like you are creating a regular expression to match the pattern of a filename, but you already know the name?

When you say special characters, are you speaking specifically about whitespace?

Here’s your code for readability:

```<code>#!/usr/bin/python
#Filename:ae.py
import os,shutil,time,re,string,sys
#re is regular expression
from nt import chdir import win32api,win32file
import unicodedata,codecs
scr=r"C:\Users\Administrator\Desktop\« How-To Geek Forums.pdf"
des="C:\Users\Administrator\Desktop\How-To Geek Forums.pdf" #
chdir(os.path.dirname(scr)) os.rename(scr,des)
</code>```

check out http://docs.python.org/library/os.html#os.listdir

I would probably just get a list of files in the directory with

```<code>chdir(os.path.dirname(scr)
files = os.listdir(“.”)
for name in files:
    os.rename(name,des+”/“+name)
</code>```

Title: python replace special character

Body:
I want to copy the file to a new place in windows7 64bit. But I found some special characters in the file name can cause error 22 when using shutil.copy2 (but this file is legal in windows GUI and can be copied with a mouse). I believe the error22 means the source file can't be found by citing this file name. So my workaround would be to remove or replace the special characters in any file name which causes this problem in windows7 64bit. In general user keep copying files from other folders to this folder so the file name must be handled by some varables rather than constants. But as an example, I just put two files names in the example code. I put the code shown in the picture:

# -*- coding: gbk*-
#!/usr/bin/python
#Filename:ae.py
import os,shutil,time,re,string,sys  #re is regular expression
from nt import chdir
import win32api,win32file
import unicodedata,codecs
scr=r"C:\Users\Administrator\Desktop\« How-To Geek Forums.pdf"
des="C:\\Users\\Administrator\\Desktop\\How-To Geek Forums.pdf"
#chdir(os.path.dirname(scr))
os.rename(scr,des)

and I got

WindowsError:[Error 123]

I think that means I can't even rename it using python script once there are some special characters like «

Body:
So, it looks like you are creating a regular expression to match the pattern of a filename, but you already know the name?

When you say special characters, are you speaking specifically about whitespace?

Here’s your code for readability:

#!/usr/bin/python
#Filename:ae.py
import os,shutil,time,re,string,sys
#re is regular expression
from nt import chdir import win32api,win32file
import unicodedata,codecs
scr=r"C:\Users\Administrator\Desktop\« How-To Geek Forums.pdf"
des="C:\Users\Administrator\Desktop\How-To Geek Forums.pdf" #
chdir(os.path.dirname(scr)) os.rename(scr,des)

check out http://docs.python.org/library/os.html#os.listdir

I would probably just get a list of files in the directory with

chdir(os.path.dirname(scr)
files = os.listdir(“.”)
for name in files:
    os.rename(name,des+”/“+name)


问:
How to use pd.concat with an un initiated dataframe?
I want to be able to concat dataframe results to memory as they go through a function and end up with a whole new dataframe with just the results. How do I do this without having a dataframe all ready created before the function? For example:

```<code>import pandas as pd
import numpy as np

rand_df = pd.DataFrame({'A': [ 'x','x','y','y','z','z','z'],'B': np.random.randn(7)})

    def myFuncOnDF(df, row):
        df = df.groupby(['A']).get_group(row).describe()

    myFuncOnDF(rand_df, 'x')
    myFuncOnDF(rand_df, 'y')
    myFuncOnDF(rand_df, 'z')
</code>```

How would I concat the results of myFuncOnDF() to a new dataframe that doesn't exist yet?

Body:
I want to be able to concat dataframe results to memory as they go through a function and end up with a whole new dataframe with just the results. How do I do this without having a dataframe all ready created before the function? For example:

import pandas as pd
import numpy as np

rand_df = pd.DataFrame({'A': [ 'x','x','y','y','z','z','z'],'B': np.random.randn(7)})

    def myFuncOnDF(df, row):
        df = df.groupby(['A']).get_group(row).describe()

    myFuncOnDF(rand_df, 'x')
    myFuncOnDF(rand_df, 'y')
    myFuncOnDF(rand_df, 'z')

How would I concat the results of myFuncOnDF() to a new dataframe that doesn't exist yet?

Body:
Not really sure what you expected but groupby and describeaccomplishes the same thing

rand_df.groupby('A').B.describe().unstack()

   count      mean       std       min       25%       50%       75%       max
A
x    2.0  0.362296  0.371891  0.099329  0.230813  0.362296  0.493779  0.625262
y    2.0  0.473104  0.188415  0.339874  0.406489  0.473104  0.539719  0.606333
z    3.0  0.506519  1.087770 -0.607696 -0.023102  0.561492  1.063626  1.565760


问:
Turn vector of dates into workable data frame
I have a vector dates with elements in the same format, like element 1 "Mon, 05 Sep 2013 01:19:18 -0000" .
I am trying to turn this vector into a data frame so I can manipulate them. For instance, I would like to be able to subtract 4 days from the first entry and get "Thu, 01 Sep 2013 01:19:18 -0000". I would also like to plot each element on a time line.

I have tried

```<code>as.Date(dates,'%a, %d %b %z %H:%M:%S %z')
</code>```

and

```<code>for (d in dates){
    as.Date(d,'%a, %d %b %z %H:%M:%S -%z')
}
</code>```

but I always get NA.

答:
You were very close. Try:

```<code>dates <- c("Mon, 05 Sep 2013 01:19:18 -0000", "Thu, 01 Sep 2013 01:19:18 -0000")
strptime(dates, '%a, %d %b %Y %H:%M:%S %z')
</code>```

You just had a typo in the year argument (should be %Y, not %z). If you want to store the time as a date, add as.Date as you have done

```<code>as.Date(dates, '%a, %d %b %Y %H:%M:%S %z')
</code>```

If you want to make a data.frame and subtract 4 days from each date, try:

```<code>data.frame(date = strptime(dates, '%a, %d %b %Y %H:%M:%S %z'),
subtracted = strptime(dates, '%a, %d %b %Y %H:%M:%S %z') - as.difftime(4, unit="days"))
</code>```

Note that R returns your system-specific times, which might differ from the times in your vector as specified by the %z argument (see ?strptime).

Body:
I have a vector dates with elements in the same format, like element 1 "Mon, 05 Sep 2013 01:19:18 -0000" .
I am trying to turn this vector into a data frame so I can manipulate them. For instance, I would like to be able to subtract 4 days from the first entry and get "Thu, 01 Sep 2013 01:19:18 -0000". I would also like to plot each element on a time line.

I have tried

as.Date(dates,'%a, %d %b %z %H:%M:%S %z')

and

for (d in dates){
    as.Date(d,'%a, %d %b %z %H:%M:%S -%z')
}

but I always get NA.

Body:
You were very close. Try:

dates <- c("Mon, 05 Sep 2013 01:19:18 -0000", "Thu, 01 Sep 2013 01:19:18 -0000")
strptime(dates, '%a, %d %b %Y %H:%M:%S %z')

You just had a typo in the year argument (should be %Y, not %z). If you want to store the time as a date, add as.Date as you have done

as.Date(dates, '%a, %d %b %Y %H:%M:%S %z')

If you want to make a data.frame and subtract 4 days from each date, try:

data.frame(date = strptime(dates, '%a, %d %b %Y %H:%M:%S %z'),
subtracted = strptime(dates, '%a, %d %b %Y %H:%M:%S %z') - as.difftime(4, unit="days"))

Note that R returns your system-specific times, which might differ from the times in your vector as specified by the %z argument (see ?strptime).


问:
How can I hook into the current FormsAuthenticationModule in a Medium Trust environment?
I've got an HttpModule in my application that hooks into the FormsAuthenticationModule's Authenticate event with the following code:

```<code>public void Init(HttpApplication context)
{
    FormsAuthenticationModule faModule =
        (FormsAuthenticationModule)context.Modules["FormsAuthentication"];
    faModule.Authenticate +=
        new FormsAuthenticationEventHandler(faModule_Authenticate);
}
</code>```

Unfortunately, the call to context.Modules fails because the app needs to run in a medium-trust environment.  Is there another way that I can hook into this event?

答:
That's a tough one - you can't even access the Modules collection from within your Global application file.

You could try calling your custom code from the AuthenticateRequest handler in Global:

```<code>protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    // Call your module's code here..
}
</code>```

You can't grab your custom module from the collection, either, so you'd need a static reference to your module's library.

Other than granting the AspNetHostingPermission (as detailed for other permissions here) to your site in the machine level web.config, I'm out of ideas!

OwnerDisplayName: Greg Hurlman

ContentLicense: CC BY-SA 2.5

Body:
I've got an HttpModule in my application that hooks into the FormsAuthenticationModule's Authenticate event with the following code:

public void Init(HttpApplication context)
{
    FormsAuthenticationModule faModule =
        (FormsAuthenticationModule)context.Modules["FormsAuthentication"];
    faModule.Authenticate +=
        new FormsAuthenticationEventHandler(faModule_Authenticate);
}

Unfortunately, the call to context.Modules fails because the app needs to run in a medium-trust environment.  Is there another way that I can hook into this event?

LastEditorDisplayName: Greg Hurlman

Body:
That's a tough one - you can't even access the Modules collection from within your Global application file.

You could try calling your custom code from the AuthenticateRequest handler in Global:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    // Call your module's code here..
}

You can't grab your custom module from the collection, either, so you'd need a static reference to your module's library.

Other than granting the AspNetHostingPermission (as detailed for other permissions here) to your site in the machine level web.config, I'm out of ideas!

OwnerDisplayName: Jarrod Dixon


问:
How can I create raster plots with the same colour scale in R
I'm creating some maps from raster files using the "raster" package in R. I'd like to create comparison rasters, showing several maps side by side. It's important for this that the colour scales used are the same for all maps, regardless of the values in each map. For example, if map 1 has values from 0-1, and map 2 has values from 0-0.5, cells with a value of 0.5 should have the same colour on both maps.

For example:

map 1 has values from 0 to 1

map 2 has values from 0 to 0.5

the colour goes from red (lowest) to green (highest)

I would like a value of 0.5 to have the same colour in both maps (i.e. yellow, as halfway between red and green). The current behaviour is that it is yellow in map 1, and green in map 2.

I can't find a way to make this work. I can't see any way to set the range of pixel values to use with the plotting function. setMinMax() doesn't help (as 'plot' always calculates the values). Even trying to set the values by hand (e.g. g1@data@max <- 10) doesn't work (these are ignored when plotting).

Finally, making a stack of the maps (which might be expected to plot everything on the same colour scale) doesn't work either - each map still has it's own colour scale.

Any thoughts on how to do this?

EDIT:

The solution I ended up using is:

```<code>plot( d, col=rev( rainbow( 99, start=0,end=1 ) ), breaks=seq(min(minValue( d )),max(maxValue(d)),length.out=100) )
</code>```

答:
Since the image::raster function specifies that the image::base arguments can be passed (and suggests that image::base is probably used), wouldn't you just specify the same col= and breaks= arguments to all calls to image::raster? You do need to get the breaks and the col arguments "in sync". The number of colors needs to be one less than the number of breaks. The example below is based on the classic volcano data and the second version shows how a range of values can be excluded from an image:

```<code> x <- 10*(1:nrow(volcano))
 y <- 10*(1:ncol(volcano))
 image(x, y, volcano, col = terrain.colors( length(seq(90, 200, by = 5))-1), axes = FALSE, breaks= seq(90, 200, by = 5) )
 axis(1, at = seq(100, 800, by = 100))
 axis(2, at = seq(100, 600, by = 100))
 box()
 title(main = "Maunga Whau Volcano", font.main = 4)

 x <- 10*(1:nrow(volcano))
 y <- 10*(1:ncol(volcano))
 image(x, y, volcano, col = terrain.colors( length(seq(150, 200, by = 5))-1), axes = FALSE, breaks= seq(150, 200, by = 5) )
 axis(1, at = seq(100, 800, by = 100))
 axis(2, at = seq(100, 600, by = 100))
 box()
 title(main = "Maunga Whau Volcano Restricted to elevations above 150", font.main = 4)
</code>```

A specific example would aid this effort.

Body:
I'm creating some maps from raster files using the "raster" package in R. I'd like to create comparison rasters, showing several maps side by side. It's important for this that the colour scales used are the same for all maps, regardless of the values in each map. For example, if map 1 has values from 0-1, and map 2 has values from 0-0.5, cells with a value of 0.5 should have the same colour on both maps.

For example:

map 1 has values from 0 to 1

map 2 has values from 0 to 0.5

the colour goes from red (lowest) to green (highest)

I would like a value of 0.5 to have the same colour in both maps (i.e. yellow, as halfway between red and green). The current behaviour is that it is yellow in map 1, and green in map 2.

I can't find a way to make this work. I can't see any way to set the range of pixel values to use with the plotting function. setMinMax() doesn't help (as 'plot' always calculates the values). Even trying to set the values by hand (e.g. g1@data@max <- 10) doesn't work (these are ignored when plotting).

Finally, making a stack of the maps (which might be expected to plot everything on the same colour scale) doesn't work either - each map still has it's own colour scale.

Any thoughts on how to do this?

EDIT:

The solution I ended up using is:

plot( d, col=rev( rainbow( 99, start=0,end=1 ) ), breaks=seq(min(minValue( d )),max(maxValue(d)),length.out=100) )

Body:
Since the image::raster function specifies that the image::base arguments can be passed (and suggests that image::base is probably used), wouldn't you just specify the same col= and breaks= arguments to all calls to image::raster? You do need to get the breaks and the col arguments "in sync". The number of colors needs to be one less than the number of breaks. The example below is based on the classic volcano data and the second version shows how a range of values can be excluded from an image:

 x <- 10*(1:nrow(volcano))
 y <- 10*(1:ncol(volcano))
 image(x, y, volcano, col = terrain.colors( length(seq(90, 200, by = 5))-1), axes = FALSE, breaks= seq(90, 200, by = 5) )
 axis(1, at = seq(100, 800, by = 100))
 axis(2, at = seq(100, 600, by = 100))
 box()
 title(main = "Maunga Whau Volcano", font.main = 4)

 x <- 10*(1:nrow(volcano))
 y <- 10*(1:ncol(volcano))
 image(x, y, volcano, col = terrain.colors( length(seq(150, 200, by = 5))-1), axes = FALSE, breaks= seq(150, 200, by = 5) )
 axis(1, at = seq(100, 800, by = 100))
 axis(2, at = seq(100, 600, by = 100))
 box()
 title(main = "Maunga Whau Volcano Restricted to elevations above 150", font.main = 4)

A specific example would aid this effort.


问:
Scrollview in 'present modally' view controller not working
I have a view controller that is to be presented modally and in that VC I have a scrollview. However, adding a scrollview normally does not seem to work when my segue is of type 'present modally'. I read somewhere that I have to put my scrollview in another view for it to work. So this is my view hierarchy:

These are my constraints for view A:

ScrollView constraints:

ViewB constraints:

And in ViewB, I have another view which I have given a top, left & right constraint of 0 to its superview. I have set this in code as well:

```<code> override func viewDidLayoutSubviews()
{
    viewB.frame.size.height = 2000
    scrollView.contentSize = viewB.frame.size
}
</code>```

However, the scrollview still does not scroll. Thanks to anyone who can help out...been stuck on this for a while.

答:
The problem is that you have given ViewB constraints to its containing scroll view. This is fine, if you're going to take that approach (which I prefer); but it means that the scroll view's contentSize is determined by ViewB's size, not by the contentSize property. Thus, your viewDidLayoutSubviews code is useless and your first move should be to throw it away.

Now then, what is ViewB's size? Unfortunately, it's the same as the scroll view's size, because you have given ViewB width and height constraints that made it the same size as the scroll view. Therefore there is nothing to scroll.

The solution is to do through constraints what you were trying to do in code, namely, give ViewB a height constraint that is fixed at 2000, instead of height constraint you have given it.

Body:
I have a view controller that is to be presented modally and in that VC I have a scrollview. However, adding a scrollview normally does not seem to work when my segue is of type 'present modally'. I read somewhere that I have to put my scrollview in another view for it to work. So this is my view hierarchy:

These are my constraints for view A:

ScrollView constraints:

ViewB constraints:

And in ViewB, I have another view which I have given a top, left & right constraint of 0 to its superview. I have set this in code as well:

 override func viewDidLayoutSubviews()
{
    viewB.frame.size.height = 2000
    scrollView.contentSize = viewB.frame.size
}

However, the scrollview still does not scroll. Thanks to anyone who can help out...been stuck on this for a while.


问:
Modified comparator for priority_queue of C++ not working properly
In the code given below, I am trying to keep some values in priority_queue sorted accordingly their key values, which are stored in the "key" vector. And then, I am changing the key values to see if the comparator working properly or not. Here, when I change the key[8] to 10, value 8 changes its position in the queue correctly. But when I changed the key[2] to -1, it changed it's position in the queue, but not correctly. It should be positioned at the top of the queue, as it's key value is the smallest, but it's not.

Is my way of writing the code of the comparator wrong? Or, It's something else that I am not doing correctly?

I want to know the correct way to modify the comparator of priority queue if I want to sort values in ascending order accordingly to their key values.

```<code>#include <bits/stdc++.h>
using namespace std;
vector <int> key(1000);
struct comp{
    bool operator()(int a,int b)const{
        return key[a]>key[b];
    }
};
int main()
{
    priority_queue <int,vector<int>,comp> q,temp;
    for(int a=0;a<10;a++){
        int n=rand()%16;
        key[a]=n;
        q.push(a);
    }
    while(!q.empty()){
        temp=q;
        while(!temp.empty()){
            cout<< temp.top() << "(" << key[temp.top()] << ") ";
            temp.pop();
        }
        cout<<endl<<endl;
        int u,v;
        cin>> u >> v;
        key[u]=v;
    }
    return 0;
}
</code>```

答: You never changed q. You made a copy of q in temp but never did anything to q.

Body:
In the code given below, I am trying to keep some values in priority_queue sorted accordingly their key values, which are stored in the "key" vector. And then, I am changing the key values to see if the comparator working properly or not. Here, when I change the key[8] to 10, value 8 changes its position in the queue correctly. But when I changed the key[2] to -1, it changed it's position in the queue, but not correctly. It should be positioned at the top of the queue, as it's key value is the smallest, but it's not.

Is my way of writing the code of the comparator wrong? Or, It's something else that I am not doing correctly?

I want to know the correct way to modify the comparator of priority queue if I want to sort values in ascending order accordingly to their key values.

#include <bits/stdc++.h>
using namespace std;
vector <int> key(1000);
struct comp{
    bool operator()(int a,int b)const{
        return key[a]>key[b];
    }
};
int main()
{
    priority_queue <int,vector<int>,comp> q,temp;
    for(int a=0;a<10;a++){
        int n=rand()%16;
        key[a]=n;
        q.push(a);
    }
    while(!q.empty()){
        temp=q;
        while(!temp.empty()){
            cout<< temp.top() << "(" << key[temp.top()] << ") ";
            temp.pop();
        }
        cout<<endl<<endl;
        int u,v;
        cin>> u >> v;
        key[u]=v;
    }
    return 0;
}


问:
How to get value with (keyup)="getSearch($event, value)" handler until the user stops typing?
now working like this: "a","an","ang","angu","angul","angula", "angular"

How to get value when user already stops typing in input area?

example: get "angular", when user stops typing.

any idea?

答:
you can try this (keyup.enter)="getSearch($event,value)" it will call when you press enter after typing.

there is one more way which i think can work in your case. you can use form field observable for this and detect changes & apply function on observable
check this code. modify it according to your need

```<code> <form [formGroup]="coolForm">
    <input formControlName="search" placeholder="Search artist">
    </form>
</code>```

component code

```<code>export class AppComponent {
    searchField: FormControl;
    coolForm: FormGroup;

    constructor(private searchService:SearchService, private fb:FormBuilder) {
        this.searchField = new FormControl();
        this.coolForm = fb.group({search: this.searchField});

        this.searchField.valueChanges
          .debounceTime(400)
            .switchMap(term => this.searchService.search(term))
            .subscribe((result) => {
                //////
            });
    }
</code>```

i hope this will help :)

Body:
you can try this (keyup.enter)="getSearch($event,value)" it will call when you press enter after typing.

there is one more way which i think can work in your case. you can use form field observable for this and detect changes & apply function on observable
check this code. modify it according to your need

 <form [formGroup]="coolForm">
    <input formControlName="search" placeholder="Search artist">
    </form>

component code

export class AppComponent {
    searchField: FormControl;
    coolForm: FormGroup;

    constructor(private searchService:SearchService, private fb:FormBuilder) {
        this.searchField = new FormControl();
        this.coolForm = fb.group({search: this.searchField});

        this.searchField.valueChanges
          .debounceTime(400)
            .switchMap(term => this.searchService.search(term))
            .subscribe((result) => {
                //////
            });
    }

i hope this will help :)


问:
How can I add button function into fragments
I'm trying to create a learning application the activity will show 3 tabs, my question is how can I put a Video View into the tab. The codes for the button that I know doesn't work. any idea about what syntax should I use when it comes to fragments?enter image description here</p>

答:
Do something like this </p>

```<code>Public class  Tab2Vid extand Fragment implement View.OnClickListener {

    Public View onCreateView(LayoutInflater inflater, ViewGroup container
                            ,Bundle savedlnstanceState) {

    View rootView = inflater.inflate(R.layout.tab2video, container, false);

    Button play = (Button)rootView.findViewById(R.id.btnplay);

    return rootView;

    }

    Public void onClick(View view)(
    switch (view.getId())
        {

            case R.id.btnplay:
              Toast.makeText(getActivity(),"Btn Play clicked", Toast.LENGTH_SHORT).show();
                break;
            default:
                return;
        }
    }
}
</code>```

Body:
Do something like this

Public class  Tab2Vid extand Fragment implement View.OnClickListener {

    Public View onCreateView(LayoutInflater inflater, ViewGroup container
                            ,Bundle savedlnstanceState) {

    View rootView = inflater.inflate(R.layout.tab2video, container, false);

    Button play = (Button)rootView.findViewById(R.id.btnplay);

    return rootView;

    }

    Public void onClick(View view)(
    switch (view.getId())
        {

            case R.id.btnplay:
              Toast.makeText(getActivity(),"Btn Play clicked", Toast.LENGTH_SHORT).show();
                break;
            default:
                return;
        }
    }
}


问:
Webpack code splitting
Im trying to set up my project with webpack, i've read about code-splitting and i am trying to make two separate bundles, one for the actual application code and the other for libraries and frameworks. So my webpack config looks like this:

```<code>entry: {
    app: './app/index.js',
    vendor: './app/vendor.js'
},
output: {
    filename: '[name].[chunkhash].js',
    path: path.resolve(__dirname, 'public/js')
},

watch: true,

module: {
    rules: [{
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
            use: 'css-loader'
        })
    }]
},

plugins: [
    new ExtractTextPlugin('styles.css'),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor'
    })
]
</code>```

in my vendor.js bundle i have only one line:

```<code> import moment from 'moment';
</code>```

And when i try to use it in my app.js file it tells me, that moment is not defined. So, the thing that i don't get, do bundles have common scope or not? If not, then how can i access variables that i've exported in another bundle and if i can't, then what's even the point of having the vendor bundle like described here https://webpack.js.org/guides/code-splitting-libraries/ ?

答:
The bundles do not share a scope. In fact webpack respects the scope of each module, just like Node.js, so you can't use anything from another module unless you import it, even if it's in the same bundle.

You need to import moment in every module you're using it. This doesn't mean you include its source code multiple times. Webpack includes the source once, and every import will refer to that.

Code splitting, the CommonsChunkPlugin in this case, simply puts the source into the vendor bundle, and every import across the bundles will refer to the vendor bundle. This means that you don't ship the vendor dependencies with your app bundle and therefore the vendor bundle can be cached by the browser. When you publish a new version of your app without changing your vendor bundle, the browser will only need to download the app bundle, as it already has the correct vendor bundle.

Let's consider this very short example app:

```<code>import moment from 'moment';
console.log(moment().format());
</code>```

Without the CommonsChunkPlugin the resulting bundles (not uglified) are:

```<code>vendor.js  470 kB       0  [emitted]  [big]  vendor
   app.js  470 kB       1  [emitted]  [big]  app
</code>```

That's 470 KB, because it contains the entire moment source in the bundle and even worse, another bundle that also uses moment, contains the entire source as well. The vendor isn't supposed to use it here, but think of another bundle that would need to use it. When you change something in the app, the user would have to download the entire 470 KB again.

With the CommonsChunkPlugin:

```<code>   app.js  504 bytes       0  [emitted]         app
vendor.js     473 kB       1  [emitted]  [big]  vendor
</code>```

Now the app went down to 504 bytes. And when you change the app, the user will only have to download this small bundle (assuming vendor.js is already cached). This also means any additional bundle that uses moment would also refer to vendor.js instead of including the source in the bundle.

The size of vendor.js slightly increased, because webpack needs some extra code to handle the imports from another bundle. This also requires the vendor.js to be loaded before the app.js.

I left out the hashes in the filenames for brevity, but they would be required for cache busting. For more information see Caching.

Title: Webpack code splitting

Body:
Im trying to set up my project with webpack, i've read about code-splitting and i am trying to make two separate bundles, one for the actual application code and the other for libraries and frameworks. So my webpack config looks like this:

entry: {
    app: './app/index.js',
    vendor: './app/vendor.js'
},
output: {
    filename: '[name].[chunkhash].js',
    path: path.resolve(__dirname, 'public/js')
},

watch: true,

module: {
    rules: [{
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
            use: 'css-loader'
        })
    }]
},

plugins: [
    new ExtractTextPlugin('styles.css'),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor'
    })
]

in my vendor.js bundle i have only one line:

 import moment from 'moment';

And when i try to use it in my app.js file it tells me, that moment is not defined. So, the thing that i don't get, do bundles have common scope or not? If not, then how can i access variables that i've exported in another bundle and if i can't, then what's even the point of having the vendor bundle like described here https://webpack.js.org/guides/code-splitting-libraries/ ?

Body:
The bundles do not share a scope. In fact webpack respects the scope of each module, just like Node.js, so you can't use anything from another module unless you import it, even if it's in the same bundle.

You need to import moment in every module you're using it. This doesn't mean you include its source code multiple times. Webpack includes the source once, and every import will refer to that.

Code splitting, the CommonsChunkPlugin in this case, simply puts the source into the vendor bundle, and every import across the bundles will refer to the vendor bundle. This means that you don't ship the vendor dependencies with your app bundle and therefore the vendor bundle can be cached by the browser. When you publish a new version of your app without changing your vendor bundle, the browser will only need to download the app bundle, as it already has the correct vendor bundle.

Let's consider this very short example app:

import moment from 'moment';
console.log(moment().format());

Without the CommonsChunkPlugin the resulting bundles (not uglified) are:

vendor.js  470 kB       0  [emitted]  [big]  vendor
   app.js  470 kB       1  [emitted]  [big]  app

That's 470 KB, because it contains the entire moment source in the bundle and even worse, another bundle that also uses moment, contains the entire source as well. The vendor isn't supposed to use it here, but think of another bundle that would need to use it. When you change something in the app, the user would have to download the entire 470 KB again.

With the CommonsChunkPlugin:

   app.js  504 bytes       0  [emitted]         app
vendor.js     473 kB       1  [emitted]  [big]  vendor

Now the app went down to 504 bytes. And when you change the app, the user will only have to download this small bundle (assuming vendor.js is already cached). This also means any additional bundle that uses moment would also refer to vendor.js instead of including the source in the bundle.

The size of vendor.js slightly increased, because webpack needs some extra code to handle the imports from another bundle. This also requires the vendor.js to be loaded before the app.js.

I left out the hashes in the filenames for brevity, but they would be required for cache busting. For more information see Caching.


问:
Copying a class object
I have an instance object named layers
which is an array of Layer objects.

I try the following, and I get an error saying that I'm trying to dump a class method:

```<code>@best_copy = Marshal.load(Marshal.dump(@layers))

TypeError: no marshal_dump is defined for class Method
</code>```

How do I make it so that it isn't trying to save the attr_accessor,
but the actual object?

答: It looks like one or more of your Layers has an instance variable that's a Method. Does that sound right? Marshal sends an object marshal_dump to get the data for marshaling, and in turn the object's attributes also get marshal_dump to get their data. Methods cannot be marshaled, so when the process gets to that part of object, it gets hung up trying to marshal your method.

Title: Copying a class object

Body:
I have an instance object named layers
which is an array of Layer objects.

I try the following, and I get an error saying that I'm trying to dump a class method:

@best_copy = Marshal.load(Marshal.dump(@layers))

TypeError: no marshal_dump is defined for class Method

How do I make it so that it isn't trying to save the attr_accessor,
but the actual object?


问:
removeClass not working
I have a li list and this list working data-project-id

I want to click list_title removeClass e "open" but not working.

tip : toggleClass not working.

```<code><div class="project-side-list scrollbar-inner">
   <ul id="sortable">
      <li data-project-id="1">
         <div class="list-title">Content</div>
           <div class="list-project-detail-content">
           </div>
      </li>
  </ul>
</div>
</code>```

JS:

```<code>$(document.body).on("click", "[data-project-id]", function() {
  var e = $(this),
    list = $(".project-side-list ul li "),
    list_title = $(".project-side-list ul li .list-title");

  if (e.hasClass("open")) {

    $(list_title).click(function() {
      e.removeClass('open');
    });

  } else {
    list.removeClass("open");
    e.addClass("open");
  }
});
</code>```

答:
Here is the simple way to do it.

```<code>$('.list-title').click(function() {
   $(this).toggleClass('open')
})
</code>```

http://codepen.io/iLavs/pen/YZBeMd

Title: removeClass not working

Body:
I have a li list and this list working data-project-id

I want to click list_title removeClass e "open" but not working.

tip : toggleClass not working.

Content

JS:

$(document.body).on("click", "[data-project-id]", function() {
  var e = $(this),
    list = $(".project-side-list ul li "),
    list_title = $(".project-side-list ul li .list-title");

  if (e.hasClass("open")) {

    $(list_title).click(function() {
      e.removeClass('open');
    });

  } else {
    list.removeClass("open");
    e.addClass("open");
  }
});

Body:
Here is the simple way to do it.

$('.list-title').click(function() {
   $(this).toggleClass('open')
})

http://codepen.io/iLavs/pen/YZBeMd


问:
C# how do I use a partially filled array in a method?
My instructor wants us to create an array of 10 elements and then fill it with random numbers using console input and then multiply all the numbers together to get the product.  I can't figure out how to pass the array to a method and then successfully get the product.  Do I use a for loop?  I don't think I can use a foreach loop because it could be partially filled.  How do I even pass the array to the method in the first place?

Here's what I have so far to store the values in the array.

```<code>for (int i = 0; i < SIZE; i++)
{

    bool valid = false;
    do
    {
         Write("Enter an integer value or 0 to stop ");
         string input = ReadLine();
         valid = int.TryParse(input, out userInput);
    } while (!valid);

    if (userInput == 0)
    {
         break;
    }
    array[i] = userInput;
}

product = p.ArrayProduct(array.Length);
</code>```

答:
The method for multiplying is as below:

```<code>public int ArrayProduct(int[] array)
{
   int p = 1;
   for(int i = 0; i < array.Length; i++)
   {
       p *= array[i];
   }
   return p;
}
</code>```

You can multiply in foreach loop as well:

```<code>public int ArrayProduct(int[] array)
{
   int p = 1;
   foreach(int element in array)
   {
       p *= element;
   }
   return p;
}
</code>```

Or you can use Array class like below:

```<code>public int ArrayProduct(int[] array)
{
    int p = 1;
    Array.ForEach(array, el =>
    {
        p *= el;
    });
    return p;
}
</code>```

There is another extension method for arrays called, gues how! ForEach

```<code>public int ArrayProduct(int[] array)
{
    int p = 1;
    array.ForEach(element =>
    {
        p *= element;
    });
    return p;
}
</code>```

Then you call it after you have the data as below:

```<code>int product = ArrayProduct(array);
Console.WriteLine(product);
</code>```

There is another way as @Peter A. Schneider said by using Linq according this question here

```<code>public int ArrayProduct(int[] array)
{
    return array.Aggregate(1, (acc, val) => acc * val);
}
</code>```

better in c# 6 and above:

```<code>public int ArrayProduct(int[] array) => array.Aggregate(1, (acc, val) => acc * val);
</code>```

If you have problem with getting the data please let me know!

Body:
My instructor wants us to create an array of 10 elements and then fill it with random numbers using console input and then multiply all the numbers together to get the product.  I can't figure out how to pass the array to a method and then successfully get the product.  Do I use a for loop?  I don't think I can use a foreach loop because it could be partially filled.  How do I even pass the array to the method in the first place?

Here's what I have so far to store the values in the array.

for (int i = 0; i < SIZE; i++)
{

    bool valid = false;
    do
    {
         Write("Enter an integer value or 0 to stop ");
         string input = ReadLine();
         valid = int.TryParse(input, out userInput);
    } while (!valid);

    if (userInput == 0)
    {
         break;
    }
    array[i] = userInput;
}

product = p.ArrayProduct(array.Length);

Body:
The method for multiplying is as below:

public int ArrayProduct(int[] array)
{
   int p = 1;
   for(int i = 0; i < array.Length; i++)
   {
       p *= array[i];
   }
   return p;
}

You can multiply in foreach loop as well:

public int ArrayProduct(int[] array)
{
   int p = 1;
   foreach(int element in array)
   {
       p *= element;
   }
   return p;
}

Or you can use Array class like below:

public int ArrayProduct(int[] array)
{
    int p = 1;
    Array.ForEach(array, el =>
    {
        p *= el;
    });
    return p;
}

There is another extension method for arrays called, gues how! ForEach

public int ArrayProduct(int[] array)
{
    int p = 1;
    array.ForEach(element =>
    {
        p *= element;
    });
    return p;
}

Then you call it after you have the data as below:

int product = ArrayProduct(array);
Console.WriteLine(product);

There is another way as @Peter A. Schneider said by using Linq according this question here

public int ArrayProduct(int[] array)
{
    return array.Aggregate(1, (acc, val) => acc * val);
}

better in c# 6 and above:

public int ArrayProduct(int[] array) => array.Aggregate(1, (acc, val) => acc * val);

If you have problem with getting the data please let me know!


问:
Windows cannot find 'C:\file_name.bat.' Make sure you typed name correctly, and then try again
I have a problem with running *.bat file.

It looks like a virus.

Does anyone know what is wrong with my Windows?

How to solve it?

I can run *.bat when I use Run as Administrator.

I tried to delete a .bat from: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\

答: Make sure cmd.exe is in System32,i placed it on desktop and i had the same problem as you.</p>


问:
How to get other array value if match?
Array 1 output

```<code> Array (
       [0] => Array ( [ID] => 335 [userid] => 4 [username] => demo [media_id] => 17 )
       [1] => Array ( [ID] => 436 [userid] => 4 [username] => demo [media_id] => 18 )
       [2] => Array ( [ID] => 637 [userid] => 4 [username] => demo [media_id] => 19 )
       [3] => Array ( [ID] => 838 [userid] => 4 [username] => demo [media_id] => 20 )
 );
</code>```

Array 2 output

```<code> Array (
        [1] => Array ( [ID] => 35 [userid] => 4  [media_id] => 17 )
        [2] => Array ( [ID] => 36 [userid] => 4  [media_id] => 18 )
     );
</code>```

How to get other array value if match? I need if media_id and userid of array 2 match in array 1 then how to get perticuler ID and username from array 1 in foreach loop of array 2 ?

Update

```<code>$array1 = array (
    0 => array ( "ID" => "335", "userid" => "4", "username" => "demo", "media_id" => "17" ),
    1 => array ( "ID" => "436", "userid" => "4", "username" => "demo", "media_id" => "18" ),
    2 => array ( "ID" => "637", "userid" => "4", "username" => "demo", "media_id" => "19" ),
    3 => array ( "ID" => "838", "userid" => "4", "username" => "demo", "media_id" => "20" )
                      );

$array2 = array (
    1 => array ( "ID" => "35", "userid" => "4", "media_id" => "17" ),
    2 => array ( "ID" => "36", "userid" => "4", "media_id" => "18" )
                          );

      foreach($array2 as $array) {

          foreach($array1 as $get_data) {
                 if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']){
                                    $get_result[] = //get_data true;
                                   } else {
                                    $get_result[] = //get_data false;
                                   }
                                }

                      //get ID and username or show false value

              }
</code>```

Final answer

```<code>foreach($array2 as $array) {
     $return = "false";
     foreach($array1 as $get_data) {
         if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']) {
         $get_result[] = ['ID' => $get_data['ID'], 'username' => $get_data['username']];
         $return = "true";
    }
  }

   if($return = "false"){
        echo false;
   }

}
</code>```

答:
If I understood well your question (I'm not sure), this should work:</p>

```<code>foreach($array2 as $array) {
  foreach($array1 as $get_data) {
    if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']) {
      $get_result[] = ['ID' => $get_data['ID'], 'username' => $get_data['username']];
    }
  }
}
if (count($get_result) == 0) {
  $get_result[] = false;
}
</code>```

Title: How to get other array value if match?

Body:
Array 1 output

 Array (
       [0] => Array ( [ID] => 335 [userid] => 4 [username] => demo [media_id] => 17 )
       [1] => Array ( [ID] => 436 [userid] => 4 [username] => demo [media_id] => 18 )
       [2] => Array ( [ID] => 637 [userid] => 4 [username] => demo [media_id] => 19 )
       [3] => Array ( [ID] => 838 [userid] => 4 [username] => demo [media_id] => 20 )
 );

Array 2 output

 Array (
        [1] => Array ( [ID] => 35 [userid] => 4  [media_id] => 17 )
        [2] => Array ( [ID] => 36 [userid] => 4  [media_id] => 18 )
     );

How to get other array value if match? I need if media_id and userid of array 2 match in array 1 then how to get perticuler ID and username from array 1 in foreach loop of array 2 ?

Update

$array1 = array (
    0 => array ( "ID" => "335", "userid" => "4", "username" => "demo", "media_id" => "17" ),
    1 => array ( "ID" => "436", "userid" => "4", "username" => "demo", "media_id" => "18" ),
    2 => array ( "ID" => "637", "userid" => "4", "username" => "demo", "media_id" => "19" ),
    3 => array ( "ID" => "838", "userid" => "4", "username" => "demo", "media_id" => "20" )
                      );

$array2 = array (
    1 => array ( "ID" => "35", "userid" => "4", "media_id" => "17" ),
    2 => array ( "ID" => "36", "userid" => "4", "media_id" => "18" )
                          );

      foreach($array2 as $array) {

          foreach($array1 as $get_data) {
                 if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']){
                                    $get_result[] = //get_data true;
                                   } else {
                                    $get_result[] = //get_data false;
                                   }
                                }

                      //get ID and username or show false value

              }

Final answer

foreach($array2 as $array) {
     $return = "false";
     foreach($array1 as $get_data) {
         if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']) {
         $get_result[] = ['ID' => $get_data['ID'], 'username' => $get_data['username']];
         $return = "true";
    }
  }

   if($return = "false"){
        echo false;
   }

}

Body:
If I understood well your question (I'm not sure), this should work:

foreach($array2 as $array) {
  foreach($array1 as $get_data) {
    if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']) {
      $get_result[] = ['ID' => $get_data['ID'], 'username' => $get_data['username']];
    }
  }
}
if (count($get_result) == 0) {
  $get_result[] = false;
}


问:
expressjs code listing on tcpv6 port only rather than ipv4
Env is :- ubuntu 14.04

My node version is :-

```<code> node --version
 v6.9.4
</code>```

Here is my code.

```<code>// dependencies :-
 var express = require ('express');
var mongoose = require ('mongoose');
var bodyParser = require ('body-parser');

var app = express();
app.use(bodyParser.urlencoded({extended: true}) );
app.use (bodyParser.json());

// routes :
api=require('./routes/api');
app.post('/register',api.register);
app.post('/authenticateUser',api.authenticateUser)
app.post('/update',api.updateUser);
//start server

app.listen (8070);

console.log('Server Started & listing at 8070 ');
</code>```

It was listing on both IPv4 & IPV6 till 2 days back my code was working fine.

But now all the way in between it seems like express code is only listing on tcp6 ( IPv6 ). Googled it but everbody faced this issue in 0.x.x.

Here is output of terminal

```<code>xxx@ubuntu:~$ netstat -a | grep 8070
 tcp6       0      0 [::]:8070               [::]:*                  LISTEN
</code>```

My Code seems to be perfect.Any ideas or any clue whats happening to system ????

Output of interfaces is :-

```<code>eth0      Link encap:Ethernet  HWaddr 00:0c:29:d1:ce:56
          inet addr:192.168.0.13  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fed1:ce56/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:26221 errors:0 dropped:0 overruns:0 frame:0
      TX packets:10916 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:27443150 (27.4 MB)  TX bytes:1365295 (1.3 MB)

lo        Link encap:Local Loopback
      inet addr:127.0.0.1  Mask:255.0.0.0
      inet6 addr: ::1/128 Scope:Host
      UP LOOPBACK RUNNING  MTU:65536  Metric:1
      RX packets:9366 errors:0 dropped:0 overruns:0 frame:0
      TX packets:9366 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:0
      RX bytes:5748317 (5.7 MB)  TX bytes:5748317 (5.7 MB)
</code>```

答:
I found the cause on my own after more investigation.

It seems like on my system, as I was running ubuntu VM under my Windows machine, the Windows IPv6 was disabled & and on VM IPv6 was not disabled.

Disabled IPV6 on ubuntu machine everything works fine.

Body:
Env is :- ubuntu 14.04

My node version is :-

 node --version
 v6.9.4

Here is my code.

// dependencies :-
 var express = require ('express');
var mongoose = require ('mongoose');
var bodyParser = require ('body-parser');

var app = express();
app.use(bodyParser.urlencoded({extended: true}) );
app.use (bodyParser.json());

// routes :
api=require('./routes/api');
app.post('/register',api.register);
app.post('/authenticateUser',api.authenticateUser)
app.post('/update',api.updateUser);
//start server

app.listen (8070);

console.log('Server Started & listing at 8070 ');

It was listing on both IPv4 & IPV6 till 2 days back my code was working fine.

But now all the way in between it seems like express code is only listing on tcp6 ( IPv6 ). Googled it but everbody faced this issue in 0.x.x.

Here is output of terminal

xxx@ubuntu:~$ netstat -a | grep 8070
 tcp6       0      0 [::]:8070               [::]:*                  LISTEN

My Code seems to be perfect.Any ideas or any clue whats happening to system ????

Output of interfaces is :-

eth0      Link encap:Ethernet  HWaddr 00:0c:29:d1:ce:56
          inet addr:192.168.0.13  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fed1:ce56/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:26221 errors:0 dropped:0 overruns:0 frame:0
      TX packets:10916 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:27443150 (27.4 MB)  TX bytes:1365295 (1.3 MB)

lo        Link encap:Local Loopback
      inet addr:127.0.0.1  Mask:255.0.0.0
      inet6 addr: ::1/128 Scope:Host
      UP LOOPBACK RUNNING  MTU:65536  Metric:1
      RX packets:9366 errors:0 dropped:0 overruns:0 frame:0
      TX packets:9366 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:0
      RX bytes:5748317 (5.7 MB)  TX bytes:5748317 (5.7 MB)


问:
Are there text processing function that operate on word level in R?
I am trying to find a group of functions in R that would operate on word level. e.g. a function that could return the position of the word. For example given the following sentence and query

```<code>sentence <- "A sample sentence for demo"
query <- "for"
</code>```

the function would return 4. for is 4th word.

It would be great if I could get a utility function that would allow me to extend query both in left and right direction.
e.g. extend(query, 'right') would return for demo and extend(query, 'left') would return sentence for

I have already gone through functions like grep, gregexp, word from stringr package and others. All seem to operate on character level.

答:
As I mentioned in my comment, stringr is useful in these instances.

```<code>library(stringr)

sentence <- "A sample sentence for demo"
wordNumber <- 4L

fourthWord <- word(string = sentence,
                   start = wordNumber)

previousWords <- word(string = sentence,
                       start = wordNumber - 1L,
                       end = wordNumber)

laterWords <- word(string = sentence,
                   start = wordNumber,
                   end = wordNumber + 1L)
</code>```

And this yields:

```<code>> fourthWord
[1] "for"
> previousWords
[1] "sentence for"
> laterWords
[1] "for demo"
</code>```

I hope that helps you.

Body:
I am trying to find a group of functions in R that would operate on word level. e.g. a function that could return the position of the word. For example given the following sentence and query

sentence <- "A sample sentence for demo"
query <- "for"

the function would return 4. for is 4th word.

It would be great if I could get a utility function that would allow me to extend query both in left and right direction.
e.g. extend(query, 'right') would return for demo and extend(query, 'left') would return sentence for

I have already gone through functions like grep, gregexp, word from stringr package and others. All seem to operate on character level.

Body:
As I mentioned in my comment, stringr is useful in these instances.

library(stringr)

sentence <- "A sample sentence for demo"
wordNumber <- 4L

fourthWord <- word(string = sentence,
                   start = wordNumber)

previousWords <- word(string = sentence,
                       start = wordNumber - 1L,
                       end = wordNumber)

laterWords <- word(string = sentence,
                   start = wordNumber,
                   end = wordNumber + 1L)

And this yields:

> fourthWord
[1] "for"
> previousWords
[1] "sentence for"
> laterWords
[1] "for demo"

I hope that helps you.


问:
XSLT: wanting to group similar output values and give them relevant headers
I'm brand new to XML and XSLT, so any guidance is deeply appreciated. I am unable to resolve my issue through researching on my own.

The Tools I'm using: I am using the Enhanced Query Export extension for VSTS. This allows you to write an XML document to export your work items in a format of your desire.

The Goal: I'd like my output to group work items by their work item type, and give these grouped work types specific headers. For example:

FIXES:

Bugs we've fixed

```<code>TITLE   TYPE   DESCRIPTION
B1      Bug    B1info
B2      Bug    B2info
B3      Bug    B3info
</code>```

...

IMPROVEMENTS:

Improvements we've made to the current features.

```<code>TITLE   TYPE     DESCRIPTION
I1      Backlog  I1info
I2      Backlog  I2info
I3      Backlog  I3info
</code>```

...

Current HTML Output Example:

Here's an image of what my output looks like with my current code.

Current Code:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" indent="yes"/>

<xsl:key name="workitem" match="//workitem" use="System.WorkItemType" />

  <xsl:template match="//workitem">
  <html>
<body>
    <table border="1">
      <tr bgcolor="#9acd32">
      <th>Title</th>
      <th>Type</th>
      <th>Description</th>
    </tr>
    <xsl:for-each select="key('workitem',System.WorkItemType)">

     <xsl:choose>

      <xsl:when test="System.WorkItemType = 'Bug' ">
              <h1>Fixes</h1>
              <h2>Bugs we've fixed.</h2>
                <tr>
                  <td><xsl:value-of select="System.Title"/></td>
                 <td><xsl:value-of select="System.WorkItemType"/></td>
                 <td><xsl:value-of select="System.Description"/></td>
               </tr>
      </xsl:when>
      <xsl:when test="System.WorkItemType = 'Product Backlog Item' ">
              <h1>Improvements</h1>
              <h2>Improvements we've made to existing functionality.</h2>
                <tr>
                  <td><xsl:value-of select="System.Title"/></td>
                 <td><xsl:value-of select="System.WorkItemType"/></td>
                 <td><xsl:value-of select="System.Description"/></td>
               </tr>
      </xsl:when>
     </xsl:choose>
    </xsl:for-each>
    </table>
  </body>
  </html>
  <xsl:apply-templates select="workitem" />
  </xsl:template>

</xsl:stylesheet>
</code>```

答:
Thanks, folks, for your comments and suggestions. I looked up Muenchian grouping as suggested by /u/tim-c and this was the solution I was looking for. I am grateful for everyone's hints to help this newbie! The code now works when formatted as follows (I've since added some additional formatting):</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes"/>

  <xsl:key name="wit" match="//workitem" use="System.WorkItemType" />

  <xsl:template match="/*">
    <html>
      <div style="width:600px; margin: 0 auto; margin-top:40px">

        <span class="title">What's New in</span>
        <img class="logo" src="images/app_name.svg" width="252" height="40" alt="" />

        <div class="body_copy">Unlike traditional dashboards or IT tools, Leading Wisely is a self-service, flexible tool that is not IT dependent, enabling users to set and monitor their choice of measure and alerts themselves.</div>

        <xsl:for-each select="//workitem
              [generate-id() = generate-id(key('wit', System.WorkItemType)[1])]">
          <xsl:sort select="System.WorkItemType" />
          <h1>
            <xsl:value-of select="System.WorkItemType" />
          </h1>
          <xsl:for-each select="key('wit', System.WorkItemType)">
            <xsl:sort select="System.Title" />
            <h3>
              <xsl:value-of select="System.Title" />
            </h3>
            <xsl:value-of select="System.Description" />
          </xsl:for-each>
        </xsl:for-each>
      </div>
      </html>
  </xsl:template>
</xsl:stylesheet>
</code>```

Body:
I'm brand new to XML and XSLT, so any guidance is deeply appreciated. I am unable to resolve my issue through researching on my own.

The Tools I'm using: I am using the Enhanced Query Export extension for VSTS. This allows you to write an XML document to export your work items in a format of your desire.

The Goal: I'd like my output to group work items by their work item type, and give these grouped work types specific headers. For example:

FIXES:

Bugs we've fixed

TITLE   TYPE   DESCRIPTION
B1      Bug    B1info
B2      Bug    B2info
B3      Bug    B3info

...

IMPROVEMENTS:

Improvements we've made to the current features.

TITLE   TYPE     DESCRIPTION
I1      Backlog  I1info
I2      Backlog  I2info
I3      Backlog  I3info

...

Current HTML Output Example:

Here's an image of what my output looks like with my current code.

Current Code:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" indent="yes"/>

<xsl:key name="workitem" match="//workitem" use="System.WorkItemType" />

  <xsl:template match="//workitem">

      Title
      Type
      Description

    <xsl:for-each select="key('workitem',System.WorkItemType)">

     <xsl:choose>

      <xsl:when test="System.WorkItemType = 'Bug' ">

Fixes

Bugs we've fixed.

                  <xsl:value-of select="System.Title"/>
                 <xsl:value-of select="System.WorkItemType"/>
                 <xsl:value-of select="System.Description"/>

      </xsl:when>
      <xsl:when test="System.WorkItemType = 'Product Backlog Item' ">

Improvements

Improvements we've made to existing functionality.

                  <xsl:value-of select="System.Title"/>
                 <xsl:value-of select="System.WorkItemType"/>
                 <xsl:value-of select="System.Description"/>

      </xsl:when>
     </xsl:choose>
    </xsl:for-each>

  <xsl:apply-templates select="workitem" />
  </xsl:template>

</xsl:stylesheet>

Body:
Thanks, folks, for your comments and suggestions. I looked up Muenchian grouping as suggested by /u/tim-c and this was the solution I was looking for. I am grateful for everyone's hints to help this newbie! The code now works when formatted as follows (I've since added some additional formatting):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes"/>

  <xsl:key name="wit" match="//workitem" use="System.WorkItemType" />

  <xsl:template match="/*">
    <html>
      <div style="width:600px; margin: 0 auto; margin-top:40px">

        <span class="title">What's New in</span>
        <img class="logo" src="images/app_name.svg" width="252" height="40" alt="" />

        <div class="body_copy">Unlike traditional dashboards or IT tools, Leading Wisely is a self-service, flexible tool that is not IT dependent, enabling users to set and monitor their choice of measure and alerts themselves.</div>

        <xsl:for-each select="//workitem
              [generate-id() = generate-id(key('wit', System.WorkItemType)[1])]">
          <xsl:sort select="System.WorkItemType" />
          <h1>
            <xsl:value-of select="System.WorkItemType" />
          </h1>
          <xsl:for-each select="key('wit', System.WorkItemType)">
            <xsl:sort select="System.Title" />
            <h3>
              <xsl:value-of select="System.Title" />
            </h3>
            <xsl:value-of select="System.Description" />
          </xsl:for-each>
        </xsl:for-each>
      </div>
      </html>
  </xsl:template>
</xsl:stylesheet>


问:
How to create a this HTML layout, by CSS?
I am newbie with CSS; so, I do not want to use CSS frameworks.

After reading some questions about fixed header and footer with CSS (on StackOverflow), I tried to create a HTML layout, as this:

In this layout, both header and menu are fixed.

I have created an HTML file with 2 column: left for menu, right for content. But, it comes with an scrolled-menu:

#menu {
  width: 33%;
  height: 100%;
  float: left;
}

#page {
  width: 66%;
  height: 100%;
  float: left;
}

#header {
  width: 100%;
  height: 100px;
  position: fixed;
}

#content {
  width: 100%;
  position: absolute;
  top: 100px;
}

#footer {
  width: 100%;
  height: 100px;
  position: fixed;
  bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="menu">
  MENU
</div>
<div id="page">
  <div id="header">Header</div>
  <div id="content">
    <p>Some content...</p>
  </div>
  <div id="footer">Footer</div>
</div></code>```

When I add this line: position: fixed; in #menu, the layout will be broken. Could help help me to fix it?

答:
```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Example of Bootstrap 2 Unequal Column Layout for Tablets and Desktops</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<style type="text/css">
    .row > div{
        margin-bottom: 15px;
    }
    .header{
        min-height: 90px;
    }
    .footer{
        min-height: 60px;
    }
    .header, .footer{
        background: #2f2f2f;
    }
    .sidebar{
        background: #dbdfe5;
    }
    .content{
        background: #b4bac0;
    }
    .sidebar, .content{
        min-height: 300px;
    }
</style>
</head>
<body>
    <!-- Open the output in a new blank tab (Click the arrow next to "Show Output" button) and resize the browser window to understand how the Bootstrap responsive grid system works. -->
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <div class="header"></div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-3">
                <div class="sidebar"></div>
            </div>
            <div class="col-sm-9">
                <div class="content"></div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12">
                <div class="footer"></div>
            </div>
        </div>
    </div>
</body>
</html>
</code>```

Body:
I am newbie with CSS; so, I do not want to use CSS frameworks.

After reading some questions about fixed header and footer with CSS (on StackOverflow), I tried to create a HTML layout, as this:

In this layout, both header and menu are fixed.

I have created an HTML file with 2 column: left for menu, right for content. But, it comes with an scrolled-menu:

#menu {
  width: 33%;
  height: 100%;
  float: left;
}

#page {
  width: 66%;
  height: 100%;
  float: left;
}

#header {
  width: 100%;
  height: 100px;
  position: fixed;
}

#content {
  width: 100%;
  position: absolute;
  top: 100px;
}

#footer {
  width: 100%;
  height: 100px;
  position: fixed;
  bottom: 0;
}

  MENU

Header

Some content...

Footer

When I add this line: position: fixed; in #menu, the layout will be broken. Could help help me to fix it?