问:
jquery addClass/removeClass ain't working
so I'm trying to add and remove a transparent background color to a div once it is open and remove when it's closed. any ideas oh great minds of stack overflow?

HTML

```<code><div class="col-md-12 col-xs-12">
    <div class="recipePicContainer">
        <div id="checkBoxes">
                <li class="recipe" id="recipe01"></li>
                       <ul class="ingredientsAndInstructions">
                           <li><input type="checkbox"> ingredient 1</li>
                           <li><input type="checkbox"> ingredient 2</li>
                           <li><input type="checkbox"> ingredient 3</li>
                           <li><input type="checkbox"> ingredient 4</li>
                            <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                </div>
            </div>
        </div>
</code>```

CSS

```<code>.selected{
    background-color: #699e6d;
    opacity: 0.7;
}
</code>```

JS

```<code>var main = function() {
    $(document).ready(function () {
        $('ul').hide();
        $('.recipe').click(function () {
            $('.ingredientsAndInstructions').toggle("slow");
            $('.recipePicContainer').click(function () {
                $(this).addClass("selected");
            }, function () {
                $(this).removeClass('selected');
            });
        });
    });
};
$(document).ready(main);
</code>```

Thanx!

答:
Use toggleClass()

Demo

$(document).ready(function() {
  $('button').click(function() {
    $('.recipes').toggleClass('selected');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.recipes {
  display: none;
}

.selected {
  background-color: #699e6d;
  opacity: 0.7;
  display: block;
}</code>```

<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>

  <button class='btn btn-primary'>
Recipes
</button>

<input type="checkbox"> ingredient 1

<input type="checkbox"> ingredient 2

<input type="checkbox"> ingredient 3

<input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

```

Body:
so I'm trying to add and remove a transparent background color to a div once it is open and remove when it's closed. any ideas oh great minds of stack overflow?

HTML

<input type="checkbox"> ingredient 1

<input type="checkbox"> ingredient 2

<input type="checkbox"> ingredient 3

<input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

CSS

.selected{
    background-color: #699e6d;
    opacity: 0.7;
}

JS

var main = function() {
    $(document).ready(function () {
        $('ul').hide();
        $('.recipe').click(function () {
            $('.ingredientsAndInstructions').toggle("slow");
            $('.recipePicContainer').click(function () {
                $(this).addClass("selected");
            }, function () {
                $(this).removeClass('selected');
            });
        });
    });
};
$(document).ready(main);

Thanx!

Body:
Use toggleClass()

Demo

$(document).ready(function() {
  $('button').click(function() {
    $('.recipes').toggleClass('selected');
  });
});

.recipes {
  display: none;
}

.selected {
  background-color: #699e6d;
  opacity: 0.7;
  display: block;
}

<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>

<div class="col-md-12 col-xs-12">

  <button class='btn btn-primary'><h3>Recipes</h3></button>
  <ul class="recipes">
    <li><input type="checkbox"> ingredient 1</li>
    <li><input type="checkbox"> ingredient 2</li>
    <li><input type="checkbox"> ingredient 3</li>
    <li><input type="checkbox"> ingredient 4</li>
    <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
  </ul>

</div>

<script src="https://cdn.jsdelivr.net/g/jquery@2.2.4,bootstrap@3.3.7"></script>


来源: stackexchange

问:
Pointer assignments in a copy constructor
I'm using the book Programming with objects by Avinash C. KAK, and in the page 452, it says constructs a copy constructor method as

```<code>class X{
int * ptr;
int size;
public:
X(const X & xobj)
{
    size = xobj.size;
    ptr = new int [size];
    for(int i = 0; i < size; i++)
    {
        ptr[i] = xobj.ptr[i];
    }
}
}
</code>```

Then it uses as

```<code>X x1;
X x2 = x1;
</code>```

But what I did not understand is that first it allocates memory for the x2.ptr and then assigns the memory address of x1.ptr to x2.ptr, which contradicts with the purpose of having a copy constructor method and the newly allocated memory is now not being used at all, so what am I missing ?

答:
If you have a pointer to a newly allocated array like:

```<code>ptr = new int[size];
</code>```

then you can index it in the same way as the arrays:

```<code>ptr[1] = 3; // equivalent to: *(ptr + 1) = 3
</code>```

So, as it's a copy constructor it copies the content of memory pointed by xobj.ptr to the newly allocated memory pointed by ptr.

ContentLicense: CC BY-SA 3.0

Body:
I'm using the book Programming with objects by Avinash C. KAK, and in the page 452, it says constructs a copy constructor method as

class X{
int * ptr;
int size;
public:
X(const X & xobj)
{
    size = xobj.size;
    ptr = new int [size];
    for(int i = 0; i < size; i++)
    {
        ptr[i] = xobj.ptr[i];
    }
}
}

Then it uses as

X x1;
X x2 = x1;

But what I did not understand is that first it allocates memory for the x2.ptr and then assigns the memory address of x1.ptr to x2.ptr, which contradicts with the purpose of having a copy constructor method and the newly allocated memory is now not being used at all, so what am I missing ?

Body:
If you have a pointer to a newly allocated array like:

ptr = new int[size];

then you can index it in the same way as the arrays:

ptr[1] = 3; // equivalent to: *(ptr + 1) = 3

So, as it's a copy constructor it copies the content of memory pointed by xobj.ptr to the newly allocated memory pointed by ptr.


问:
Why are my icons not showing up?
This is a zip to the full project QuickLinks.v4

I have been collaborating on a project and we are stuck on an issue, we want all of the icon to have a right click menu that has several options that are unique to each icon. We are almost done but now the icons are not being drawn to the screen. We are only working on the first 5 at the time. This is my first time working with jQuery and I would appreciate any help.

I will now post pieces of the project that I think are relevant.

icon.html

```<code><a target="_blank">
    <img class="icons" />
    <div class="data">
           <div>
                 <input type="hidden" class="login" />
                 <input type="hidden" class="username" />
                 <input type="hidden" class="password" />
           </div>
    </div>
</a>
</code>```

icon.js

```<code>function buildIcons() {
    var icons = [
        ["https://discordapp.com/", "discord-icon", "icons/discord.png", "social", "Discord",
            [
                 ["Main Account", "lela_null", "somepass"],
                 ["Bot Account", "Uta Yuki", "somepass"]
            ]
        ],
        ["https://www.youtube.com/", "youtube-icon", "icons/youtube.png", "social", "YouTube",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ],
        ["https://www.facebook.com/?sk=h_chr", "facebook-icon", "icons/facebook.png", "social", "Facebook",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ],
        ["https://www.twitter.com/", "twitter-icon", "icons/twitter.png", "social", "Twitter",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ],
        ["https://mg.mail.yahoo.com/neo/launch?.rand=8647i3s40jpvp", "ymail-icon", "icons/ymail.png", "social", "Yahoo Mail",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ]
    ];

    $.get('data/icon.html', function(data) {
        var icon;
        icons.forEach(function(iconData, index, array) {
            console.log(index);
            icon = $(data).insertAfter("#" + iconData[3]);
            $(icon).find("img").attr("src", iconData[2]);
        });
    });
};
</code>```

script.js

```<code>/* get icon id */
function buildMenu(iconId) {
    $("#remove").click(function() {
       $("#" + iconId).hide();
       cancel();
    });
    $("#menu-title").text($("#"+iconId).data("name"));
    $("#site-link").attr("href", $("#" + iconId).parent().attr("href")).click(cancel);
    switch(iconId) {
    };
}

/* set right click for icons */
$(document).ready(function() {
    buildIcons();
    $(".icons").on("contextmenu", function(e) {
        buildMenu(this.id);
        $("#contextmenu").show().css({
            top: e.clientY,
            left: e.clientX
        });
        e.preventDefault();
    });
});

function cancel() {
    $("#contextmenu").hide();
}
</code>```

There is more files and code, if you may need, you may download it above.

Also the console says TypeError: a is null in my jQuery.js file.

答: jQuery does not have the ability to include html from another file.</p>

Title: Why are my icons not showing up?

Body:
This is a zip to the full project QuickLinks.v4

I have been collaborating on a project and we are stuck on an issue, we want all of the icon to have a right click menu that has several options that are unique to each icon. We are almost done but now the icons are not being drawn to the screen. We are only working on the first 5 at the time. This is my first time working with jQuery and I would appreciate any help.

I will now post pieces of the project that I think are relevant.

icon.html

                 <input type="hidden" class="login" />
                 <input type="hidden" class="username" />
                 <input type="hidden" class="password" />

icon.js

function buildIcons() {
    var icons = [
        ["https://discordapp.com/", "discord-icon", "icons/discord.png", "social", "Discord",
            [
                 ["Main Account", "lela_null", "somepass"],
                 ["Bot Account", "Uta Yuki", "somepass"]
            ]
        ],
        ["https://www.youtube.com/", "youtube-icon", "icons/youtube.png", "social", "YouTube",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ],
        ["https://www.facebook.com/?sk=h_chr", "facebook-icon", "icons/facebook.png", "social", "Facebook",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ],
        ["https://www.twitter.com/", "twitter-icon", "icons/twitter.png", "social", "Twitter",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ],
        ["https://mg.mail.yahoo.com/neo/launch?.rand=8647i3s40jpvp", "ymail-icon", "icons/ymail.png", "social", "Yahoo Mail",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ]
    ];

    $.get('data/icon.html', function(data) {
        var icon;
        icons.forEach(function(iconData, index, array) {
            console.log(index);
            icon = $(data).insertAfter("#" + iconData[3]);
            $(icon).find("img").attr("src", iconData[2]);
        });
    });
};

script.js

/* get icon id */
function buildMenu(iconId) {
    $("#remove").click(function() {
       $("#" + iconId).hide();
       cancel();
    });
    $("#menu-title").text($("#"+iconId).data("name"));
    $("#site-link").attr("href", $("#" + iconId).parent().attr("href")).click(cancel);
    switch(iconId) {
    };
}

/* set right click for icons */
$(document).ready(function() {
    buildIcons();
    $(".icons").on("contextmenu", function(e) {
        buildMenu(this.id);
        $("#contextmenu").show().css({
            top: e.clientY,
            left: e.clientX
        });
        e.preventDefault();
    });
});

function cancel() {
    $("#contextmenu").hide();
}

There is more files and code, if you may need, you may download it above.

Also the console says TypeError: a is null in my jQuery.js file.


问:
Uncaught TypeError: e.map is not a function after updating to angular 4
after updating to angular 4 i getting this errormessaging. i dont know where it comes from and i dont understand what exactly chrome will say to me. </p>

```<code>Uncaught TypeError: e.map is not a function
at t.parameters (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51)
at e.parameters (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51)
at t.getDependenciesMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at t.getTypeMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
at Array.forEach (<anonymous>)
at t.getProvidersMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at t.getNgModuleMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
at Array.forEach (<anonymous>)
t.parameters    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51
e.parameters    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51
t.getDependenciesMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getTypeMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
(anonymous) @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getProvidersMetadata  @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getNgModuleMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
(anonymous) @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getNgModuleMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t._compileComponents    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:122
t._compileModuleAndComponents   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:121
t.compileModuleAsync    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:121
e._bootstrapModuleWithZone  @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:59
e.bootstrapModule   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:59
bootApplication @   boot-client.ts:17
t.invokeTask    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:201
n.runTask   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:201
invoke  @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:201
</code>```

答:
First save your code somewhere.

It seems have angular cli v4 installed, otherwise do in your terminal:

```<code>cd yourDevelopmentRootDirectory

npm uninstall -g angular-cli
npm cache clean
npm install -g @angular/cli@latest
</code>```

once finished:

```<code>ng new yourProjectName
</code>```

this will create an angular4 starter project.

Serve the application at the port localhost:4200:

```<code>cd yourProjectName
ng serve --open
</code>```

For your reference : https://angular.io/guide/quickstart and https://github.com/angular/angular-cli

Now, copy for saved project code (./src/app) back in yourProjectName directory, and check if it's compiling.

Body:
after updating to angular 4 i getting this errormessaging. i dont know where it comes from and i dont understand what exactly chrome will say to me.

Uncaught TypeError: e.map is not a function
at t.parameters (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51)
at e.parameters (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51)
at t.getDependenciesMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at t.getTypeMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
at Array.forEach (<anonymous>)
at t.getProvidersMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at t.getNgModuleMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
at Array.forEach (<anonymous>)
t.parameters    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51
e.parameters    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51
t.getDependenciesMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getTypeMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
(anonymous) @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getProvidersMetadata  @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getNgModuleMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
(anonymous) @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getNgModuleMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t._compileComponents    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:122
t._compileModuleAndComponents   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:121
t.compileModuleAsync    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:121
e._bootstrapModuleWithZone  @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:59
e.bootstrapModule   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:59
bootApplication @   boot-client.ts:17
t.invokeTask    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:201
n.runTask   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:201
invoke  @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:201

Body:
First save your code somewhere.

It seems have angular cli v4 installed, otherwise do in your terminal:

cd yourDevelopmentRootDirectory

npm uninstall -g angular-cli
npm cache clean
npm install -g @angular/cli@latest

once finished:

ng new yourProjectName

this will create an angular4 starter project.

Serve the application at the port localhost:4200:

cd yourProjectName
ng serve --open

For your reference : https://angular.io/guide/quickstart and https://github.com/angular/angular-cli

Now, copy for saved project code (./src/app) back in yourProjectName directory, and check if it's compiling.


问:
Calabash Android run error: The first parameter must be the path to the apk file
I am trying to run sample calabash-android test. But I am facing the below error.

C:\Ruby23\TMSampleAndroid-master>calabash-android run TestmunkTest_debug.apk --verbose
  The first parameter must be the path to the apk file.

答:
Consider the following:

Separate the project directory from your Ruby23 installation by moving the calabash project inside a Workspace folder for example.

Create a folder to hold your .apk inside the calabash project, for example "APKFile"

In the run command specify the full path to the .apk file and see if it runs, like this:

calabash-android run
  C:\Ruby23\TMSampleAndroid-master\TestmunkTest_debug.apk

or for my example:

calabash-android run
  C:\Workspace\TMSampleAndroid-master\TestmunkTest_debug.apk

To add logging write "--verbose" after the command. The error that you get might be because of the typo "--v erbose"

ContentLicense: CC BY-SA 4.0


问:
Align a set of inline-blocks by a middle element
Consider we have a bunch of inline-blocks in a row:

```<code><div class="elements-row">
  <div class="element">January</div>
  <div class="element">February</div>
  <div class="element">March</div>
  <div class="element featured">April</div>
  <div class="element">May</div>
  <div class="element">June</div>
  <div class="element">July</div>
<div>
</code>```

```<code>.elements-row {
    height: 140px;
    display: inline-block;
    text-align: center;
    overflow: hidden;
}

.elements-row .element {
    display: inline-block;
    font-size: 40px;
    color: #abb8c2;
    margin: 0 15px;
}

.elements-row .element.featured {
    margin: 0 40px;
    color: #4a667f;
}
</code>```

Is there a way to horizontally align the row the way that .featured block always remains in the middle of the .elements-row block no matter what other elements width is (its' content is dynamic). Elements are allowed to go out of row's boundaries, but a space between all elements except of .featured should be constant.

A demo on CodePen

答:
Using flex this would also be possible.

You can check what I mean by stretching the window.
Instead of using justify-content: space-around you might want to use justify-content: space-between.

More information about flex can be found at this w3schools page.

Update:

Here is a JSFiddle with the new code, it  probably works better if you want to try and resize the window.

.elements-row {
  display: flex;
  justify-content: space-around;
}

.element {
  font-size: 30px;
  color: #abb8c2;
  margin: 0 15px;
}

.featured {
  color: #AAA;
}

.elements-left {
  display: flex;
  justify-content: flex-end;
  flex: 1;
}

.elements-right {
  display: flex;
  justify-content: flex-start;
  flex: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="elements-row">
  <div class="elements-left">
    <div class="element">lorem ipsum dolor sit amet</div>
    <div class="element">February</div>
    <div class="element">March</div>
  </div>
  <div class="element featured">April</div>
  <div class="elements-right">
    <div class="element">May</div>
    <div class="element">June</div>
    <div class="element">July</div>
  </div>
</div></code>```

Old code, might be useful for somebody else:

Also a link to the JSFiddle

.elements-row {
  display: flex;
  justify-content: space-around;
}

.element {
  font-size: 30px;
  color: #abb8c2;
  margin: 0 15px;
}

.featured {
  color: #AAA;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="elements-row">
      <div class="element">January</div>
      <div class="element">February</div>
      <div class="element">March</div>
      <div class="element featured">April</div>
      <div class="element">May</div>
      <div class="element">June</div>
      <div class="element">July</div>
    </div></code>```

Body:
Consider we have a bunch of inline-blocks in a row:

January

February

March

April

May

June

July

.elements-row {
    height: 140px;
    display: inline-block;
    text-align: center;
    overflow: hidden;
}

.elements-row .element {
    display: inline-block;
    font-size: 40px;
    color: #abb8c2;
    margin: 0 15px;
}

.elements-row .element.featured {
    margin: 0 40px;
    color: #4a667f;
}

Is there a way to horizontally align the row the way that .featured block always remains in the middle of the .elements-row block no matter what other elements width is (its' content is dynamic). Elements are allowed to go out of row's boundaries, but a space between all elements except of .featured should be constant.

A demo on CodePen

Body:
Using flex this would also be possible.

You can check what I mean by stretching the window.
Instead of using justify-content: space-around you might want to use justify-content: space-between.

More information about flex can be found at this w3schools page.

Update:

Here is a JSFiddle with the new code, it  probably works better if you want to try and resize the window.

.elements-row {
  display: flex;
  justify-content: space-around;
}

.element {
  font-size: 30px;
  color: #abb8c2;
  margin: 0 15px;
}

.featured {
  color: #AAA;
}

.elements-left {
  display: flex;
  justify-content: flex-end;
  flex: 1;
}

.elements-right {
  display: flex;
  justify-content: flex-start;
  flex: 1;
}

<div class="elements-row">
  <div class="elements-left">
    <div class="element">lorem ipsum dolor sit amet</div>
    <div class="element">February</div>
    <div class="element">March</div>
  </div>
  <div class="element featured">April</div>
  <div class="elements-right">
    <div class="element">May</div>
    <div class="element">June</div>
    <div class="element">July</div>
  </div>
</div>

Old code, might be useful for somebody else:

Also a link to the JSFiddle

.elements-row {
  display: flex;
  justify-content: space-around;
}

.element {
  font-size: 30px;
  color: #abb8c2;
  margin: 0 15px;
}

.featured {
  color: #AAA;
}

<div class="elements-row">
      <div class="element">January</div>
      <div class="element">February</div>
      <div class="element">March</div>
      <div class="element featured">April</div>
      <div class="element">May</div>
      <div class="element">June</div>
      <div class="element">July</div>
    </div>


问:
Equivalent R "findcorrelation(corr,cutoff = 0.75)" in python pandas
I have dataFrame named "data". I calculated correlation for data:

```<code>corr = data.corr()
</code>```

I wanted remove columns which have correlation greater than 0.75 from "data" file.
This can be done in R very easily using the following command:

```<code>hc=findCorrelation(corr,cutoff = 0.75)
data <- data[,-c(hc)]
</code>```

I am looking for similar command in python. Is there any command in pandas or scikit-learn which can do the similar job ?

答:
Step 1. Prepare some data

```<code>from scipy.stats import multivariate_normal

covs = np.eye(10)
for i in range(10):
    for j in range(10):
        if i!=j:
            covs[i,j] = (i*j)/100

mvn = multivariate_normal(cov=covs)
data = mvn.rvs(size = 100)
data.shape
(100, 10)
</code>```

Step 2. Vizualize correlation.

Here, you have a 2-d correlated ndarray. The data is organized into columns, cases are in rows. In order to run correlation on column data, you need to transpose the array first (hint: numpy runs correlation row-wise):

```<code>r = np.corrcoef(data.T)
plt.imshow(r, cmap = "coolwarm")
plt.colorbar();
</code>```

As you might see, some columns (features, as they say in Statistics or ML) are highly correlated.

Step 3. Drop correlated columns

Let's find which ones are correlated in excess of .5 threshold, excluding diagonal elements, which are obviously perfectly self-correlated:

```<code>idx = np.abs(np.tril(r, k= -1)) < .5
idx_drop = np.all(idx, axis=1)
data_uncorr = data[:, idx_drop]
data_uncorr.shape
(100, 8)
</code>```

which means we got rid off 2 collinear columns.

Step 4. Sanity check

Let's do some checking, visually and mathematically:

```<code>plt.imshow(np.corrcoef(data_uncorr.T), cmap = "coolwarm")
plt.colorbar();
</code>```

```<code>np.sum(np.abs(np.tril(np.corrcoef(data_uncorr.T), k=-1)) >.5)
0
</code>```

Body:
I have dataFrame named "data". I calculated correlation for data:

corr = data.corr()

I wanted remove columns which have correlation greater than 0.75 from "data" file.
This can be done in R very easily using the following command:

hc=findCorrelation(corr,cutoff = 0.75)
data <- data[,-c(hc)]

I am looking for similar command in python. Is there any command in pandas or scikit-learn which can do the similar job ?

Body:
Step 1. Prepare some data

from scipy.stats import multivariate_normal

covs = np.eye(10)
for i in range(10):
    for j in range(10):
        if i!=j:
            covs[i,j] = (i*j)/100

mvn = multivariate_normal(cov=covs)
data = mvn.rvs(size = 100)
data.shape
(100, 10)

Step 2. Vizualize correlation.

Here, you have a 2-d correlated ndarray. The data is organized into columns, cases are in rows. In order to run correlation on column data, you need to transpose the array first (hint: numpy runs correlation row-wise):

r = np.corrcoef(data.T)
plt.imshow(r, cmap = "coolwarm")
plt.colorbar();

As you might see, some columns (features, as they say in Statistics or ML) are highly correlated.

Step 3. Drop correlated columns

Let's find which ones are correlated in excess of .5 threshold, excluding diagonal elements, which are obviously perfectly self-correlated:

idx = np.abs(np.tril(r, k= -1)) < .5
idx_drop = np.all(idx, axis=1)
data_uncorr = data[:, idx_drop]
data_uncorr.shape
(100, 8)

which means we got rid off 2 collinear columns.

Step 4. Sanity check

Let's do some checking, visually and mathematically:

plt.imshow(np.corrcoef(data_uncorr.T), cmap = "coolwarm")
plt.colorbar();

np.sum(np.abs(np.tril(np.corrcoef(data_uncorr.T), k=-1)) >.5)
0


问:
Change cell color based on value faster
I have vba code to change the color of cells based on the content of it currently I am looping through 13000 cells individually using row and column indexed for loops and a select case statement but it takes around 30 secs. Does anyone know a quicker way ?</p>

答:
I suspect reading each value from the cell is taking up a large chunk of the time. Try reading the data into an array and then creating 15 ranges, one for each colour. You'd then just fill each range with the appropriate colour at the end.

Having said that, 13,000 cells to colour is going to take some time. I couldn't get better than 10 seconds. If you only have to do it once though, 30 seconds doesn't seem so bad?

```<code>Dim r As Long, c As Long, i As Long, rOff As Long, cOff As Long
Dim data As Variant
Dim dataRange As Range, cell As Range
Dim colourRanges(14) As Range
Dim colours(14) As Long

'Define the colours
colours(0) = 255
colours(1) = 65535
colours(2) = 5296274
colours(3) = 12611584
colours(4) = 10498160
colours(5) = 49407
colours(6) = 192
colours(7) = 5287936
colours(8) = 15773696
colours(9) = 6299648
colours(10) = 5540756
colours(11) = 9803737
colours(12) = 13083058
colours(13) = 9486586
colours(14) = 14474738

'Define the target range
With Sheet1
    Set dataRange = .Range(.Range("A2"), _
                           .Cells(.Rows.Count, "A").End(xlUp)) _
                    .Resize(, 103)
End With

'Calculate offsets from "A1"
With dataRange
    rOff = .Cells(1).Row - 1
    cOff = .Cells(1).Column - 1
End With

'Read data
data = dataRange.Value2

'Test the data
For r = 1 To UBound(data, 1)
    For c = 1 To UBound(data, 2)
        Select Case data(r, c)
            Case 1: i = 0
            Case 2: i = 1
            Case 3: i = 2
            Case 4: i = 3
            Case 5: i = 4
            Case 6: i = 5
            Case 7: i = 6
            Case 8: i = 7
            Case 9: i = 8
            Case 10: i = 9
            Case 11: i = 10
            Case 12: i = 11
            Case 13: i = 12
            Case 14: i = 13
            Case 15: i = 14
            Case Else: i = -1
        End Select

        'Build the colour ranges
        If i <> -1 Then
            With Sheet1
                Set cell = .Cells(r + rOff, c + cOff)
                If colourRanges(i) Is Nothing Then
                    Set colourRanges(i) = cell
                Else
                    Set colourRanges(i) = Union(colourRanges(i), cell)
                End If
            End With
        End If
    Next
Next

'Colour the ranges
Application.ScreenUpdating = False
For i = 0 To 14
    colourRanges(i).Interior.Color = colours(i)
Next
Application.ScreenUpdating = True
</code>```

Title: Change cell color based on value faster

Body:
I suspect reading each value from the cell is taking up a large chunk of the time. Try reading the data into an array and then creating 15 ranges, one for each colour. You'd then just fill each range with the appropriate colour at the end.

Having said that, 13,000 cells to colour is going to take some time. I couldn't get better than 10 seconds. If you only have to do it once though, 30 seconds doesn't seem so bad?

Dim r As Long, c As Long, i As Long, rOff As Long, cOff As Long
Dim data As Variant
Dim dataRange As Range, cell As Range
Dim colourRanges(14) As Range
Dim colours(14) As Long

'Define the colours
colours(0) = 255
colours(1) = 65535
colours(2) = 5296274
colours(3) = 12611584
colours(4) = 10498160
colours(5) = 49407
colours(6) = 192
colours(7) = 5287936
colours(8) = 15773696
colours(9) = 6299648
colours(10) = 5540756
colours(11) = 9803737
colours(12) = 13083058
colours(13) = 9486586
colours(14) = 14474738

'Define the target range
With Sheet1
    Set dataRange = .Range(.Range("A2"), _
                           .Cells(.Rows.Count, "A").End(xlUp)) _
                    .Resize(, 103)
End With

'Calculate offsets from "A1"
With dataRange
    rOff = .Cells(1).Row - 1
    cOff = .Cells(1).Column - 1
End With

'Read data
data = dataRange.Value2

'Test the data
For r = 1 To UBound(data, 1)
    For c = 1 To UBound(data, 2)
        Select Case data(r, c)
            Case 1: i = 0
            Case 2: i = 1
            Case 3: i = 2
            Case 4: i = 3
            Case 5: i = 4
            Case 6: i = 5
            Case 7: i = 6
            Case 8: i = 7
            Case 9: i = 8
            Case 10: i = 9
            Case 11: i = 10
            Case 12: i = 11
            Case 13: i = 12
            Case 14: i = 13
            Case 15: i = 14
            Case Else: i = -1
        End Select

        'Build the colour ranges
        If i <> -1 Then
            With Sheet1
                Set cell = .Cells(r + rOff, c + cOff)
                If colourRanges(i) Is Nothing Then
                    Set colourRanges(i) = cell
                Else
                    Set colourRanges(i) = Union(colourRanges(i), cell)
                End If
            End With
        End If
    Next
Next

'Colour the ranges
Application.ScreenUpdating = False
For i = 0 To 14
    colourRanges(i).Interior.Color = colours(i)
Next
Application.ScreenUpdating = True


问:
How to use Gammaray on Android
I've used the Qt debugging tool Gammaray quite a bit on Linux. Now I want to use it also on Android but fail to make it work.

I've followed the instructions outlined here:
https://github.com/KDAB/GammaRay/blob/master/Install.txt

The make install step completes successfully.

```<code>...
[ 92%] Built target gammaray_widgetinspector_plugin
[ 95%] Built target gammaray_qmlsupport
[100%] Built target gammaray_styleinspector_plugin
Install the project...
-- Install configuration: "Release"
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libgammaray_kitemmodels-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libgammaray_common-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libgammaray_core-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libgammaray_probe-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/styles/gammaray_injector_style-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_codecbrowser_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_fontbrowser_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_modelinspector-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_quickinspector-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_signalmonitor-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_statemachineviewer_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_mimetypes-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_network-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_translatorinspector-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_guisupport-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_textdocumentinspector-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_actioninspector_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_widgetinspector_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libgammaray_widget_export_actions-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_sceneinspector_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_styleinspector_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_qmlsupport-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_quickwidgetsupport-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_bluetooth-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_positioning-qt5_8-arm.so
</code>```

Now I've created a simple qmake test project and added
android: QT += GammaRayProbe to it as outlined in the documentation.

When I now run qmake I always get:
Project ERROR: Unknown module(s) in QT: GammaRayProbe

From poking around in the mkspec files of my Qt5.8 install I wonder how this is supposed to work. The make install step doesn't install a .pri file that would allow QT += GammaRayProbe to work.

What am I doing wrong?

答:
The Install.md was outdated at that point in time. It has been updated to be correct.

Two additional things to keep in mind.
- you need to build a full GammaRay in addition to the Android probe.
- make sure to add the various plugins of GammaRa to your .apk.

Title: How to use Gammaray on Android

Body:
I've used the Qt debugging tool Gammaray quite a bit on Linux. Now I want to use it also on Android but fail to make it work.

I've followed the instructions outlined here:
https://github.com/KDAB/GammaRay/blob/master/Install.txt

The make install step completes successfully.

...
[ 92%] Built target gammaray_widgetinspector_plugin
[ 95%] Built target gammaray_qmlsupport
[100%] Built target gammaray_styleinspector_plugin
Install the project...
-- Install configuration: "Release"
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libgammaray_kitemmodels-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libgammaray_common-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libgammaray_core-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libgammaray_probe-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/styles/gammaray_injector_style-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_codecbrowser_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_fontbrowser_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_modelinspector-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_quickinspector-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_signalmonitor-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_statemachineviewer_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_mimetypes-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_network-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_translatorinspector-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_guisupport-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_textdocumentinspector-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_actioninspector_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_widgetinspector_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libgammaray_widget_export_actions-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_sceneinspector_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_styleinspector_plugin-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_qmlsupport-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_quickwidgetsupport-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_bluetooth-qt5_8-arm.so
-- Installing: /usr/local/Qt/5.8/android_armv7/lib/libplugins_gammaray_gammaray_positioning-qt5_8-arm.so

Now I've created a simple qmake test project and added
android: QT += GammaRayProbe to it as outlined in the documentation.

When I now run qmake I always get:
Project ERROR: Unknown module(s) in QT: GammaRayProbe

From poking around in the mkspec files of my Qt5.8 install I wonder how this is supposed to work. The make install step doesn't install a .pri file that would allow QT += GammaRayProbe to work.

What am I doing wrong?


问:
Using :focus to style outer div?
When I begin writing text in the textarea, I want the outer div, with a class box, to have its border turned solid instead of dashed, but somehow the :focus doesn't apply in this case. If it works with :active, how come it doesn't work with :focus?

Any ideas why?

(Note. I want the DIV's border to turn solid, NOT the textareas)

```<code>div.box
{
    width: 300px;
    height: 300px;
    border: thin dashed black;
}

div.box:focus{
    border: thin solid black;
}

<div class="box">
    <textarea rows="10" cols="25"></textarea>
</div>
</code>```

答:
Other posters have already explained why the :focus pseudo class is insufficient, but finally there is a CSS-based standard solution.

CSS Selectors Level 4 defines a new pseudo class:

:focus-within

From MDN:

The :focus-within CSS pseudo-class matches any element that the :focus
  pseudo-class matches or that has a descendant that the :focus
  pseudo-class matches.  (This includes descendants in shadow trees.)

So now with the :focus-within pseudo class - styling the outer div when the textarea gets clicked becomes trivial.

```<code>.box:focus-within {
    border: thin solid black;
}
</code>```

.box {
    width: 300px;
    height: 300px;
    border: 5px dashed red;
}

.box:focus-within {
    border: 5px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>The outer box border changes when the textarea gets focus.</p>
<div class="box">
    <textarea rows="10" cols="25"></textarea>
</div></code>```

Codepen demo

NB: Browser Support : Chrome (60+), Firefox and Safari

Title: Using :focus to style outer div?

Body:
When I begin writing text in the textarea, I want the outer div, with a class box, to have its border turned solid instead of dashed, but somehow the :focus doesn't apply in this case. If it works with :active, how come it doesn't work with :focus?

Any ideas why?

(Note. I want the DIV's border to turn solid, NOT the textareas)

div.box
{
    width: 300px;
    height: 300px;
    border: thin dashed black;
}

div.box:focus{
    border: thin solid black;
}

    <textarea rows="10" cols="25"></textarea>

Body:
Other posters have already explained why the :focus pseudo class is insufficient, but finally there is a CSS-based standard solution.

CSS Selectors Level 4 defines a new pseudo class:

:focus-within

From MDN:

The :focus-within CSS pseudo-class matches any element that the :focus
  pseudo-class matches or that has a descendant that the :focus
  pseudo-class matches.  (This includes descendants in shadow trees.)

So now with the :focus-within pseudo class - styling the outer div when the textarea gets clicked becomes trivial.

.box:focus-within {
    border: thin solid black;
}

.box {
    width: 300px;
    height: 300px;
    border: 5px dashed red;
}

.box:focus-within {
    border: 5px solid green;
}

<p>The outer box border changes when the textarea gets focus.</p>
<div class="box">
    <textarea rows="10" cols="25"></textarea>
</div>

Codepen demo

NB: Browser Support : Chrome (60+), Firefox and Safari


问:
When using range function to populate list why do I get list formatting error when printing with %d?
I'm learning python and I'm a bit puzzled by some behavior of lists when I create one using the range function. Hopefully someone can help me wrap my head around this? Here is a block of code I wrote:

```<code>elements = []
elements.append(range(1, 6))
for number in elements:
    print "Line %d" % number
</code>```

When I run this, I get the error for line 4:

TypeError: %d format: a number is required, not list

If I re-write the code as such:

```<code>elements = []
for i in range(1, 6):
    elements.append(i)
for number in elements:
    print "Line %d" % number
</code>```

it runs how I expected the first block would.

If I replace the %d with a %r, it prints the list as

Line [1, 2, 3, 4, 5]

instead of printing each number on its own line.

When I directly append the range to the elements list is it somehow making a list of a list instead of iterated values like it does when using the for?
With a little testing I got this:

```<code>>>> print range(1, 6)
[1, 2, 3, 4, 5]
>>> elements = []
>>> elements.append(range(1, 6))
>>> print elements
[[1, 2, 3, 4, 5]]
</code>```

Is this why it won't let me print the numbers using the %d formatter? How would I un-nest this list or access the contents of it? I'd be very grateful if someone could walk me through this. Thanks!

答:
Because range(1,6) returns a list.  So elements looks like:
[[1, 2, 3, 4, 5]] and the first iteration of your for loop number = elements[0] = [1, 2, 3, 4, 5], which is a list.

If you do this, you will get what you expect:

```<code>elements = []
elements = range(1, 6)
for number in elements:
    print "Line %d" % numberr
</code>```

Body:
I'm learning python and I'm a bit puzzled by some behavior of lists when I create one using the range function. Hopefully someone can help me wrap my head around this? Here is a block of code I wrote:

elements = []
elements.append(range(1, 6))
for number in elements:
    print "Line %d" % number

When I run this, I get the error for line 4:

TypeError: %d format: a number is required, not list

If I re-write the code as such:

elements = []
for i in range(1, 6):
    elements.append(i)
for number in elements:
    print "Line %d" % number

it runs how I expected the first block would.

If I replace the %d with a %r, it prints the list as

Line [1, 2, 3, 4, 5]

instead of printing each number on its own line.

When I directly append the range to the elements list is it somehow making a list of a list instead of iterated values like it does when using the for?
With a little testing I got this:

>>> print range(1, 6)
[1, 2, 3, 4, 5]
>>> elements = []
>>> elements.append(range(1, 6))
>>> print elements
[[1, 2, 3, 4, 5]]

Is this why it won't let me print the numbers using the %d formatter? How would I un-nest this list or access the contents of it? I'd be very grateful if someone could walk me through this. Thanks!

Body:
Because range(1,6) returns a list.  So elements looks like:
[[1, 2, 3, 4, 5]] and the first iteration of your for loop number = elements[0] = [1, 2, 3, 4, 5], which is a list.

If you do this, you will get what you expect:

elements = []
elements = range(1, 6)
for number in elements:
    print "Line %d" % numberr


问:
Easy Way To Add Huge Amount of predefined strings to Spinner widget?
is there a way to make inputting this text
Alfa Romeo
Aston Martin
Audi
Bentley
Benz
BMW
Bugatti
Cadillac
Chevrolet
Chrysler
Citroen
Corvette
DAF
Dacia
Daewoo
Daihatsu
Datsun
De Lorean
Dino
Dodge
Farboud
Ferrari
Fiat
Ford
Honda
Hummer
Hyundai
Jaguar
Jeep
KIA
Koenigsegg
Lada
Lamborghini
Lancia
Land Rover
Lexus
Ligier
... All the car companies;

into the strings.xml easily/fast...for example i dont want to write <item></item> around each car make individually.

or do i?....

Any help much appreciated

答:
Well you can keep a text file in the raw folder with comma(,) separated values and read them in onCreate of any activity:

```<code> private List<String> mFileItems;
</code>```

and then

```<code>int textFile = R.raw.keywords;
mFileItems = Arrays.asList(Utils.getStringFromRaw(this, textFile).replace("\"", "").split("\\s*,\\s*"));
</code>```

and

```<code>public class Utils {

public static String getStringFromRaw(Context mContext, int resource) throws IOException {
    Resources r = mContext.getResources();
    InputStream is = r.openRawResource(resource);
    String statesText = convertStreamToString(is);
    is.close();
    return statesText;
}

private static String convertStreamToString(InputStream is) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int i = is.read();
    while (i != -1) {
        byteArrayOutputStream.write(i);
        i = is.read();
    }
    return byteArrayOutputStream.toString();
}
}
</code>```

This will compile you a list of all the items in the list which are comma separated. Then you can set it in the spinner adapter.

Hope this helps.

Body:
Well you can keep a text file in the raw folder with comma(,) separated values and read them in onCreate of any activity:

 private List<String> mFileItems;

and then

int textFile = R.raw.keywords;
mFileItems = Arrays.asList(Utils.getStringFromRaw(this, textFile).replace("\"", "").split("\\s*,\\s*"));

and

public class Utils {

public static String getStringFromRaw(Context mContext, int resource) throws IOException {
    Resources r = mContext.getResources();
    InputStream is = r.openRawResource(resource);
    String statesText = convertStreamToString(is);
    is.close();
    return statesText;
}

private static String convertStreamToString(InputStream is) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int i = is.read();
    while (i != -1) {
        byteArrayOutputStream.write(i);
        i = is.read();
    }
    return byteArrayOutputStream.toString();
}
}

This will compile you a list of all the items in the list which are comma separated. Then you can set it in the spinner adapter.

Hope this helps.


问:
Asynctask: pass two or more values from doInBackground to onPostExecute
I have an Asynctask which retrieves two int vaules and i want to pass them to onPostExecute to show them on the view.

Here is my code:

```<code>    public class QueryServer extends AsyncTask <String, Void, Integer> {

    protected Integer doInBackground(String... serverAddress) {
        Log.d("QueryServer", ""+serverAddress[0]);
        MCQuery mcQuery = new MCQuery("" + serverAddress[0] ,25565);
        QueryResponse response = mcQuery.basicStat();

        int Onlineplayers = response.getOnlinePlayers(); //first vaule
        int Maxplayers = response.getMaxPlayers();  //second vaule

        Log.d("MCQuery", "" + Onlineplayers + " OnlinePlayers");
        return Onlineplayers;

    }

    protected void onPostExecute(Integer Onlineplayers){

        TextView onlinePlayersView = (TextView) findViewById(R.id.online_players);

        onlinePlayersView.setText(""+Onlineplayers+"/"+ Maxplayers); //i need to pass Maxplayers to use it here

    }
</code>```

Thank you in advance.

答: Generally speaking, replace Integer with ArrayList of Objects. with this array, you can pass any collection of any types. but obviously, the downside is you should cast the members and you should know all the types...

Body:
I have an Asynctask which retrieves two int vaules and i want to pass them to onPostExecute to show them on the view.

Here is my code:

    public class QueryServer extends AsyncTask <String, Void, Integer> {

    protected Integer doInBackground(String... serverAddress) {
        Log.d("QueryServer", ""+serverAddress[0]);
        MCQuery mcQuery = new MCQuery("" + serverAddress[0] ,25565);
        QueryResponse response = mcQuery.basicStat();

        int Onlineplayers = response.getOnlinePlayers(); //first vaule
        int Maxplayers = response.getMaxPlayers();  //second vaule

        Log.d("MCQuery", "" + Onlineplayers + " OnlinePlayers");
        return Onlineplayers;

    }

    protected void onPostExecute(Integer Onlineplayers){

        TextView onlinePlayersView = (TextView) findViewById(R.id.online_players);

        onlinePlayersView.setText(""+Onlineplayers+"/"+ Maxplayers); //i need to pass Maxplayers to use it here

    }

Thank you in advance.


问:
how to parse json into php
i have a json data retrieved from data base i.e```<code>$result=array();
$query="SELECT * FROM fish";
$result1 = mysql_query($query, $conn);
while ($table = mysql_fetch_array($result1, MYSQL_ASSOC)){
   $result[]=$table;
}
   echo json_encode($result);</code>```
and this give me the result ```[{"fish_id":"1","name":"first fish update","info":"this is my first fish update","image":"http:\/\/www.localhost\/cafe\/pics\/logout (1).gif"}]```

but from another page when i call this json data i.e```$input = file_get_contents("http://localhost/fish/fish-json.php");
$json=json_decode($input);
echo $json->fish_id;```

it give me the error

```Notice: Trying to get property of non-object in /var/www/fish/json-to-php.php on line 13 Call Stack: 0.0005 318764 1. {main}() /var/www/fish/json-to-php.php:0```

答:
Try </p>

```<code>$input = file_get_contents("http://localhost/fish/fish-json.php");
$json=json_decode($input);
echo $json['fish_id'];
</code>```

ContentLicense: CC BY-SA 2.5

Title: how to parse json into php

Body:
i have a json data retrieved from data base i.e
$result=array();
$query="SELECT * FROM fish";
$result1 = mysql_query($query, $conn);
while ($table = mysql_fetch_array($result1, MYSQL_ASSOC)){
   $result[]=$table;
}
   echo json_encode($result);

and this give me the result
[{"fish_id":"1","name":"first fish update","info":"this is my first fish update","image":"http:\/\/www.localhost\/cafe\/pics\/logout (1).gif"}]

but from another page when i call this json data i.e
$input = file_get_contents("http://localhost/fish/fish-json.php");
$json=json_decode($input);
echo $json->fish_id;

it give me the error

Notice: Trying to get property of non-object in /var/www/fish/json-to-php.php on line 13 Call Stack: 0.0005 318764 1. {main}() /var/www/fish/json-to-php.php:0

Body:
Try

$input = file_get_contents("http://localhost/fish/fish-json.php");
$json=json_decode($input);
echo $json['fish_id'];


问:
numpy mean of multidimensional array
I have a multidimensional numpy array that happens to be an array of images. Why does computing the image channel mean produce different results when using the axis argument to np.mean?

```<code>>>> X = np.array(np.random.random((9999, 128, 128, 4)) * 1e5, dtype='float32')
>>> X.shape
(9999, 128, 128, 4)
>>> mean_by_axis = np.mean(X, axis=(0, 1, 2))
array([ 13423.11523438,  13423.11523438,  13423.11523438,  13423.11523438], dtype=float32)
>>> mean = np.mean(X[:, :, :, 0])
50001.297
</code>```

I expect mean_by_axis[0] == mean. Why is this not the case? The same is true of the remaining axis-3 indices 1, 2 and 3. Am I misunderstanding how to use the axis argument in np.mean?

Using numpy version '1.12.1'

Is it possible that I am overflowing the float32 accumulator? For instance:

```<code>>>> X = np.random.random(size=(100, 128, 128, 4))
>>> np.mean(X, axis=(0, 1, 2))
array([ 0.49978557,  0.49985835,  0.50000321,  0.50015689])]
>>> np.mean(X[:, :, :, 0])
0.49978556940636332
</code>```

This looks about correct. If this is the case, why does the slice method not also overflow the accumulator and give the same result? Perhaps the slice methods uses a float64 accumulator and the axis method uses a float32 accumulator?

答:
I am unable to exactly reproduce your result since you do not provide your data, but with random data I can reproduce the issue:

```<code>>>> import numpy as np
>>> X = np.random.rand(9999, 128, 128, 4).astype('float32')
>>> X.shape
>>> np.mean(X, axis=(0, 1, 2))
array([ 0.10241024,  0.10241024,  0.10241024,  0.10241024], dtype=float32)
>>> np.mean(X[:, :, :, 0])
0.50000387
>>> np.mean(X[:, :, :, 0].flatten())
0.50000387
</code>```

This is likely a case of insufficient numerical precision. You are summing (9999*128*128 = 163823616) floating point values, and the relative precision of a float32 is ~10^-7 so you are skimming the boundaries of the precision.

I would recommend you try casting your array to float64, which has higher precision, before calling mean and see what happens.

```<code>>>> np.mean(X.astype('float64'), axis=(0, 1, 2))
array([ 0.50000323,  0.50004907,  0.50003198,  0.49999848])
>>> np.mean(X[:, :, :, 0].astype('float64'))
0.50000323305421812
>>> np.mean(X[:, :, :, 0].flatten().astype('float64'))
0.50000323305421812
</code>```

Title: numpy mean of multidimensional array

Body:
I have a multidimensional numpy array that happens to be an array of images. Why does computing the image channel mean produce different results when using the axis argument to np.mean?

>>> X = np.array(np.random.random((9999, 128, 128, 4)) * 1e5, dtype='float32')
>>> X.shape
(9999, 128, 128, 4)
>>> mean_by_axis = np.mean(X, axis=(0, 1, 2))
array([ 13423.11523438,  13423.11523438,  13423.11523438,  13423.11523438], dtype=float32)
>>> mean = np.mean(X[:, :, :, 0])
50001.297

I expect mean_by_axis[0] == mean. Why is this not the case? The same is true of the remaining axis-3 indices 1, 2 and 3. Am I misunderstanding how to use the axis argument in np.mean?

Using numpy version '1.12.1'

Is it possible that I am overflowing the float32 accumulator? For instance:

>>> X = np.random.random(size=(100, 128, 128, 4))
>>> np.mean(X, axis=(0, 1, 2))
array([ 0.49978557,  0.49985835,  0.50000321,  0.50015689])]
>>> np.mean(X[:, :, :, 0])
0.49978556940636332

This looks about correct. If this is the case, why does the slice method not also overflow the accumulator and give the same result? Perhaps the slice methods uses a float64 accumulator and the axis method uses a float32 accumulator?

Body:
I am unable to exactly reproduce your result since you do not provide your data, but with random data I can reproduce the issue:

>>> import numpy as np
>>> X = np.random.rand(9999, 128, 128, 4).astype('float32')
>>> X.shape
>>> np.mean(X, axis=(0, 1, 2))
array([ 0.10241024,  0.10241024,  0.10241024,  0.10241024], dtype=float32)
>>> np.mean(X[:, :, :, 0])
0.50000387
>>> np.mean(X[:, :, :, 0].flatten())
0.50000387

This is likely a case of insufficient numerical precision. You are summing (9999*128*128 = 163823616) floating point values, and the relative precision of a float32 is ~10^-7 so you are skimming the boundaries of the precision.

I would recommend you try casting your array to float64, which has higher precision, before calling mean and see what happens.

>>> np.mean(X.astype('float64'), axis=(0, 1, 2))
array([ 0.50000323,  0.50004907,  0.50003198,  0.49999848])
>>> np.mean(X[:, :, :, 0].astype('float64'))
0.50000323305421812
>>> np.mean(X[:, :, :, 0].flatten().astype('float64'))
0.50000323305421812


问:
flip order of passed arguments
Is there a idiomatic / built-in way to flip the argument order that is passed to a function in Clojure?

As I do here with the definition of a helper function:

```<code>(defn flip [f & xs]
   (apply f (reverse xs)))

(vector 1 2)       ; [1 2]
(flip vector 1 2)  ; [2 1]
</code>```

答:
I think it makes sense most times to create a flipped function that you use later, so the variation on your function would be this:</p>

```<code>(defn flip [f]
  (fn [& xs]
    (apply f (reverse xs))))
</code>```

Title: flip order of passed arguments

Body:
Is there a idiomatic / built-in way to flip the argument order that is passed to a function in Clojure?

As I do here with the definition of a helper function:

(defn flip [f & xs]
   (apply f (reverse xs)))

(vector 1 2)       ; [1 2]
(flip vector 1 2)  ; [2 1]

Body:
I think it makes sense most times to create a flipped function that you use later, so the variation on your function would be this:

(defn flip [f]
  (fn [& xs]
    (apply f (reverse xs))))


问:
Manage sessions with Telegram TL
I want to do following:

List all sessions

Get date and time that each session sign-ined

Terminate unwanted sessions

I read official telegram document and this unofficial, but I couldn't find anything. I looking for something like "getSessions".

答:
you can do these steps:

call the below api:
account.getAuthorizations#e320c158 = account.Authorizations;

use date_created and date_active of the Authorization object. (#7bf2e6f6)

call the below api by providing your desired session's hash:

account.resetAuthorization#df77f3bc hash:long = Bool;

you're done!

Title: Manage sessions with Telegram TL


问:
Angular 4 routing with infinite /#/ in url
Since some days I have this issue with Angular CLI and Routing.
If you point to the exact url, it seems work fine.
When you try to redirect with routerLink, it writes infinite /#page in the url.
If you are on index and try to go to about page it writes http://baseurl/index#/about#/index#/index#/index#/index#/index#/index#/index#/... and goes on until finish the RAM :D

This problem is only in devmode with "ng serve" (but works with hashlocationstrategy). In production mode seems work fine.

Here some codes.

in index.html

```<code><base href="/">
</code>```

app.module

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';

import { ConnectionService, ownerEnums, requestIdEnums } from './services/connection.service';
import { AuthService } from './services/auth.service';

import { AboutComponent } from './about/about.component';
import { ConnectComponent } from './connect/connect.component';
import { LayoutComponent } from './layout/layout.component';

import { HeaderComponent } from './layout/header/header.component';
import { BreadcrumbComponent } from './layout/breadcrumb/breadcrumb.component';
import { FooterComponent } from './layout/footer/footer.component';
import { IndexComponent } from './layout/index/index.component';

@NgModule({
  imports: [
    RouterModule.forRoot([
    { path: '', redirectTo: '/index', pathMatch: 'full' },
    { path: 'about', component: AboutComponent },
    { path: 'connect', component: ConnectComponent },
    { path: 'index', component: LayoutComponent }
    ]),
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  declarations: [
    AppComponent,
    AboutComponent,
    ConnectComponent,
    LayoutComponent,
    HeaderComponent,
    BreadcrumbComponent,
    FooterComponent,
    IndexComponent
  ],
  providers: [ ConnectionService, AuthService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
</code>```

anchors with routerLink in about page

```<code>    <div>
        <a class="navbar-brand" [routerLink]="['/about']"><i class="fa fa-info"></i></a>
        <a class="navbar-brand" [routerLink]="['/connect']"><i class="fa fa-plug"></i></a>
    </div>
</code>```

答:
Change your router module to    </p>

```<code>{ path: 'about', component: AboutComponent },
{ path: 'connect', component: ConnectComponent },
{ path: 'index', component: LayoutComponent },
{ path: '', redirectTo: 'index', pathMatch: 'full'},
{path:'**',redirectTo:'index',pathMatch:'full'}
</code>```

Body:
Since some days I have this issue with Angular CLI and Routing.
If you point to the exact url, it seems work fine.
When you try to redirect with routerLink, it writes infinite /#page in the url.
If you are on index and try to go to about page it writes http://baseurl/index#/about#/index#/index#/index#/index#/index#/index#/index#/... and goes on until finish the RAM :D

This problem is only in devmode with "ng serve" (but works with hashlocationstrategy). In production mode seems work fine.

Here some codes.

in index.html

<base href="/">

app.module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';

import { ConnectionService, ownerEnums, requestIdEnums } from './services/connection.service';
import { AuthService } from './services/auth.service';

import { AboutComponent } from './about/about.component';
import { ConnectComponent } from './connect/connect.component';
import { LayoutComponent } from './layout/layout.component';

import { HeaderComponent } from './layout/header/header.component';
import { BreadcrumbComponent } from './layout/breadcrumb/breadcrumb.component';
import { FooterComponent } from './layout/footer/footer.component';
import { IndexComponent } from './layout/index/index.component';

@NgModule({
  imports: [
    RouterModule.forRoot([
    { path: '', redirectTo: '/index', pathMatch: 'full' },
    { path: 'about', component: AboutComponent },
    { path: 'connect', component: ConnectComponent },
    { path: 'index', component: LayoutComponent }
    ]),
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  declarations: [
    AppComponent,
    AboutComponent,
    ConnectComponent,
    LayoutComponent,
    HeaderComponent,
    BreadcrumbComponent,
    FooterComponent,
    IndexComponent
  ],
  providers: [ ConnectionService, AuthService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

anchors with routerLink in about page

Body:
Change your router module to

{ path: 'about', component: AboutComponent },
{ path: 'connect', component: ConnectComponent },
{ path: 'index', component: LayoutComponent },
{ path: '', redirectTo: 'index', pathMatch: 'full'},
{path:'**',redirectTo:'index',pathMatch:'full'}


问:
IN() Function not returning results using percentage sign
It's short and simple.

I'm using this query:

```<code>SELECT * FROM TABLE_NAME WHERE COL_NAME IN('%VALUE1%', '%VALUE2%')
</code>```

However it doesn't seem to work, I've used LIKE for both values combined using OR and it returns results, so I'm certain that there's rows in the table with these values.. am I missing something here?

Does MYSQL IN() function accept percentage sign? What is the right way to do it?

Thanks in advance!

答:
You could try with RLIKE:

```<code>SELECT * FROM TABLE_NAME WHERE COL_NAME RLIKE 'VALUE[12]'
</code>```

Keep in mind these sorts of queries tend to perform very badly because they require a full table scan. If you're doing this a lot you may want to adjust your schema to better represent your usage patterns.

Body:
It's short and simple.

I'm using this query:

SELECT * FROM TABLE_NAME WHERE COL_NAME IN('%VALUE1%', '%VALUE2%')

However it doesn't seem to work, I've used LIKE for both values combined using OR and it returns results, so I'm certain that there's rows in the table with these values.. am I missing something here?

Does MYSQL IN() function accept percentage sign? What is the right way to do it?

Thanks in advance!

Body:
You could try with RLIKE:

SELECT * FROM TABLE_NAME WHERE COL_NAME RLIKE 'VALUE[12]'

Keep in mind these sorts of queries tend to perform very badly because they require a full table scan. If you're doing this a lot you may want to adjust your schema to better represent your usage patterns.


问:
How can I programatically close an iPad app?
When I press the Home button it doesn't fully close, but resides in memory. I would like to restart an app from scratch and not keep its latest state.

How can I programatically close when the home button is pressed?

答: To get your app to close when the home button is pressed you need to add an entry for UIApplicationExitsOnSuspend to your Info.plist. This causes the app to revert to pre-4.0 behaviour which is as you describe.


问:
Android Studio - devices not available when I run a project
When I try to run a project, android studio cannot find either real or virtual devices, although they are available.

If I open AVD manager, I get two virtual devices in the AVD manager window. If I run either of these from AVD manager, it creates an emulator correctly. However, when I run the app ('run' then 'run app' from the toolbar), the 'Select Deployment Target' window opens, but then says 'Nothing to show' and no devices appear.

If I connect a real device, the Select Deployment target window still says 'Nothing to show'. Also, the 'allow USB debugging' window does not appear on the device, even though USB debugging is enabled.

It was all working ok two weeks ago. Having been away, I came back yesterday to find this problem. After that, last night I had a Windows 10 update and I have updated everything connected with Android studio, and I have also created a new basic 'Hello World' app, but still no change.

Can anyone help with a solution? Has anyone had the same problem? Is there some option or setting that might need changing?

答:
I only posted this question after many hours of trying suggestions from this site and elsewhere. Just as I was about to give up, I found this:

Android Studio: Unable to obtain result of 'adb version'

Answer 2 from Prashant

and it worked! The problem was incorrect memory allocation slowing up my whole machine so that the time-out in Android Studio was exceeded. Reducing the virtual memory size solved the specific problem and also speeded up my whole machine.


问:
SQL won't connect after deploying
I recently deployed my website on IIS (LocalDB). But whenever I try to run the website, the SQL fails to connect. I've been through hundreds of posts/articles now but I am unable to resolve it.

Error

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 50 - Local Database Runtime error occurred.
  Cannot create an automatic instance. See the Windows Application event
  log for error details. )

Windows Application event log

Windows API call SHGetKnownFolderPath returned error code: 5. Windows
  system error message is: Access is denied. Reported at line: 422.

Second log -

Cannot get a local application data path. Most probably a user profile
  is not loaded. If LocalDB is executed under IIS, make sure that
  profile loading is enabled for the current user.

My Connection Strings (tried both)-

```<code><appSettings>
    <add key="ConnectionString" value="Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=test;Integrated Security=True" />
    <!--<add key="ConnectionString" value="data source=(LocalDB)\MSSQLLocalDB;UID=SOME_USERNAME;PWD=SOME_PASSWORD;initial catalog=test;connection timeout=30"/>-->
  </appSettings>
</code>```

I tried editing applicationHost.config.

Load User Profile was already True for me

My ApplicationHost.config file

```<code> <applicationPools>

            <add name="Classic .NET AppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
            <add name=".NET v2.0 Classic" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
            <add name=".NET v2.0" managedRuntimeVersion="v2.0" />
            <add name=".NET v4.5 Classic" managedRuntimeVersion="v4.0" managedPipelineMode="Classic" />
            <add name=".NET v4.5" managedRuntimeVersion="v4.0" />
            <add name="ASP.NET v4.0" managedRuntimeVersion="v4.0">

            <add name="DefaultAppPool" autoStart="true" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated">
           <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
            </add>
        </applicationPools>
</code>```

My IIS manager -

DefaultApplicationPool -

My web app configuration -

App Pool permission

EDIT -

Added IIS Apppool using

```<code>icacls c:\inetpub\wwwroot /grant "IIS APPPOOL\DefaultAppPool":(OI)(CI)(RX)
</code>```

Still not able to connect.

Any help is appreciated.

I am on Windows 10 using Visual Studio 2015 with SQL Server 2016.

答:
I had exactly same issue and finally I solved. Hope it works for you too.
My problem was I created a web application with Visual Studio 2017 and which is by default hosted on IIS Express. And I changed to IIS then I got this error.

In event Log, I saw these 2 errors:

Windows API call SHGetKnownFolderPath returned error code: 5. Windows system error message is: Access is denied.

Cannot get a local application data path. Most probably a user profile is not loaded. If LocalDB is executed under IIS, make sure that profile loading is enabled for the current user.

For me the solution is:

First I have Attached the database with SQL Server Management Studio with login to (LocalDB)\MSSQLLocalDB which I found in my web.config connection string.

```<code><connectionStrings>
 <add name="EFWeatherDBEntities"
     connectionString="metadata=res://*/Models.EFModel.csdl|res://*/Models.EFModel.ssdl|res://*/Models.EFModel.msl;provider=System.Data.SqlClient;
     provider connection string="
     data source=(LocalDB)\MSSQLLocalDB;
     attachdbfilename=|DataDirectory|\WeatherDB.mdf;
     integrated security=True;connect timeout=30;
     MultipleActiveResultSets=True;App=EntityFramework""
     providerName="System.Data.EntityClient" />
</connectionStrings>
</code>```

Then I realized in IIS when I try to click Test Settings in Basic Settings, I was getting Invalid Application Path error message.
So I changed the credential as a different user(my user which is admin but I believe without admin permission it should work as well).

So basically:

click the website in IIS

click Basic Settings on right panel

click Connect As

and enter a user in Specific User section

then check if you still get path error with clicking Test Settings.

Then in Application Pool set Identity to LocalSystem

Title: SQL won't connect after deploying

Body:
I recently deployed my website on IIS (LocalDB). But whenever I try to run the website, the SQL fails to connect. I've been through hundreds of posts/articles now but I am unable to resolve it.

Error

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 50 - Local Database Runtime error occurred.
  Cannot create an automatic instance. See the Windows Application event
  log for error details. )

Windows Application event log

Windows API call SHGetKnownFolderPath returned error code: 5. Windows
  system error message is: Access is denied. Reported at line: 422.

Second log -

Cannot get a local application data path. Most probably a user profile
  is not loaded. If LocalDB is executed under IIS, make sure that
  profile loading is enabled for the current user.

My Connection Strings (tried both)-

<appSettings>
    <add key="ConnectionString" value="Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=test;Integrated Security=True" />

  </appSettings>

I tried editing applicationHost.config.

Load User Profile was already True for me

My ApplicationHost.config file

 <applicationPools>

            <add name="Classic .NET AppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
            <add name=".NET v2.0 Classic" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
            <add name=".NET v2.0" managedRuntimeVersion="v2.0" />
            <add name=".NET v4.5 Classic" managedRuntimeVersion="v4.0" managedPipelineMode="Classic" />
            <add name=".NET v4.5" managedRuntimeVersion="v4.0" />
            <add name="ASP.NET v4.0" managedRuntimeVersion="v4.0">

            <add name="DefaultAppPool" autoStart="true" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated">
           <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
            </add>
        </applicationPools>

My IIS manager -

DefaultApplicationPool -

My web app configuration -

App Pool permission

EDIT -

Added IIS Apppool using

icacls c:\inetpub\wwwroot /grant "IIS APPPOOL\DefaultAppPool":(OI)(CI)(RX)

Still not able to connect.

Any help is appreciated.

I am on Windows 10 using Visual Studio 2015 with SQL Server 2016.

Body:
I had exactly same issue and finally I solved. Hope it works for you too.
My problem was I created a web application with Visual Studio 2017 and which is by default hosted on IIS Express. And I changed to IIS then I got this error.

In event Log, I saw these 2 errors:

Windows API call SHGetKnownFolderPath returned error code: 5. Windows system error message is: Access is denied.

Cannot get a local application data path. Most probably a user profile is not loaded. If LocalDB is executed under IIS, make sure that profile loading is enabled for the current user.

For me the solution is:

First I have Attached the database with SQL Server Management Studio with login to (LocalDB)\MSSQLLocalDB which I found in my web.config connection string.

<connectionStrings>
 <add name="EFWeatherDBEntities"
     connectionString="metadata=res://*/Models.EFModel.csdl|res://*/Models.EFModel.ssdl|res://*/Models.EFModel.msl;provider=System.Data.SqlClient;
     provider connection string=&quot;
     data source=(LocalDB)\MSSQLLocalDB;
     attachdbfilename=|DataDirectory|\WeatherDB.mdf;
     integrated security=True;connect timeout=30;
     MultipleActiveResultSets=True;App=EntityFramework&quot;"
     providerName="System.Data.EntityClient" />
</connectionStrings>

Then I realized in IIS when I try to click Test Settings in Basic Settings, I was getting Invalid Application Path error message.
So I changed the credential as a different user(my user which is admin but I believe without admin permission it should work as well).

So basically:

click the website in IIS

click Basic Settings on right panel

click Connect As

and enter a user in Specific User section

then check if you still get path error with clicking Test Settings.

Then in Application Pool set Identity to LocalSystem


问:
When added an embedded framework in an Xcode project, how do you differentiate between Debug and Release?
When I add a framework to my Xcode project, to be embedded in my app bundle, how do I make two different options for whether it's Debug or Release (I have two versions of the framework, one compiled for release and one for debug).

This is what I'm referring to:

As you see, with that configuration, it'll just copy the one on CEF/Debug regardless of whether it's in being compiled in Release or Debug mode.

Ideally I want something like you have for setting:

答:
You don't need to. Embedded frameworks will build according to the build of the consumer app.
You can test it by adding a build schema on the app (like Debug2) and then compiling. You will receive an error from the embedded because it tried to compile it with the Debug2 schema, which is not available in the embedded framework. Now duplicate some schema and call it Debug2. It will build.</p>


问:
In Entity Framework code first, to map a navigation property do I also need to map the foreign key column
Say I have a Trade object which has a foreign key to a Counterparty object. I want to have a navigation property of type Counterparty in my Trade object- do I also need to have the foreign key column (CounterpartyId) in my Trade object? My experimentation seems to indicate that I do. I tried adding [ForeignKey("CounterpartyId"] on the navigation but it doesn't work without also having the CounterpartyId column. </p>

答:
No, the explicit FK property is not mandatory. Just if you skip it, by convention EF assumes "Counterparty_Id" shadow property and column name in the corresponding database table.

In this case there is no way to configure the shadow property/column name with data annotations, so if you want to do that you'll need fluent configuration with MapKey (as opposed to HasForeignKey when you do have an explicit property):

```<code>modelBuilder.Entity<Trade>()
    .HasRequired(e => e.Counterparty) // or HasOptional if you want nullable column
    .WithMany() // or WithMany(e => e.Trades) if you have inverse collection navigation property
    .Map(m => m.MapKey("CounterpartyId"));
</code>```

Note that the fluent configuration must reflect exactly your model navigation / FK properties. For instance, you later on you decide to add ConterpartyId property to your Trade object, you should replace the Map with

```<code>.HasForegnKey(e => e.CounterpartyId)
</code>```

Body:
No, the explicit FK property is not mandatory. Just if you skip it, by convention EF assumes "Counterparty_Id" shadow property and column name in the corresponding database table.

In this case there is no way to configure the shadow property/column name with data annotations, so if you want to do that you'll need fluent configuration with MapKey (as opposed to HasForeignKey when you do have an explicit property):

modelBuilder.Entity<Trade>()
    .HasRequired(e => e.Counterparty) // or HasOptional if you want nullable column
    .WithMany() // or WithMany(e => e.Trades) if you have inverse collection navigation property
    .Map(m => m.MapKey("CounterpartyId"));

Note that the fluent configuration must reflect exactly your model navigation / FK properties. For instance, you later on you decide to add ConterpartyId property to your Trade object, you should replace the Map with

.HasForegnKey(e => e.CounterpartyId)


问:
What is the rationale behind the behavior of constructor pointer in JavaScript?
Considering the simplistic scenario:

```
function Base() {}
function Child() {}
Child.prototype = new Base;
```

I wonder why would an instance of Child have constructor property set to Base and not to Child?

答:
It's all tied to how inheritance works in JavaScript. Check this link for a detailed explanation (basically, constructor is just another property of the prototype).

Edit: Also, if you want 'real' prototypical inheritance, you have to use some sort of clone function, eg

```<code>function clone(obj) {
    if(typeof obj !== 'undefined') {
        arguments.callee.prototype = Object(obj);
        return new arguments.callee;
    }
}
</code>```

Then, you can do things like this

```<code>function Base() {}
function Sub() {}
Sub.prototype = clone(Base.prototype);

var obj = new Sub;
</code>```

and you'll still get true two times on

```<code>document.writeln(obj instanceof Sub);
document.writeln(obj instanceof Base);
</code>```

The difference to your solution is that Base() won't be called and Sub.prototype will only inherit the properties of Base.prototype - and not the ones set in the constructor.

OwnerDisplayName: Sergey Ilinsky

Body:
Considering the simplistic scenario:

function Base() {}
function Child() {}
Child.prototype = new Base;

I wonder why would an instance of Child have constructor property set to Base and not to Child?

LastEditorDisplayName: PhiLho

Body:
It's all tied to how inheritance works in JavaScript. Check this link for a detailed explanation (basically, constructor is just another property of the prototype).

Edit: Also, if you want 'real' prototypical inheritance, you have to use some sort of clone function, eg

function clone(obj) {
    if(typeof obj !== 'undefined') {
        arguments.callee.prototype = Object(obj);
        return new arguments.callee;
    }
}

Then, you can do things like this

function Base() {}
function Sub() {}
Sub.prototype = clone(Base.prototype);

var obj = new Sub;

and you'll still get true two times on

document.writeln(obj instanceof Sub);
document.writeln(obj instanceof Base);

The difference to your solution is that Base() won't be called and Sub.prototype will only inherit the properties of Base.prototype - and not the ones set in the constructor.

OwnerDisplayName: Christoph

LastEditorDisplayName: Christoph


问:
Visual Studio 2010: How to replace all <%: Resources.A.B %>
Need help with Visual Studio 2010.

My problem:
I have millions

```<code><%: Resources.A.B %>
</code>```

all over in my aspx sites and I just want to change them all to

```<code><%: Html.FormatResourceString(Resources.A.B) %>
</code>```

Yes thats all ;-)

Please note:

I want to do it in Visual Studio 2010 and NOT at runtime!

Replacing

```<code><%: Resources
</code>```

with

```<code><%: Html.FormatResourceString(Resources
</code>```

is not the problem, the problem is the ")" and the end.

How can this be made?
How must the regular expression look like?

答:
Find: \<%\: Resources\.{.+} %\>

Replace with: <%: Html.FormatResourceString(Resources.\1) %>

You may also take a look at this article. There are some nice examples at the end.

Body:
Need help with Visual Studio 2010.

My problem:
I have millions

<%: Resources.A.B %>

all over in my aspx sites and I just want to change them all to

<%: Html.FormatResourceString(Resources.A.B) %>

Yes thats all ;-)

Please note:

I want to do it in Visual Studio 2010 and NOT at runtime!

Replacing

<%: Resources

with

<%: Html.FormatResourceString(Resources

is not the problem, the problem is the ")" and the end.

How can this be made?
How must the regular expression look like?


问:
What numbers that I can put in numpy.random.seed()?
I have noticed that you can put various numbers inside of numpy.random.seed(), for example numpy.random.seed(1), numpy.random.seed(101). What do the different numbers mean? How do you choose the numbers?

答:
What is normally called a random number sequence in reality is a "pseudo-random" number sequence because the values are computed using a deterministic algorithm and probability plays no real role.

The "seed" is a starting point for the sequence and the guarantee is that if you start from the same seed you will get the same sequence of numbers. This is very useful for example for debugging (when you are looking for an error in a program you need to be able to reproduce the problem and study it, a non-deterministic program would be much harder to debug because every run would be different).


问:
When using range function to populate list why do I get list formatting error when printing with %d?
I'm learning python and I'm a bit puzzled by some behavior of lists when I create one using the range function. Hopefully someone can help me wrap my head around this? Here is a block of code I wrote:

```<code>elements = []
elements.append(range(1, 6))
for number in elements:
    print "Line %d" % number
</code>```

When I run this, I get the error for line 4:

TypeError: %d format: a number is required, not list

If I re-write the code as such:

```<code>elements = []
for i in range(1, 6):
    elements.append(i)
for number in elements:
    print "Line %d" % number
</code>```

it runs how I expected the first block would.

If I replace the %d with a %r, it prints the list as

Line [1, 2, 3, 4, 5]

instead of printing each number on its own line.

When I directly append the range to the elements list is it somehow making a list of a list instead of iterated values like it does when using the for?
With a little testing I got this:

```<code>>>> print range(1, 6)
[1, 2, 3, 4, 5]
>>> elements = []
>>> elements.append(range(1, 6))
>>> print elements
[[1, 2, 3, 4, 5]]
</code>```

Is this why it won't let me print the numbers using the %d formatter? How would I un-nest this list or access the contents of it? I'd be very grateful if someone could walk me through this. Thanks!

答:
In Python 2.7, range returns a list. And append method adds an item to the end of the list.

So, when you write elements.append(range(1, 6)), elements is now a list with a single element (that is a list).

You may want to use

```<code>elements.extend(range(1,6)) # 'extend' append all elements of the given list
</code>```

Or directly

```<code>elements = range(1,6)
</code>```

Body:
I'm learning python and I'm a bit puzzled by some behavior of lists when I create one using the range function. Hopefully someone can help me wrap my head around this? Here is a block of code I wrote:

elements = []
elements.append(range(1, 6))
for number in elements:
    print "Line %d" % number

When I run this, I get the error for line 4:

TypeError: %d format: a number is required, not list

If I re-write the code as such:

elements = []
for i in range(1, 6):
    elements.append(i)
for number in elements:
    print "Line %d" % number

it runs how I expected the first block would.

If I replace the %d with a %r, it prints the list as

Line [1, 2, 3, 4, 5]

instead of printing each number on its own line.

When I directly append the range to the elements list is it somehow making a list of a list instead of iterated values like it does when using the for?
With a little testing I got this:

>>> print range(1, 6)
[1, 2, 3, 4, 5]
>>> elements = []
>>> elements.append(range(1, 6))
>>> print elements
[[1, 2, 3, 4, 5]]

Is this why it won't let me print the numbers using the %d formatter? How would I un-nest this list or access the contents of it? I'd be very grateful if someone could walk me through this. Thanks!

Body:
In Python 2.7, range returns a list. And append method adds an item to the end of the list.

So, when you write elements.append(range(1, 6)), elements is now a list with a single element (that is a list).

You may want to use

elements.extend(range(1,6)) # 'extend' append all elements of the given list

Or directly

elements = range(1,6)


问:
Is it possible to render table at end tag
Let's say I have a large table (a couple of thousand rows) and I want the whole table to render as fast as possible.

Is it possible to somehow delay rendering of a table until the whole table is downloaded ? Otherwise the width calculations after each row seem to take up too much time.

When I use IE without a declared doctype the browser seem to wait until it gets the table’s closing tag. However when I do declare a doctype the table start rendering at once and therefore have to calculate the table width after each new row.
I don't want to use table-layout:fixed since I don’t want the content to line break where it shouldn’t.

It only seem to be a significant time difference in IE(8)?

(Pagination is not an option)

Thanks!

答:
You could hide the table until it's loaded:</p>

```<code><table id="PopTable" style="display:none">
  ...
</table>
<script type="text/javascript">
document.getElementById('PopTable').style.display = '';
</script>
</code>```

Body:
You could hide the table until it's loaded:

<table id="PopTable" style="display:none">
  ...
</table>
<script type="text/javascript">
document.getElementById('PopTable').style.display = '';
</script>