问:
Angular 2 router error
I created Angular 2 router module but it doen't work at the moment and I get an error when I want to open link /city 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet
Error: Cannot activate an already activated outlet'

But I can open this link manually

Here is the code of:
Router module

```<code>import { NgModule }from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import {WeatherListComponent} from "../weather-list/weather-list.component";
import {AddedCityComponent} from "../added-city/added-city.component";
import {AppComponent} from "../app.component";

const routes: Routes = [
    { path: '', redirectTo: '/weather-list', pathMatch: 'full'},
    { path: 'city', component: AddedCityComponent },
    { path: 'weather-list',  component: WeatherListComponent }

];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}
</code>```

2) Appmodule

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MdButtonModule, MdCheckboxModule, MdCardModule, MdInputModule} from '@angular/material';

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

import { AppComponent } from './app.component';
import { WeatherListComponent } from './weather-list/weather-list.component';

import { WeatherService } from './service/weather.service';
import { WeatherSearchComponent } from './weather-search/weather-search.component';
import { CloudsComponent } from './clouds/clouds.component';
import { SunComponent } from './sun/sun.component';
import { RainComponent } from './rain/rain.component';
import { AddedCityComponent } from './added-city/added-city.component';

import { AppRoutingModule } from './service/app.routing';

@NgModule({
  declarations: [
    AppComponent,
    WeatherListComponent,
    AddedCityComponent,
    WeatherSearchComponent,
    CloudsComponent,
    SunComponent,
    RainComponent

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule,
    MdButtonModule,
    MdCardModule,
    MdInputModule,
    NgbModule.forRoot(),
    AppRoutingModule

  ],
  providers: [
    WeatherService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

3) AppComponentHTML

```<code><div class="page-wrapper" [ngClass]="{
                                    'sun-background': weatherDesc == 'Clear',
                                    'rain-background': weatherDesc == 'Rain',
                                    'clouds-background': weatherDesc == 'Clouds'
                                      }">
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-12">
        <header>
          <div class="header-wrapper">
            <h3 class=" text-left">Weather App</h3>
            <a routerLink="/city" routerLinkActive="active">cities</a>
            <a routerLink="/weather-list" routerLinkActive="active">weather</a>
            <app-weather-search></app-weather-search>
          </div>
        </header>
      </div>
    </div>
  </div>
  <!--<app-weather-list (notify)="background($event)"></app-weather-list>-->
  <!--<app-weather-list></app-weather-list>-->
  <router-outlet></router-outlet>

</div>
</code>```

答:
try

```<code>   const routes: Routes = [

    { path: 'city', component: AddedCityComponent },
    { path: 'weather-list',  component: WeatherListComponent },
    { path: '', redirectTo: '/weather-list', pathMatch: 'full'}

  ];
</code>```

and move appRoutingModule to the start of the list in the imports declaration

Title: Angular 2 router error

Body:
I created Angular 2 router module but it doen't work at the moment and I get an error when I want to open link /city 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet
Error: Cannot activate an already activated outlet'

But I can open this link manually

Here is the code of:
Router module

import { NgModule }from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import {WeatherListComponent} from "../weather-list/weather-list.component";
import {AddedCityComponent} from "../added-city/added-city.component";
import {AppComponent} from "../app.component";

const routes: Routes = [
    { path: '', redirectTo: '/weather-list', pathMatch: 'full'},
    { path: 'city', component: AddedCityComponent },
    { path: 'weather-list',  component: WeatherListComponent }

];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}

2) Appmodule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MdButtonModule, MdCheckboxModule, MdCardModule, MdInputModule} from '@angular/material';

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

import { AppComponent } from './app.component';
import { WeatherListComponent } from './weather-list/weather-list.component';

import { WeatherService } from './service/weather.service';
import { WeatherSearchComponent } from './weather-search/weather-search.component';
import { CloudsComponent } from './clouds/clouds.component';
import { SunComponent } from './sun/sun.component';
import { RainComponent } from './rain/rain.component';
import { AddedCityComponent } from './added-city/added-city.component';

import { AppRoutingModule } from './service/app.routing';

@NgModule({
  declarations: [
    AppComponent,
    WeatherListComponent,
    AddedCityComponent,
    WeatherSearchComponent,
    CloudsComponent,
    SunComponent,
    RainComponent

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule,
    MdButtonModule,
    MdCardModule,
    MdInputModule,
    NgbModule.forRoot(),
    AppRoutingModule

  ],
  providers: [
    WeatherService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

3) AppComponentHTML

Weather App

            cities
            weather
            <app-weather-search></app-weather-search>

  <router-outlet></router-outlet>

Body:
try

   const routes: Routes = [

    { path: 'city', component: AddedCityComponent },
    { path: 'weather-list',  component: WeatherListComponent },
    { path: '', redirectTo: '/weather-list', pathMatch: 'full'}

  ];

and move appRoutingModule to the start of the list in the imports declaration


来源: stackexchange

问:
Django runserver on all ports?
Why can't I run python manage.py runserver on all ports?

I understand this is probably a newbie question, but what prevents me from achieving this?

I would like to access my app without having to include the port, like a regular website

答:
Just run it on port 80 and you won't have to specify the port.

You can't blast it on all other ports because many, many other services already use those other ports. Network services need to have ports specified.

ContentLicense: CC BY-SA 3.0

Title: Django runserver on all ports?


问:
Storing table at different memory address - C for AVR XMEGA256A3BU
I'm trying to figure out how to store the fahrenheit table to memory address 0x20 instead of the default 0x0000. I have tried several routes, but so far, nothing that works. The code is in C.</p>

```<code>#include <avr/io.h>
#include <avr/eeprom.h>

int main(void)
{
    uint8_t fahrenheit[20] =
         {32,34,36,37,39,41,43,45,46,48,50,52,54,55,57,59,61,63,64,66};

    for(int i = 0; i < 20; i++)
   {
       eeprom_write_byte((uint8_t *)i, fahrenheit[i]);
   }
}
</code>```

答: eeprom_write_byte((uint8_t *)i, fahrenheit[i]); writes a value to address i. Therefore, to write value starting from 0x0020 as you wish, just do this eeprom_write_byte((uint8_t *)i+20, fahrenheit[i]);

Body:
I'm trying to figure out how to store the fahrenheit table to memory address 0x20 instead of the default 0x0000. I have tried several routes, but so far, nothing that works. The code is in C.

#include <avr/io.h>
#include <avr/eeprom.h>

int main(void)
{
    uint8_t fahrenheit[20] =
         {32,34,36,37,39,41,43,45,46,48,50,52,54,55,57,59,61,63,64,66};

    for(int i = 0; i < 20; i++)
   {
       eeprom_write_byte((uint8_t *)i, fahrenheit[i]);
   }
}


问:
.NET - Can you change a process's parameters after process start?
The ultimate goal is to change PowerShell.exe's process parameter to set EnableRaisingEvents to $true so that I can trap the exit event if/when my script is terminated.

All of the examples I can find are of setting the properties on a new process object first and then programmticaly spawning it with the start method but I'd like to know if I can just modify the existing process to accomplish this?   ... like an inline update?

If it's possible in .NET, easy but if I need to drop down to WinAPI with p/invoke, I can figure that out too if anyone knows the library/function.  Thx.

答:
EnableRaisingEvents is a property of the System.Diagnostics.Process instance, not the actual underlying operating system process, you can easily modify it regardless of whether the underlying process is already running:

```<code>$process = Start-Process notepad -PassThru

# Change EnableRaisingEvents flag after process start
$process.EnableRaisingEvents = $true

# Now the Process instance can raise the Exited event
Register-ObjectEvent -InputObject $process -EventName Exited -SourceIdentifier notepadExited -Action {
    Write-Host "Notepad exited" -ForegroundColor Red
}
$process.Kill()
</code>```

If you need to monitor an already running process that you didn't start yourself, you can use the Win32_ProcessStopTrace WMI event class:

```<code># Using Start-Process for this example, but could be any existing process
$process = Start-Process notepad -PassThru

# Use the query to filter events raised based on process ID
$eventQuery = "SELECT ProcessName,ExitStatus FROM Win32_ProcessStopTrace WHERE ProcessId = $($process.Id)"

# Register WMI Event listener
Register-WmiEvent -Query $eventQuery -Action {
    $traceEvent = $Event.SourceEventArgs.NewEvent
    Write-Host "$($traceEvent.ProcessName) exited with status code: $($traceEvent.ExitStatus)"
} -SourceIdentifier notepadExited
$process.Kill()
</code>```

Body:
EnableRaisingEvents is a property of the System.Diagnostics.Process instance, not the actual underlying operating system process, you can easily modify it regardless of whether the underlying process is already running:

$process = Start-Process notepad -PassThru

# Change EnableRaisingEvents flag after process start
$process.EnableRaisingEvents = $true

# Now the Process instance can raise the Exited event
Register-ObjectEvent -InputObject $process -EventName Exited -SourceIdentifier notepadExited -Action {
    Write-Host "Notepad exited" -ForegroundColor Red
}
$process.Kill()

If you need to monitor an already running process that you didn't start yourself, you can use the Win32_ProcessStopTrace WMI event class:

# Using Start-Process for this example, but could be any existing process
$process = Start-Process notepad -PassThru

# Use the query to filter events raised based on process ID
$eventQuery = "SELECT ProcessName,ExitStatus FROM Win32_ProcessStopTrace WHERE ProcessId = $($process.Id)"

# Register WMI Event listener
Register-WmiEvent -Query $eventQuery -Action {
    $traceEvent = $Event.SourceEventArgs.NewEvent
    Write-Host "$($traceEvent.ProcessName) exited with status code: $($traceEvent.ExitStatus)"
} -SourceIdentifier notepadExited
$process.Kill()


问:
Seemingly endless loop terminates, unless System.out.println is used
I had a simple bit of code that was supposed to be an endless loop since x will always be growing and will always remain larger than j.

```<code>int x = 5;
int y = 9;
for (int j = 0; j < x; j++) {
   x = x + y;
}
System.out.println(y);
</code>```

but as is, it prints y and does not loop endlessly. I cannot figure out why. However, when I adjust the code in the following manner:

```<code>int x = 5;
int y = 9;
for (int j = 0; j < x; j++) {
    x = x + y;
    System.out.println(y);
}
System.out.println(y);
</code>```

It becomes an endless loop and I have no idea why. Does java recognize its an endless loop and skip it in the first situation but has to execute a method call in the second so it behaves as expected?
Confused :)

答:
Interesting problem Actually in both cases loop isn't endless

But the main difference between them is when it will terminate and how much time x will take to exceed max int value which is 2,147,483,647 after that it will reach overflow state and the loop will terminate.

Best way to understand this problem is to test a simple example and preserve its results.

Example:

```<code>for(int i = 10; i > 0; i++) {}
System.out.println("finished!");
</code>```

Output:

```<code>finished!
BUILD SUCCESSFUL (total time: 0 seconds)
</code>```

After testing this infinite loop it will take less than 1 second to terminate.

```<code>for(int i = 10; i > 0; i++) {
    System.out.println("infinite: " + i);
}
System.out.println("finished!");
</code>```

Output:

```<code>infinite: 314572809
infinite: 314572810
infinite: 314572811
.
.
.
infinite: 2147483644
infinite: 2147483645
infinite: 2147483646
infinite: 2147483647
finished!
BUILD SUCCESSFUL (total time: 486 minutes 25 seconds)
</code>```

On this test case you will notice a huge difference in the time taken to terminate and finish running the program.

If you aren't patience you will think this loop is endless and won't  terminate but in fact it will take hours to terminate and reach the overflow state at i value.

Finally we concluded after we put print statement inside for loop that it will take much more time than loop in the first case without print statement.

That time taken to run the program depends on your computer specifications in particular processing power(processor capacity), operating system and your IDE which is compiling the program.

I test this case on:

Lenovo 2.7 GHz Intel Core i5

OS : Windows 8.1 64x

IDE : NetBeans 8.2

It takes about 8 hours (486 minutes) to finish the program.

Also you can notice that the step increment in the for loop i = i + 1 is very slow factor to reach the max int value.

We can change this factor and make step increment more faster in order to test for loop in less time.

if we put i = i * 10 and test it:

```<code>for(int i = 10; i > 0; i*=10) {
           System.out.println("infinite: " + i);
}
     System.out.println("finished!");
</code>```

Output:

```<code>infinite: 100000
infinite: 1000000
infinite: 10000000
infinite: 100000000
infinite: 1000000000
infinite: 1410065408
infinite: 1215752192
finished!
BUILD SUCCESSFUL (total time: 0 seconds)
</code>```

As you see it's very fast comparing to the previous loop

it takes less than 1 second to terminate and finish running the program.

After this test example I think it should clarify the problem and proves validity of Zbynek Vyskovsky - kvr000's answer, also it will be answer to this question.

Body:
I had a simple bit of code that was supposed to be an endless loop since x will always be growing and will always remain larger than j.

int x = 5;
int y = 9;
for (int j = 0; j < x; j++) {
   x = x + y;
}
System.out.println(y);

but as is, it prints y and does not loop endlessly. I cannot figure out why. However, when I adjust the code in the following manner:

int x = 5;
int y = 9;
for (int j = 0; j < x; j++) {
    x = x + y;
    System.out.println(y);
}
System.out.println(y);

It becomes an endless loop and I have no idea why. Does java recognize its an endless loop and skip it in the first situation but has to execute a method call in the second so it behaves as expected?
Confused :)

Body:
Interesting problem Actually in both cases loop isn't endless

But the main difference between them is when it will terminate and how much time x will take to exceed max int value which is 2,147,483,647 after that it will reach overflow state and the loop will terminate.

Best way to understand this problem is to test a simple example and preserve its results.

Example:

for(int i = 10; i > 0; i++) {}
System.out.println("finished!");

Output:

finished!
BUILD SUCCESSFUL (total time: 0 seconds)

After testing this infinite loop it will take less than 1 second to terminate.

for(int i = 10; i > 0; i++) {
    System.out.println("infinite: " + i);
}
System.out.println("finished!");

Output:

infinite: 314572809
infinite: 314572810
infinite: 314572811
.
.
.
infinite: 2147483644
infinite: 2147483645
infinite: 2147483646
infinite: 2147483647
finished!
BUILD SUCCESSFUL (total time: 486 minutes 25 seconds)

On this test case you will notice a huge difference in the time taken to terminate and finish running the program.

If you aren't patience you will think this loop is endless and won't  terminate but in fact it will take hours to terminate and reach the overflow state at i value.

Finally we concluded after we put print statement inside for loop that it will take much more time than loop in the first case without print statement.

That time taken to run the program depends on your computer specifications in particular processing power(processor capacity), operating system and your IDE which is compiling the program.

I test this case on:

Lenovo 2.7 GHz Intel Core i5

OS : Windows 8.1 64x

IDE : NetBeans 8.2

It takes about 8 hours (486 minutes) to finish the program.

Also you can notice that the step increment in the for loop i = i + 1 is very slow factor to reach the max int value.

We can change this factor and make step increment more faster in order to test for loop in less time.

if we put i = i * 10 and test it:

for(int i = 10; i > 0; i*=10) {
           System.out.println("infinite: " + i);
}
     System.out.println("finished!");

Output:

infinite: 100000
infinite: 1000000
infinite: 10000000
infinite: 100000000
infinite: 1000000000
infinite: 1410065408
infinite: 1215752192
finished!
BUILD SUCCESSFUL (total time: 0 seconds)

As you see it's very fast comparing to the previous loop

it takes less than 1 second to terminate and finish running the program.

After this test example I think it should clarify the problem and proves validity of Zbynek Vyskovsky - kvr000's answer, also it will be answer to this question.


问:
Get list of classes from array of elements
I have the following array that holds a number of option elements, depending on if it has the hidden class or not.

```<code>var list = $('#condition option').not('.hidden');
</code>```

How can I get an array of classes these elements have?

What I have tried:

```<code>var list = $('#condition option').not('.hidden').attr('class');
</code>```

However, this only returns classes associated with the last element in the array.

答:
Like suggested in the comments, use JQuery's each function.

```<code>var list_condition = $('#condition option').not('.hidden');
var list_class = []; // Creates an empty array

$(list_condition).each(function(index) {
  list_class.push($(list_condition)[index].attr('class')); // Pushes the element into the array
});
</code>```

Body:
I have the following array that holds a number of option elements, depending on if it has the hidden class or not.

var list = $('#condition option').not('.hidden');

How can I get an array of classes these elements have?

What I have tried:

var list = $('#condition option').not('.hidden').attr('class');

However, this only returns classes associated with the last element in the array.

Body:
Like suggested in the comments, use JQuery's each function.

var list_condition = $('#condition option').not('.hidden');
var list_class = []; // Creates an empty array

$(list_condition).each(function(index) {
  list_class.push($(list_condition)[index].attr('class')); // Pushes the element into the array
});


问:
How to type into a UITextView inside a XCTestCase
How do you type into a UITextView inside a XCTestCase? The UITextView is the first responder so it already had focus and the keyboard is up.

I've tried:

```<code>app.typeText("footer")
app.textViews.element(boundBy: 0).typeText("foobar")
app.links.element(boundBy: 0).typeText("foobar")
</code>```

for some reason app.textViews.count always returns 0?

答:
The problem is not that .typeText(_:) doesn't work, it's that your query doesn't resolve to an element.

It can sometimes seem like the query is not working properly when the view you're trying to find is inside an accessible container view of some sort. You can mitigate this by explicitly disabling accessibility in the container view.

Set the stack view that contains the text view to not be an accessibility element and then set an accessibility identifier on the text view.

```<code>// app code
let stack: UIStackView!
let textView: UITextView!
stack.isAccessibilityElement = false
textView.isAccessibilityElement = true
textView.accessibilityIdentifier = "myTextView"

// test code
let app = XCUIApplication()
let textView = app.textViews["myTextView"]
textView.typeText("something")
</code>```

Body:
How do you type into a UITextView inside a XCTestCase? The UITextView is the first responder so it already had focus and the keyboard is up.

I've tried:

app.typeText("footer")
app.textViews.element(boundBy: 0).typeText("foobar")
app.links.element(boundBy: 0).typeText("foobar")

for some reason app.textViews.count always returns 0?

Body:
The problem is not that .typeText(_:) doesn't work, it's that your query doesn't resolve to an element.

It can sometimes seem like the query is not working properly when the view you're trying to find is inside an accessible container view of some sort. You can mitigate this by explicitly disabling accessibility in the container view.

Set the stack view that contains the text view to not be an accessibility element and then set an accessibility identifier on the text view.

// app code
let stack: UIStackView!
let textView: UITextView!
stack.isAccessibilityElement = false
textView.isAccessibilityElement = true
textView.accessibilityIdentifier = "myTextView"

// test code
let app = XCUIApplication()
let textView = app.textViews["myTextView"]
textView.typeText("something")


答:
Maybe something like this. The list selects all of the dom elements.
The <code>.each</code> iterates through them all. </p>

```<code>var list = $('#condition option').not('.hidden').attr('class');
$(list).each(function( index ) {
  var myClass = $(this).attr("class");
  console.log(myClass);
});
</code>```

Title: Get list of classes from array of elements

Body:
Maybe something like this. The list selects all of the dom elements.
The .each iterates through them all.

var list = $('#condition option').not('.hidden').attr('class');
$(list).each(function( index ) {
  var myClass = $(this).attr("class");
  console.log(myClass);
});


问:
How to ease nested looping?
I find myself looping over vectors of vectors a lot:

```<code>std::vector<std::vector<int> > foo;

for(unsigned int i=0; i != foo.size(); ++i) {
 for(unsigned int j=0; j != foo[i].size(); ++j) {
  // use foo[i][j]
 }
}
</code>```

I don't have a good minimal example why the "data" is represented best by a vector of vectors of int but let's don't doubt it here.

What do you suggest to simplify the looping? I could think of a function that implements the explicit looping and takes a pointer to a function for the body.

How to "generate" nested for-loops in case of more levels?

Are there languages that have "built-in" support for "nested looping"?

Thanks in advance,

Somebody

答:
There is no built-in looping for nested structures (given the depth of nesting could be arbitrary). You have several options.

Flatten the 2D vector into a single dimensional vector and iterate over that or, Use something like for_each, e.g.

```<code>template <typename T>
struct do_foo
{
  void operator()(T v)
  {
    // Use the v
  }
};

template <typename Handler, typename Container>
struct handle_nested
{
  void operator()(Container const& internal)
  {
    // inner loop, container type has been abstracted away and the handler type
    for_each(internal.begin(), internal.end(), Handler());
  }
};

// outer loop
for_each(foo.begin(), foo.end(), handle_nested<do_foo<int>, std::vector<int> >());
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to ease nested looping?

Body:
I find myself looping over vectors of vectors a lot:

std::vector<std::vector<int> > foo;

for(unsigned int i=0; i != foo.size(); ++i) {
 for(unsigned int j=0; j != foo[i].size(); ++j) {
  // use foo[i][j]
 }
}

I don't have a good minimal example why the "data" is represented best by a vector of vectors of int but let's don't doubt it here.

What do you suggest to simplify the looping? I could think of a function that implements the explicit looping and takes a pointer to a function for the body.

How to "generate" nested for-loops in case of more levels?

Are there languages that have "built-in" support for "nested looping"?

Thanks in advance,

Somebody

Body:
There is no built-in looping for nested structures (given the depth of nesting could be arbitrary). You have several options.

Flatten the 2D vector into a single dimensional vector and iterate over that or, Use something like for_each, e.g.

template <typename T>
struct do_foo
{
  void operator()(T v)
  {
    // Use the v
  }
};

template <typename Handler, typename Container>
struct handle_nested
{
  void operator()(Container const& internal)
  {
    // inner loop, container type has been abstracted away and the handler type
    for_each(internal.begin(), internal.end(), Handler());
  }
};

// outer loop
for_each(foo.begin(), foo.end(), handle_nested<do_foo<int>, std::vector<int> >());


问:
Apply three.js subdivision modifier without changing outer geometry?
I am trying to take any three.js geometry and subdivide its existing faces into smaller faces. This would essentially give the geometry a higher "resolution". There is a subdivision modifier tool in the examples of three.js that works great for what I'm trying to do, but it ends up changing and morphing the original shape of the geometry. I'd like to retain the original shape.

View the Subdivision Modifier Example

Example of how the current subdivision modifier behaves:

Rough example of how I'd like it to behave:

The subdivision modifier is applied like this:

let originalGeometry = new THREE.BoxGeometry(1, 1, 1);
let subdivisionModifier = new THREE.SubdivisionModifier(3);
let subdividedGeometry = originalGeometry.clone();
subdivisionModifier.modify(subdividedGeometry);
```

I attempted to dig around the source of the subdivision modifier, but I wasn't sure how to modify it to get the desired result.

Note: The subdivision should be able to be applied to any geometry. My example of the desired result might make it seem that a three.js PlaneGeometry with increased segments would work, but I need this to be applied to a variety of geometries.

答:
Based on the suggestions in the comments by TheJim01, I was able to dig through the original source and modify the vertex weight, edge weight, and beta values to retain the original shape. My modifications should remove any averaging, and put all the weight toward the source shape.

There were three sections that had to be modified, so I went ahead and made it an option that can be passed into the constructor called retainShape, which defaults to false.

I made a gist with the modified code for SubdivisionGeometry.js.

View the modified SubdivisionGeometry.js Gist

Below is an example of a cube being subdivided with the option turned off, and turned on.

Left: new THREE.SubdivisionModifier(2, false);

Right: new THREE.SubdivisionModifier(2, true);

If anyone runs into any issues with this or has any questions, let me know!

Body:
I am trying to take any three.js geometry and subdivide its existing faces into smaller faces. This would essentially give the geometry a higher "resolution". There is a subdivision modifier tool in the examples of three.js that works great for what I'm trying to do, but it ends up changing and morphing the original shape of the geometry. I'd like to retain the original shape.

View the Subdivision Modifier Example

Example of how the current subdivision modifier behaves:

Rough example of how I'd like it to behave:

The subdivision modifier is applied like this:

let originalGeometry = new THREE.BoxGeometry(1, 1, 1);
let subdivisionModifier = new THREE.SubdivisionModifier(3);
let subdividedGeometry = originalGeometry.clone();
subdivisionModifier.modify(subdividedGeometry);

I attempted to dig around the source of the subdivision modifier, but I wasn't sure how to modify it to get the desired result.

Note: The subdivision should be able to be applied to any geometry. My example of the desired result might make it seem that a three.js PlaneGeometry with increased segments would work, but I need this to be applied to a variety of geometries.


答:
You can use .map():

```<code>$('#condition option').not('.hidden').map(function() {
  return this.className.split(' ');
}).get();
</code>```

Here's a fiddle

Body:
You can use .map():

$('#condition option').not('.hidden').map(function() {
  return this.className.split(' ');
}).get();

Here's a fiddle


问:
ng2-material + Angular Cli installation Failed
I am using the latest version of angular-cli. When am trying to install ng2-material am getting the following error.</p>

```<code>leox@leox ~/workspace/MaterialTest $ sudo npm install --save ng2-material @angular2-material/core
[sudo] password for leox:

> ng2-material@0.6.1 postinstall /home/leox/workspace/MaterialTest/node_modules/ng2-material
> typings install

sh: 1: typings: not found
material-test@0.0.0 /home/leox/workspace/MaterialTest
+-- UNMET PEER DEPENDENCY @angular/common@2.0.0
+-- UNMET PEER DEPENDENCY @angular/compiler@2.0.0
+-- UNMET PEER DEPENDENCY @angular/core@2.0.0
+-- UNMET PEER DEPENDENCY @angular/platform-browser@2.0.0
`-- @angular2-material/core@2.0.0-alpha.8-2

npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.14
npm WARN @angular/compiler-cli@0.6.4 requires a peer of     @angular/compiler@2.0.2 but none was installed.
npm WARN @angular/compiler-cli@0.6.4 requires a peer of @angular/core@2.0.2 but none was installed.
npm WARN @angular/platform-server@2.0.2 requires a peer of @angular/core@2.0.2 but none was installed.
npm WARN @angular/platform-server@2.0.2 requires a peer of @angular/common@2.0.2 but none was installed.
npm WARN @angular/platform-server@2.0.2 requires a peer of @angular/compiler@2.0.2 but none was installed.
npm WARN @angular/platform-server@2.0.2 requires a peer of @angular/platform-browser@2.0.2 but none was installed.
npm WARN grunt-sass@1.2.1 requires a peer of grunt@>=0.4.0 but none was installed.
npm WARN @angular2-material/checkbox@2.0.0-alpha.6 requires a peer of @angular2-material/core@2.0.0-alpha.6 but none was installed.
npm WARN @angular2-material/checkbox@2.0.0-alpha.6 requires a peer of @angular/forms@^0.1.0 but none was installed.
npm ERR! Linux 3.19.0-32-generic
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "--save" "ng2-material" "@angular2-material/core"
npm ERR! node v6.7.0
npm ERR! npm  v3.10.3
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn

npm ERR! ng2-material@0.6.1 postinstall: `typings install`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the ng2-material@0.6.1 postinstall script 'typings install'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the ng2-material package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     typings install
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs ng2-material
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls ng2-material
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/leox/workspace/MaterialTest/npm-debug.log
</code>```

答:
I know this is late, but if you or anyone else are still having issues. Per ng2-material's documentation, this project is now deprecated

IMPORTANT This project is deprecated, please visit the official @angular/material site.

In order to install, you would now run

```<code>npm install --save @angular/material
</code>```

For more information, please visit Getting Started with Angular Material

Body:
I am using the latest version of angular-cli. When am trying to install ng2-material am getting the following error.

leox@leox ~/workspace/MaterialTest $ sudo npm install --save ng2-material @angular2-material/core
[sudo] password for leox:

> ng2-material@0.6.1 postinstall /home/leox/workspace/MaterialTest/node_modules/ng2-material
> typings install

sh: 1: typings: not found
material-test@0.0.0 /home/leox/workspace/MaterialTest
+-- UNMET PEER DEPENDENCY @angular/common@2.0.0
+-- UNMET PEER DEPENDENCY @angular/compiler@2.0.0
+-- UNMET PEER DEPENDENCY @angular/core@2.0.0
+-- UNMET PEER DEPENDENCY @angular/platform-browser@2.0.0
`-- @angular2-material/core@2.0.0-alpha.8-2

npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.14
npm WARN @angular/compiler-cli@0.6.4 requires a peer of     @angular/compiler@2.0.2 but none was installed.
npm WARN @angular/compiler-cli@0.6.4 requires a peer of @angular/core@2.0.2 but none was installed.
npm WARN @angular/platform-server@2.0.2 requires a peer of @angular/core@2.0.2 but none was installed.
npm WARN @angular/platform-server@2.0.2 requires a peer of @angular/common@2.0.2 but none was installed.
npm WARN @angular/platform-server@2.0.2 requires a peer of @angular/compiler@2.0.2 but none was installed.
npm WARN @angular/platform-server@2.0.2 requires a peer of @angular/platform-browser@2.0.2 but none was installed.
npm WARN grunt-sass@1.2.1 requires a peer of grunt@>=0.4.0 but none was installed.
npm WARN @angular2-material/checkbox@2.0.0-alpha.6 requires a peer of @angular2-material/core@2.0.0-alpha.6 but none was installed.
npm WARN @angular2-material/checkbox@2.0.0-alpha.6 requires a peer of @angular/forms@^0.1.0 but none was installed.
npm ERR! Linux 3.19.0-32-generic
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "--save" "ng2-material" "@angular2-material/core"
npm ERR! node v6.7.0
npm ERR! npm  v3.10.3
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn

npm ERR! ng2-material@0.6.1 postinstall: `typings install`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the ng2-material@0.6.1 postinstall script 'typings install'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the ng2-material package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     typings install
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs ng2-material
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls ng2-material
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/leox/workspace/MaterialTest/npm-debug.log

Body:
I know this is late, but if you or anyone else are still having issues. Per ng2-material's documentation, this project is now deprecated

IMPORTANT This project is deprecated, please visit the official @angular/material site.

In order to install, you would now run

npm install --save @angular/material

For more information, please visit Getting Started with Angular Material


问:
Is using COUNT(*) or SELECT * a good idea?
I've heard several times that you shouldn't perform COUNT(*) or SELECT * for performance reasons, but wasn't able to dig up some further information about it.

I can imagine that the database is then using all columns for the action, which can be an impressive performance loss, but I'm not sure about that. Does somebody have further information about the topic?

答:
When using count(*) the * doesn't mean "all fields". Using count(field) will count all non-null values in the field, but count(*) will always count all records even if all fields in all records are null, so it doesn't need to check the data in the fields at all.

Using select * means that you almost always return more data than you are going to use, which of course is a waste. However, perhaps more serious is the maintainence problem; if you add fields to a table your query will return these too. That might mean that the record becomes too large to fit in the buffer, resulting in an error message.


问:
How can I get new selection in "select" in Angular 2?
I am using Angular 2 (TypeScript).

I want to do something with the new selection, but what I get in onChange() is always the last selection. How can I get the new selection?

<select [(ngModel)]="selectedDevice" (change)="onChange($event)">
   <option *ngFor="#i of devices">{{i}}</option>
</select>
```

```onChange($event) {
    console.log(this.selectedDevice);
    // I want to do something here with the new selectedDevice, but what I
    // get here is always the last selection, not the one I just selected.
}
```

答:
latest ionic 3.2.0 have modified (change) to (ionChange)

eg:
HTML

```<code><ion-select (ionChange)="function($event)"> <ion-option>1<ion-option>
</ion-select>
</code>```

TS

```<code>function($event){
// this gives the selected element
 console.log($event);

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Angular 2 (TypeScript).

I want to do something with the new selection, but what I get in onChange() is always the last selection. How can I get the new selection?

<select [(ngModel)]="selectedDevice" (change)="onChange($event)">
   <option *ngFor="#i of devices">{{i}}</option>
</select>

onChange($event) {
    console.log(this.selectedDevice);
    // I want to do something here with the new selectedDevice, but what I
    // get here is always the last selection, not the one I just selected.
}

Body:
latest ionic 3.2.0 have modified (change) to (ionChange)

eg:
HTML

<ion-select (ionChange)="function($event)"> <ion-option>1<ion-option>
</ion-select>

TS

function($event){
// this gives the selected element
 console.log($event);

}


问:
How to use ng-min or ng-pattern together with ng-required?
I have some form fields that shouldn't be required sometimes. I want to use ng-min or ng-pattern together with ng-required.

But if I delete field value itself (or make them invalid somehow) when field is not required (ng-required is falsy) the form still is invalid state because of wrong value that doesn't satisfy either ng-min or ng-pattern.

I assume that ng-pattern and ng-min won't mark field as invalid when it's not required (ng-required is falsy)

答:
This sounds like a perfect use of a custom validator. More information from the angular team on custom validators can be found here. I would simply create maybe a couple different custom validators that check if the value is null and or meets some additional pattern or numerical requirement.

There may also be a validtor library on npm that has this ready to go for you.

Simple Example (Not Tested)

```<code>export const customMin(minimum: number): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} => {
    const val = control.value;
    const valid = val && val >= minimum ? true
    if (!val) {
      return {"minValue": true};
    } else {
      return val >= minimum ? return {"minValue": true} : null
    }
  };
}
</code>```

Body:
This sounds like a perfect use of a custom validator. More information from the angular team on custom validators can be found here. I would simply create maybe a couple different custom validators that check if the value is null and or meets some additional pattern or numerical requirement.

There may also be a validtor library on npm that has this ready to go for you.

Simple Example (Not Tested)

export const customMin(minimum: number): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} => {
    const val = control.value;
    const valid = val && val >= minimum ? true
    if (!val) {
      return {"minValue": true};
    } else {
      return val >= minimum ? return {"minValue": true} : null
    }
  };
}


问:
C# Get Child Rows Column Issue
I am working on a database program in c# and want to add the data relations to the project. I am having issues with the getting of the child rows, however. I have used the code provided by Microsoft's documentation:

```<code>    static void childRows() {
        DataRow[] arrRows;

        foreach(DataRelation relation in dataSet.Tables["Artist"].ChildRelations) {
            foreach(DataRow row in dataSet.Tables["Artist"].Rows) {
                arrRows = row.GetChildRows(relation);

                for(int i = 0; i < arrRows.Length; i++) {
                    foreach(DataColumn column in dataSet.Tables["Artist"].Columns) {
                        Console.WriteLine(arrRows[i][column.ColumnName]);
                    }
                }
            }
        }

    }
</code>```

But I am getting an error saying that the second column (the name of the artist) does not exist in the linked table; which I would think wouldn't be a problem.

My data relations are:

```<code>r1 = new DataRelation("Artist_Records", dataSet.Tables["Artist"].Columns[0], dataSet.Tables["Record"].Columns[1]);
r2 = new DataRelation("Label_Records", dataSet.Tables["RecordLabel"].Columns[0], dataSet.Tables["Record"].Columns[4]);

dataSet.Relations.Add(r1);
dataSet.Relations.Add(r2);
</code>```

What am I doing wrong?

答:
Try following :</p>

```<code>            foreach(DataRelation relation in dataSet.Tables["Artist"].ChildRelations)
            {
                   foreach(DataRow row in  relation.ChildTable.AsEnumerable())
                   {
                       Console.WriteLine(string.Join(",", row.ItemArray.Select(x => x.ToString())));
                   }
                   DataTable dt2 = relation.ChildTable.AsEnumerable().CopyToDataTable();
            }
</code>```

Title: C# Get Child Rows Column Issue

Body:
I am working on a database program in c# and want to add the data relations to the project. I am having issues with the getting of the child rows, however. I have used the code provided by Microsoft's documentation:

    static void childRows() {
        DataRow[] arrRows;

        foreach(DataRelation relation in dataSet.Tables["Artist"].ChildRelations) {
            foreach(DataRow row in dataSet.Tables["Artist"].Rows) {
                arrRows = row.GetChildRows(relation);

                for(int i = 0; i < arrRows.Length; i++) {
                    foreach(DataColumn column in dataSet.Tables["Artist"].Columns) {
                        Console.WriteLine(arrRows[i][column.ColumnName]);
                    }
                }
            }
        }

    }

But I am getting an error saying that the second column (the name of the artist) does not exist in the linked table; which I would think wouldn't be a problem.

My data relations are:

r1 = new DataRelation("Artist_Records", dataSet.Tables["Artist"].Columns[0], dataSet.Tables["Record"].Columns[1]);
r2 = new DataRelation("Label_Records", dataSet.Tables["RecordLabel"].Columns[0], dataSet.Tables["Record"].Columns[4]);

dataSet.Relations.Add(r1);
dataSet.Relations.Add(r2);

What am I doing wrong?

Body:
Try following :

            foreach(DataRelation relation in dataSet.Tables["Artist"].ChildRelations)
            {
                   foreach(DataRow row in  relation.ChildTable.AsEnumerable())
                   {
                       Console.WriteLine(string.Join(",", row.ItemArray.Select(x => x.ToString())));
                   }
                   DataTable dt2 = relation.ChildTable.AsEnumerable().CopyToDataTable();
            }


问:
Detect windows version in Go to figure out the starup folder
Is there anyway to detect if the host operating system is XP, Vista, 7, 8, or 10?
runtime.GOOS just returns "windows".

The reason for this is because I'm trying to manipulate files in the startup folder.

On windows vista, 7, 8, 10 it's located at:

%appdata%\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

On windows XP it's located at:

Documents and Settings\%username%\Start Menu\Programs\Startup

答:
Why not use the windows registry?

https://godoc.org/golang.org/x/sys/windows/registry

How to return a default value from windows/registry with golang

```<code>package main

import (
    "golang.org/x/sys/windows/registry"
    "log"
    "fmt"
)

func main() {

    k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
    if err != nil {
        log.Fatal(err)
    }
    defer k.Close()

    cv, _, err := k.GetStringValue("CurrentVersion")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("CurrentVersion: %s\n", cv)

    pn , _, err := k.GetStringValue("ProductName")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("ProductName: %s\n", pn)

    maj, _, err := k.GetIntegerValue("CurrentMajorVersionNumber")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("CurrentMajorVersionNumber: %d\n", maj)

    min, _, err := k.GetIntegerValue("CurrentMinorVersionNumber")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("CurrentMinorVersionNumber: %d\n", min)

    cb, _, err := k.GetStringValue("CurrentBuild")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("CurrentVersion: %s\n", cb)
}
</code>```

This returns:

```<code>PS C:\Users\Adamar\Desktop> .\WindowsVersion.exe
CurrentVersion: 6.3
ProductName: Windows Server 2016 Standard Evaluation
CurrentMajorVersionNumber: 10
CurrentMinorVersionNumber: 0
CurrentVersion: 14393
</code>```

Although in the newest version of windows you have to read the following keys to get the version: CurrentMajorVersionNumber & CurrentMinorVersionNumber

Body:
Why not use the windows registry?

https://godoc.org/golang.org/x/sys/windows/registry

How to return a default value from windows/registry with golang

package main

import (
    "golang.org/x/sys/windows/registry"
    "log"
    "fmt"
)

func main() {

    k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
    if err != nil {
        log.Fatal(err)
    }
    defer k.Close()

    cv, _, err := k.GetStringValue("CurrentVersion")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("CurrentVersion: %s\n", cv)

    pn , _, err := k.GetStringValue("ProductName")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("ProductName: %s\n", pn)

    maj, _, err := k.GetIntegerValue("CurrentMajorVersionNumber")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("CurrentMajorVersionNumber: %d\n", maj)

    min, _, err := k.GetIntegerValue("CurrentMinorVersionNumber")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("CurrentMinorVersionNumber: %d\n", min)

    cb, _, err := k.GetStringValue("CurrentBuild")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("CurrentVersion: %s\n", cb)
}

This returns:

PS C:\Users\Adamar\Desktop> .\WindowsVersion.exe
CurrentVersion: 6.3
ProductName: Windows Server 2016 Standard Evaluation
CurrentMajorVersionNumber: 10
CurrentMinorVersionNumber: 0
CurrentVersion: 14393

Although in the newest version of windows you have to read the following keys to get the version: CurrentMajorVersionNumber & CurrentMinorVersionNumber


问:
How do I keep the divs side by side in the container?
I want to create container that has two elements with colors given in the picture.  The two are different divs and must stay side by side.  How do I do it?

Here is my code:

  <title>Testing</title>

```

答:
Your code Updated!

    body, html{
      padding:0px;
      margin:0px;
      height:100%;
    }

    .container{
      width: 50%;
   height: 50%;
    }

    .sidenav{
   width: 25%;
   height: 100%;
   background-color: black;
   float: left;
     }

 .bgrnd{
   width: 75%;
   height: 100%;
   background-color: blue;
      float: left;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="sidenav"></div>
  <div class="bgrnd"></div>
</div></code>```

Body:
Your code Updated!

    body, html{
      padding:0px;
      margin:0px;
      height:100%;
    }

    .container{
      width: 50%;
   height: 50%;
    }

    .sidenav{
   width: 25%;
   height: 100%;
   background-color: black;
   float: left;
     }

 .bgrnd{
   width: 75%;
   height: 100%;
   background-color: blue;
      float: left;
 }

<div class="container">
  <div class="sidenav"></div>
  <div class="bgrnd"></div>
</div>


问:
Why am I getting an UnboundLocalError in the except clause of my Python script?
I have the following part of code from a Python script.

```<code>status = 'success'
try:
 sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
  #traceback.print_exc()
  error_message = e
#  print str(e)
  status = 'fail'
print ("{},{},{},{}".format(hivedb,table,status,error_message))
sys.exit(1)
</code>```

Here in this part of code, if there is an exception then I am setting error_message.

If there is no error, then I get UnboundLocalError: local variable 'e' referenced before assignment.

What I want is if there is no error, I want the error_message set to No error.

How can I achieve that?

答:
A cleaner approach for this is to use an else, since state updates should be atomic.

```<code>try:
    sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
    status = 'fail'
    error_message = e
else:  # Executes only if no Exception.
    status = 'success'
    error_message = 'No error'
</code>```

As a side note, it's a bad idea to do blanket exception-catching with except Exception. You should specify the type of exception you're getting or you risk catching others, like KeyboardInterrupt and SystemExit.

Body:
I have the following part of code from a Python script.

status = 'success'
try:
 sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
  #traceback.print_exc()
  error_message = e
#  print str(e)
  status = 'fail'
print ("{},{},{},{}".format(hivedb,table,status,error_message))
sys.exit(1)

Here in this part of code, if there is an exception then I am setting error_message.

If there is no error, then I get UnboundLocalError: local variable 'e' referenced before assignment.

What I want is if there is no error, I want the error_message set to No error.

How can I achieve that?

Body:
A cleaner approach for this is to use an else, since state updates should be atomic.

try:
    sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
    status = 'fail'
    error_message = e
else:  # Executes only if no Exception.
    status = 'success'
    error_message = 'No error'

As a side note, it's a bad idea to do blanket exception-catching with except Exception. You should specify the type of exception you're getting or you risk catching others, like KeyboardInterrupt and SystemExit.


答:
WARNING - Do not run the test server in production!

The reason you have to type in the port when connecting to the test server is because it doesn't run on a standard web port being "http: 80 and https: 443". If you use the command below it will not require the port number be provided when connecting to the test server. Keep in mind that you will need root or sudo access and if something is already running on port 80 it will fail.

Runserver with port:
python manage.py runserver -p 80

Title: Django runserver on all ports?

Body:
Why can't I run python manage.py runserver on all ports?

I understand this is probably a newbie question, but what prevents me from achieving this?

I would like to access my app without having to include the port, like a regular website


问:
Owin test server how to add a header before executing middleware
I am using OWIN middleware and I am trying to set a header that is getting set on a controller. For unit testing I am trying to set the header in the test to no avail. What is the best way to set this header? </p>

```<code>[TestMethod]
public async Task HasHeader()
{
        using (var server = TestServer.Create(app =>
        {
            //need to set header before calling the below middleware header name is bobsyouruncle
            app.Use(typeof(HeaderMiddleware));

        }))

        using (var client = new HttpClient(server.Handler))
        {
            var response = await client.GetAsync("http://win.example.com/bob/");
            System.Diagnostics.Debugger.Break();
        }
}
</code>```

答:
Create a test middleware that sets the header.

```<code> [TestMethod]
 public async Task HasHeader()
  {
    using (var server = TestServer.Create(app =>
    {
        //need to set header before calling the below middleware header name is bobsyouruncle
        app.Use(typeof(TestMiddleware));
        app.Use(typeof(HeaderMiddleware));

    }))
    using (var client = new HttpClient(server.Handler))
    {
        var response = await client.GetAsync("http://win.example.com/bob/");
        System.Diagnostics.Debugger.Break();
    }
}
</code>```

middleware

```<code> public TestMiddleware(OwinMiddleware next)
        : base(next)
    {

    }

    public async override Task Invoke(IOwinContext context)
    {
        await Next.Invoke(context);
        context.Response.Headers.Add("bobsyouruncle", new string[] { "test1234" });

    }
</code>```

I'm not sure how to pass that header value.

Body:
I am using OWIN middleware and I am trying to set a header that is getting set on a controller. For unit testing I am trying to set the header in the test to no avail. What is the best way to set this header?

[TestMethod]
public async Task HasHeader()
{
        using (var server = TestServer.Create(app =>
        {
            //need to set header before calling the below middleware header name is bobsyouruncle
            app.Use(typeof(HeaderMiddleware));

        }))

        using (var client = new HttpClient(server.Handler))
        {
            var response = await client.GetAsync("http://win.example.com/bob/");
            System.Diagnostics.Debugger.Break();
        }
}

Body:
Create a test middleware that sets the header.

 [TestMethod]
 public async Task HasHeader()
  {
    using (var server = TestServer.Create(app =>
    {
        //need to set header before calling the below middleware header name is bobsyouruncle
        app.Use(typeof(TestMiddleware));
        app.Use(typeof(HeaderMiddleware));

    }))
    using (var client = new HttpClient(server.Handler))
    {
        var response = await client.GetAsync("http://win.example.com/bob/");
        System.Diagnostics.Debugger.Break();
    }
}

middleware

 public TestMiddleware(OwinMiddleware next)
        : base(next)
    {

    }

    public async override Task Invoke(IOwinContext context)
    {
        await Next.Invoke(context);
        context.Response.Headers.Add("bobsyouruncle", new string[] { "test1234" });

    }

I'm not sure how to pass that header value.


问:
Mounting local directory into Docker container path that is not exposed as a VOLUME
Is there any difference between:

Mounting a host directory into a container path (the path is not exposed as a volume), e.g.:

docker run -v /host/directory:/container/directory my_image command_to_run

Dockerfile of my_image does not include VOLUME ["/container/directory"]

Mounting a host directory into a a container path exposed as a volume:

docker run -v /host/directory:/container/directory my_image command_to_run

Dockerfile of my_image includes VOLUME ["/container/directory"]

I know that volume data persists independent of the container life-cycle. However, since I want to work on my local data from within a container, does that make any difference if the mount-point inside the container is a volume?

答:
There is no difference if you mount the path from the host into the container. The filesystem from the host will be mounted over top of that directory inside the container.

The difference between listing the volume and not listing it inside the image is the behavior of docker when you create an image without specifying a volume. When the volume is defined on the image, docker will create an "anonymous" volume you can see with docker volume ls as a long uuid string. These volumes are rarely useful, so I recommend against defining a volume in the image and instead only defining them on your docker run command or docker-compose.yml definition.

Downsides of defining a volume in the image include:

Later lines in the Dockerfile or in descendant Dockerfile's may not be able to change the contents at this location. Docker's behavior with this varies by scenario and version, so for predictability, once a volume is defined in an image, I consider that directory off limits.

Creation of anonymous volumes are difficult to use and are likely to clutter up the filesystem.

I posted a blog on this topic a while back if you're interested in more details.


问:
How to get different answers from different threads?
To get to know threading concept better I tried to use threads in a simple program. I want to call a function 3 times which does random selection.

```<code>def func(arg):
    lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    num = random.choice(lst)
    arg.append(num)
    return arg

def search(arg):
    a = func(arg)
    a = func(a)
    threads_list = []
    que = queue.Queue()
    for i in range(3):
        t = threading.Thread(target=lambda q, arg1: q.put(func(arg1)), args=(que, a))
        t.start()
        threads_list.append(t)

    for t in threads_list:
        t.join()
    while not que.empty():
        result = que.get()
        print (result)

 if __name__ == '__main__':
     lst = []
     search(lst)
</code>```

As you can see In the third part, I used threads but I expected to get different lists ( different for the third part).
but all the threads return the same answer.

Can anyone help me to get different lists from different threads?

I think I misunderstood the concept of multiprocessing and multithreading.

答:
Possibly, the pseudo-random number generator which random.choice is using is using three instances - one for each thread - and in the absence of a unique seed will produce the same pseudo-random sequence. Since no seed is provided, it may be using the system time which, depending on the precision, may be the same for all three threads.

You might try seeding the PRNG with something that will differ from thread to thread, inside the thread that invokes the PRNG. This should cause the three threads to use different seeds and give you different pseudo-random sequences.

Body:
To get to know threading concept better I tried to use threads in a simple program. I want to call a function 3 times which does random selection.

def func(arg):
    lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    num = random.choice(lst)
    arg.append(num)
    return arg

def search(arg):
    a = func(arg)
    a = func(a)
    threads_list = []
    que = queue.Queue()
    for i in range(3):
        t = threading.Thread(target=lambda q, arg1: q.put(func(arg1)), args=(que, a))
        t.start()
        threads_list.append(t)

    for t in threads_list:
        t.join()
    while not que.empty():
        result = que.get()
        print (result)

 if __name__ == '__main__':
     lst = []
     search(lst)

As you can see In the third part, I used threads but I expected to get different lists ( different for the third part).
but all the threads return the same answer.

Can anyone help me to get different lists from different threads?

I think I misunderstood the concept of multiprocessing and multithreading.


问:
create a custom view programmatically then animate it
I'm creating a custom view programmatically, which is working fine, then I'm trying to animate the view.  For some strange reason the view is animating at all, I'm not sure why.  Here is the code:</p>

```<code>  override func viewDidLoad() {
    super.viewDidLoad()

    let customView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))

    customView.backgroundColor = UIColor.blue
    customView.layer.cornerRadius = 25
    customView.layer.borderWidth = 8
    customView.layer.borderColor = UIColor.red.cgColor

    self.view.addSubview(customView)

    UIView.animate(withDuration: 4, animations: {

      customView.transform.translatedBy(x: 40, y: 60)
      customView.transform.rotated(by: CGFloat.pi/2)
      customView.transform.scaledBy(x: 0, y: 0.5)

    })
  }
</code>```

答:
Your question is not correct. your view is not animating.

Why?

You are using a return function and your customView needs to catch the modified version like this.

```<code>customView.transform =  customView.transform.translatedBy(x: 40, y: 60)
</code>```

So your code would be like this.

let customView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))

```<code>    customView.backgroundColor = UIColor.blue
    customView.layer.cornerRadius = 25
    customView.layer.borderWidth = 8
    customView.layer.borderColor = UIColor.red.cgColor

    self.view.addSubview(customView)

    UIView.animate(withDuration: 4, animations: {

       customView.transform =  customView.transform.translatedBy(x: 40, y: 60)
       //customView.transform = customView.transform.rotated(by: CGFloat.pi/2)
       //customView.transform = customView.transform.scaledBy(x: 0, y: 0.5)

    })
</code>```

There are lots of online resources how to group animation.Just google it.:)

Body:
I'm creating a custom view programmatically, which is working fine, then I'm trying to animate the view.  For some strange reason the view is animating at all, I'm not sure why.  Here is the code:

  override func viewDidLoad() {
    super.viewDidLoad()

    let customView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))

    customView.backgroundColor = UIColor.blue
    customView.layer.cornerRadius = 25
    customView.layer.borderWidth = 8
    customView.layer.borderColor = UIColor.red.cgColor

    self.view.addSubview(customView)

    UIView.animate(withDuration: 4, animations: {

      customView.transform.translatedBy(x: 40, y: 60)
      customView.transform.rotated(by: CGFloat.pi/2)
      customView.transform.scaledBy(x: 0, y: 0.5)

    })
  }

Body:
Your question is not correct. your view is not animating.

Why?

You are using a return function and your customView needs to catch the modified version like this.

customView.transform =  customView.transform.translatedBy(x: 40, y: 60)

So your code would be like this.

let customView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))

    customView.backgroundColor = UIColor.blue
    customView.layer.cornerRadius = 25
    customView.layer.borderWidth = 8
    customView.layer.borderColor = UIColor.red.cgColor

    self.view.addSubview(customView)

    UIView.animate(withDuration: 4, animations: {

       customView.transform =  customView.transform.translatedBy(x: 40, y: 60)
       //customView.transform = customView.transform.rotated(by: CGFloat.pi/2)
       //customView.transform = customView.transform.scaledBy(x: 0, y: 0.5)

    })

There are lots of online resources how to group animation.Just google it.:)


答:
You can set .sidenav and .bgrnd to position: absolute; and position them accordingly from there. Also, you've set .container to: width: 50%; and height: 50%; which I presume you don't want.

.container {
  height: 100%;
  width: 100%;
}
.sidenav {
  width: 25%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background-color: black;
}
.bgrnd {
  width: 75%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 25%;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title>Testing</title>
</head>
<body>
  <div class="container">
    <div class="sidenav"></div>
    <div class="bgrnd"></div>
  </div>
</body>
</html></code>```

Title: How do I keep the divs side by side in the container?

Body:
I want to create container that has two elements with colors given in the picture.  The two are different divs and must stay side by side.  How do I do it?

Here is my code:

  <title>Testing</title>

Body:
You can set .sidenav and .bgrnd to position: absolute; and position them accordingly from there. Also, you've set .container to: width: 50%; and height: 50%; which I presume you don't want.

.container {
  height: 100%;
  width: 100%;
}
.sidenav {
  width: 25%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background-color: black;
}
.bgrnd {
  width: 75%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 25%;
  background-color: blue;
}

<!DOCTYPE html>
<html>
<head>
  <title>Testing</title>
</head>
<body>
  <div class="container">
    <div class="sidenav"></div>
    <div class="bgrnd"></div>
  </div>
</body>
</html>


问:
R - how to index rank and accordingly display a data frame?
I have a data frame that lists down some names of individuals and their monetary transactions carried out in USD. The table lists down data according to several districts and the valid transactions made by either cash or credit cards, like so:

```<code>X    Dist    transact.cash    transact.card
a    1       USD              USD
b    1       USD              USD
</code>```

Where X is an individual and his/her transactions for a period of time keeping that period fixed and Dist is the district where he/she resides. There are over 4000 observations in total for an approx. 80-100 rows per Dist. So far, the sorting, slicing and everything else have been simple operations with dat.cash and dat.card being subsetted tables according to mode of transaction; but I'm having problems when extracting information in reference to ranking the dataset. For this, I have written a function where I specify a rank and the function should show those rows starting from that rank:

```<code>rankdat <- function(transact, numb) {
               # Truncated
                 valid.nums = c('highest', 'lowest', 1:nrow(dat.cash)) # for cash subset
                     if (transact == 'cash' && numb == 'highest') { # This is easy
                 sort <- dat.cash[order(dat.cash[, 3], decreasing = T), ]# For sorting only cash data set
                  } else if (transact == 'cash' and numb == 1:nrow(dat.cash)) {
                 sort <- dat.cash[order(dat.cash[, 3], decreasing = T) == numb, ] } # Not getting results here
                 }
</code>```

The last line is returning NULL instead of a ranked transaction and all its rows. Replacing == with %in% still gives NULL and using rank() doesn't change anything. For highest and lowest numbers, its not a great deal since it only involves simple sorting. If I specify rankdat('cash', 10), the function should return values starting from the 10th highest transaction and decreasing irrespective of Dist, similar to:

```<code> X    Dist    transact.cash
 b    1       10th highest
 h    2       11th highest
 p    1       12th highest
 and  so      on
</code>```

答:
This function is able to do that:</p>

```<code>rankdat <- function(df,rank.by,num=10,method="top",decreasing=T){
  # ------------------------------------------------------
  # RANKDAT
  # ------------------------------------------------------
  # ARGUMENT
  # ========
  # df        Input dataFrame [d.f]
  # num       Selected row [num]
  # rank.by   Name of column(s) used to rank dataFrame
  # method    Method used to extract rows
  #             top - to select top rank (e.g. 10 first rows)
  #             specific - to select specific row
  # ------------------------------------------------------
  eval(parse(text=paste("sort=df[with(df,order(",rank.by,"), decreasing=",decreasing,"),]",sep=""))) # order dataFrame by
  if(method %in% "top"){
    return(sort[1:num,])
  }else if(method %in% "specific"){
    return(sort[num,])
  }else{
    stop("Please select method used to extract data !!!")
  }
}
</code>```

Body:
I have a data frame that lists down some names of individuals and their monetary transactions carried out in USD. The table lists down data according to several districts and the valid transactions made by either cash or credit cards, like so:

X    Dist    transact.cash    transact.card
a    1       USD              USD
b    1       USD              USD

Where X is an individual and his/her transactions for a period of time keeping that period fixed and Dist is the district where he/she resides. There are over 4000 observations in total for an approx. 80-100 rows per Dist. So far, the sorting, slicing and everything else have been simple operations with dat.cash and dat.card being subsetted tables according to mode of transaction; but I'm having problems when extracting information in reference to ranking the dataset. For this, I have written a function where I specify a rank and the function should show those rows starting from that rank:

rankdat <- function(transact, numb) {
               # Truncated
                 valid.nums = c('highest', 'lowest', 1:nrow(dat.cash)) # for cash subset
                     if (transact == 'cash' && numb == 'highest') { # This is easy
                 sort <- dat.cash[order(dat.cash[, 3], decreasing = T), ]# For sorting only cash data set
                  } else if (transact == 'cash' and numb == 1:nrow(dat.cash)) {
                 sort <- dat.cash[order(dat.cash[, 3], decreasing = T) == numb, ] } # Not getting results here
                 }

The last line is returning NULL instead of a ranked transaction and all its rows. Replacing == with %in% still gives NULL and using rank() doesn't change anything. For highest and lowest numbers, its not a great deal since it only involves simple sorting. If I specify rankdat('cash', 10), the function should return values starting from the 10th highest transaction and decreasing irrespective of Dist, similar to:

 X    Dist    transact.cash
 b    1       10th highest
 h    2       11th highest
 p    1       12th highest
 and  so      on

Body:
This function is able to do that:

rankdat <- function(df,rank.by,num=10,method="top",decreasing=T){
  # ------------------------------------------------------
  # RANKDAT
  # ------------------------------------------------------
  # ARGUMENT
  # ========
  # df        Input dataFrame [d.f]
  # num       Selected row [num]
  # rank.by   Name of column(s) used to rank dataFrame
  # method    Method used to extract rows
  #             top - to select top rank (e.g. 10 first rows)
  #             specific - to select specific row
  # ------------------------------------------------------
  eval(parse(text=paste("sort=df[with(df,order(",rank.by,"), decreasing=",decreasing,"),]",sep=""))) # order dataFrame by
  if(method %in% "top"){
    return(sort[1:num,])
  }else if(method %in% "specific"){
    return(sort[num,])
  }else{
    stop("Please select method used to extract data !!!")
  }
}


问:
How to hide tab bar programmatically and then expand view to fit
I got the code from this question: How to hide UITabBarController programmatically? which is brilliant, however the view doesn't expand to fit the space left by the tab bar now.

I have set the appropriate UIViewAutoresizingMasks to the view, but I'm assuming that just because its hidden doesn't mean its not still taking up the space?

Anyway, if I do [self.navigationController setNavigationBarHidden:YES animated:YES]; then the navigation bar moves up and off the screen expanding the view with it.

How can I replicate this behavior for the Tab Bar?

答: Turns out its not quite possible. Best way is to present a modal view (navigation) controller instead of pushing a view controller.</p>


问:
When does the UIColletionView calls his datasource and delegate methods
I created a UICollectionView with a custom cell. In the viewDidLoad() method I was registering my cellclass.

```<code>   collectionView?.register(CustomCell.self, forCellWithReuseIdentifier: cellId)
  collectionView?.reloadData()
</code>```

While debugging my code to check the behavior I saw that in the line where I was registering my collectionView and called collectionView.reloadData()  with the custom Cellclass none of the datasource and delegate methods got executed like cellForItem at etc.. ? Why is that so ?

答:
Deffinately strange staff you are doing, after registering cell, you are reloading collectionView data.. Why? You should reload data when something changes in your array of data. But anyhow, try to call reloadData on the main thread.</p>

```<code>DispathQueue.main.async {
   self.collecitonView.reloadData()
}
</code>```

Body:
I created a UICollectionView with a custom cell. In the viewDidLoad() method I was registering my cellclass.

   collectionView?.register(CustomCell.self, forCellWithReuseIdentifier: cellId)
  collectionView?.reloadData()

While debugging my code to check the behavior I saw that in the line where I was registering my collectionView and called collectionView.reloadData()  with the custom Cellclass none of the datasource and delegate methods got executed like cellForItem at etc.. ? Why is that so ?

Body:
Deffinately strange staff you are doing, after registering cell, you are reloading collectionView data.. Why? You should reload data when something changes in your array of data. But anyhow, try to call reloadData on the main thread.

DispathQueue.main.async {
   self.collecitonView.reloadData()
}


问:
How to pass a List<string> from Form to user controls in C#
I have a Form with 4 UserControls, each for a different page.
Some of my controls are used on multiple UC.

What I'm trying to do is this :

Form

```<code>public List<string> MyList;
MyList = new List<string>(Directory.GetDirectories("C:\\"));
</code>```

and I'm trying to access the list in my UserControl :

uc1

```<code>foreach (string item in MyList)
{
    ComboBox.Items.add(item);
}
</code>```

And obviously, MyList in the UserControl isn't recognized.
Be it uc1 or any other one.

I don't understand what the problem is.
Also it's obvious from the problem I think but, I'm a beginner so, please avoid complicated answers, I'll afraid of programming after that :)

答:
make property in your UserControl, something like

```<code>public List<string> MyList { get; set; }
</code>```

in your Form, when needed, pass reference to UserControl:

```<code>public List<string> MyList;
MyList = new List<string>(Directory.GetDirectories("C:\\"));
uc1.MyList = MyList;
</code>```

Body:
I have a Form with 4 UserControls, each for a different page.
Some of my controls are used on multiple UC.

What I'm trying to do is this :

Form

public List<string> MyList;
MyList = new List<string>(Directory.GetDirectories("C:\\"));

and I'm trying to access the list in my UserControl :

uc1

foreach (string item in MyList)
{
    ComboBox.Items.add(item);
}

And obviously, MyList in the UserControl isn't recognized.
Be it uc1 or any other one.

I don't understand what the problem is.
Also it's obvious from the problem I think but, I'm a beginner so, please avoid complicated answers, I'll afraid of programming after that :)

Body:
make property in your UserControl, something like

public List<string> MyList { get; set; }

in your Form, when needed, pass reference to UserControl:

public List<string> MyList;
MyList = new List<string>(Directory.GetDirectories("C:\\"));
uc1.MyList = MyList;


问:
Asp.Net Core Model binding, how to get empty field to bind as a blank string?
If a form like the one below is submitted and MyField is left blank on the form, then by default Asp.Net Core model binding will place null into the corresponding property on the model as indicated below.

Example Form

```<code> <form asp-controller="SomeController" asp-action="SomeAction">
        <label asp-for="MyField">My Field</label><input asp-for="MyField" type="text" />
        <button type="submit">Submit</button>
 </form>
</code>```

Example Model

```<code> public class MyModel{
     public string MyField { get; set; }
 }
</code>```

Example Action Method

```<code>    [HttpPost]
    public IActionResult Post(MyModel m) {
          //m.MyField will be null if the field was left empty
          //but I want it set to a blank string by the model binder
    }
</code>```

However, since MyField is actually transmitted in the Http Post body I'd prefer that the model binder set the MyField property on the model to a blank string rather than setting it to null.  I'd prefer to reserve null for cases where MyField is not transmitted in the Http Post body.  How can the model binder be changed to exhibit this behavior?

答:
Have you tried making the property have a default value of empty string?

```<code>public string MyField { get; set; } = string.Empty;
</code>```

an uglier solution to try is:

```<code>private string myField  = string.Empty;
public string MyField
{
    get { return myField ?? string.Empty; }
    set { myField = value; }
}
</code>```

I think it should work

Body:
If a form like the one below is submitted and MyField is left blank on the form, then by default Asp.Net Core model binding will place null into the corresponding property on the model as indicated below.

Example Form

 <form asp-controller="SomeController" asp-action="SomeAction">
        My Field<input asp-for="MyField" type="text" />
        <button type="submit">Submit</button>
 </form>

Example Model

 public class MyModel{
     public string MyField { get; set; }
 }

Example Action Method

    [HttpPost]
    public IActionResult Post(MyModel m) {
          //m.MyField will be null if the field was left empty
          //but I want it set to a blank string by the model binder
    }

However, since MyField is actually transmitted in the Http Post body I'd prefer that the model binder set the MyField property on the model to a blank string rather than setting it to null.  I'd prefer to reserve null for cases where MyField is not transmitted in the Http Post body.  How can the model binder be changed to exhibit this behavior?

Body:
Have you tried making the property have a default value of empty string?

public string MyField { get; set; } = string.Empty;

an uglier solution to try is:

private string myField  = string.Empty;
public string MyField
{
    get { return myField ?? string.Empty; }
    set { myField = value; }
}

I think it should work


问:
When I run this code only data of two nodes and the data of new node is shown but data third and fourth node is not shown
In this code only data of first second and new node is shown but I want the data of all the nodes.

```<code>package linkedlispack;

 public class InsertLast {
  Node head;
  static class Node{
    int data;
    Node next;
    Node(int d){
        data=d;
        next=null;

    }
   }
    public void printlist()
    {
    Node n = head;
    while(n!=null){
        System.out.println(n.data+"");
        n=n.next;
    }
      }
     public void push(int new_data){
      Node new_node=new Node(new_data);
       if(head==null){
        head=new Node(new_data);
        return;
       }

    new_node.next=null;

    Node last=head;
    while(last!=null){
        last=last.next;

        last.next=new_node;
        return;
    }
</code>```

upto last node is created

```<code>     }
     public static void main(String[] args) {
    // TODO Auto-generated method stub
       InsertLast list=new InsertLast();
       list.head=new Node(4);
       Node second=new Node(10);
</code>```

here third and fourth node

```<code>       Node third=new Node(12);
       Node fourth=new Node(20);

        list.head.next=second;

        second.next=third;
        third.next=fourth;

        list.push(15);
        list.printlist();

}

 }
</code>```

output shown 4 10 15 .But I want output 4 10 12 20 15

答:
Why dont you use debugger and step through your code?

Your pushis wrong. By calling list.push(15) you are attaching new node to second node and dropping third and fourth nodes.

Body:
In this code only data of first second and new node is shown but I want the data of all the nodes.

package linkedlispack;

 public class InsertLast {
  Node head;
  static class Node{
    int data;
    Node next;
    Node(int d){
        data=d;
        next=null;

    }
   }
    public void printlist()
    {
    Node n = head;
    while(n!=null){
        System.out.println(n.data+"");
        n=n.next;
    }
      }
     public void push(int new_data){
      Node new_node=new Node(new_data);
       if(head==null){
        head=new Node(new_data);
        return;
       }

    new_node.next=null;

    Node last=head;
    while(last!=null){
        last=last.next;

        last.next=new_node;
        return;
    }

upto last node is created

     }
     public static void main(String[] args) {
    // TODO Auto-generated method stub
       InsertLast list=new InsertLast();
       list.head=new Node(4);
       Node second=new Node(10);

here third and fourth node

       Node third=new Node(12);
       Node fourth=new Node(20);

        list.head.next=second;

        second.next=third;
        third.next=fourth;

        list.push(15);
        list.printlist();

}

 }

output shown 4 10 15 .But I want output 4 10 12 20 15


问:
How do I get the value of the first occurrence of array_walk_recursive in php
I have a deep multidimensional array that I am needing to extract the value of a specific key. I have found that the array_walk_recursive function will be my best option. I only need the first occurrence.

My array looks like this - (except much more complicated)

```<code>Array (
    [vehicle info] => Array (
        [one] => Array (
            [submodel] => LX
            [engine] => 2.3
        )
        [two] => Array (
            [color] => blue
            [year] => 2007
            [wheels] => 4
        )
        [three] => Array (
            [submodel] => LX
            [make] => Ford
            [model] => F-150
            [offroad] => No
        )
    )
)
</code>```

The issue here is, submodel is in both one and three. Additionally, the array is not consistent, so I must use array_walk_recursive to search through it for the matching key, then return the value for that key.

Here is my current code -

```<code>array_walk_recursive ($array, (function ($item, $key) {
    $wanted = "submodel";
    if ($key === $wanted) {
        echo ("$key is $item");
    }
}));
</code>```

The above returns submodel is LXsubmodel is LX.

Bonus Question!!
How can I search for multiple keys and return the first corresponding value for each of those? I was thinking putting all wanted keys in an array, then do a foreach loop, but don't quite know how to structure this. I am new to php.

答:
I would start by setting the values you want to null, and then only saving them if they haven't been found yet, by checking is_null(). I haven't tested this code, but it should look something like this:

```<code>$submodel = null;
array_walk_recursive ($array, (function ($item, $key) {
    $wanted = "submodel";
    if ($key === $wanted && is_null($submodel)) {
        echo ("$key is $item");
        $submodel = $item;
    }
}));
</code>```

Body:
I have a deep multidimensional array that I am needing to extract the value of a specific key. I have found that the array_walk_recursive function will be my best option. I only need the first occurrence.

My array looks like this - (except much more complicated)

Array (
    [vehicle info] => Array (
        [one] => Array (
            [submodel] => LX
            [engine] => 2.3
        )
        [two] => Array (
            [color] => blue
            [year] => 2007
            [wheels] => 4
        )
        [three] => Array (
            [submodel] => LX
            [make] => Ford
            [model] => F-150
            [offroad] => No
        )
    )
)

The issue here is, submodel is in both one and three. Additionally, the array is not consistent, so I must use array_walk_recursive to search through it for the matching key, then return the value for that key.

Here is my current code -

array_walk_recursive ($array, (function ($item, $key) {
    $wanted = "submodel";
    if ($key === $wanted) {
        echo ("$key is $item");
    }
}));

The above returns submodel is LXsubmodel is LX.

Bonus Question!!
How can I search for multiple keys and return the first corresponding value for each of those? I was thinking putting all wanted keys in an array, then do a foreach loop, but don't quite know how to structure this. I am new to php.

Body:
I would start by setting the values you want to null, and then only saving them if they haven't been found yet, by checking is_null(). I haven't tested this code, but it should look something like this:

$submodel = null;
array_walk_recursive ($array, (function ($item, $key) {
    $wanted = "submodel";
    if ($key === $wanted && is_null($submodel)) {
        echo ("$key is $item");
        $submodel = $item;
    }
}));


问:
What should I do when get "SUCCESSWITHWARNING" from Paypal
How should I handle SUCCESSWITHWARNING when using classic Paypal api?

I searched web for this response but I can't find what it exactly mean and what should I do when I get SUCCESSWITHWARNING response from Paypal.

答:
I know this is an old question, but I'd like to share our recent experience with the "SuccessWithWarning" response.

Here was the relevant parts of the paypal response:

```<code>[ACK] => SuccessWithWarning
[L_ERRORCODE0] => 10571
[L_SHORTMESSAGE0] => Transaction approved but with invalid CSC format.
[L_LONGMESSAGE0] => This transaction was approved. However, the Card Security Code provided had too few, too many, or invalid character types but, as per your account option settings, was not required in the approval process.
</code>```

After looking at the long message, we decided that in this instance, it should be handled as a successful transaction.

In the paypal Fraud prevention documentation they give an example of when this might occur, https://developer.paypal.com/docs/classic/fmf/integration-guide/FMFProgramming/#nvp-example, eg: it's waiting for you to review it. They suggest that you do not discard these transactions, but capture them. Put your order in pending, but do NOT automatically ship them.

So, capture the short and long message, but review the message before shipping.

Body:
I know this is an old question, but I'd like to share our recent experience with the "SuccessWithWarning" response.

Here was the relevant parts of the paypal response:

[ACK] => SuccessWithWarning
[L_ERRORCODE0] => 10571
[L_SHORTMESSAGE0] => Transaction approved but with invalid CSC format.
[L_LONGMESSAGE0] => This transaction was approved. However, the Card Security Code provided had too few, too many, or invalid character types but, as per your account option settings, was not required in the approval process.

After looking at the long message, we decided that in this instance, it should be handled as a successful transaction.

In the paypal Fraud prevention documentation they give an example of when this might occur, https://developer.paypal.com/docs/classic/fmf/integration-guide/FMFProgramming/#nvp-example, eg: it's waiting for you to review it. They suggest that you do not discard these transactions, but capture them. Put your order in pending, but do NOT automatically ship them.

So, capture the short and long message, but review the message before shipping.


问:
android 9 patch drawable xml
Is there a way to define a 9 patch drawable in an android xml file?  The reason I ask, is that when you apply a scale animation to a drawable w/ a stroke on it, the stroke appears to thicken.  I'd like to make the stroke stay the same size as the animation plays...</p>

答:
Yes, but this is done mostly to define dithering for the 9-patch.
Here's an example:

```<code><?xml version="1.0" encoding="utf-8"?>
<nine-patch
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/your_drawable_here"
        android:dither="true"
        >
</nine-patch>
</code>```

For more information see the documentation

Title: android 9 patch drawable xml

Body:
Yes, but this is done mostly to define dithering for the 9-patch.
Here's an example:

<?xml version="1.0" encoding="utf-8"?>
<nine-patch
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/your_drawable_here"
        android:dither="true"
        >
</nine-patch>

For more information see the documentation


问:
How to zoom image based off JQuery UI range slide value?
I am trying to zoom in and out of an image based off the value of a JQuery UI slider. I have two issues, one I need to keep the image centered as it zooms in and out. And two, sometimes the image scales smaller when it should be scaling larger. That probably has to do with the math involved, but how can I fix this?

You can see my code here.

Here's my HTML:

```<code><div class="zoom-me">
   <img src="http://theartmad.com/wp-content/uploads/Happy-Fairy-Tail-Wallpaper-5.jpg">
  </div>
</div>
<div id="range5"></div>
</code>```

Here's my CSS:

```<code>img {
   position:absolute;
    left:0;
    right:0;
    margin-left:auto;
    margin-right:auto;
  width:200%;

}
.zoom-me {
  background-color: blue;
    overflow: hidden;
    border: 10px solid white;
    max-width: 400px;
    width: 400px;
    position: relative;
    display: block;
    margin: 0 auto;
    height: 260px;
}
#range5 {
  position: absolute;
  width: 300px;
  top: 75%;
  left: 20%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  border: 0;
  height: 13px;
  -webkit-border-radius: 0%;
  border-radius: 0%;
  background: #e6e7e8;
  outline: none;
}
#range5 .ui-slider-handle{
  position: absolute;
  margin: -18px 0 0 -9px;
  -webkit-border-radius: 0%;
  border-radius: 0%;
  background: #0B5788;
  border: 0;
  height: 20px;
  width: 11px;
  outline: none;
  cursor: pointer;
}
#range5 .ui-slider-range{
  background: #0d78bd;
  height: 13px;
}
</code>```

And here's my JS:

```<code>$('#range5').slider({
    range: 'min',
    max: 500,
    step: 100,
    value: 50,
    slide: function (e, ui) {
        var cv = $('#range5').slider( "value" );
      $('img').animate({
       width: 200 - cv/5 + "%",
       height: 200 - cv/5 + "%"},500);

    }
});
</code>```

答:
https://github.com/timmywil/jquery.panzoom
here is working demos
https://timmywil.github.io/jquery.panzoom/demo/</p>

```<code><section id="panzoom-section">
      <div class="parent">
        <div class="panzoom">
          <img src="image-src" width="900" height="900">
        </div>
      </div>
      <div class="buttons">
        <input type="range" class="zoom-range">
      </div>
      <script>
        (function() {
          var $section = $('#panzoom-section');
          $section.find('.panzoom').panzoom({
            $zoomRange: $section.find(".zoom-range"),
          });
        })();
      </script>
</section>
</code>```

Body:
I am trying to zoom in and out of an image based off the value of a JQuery UI slider. I have two issues, one I need to keep the image centered as it zooms in and out. And two, sometimes the image scales smaller when it should be scaling larger. That probably has to do with the math involved, but how can I fix this?

You can see my code here.

Here's my HTML:

Here's my CSS:

img {
   position:absolute;
    left:0;
    right:0;
    margin-left:auto;
    margin-right:auto;
  width:200%;

}
.zoom-me {
  background-color: blue;
    overflow: hidden;
    border: 10px solid white;
    max-width: 400px;
    width: 400px;
    position: relative;
    display: block;
    margin: 0 auto;
    height: 260px;
}
#range5 {
  position: absolute;
  width: 300px;
  top: 75%;
  left: 20%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  border: 0;
  height: 13px;
  -webkit-border-radius: 0%;
  border-radius: 0%;
  background: #e6e7e8;
  outline: none;
}
#range5 .ui-slider-handle{
  position: absolute;
  margin: -18px 0 0 -9px;
  -webkit-border-radius: 0%;
  border-radius: 0%;
  background: #0B5788;
  border: 0;
  height: 20px;
  width: 11px;
  outline: none;
  cursor: pointer;
}
#range5 .ui-slider-range{
  background: #0d78bd;
  height: 13px;
}

And here's my JS:

$('#range5').slider({
    range: 'min',
    max: 500,
    step: 100,
    value: 50,
    slide: function (e, ui) {
        var cv = $('#range5').slider( "value" );
      $('img').animate({
       width: 200 - cv/5 + "%",
       height: 200 - cv/5 + "%"},500);

    }
});

Body:
https://github.com/timmywil/jquery.panzoom
here is working demos
https://timmywil.github.io/jquery.panzoom/demo/

<section id="panzoom-section">
      <div class="parent">
        <div class="panzoom">
          <img src="image-src" width="900" height="900">
        </div>
      </div>
      <div class="buttons">
        <input type="range" class="zoom-range">
      </div>
      <script>
        (function() {
          var $section = $('#panzoom-section');
          $section.find('.panzoom').panzoom({
            $zoomRange: $section.find(".zoom-range"),
          });
        })();
      </script>
</section>


问:
Low Frequency Terms - Naive Bayes Improving Accuracy
I have thousands of factors (categorical variables) that I am applying a classification on using Naive Bayes.

My problem is that I have many factors that appear very few times in my dataset so it seems they decrease the performance of my prediction.

Indeed, I noticed that if I removed the categorical variables that were happening very few times, I had a signicant improvement of my accuracy. But ideally I would like to keep all my factors, do you know what is the best practice to do so ?

Big Thanks.

答:
This is too long for a comment.

The lowest frequency terms may be adversely affecting the accuracy simply because there is not enough data to make an accurate prediction.  Hence, the observations in the training set may say nothing about the validation set.

You could combine all the lowest frequency observations into a single value.  Off-hand, I don't know what the right threshold is.  You can start by taking everything that occurs 5 or fewer times and lumping them together.