问:
Dependency errors when using Puppeteer (Headless Chrome) with Vue + Webpack
I'm using these two libraries/templates:

https://github.com/GoogleChrome/puppeteer (Headless Chrome)

https://github.com/vuejs-templates/pwa (Vue template using Webpack and Express).

This is the code:

```<code>export default {
  mounted () {
    const puppeteer = require('puppeteer')

    ;(async () => {
      const browser = await puppeteer.launch()
      const page = await browser.newPage()
      await page.goto('https://www.google.com/search?tbm=bks&q=%22this+is%22')
      const result = await page.evaluate(() => {
        const stats = document.querySelector('#resultStats')
        return stats.textContent
      })
      console.log(result)
      await browser.close()
    })()
  }
}
</code>```

I did npm install many times but I still have dependency errors:

These dependencies were not found:

child_process in ./node_modules/puppeteer/lib/Launcher.js, ./node_modules/puppeteer/node6/Launcher.js

fs in ./node_modules/extract-zip/index.js, ./node_modules/extract-zip/node_modules/mkdirp/index.js and 18 others

To install them, you can run: npm install --save child_process fs
  Listening at http://localhost:8080

Node: I also did npm install --save child_process fs many times. Same error.

答: Are you trying to bundle up puppeteer for usage in the browser? It's a node-specific module and I doubt it'll work on the front-end. Instead you might try and understand why this file is being bundled and if that's what you are intending to do.</p>

Body:
I'm using these two libraries/templates:

https://github.com/GoogleChrome/puppeteer (Headless Chrome)

https://github.com/vuejs-templates/pwa (Vue template using Webpack and Express).

This is the code:

export default {
  mounted () {
    const puppeteer = require('puppeteer')

    ;(async () => {
      const browser = await puppeteer.launch()
      const page = await browser.newPage()
      await page.goto('https://www.google.com/search?tbm=bks&q=%22this+is%22')
      const result = await page.evaluate(() => {
        const stats = document.querySelector('#resultStats')
        return stats.textContent
      })
      console.log(result)
      await browser.close()
    })()
  }
}

I did npm install many times but I still have dependency errors:

These dependencies were not found:

child_process in ./node_modules/puppeteer/lib/Launcher.js, ./node_modules/puppeteer/node6/Launcher.js

fs in ./node_modules/extract-zip/index.js, ./node_modules/extract-zip/node_modules/mkdirp/index.js and 18 others

To install them, you can run: npm install --save child_process fs
  Listening at http://localhost:8080

Node: I also did npm install --save child_process fs many times. Same error.


来源: stackexchange

问:
Conditional statement syntax help
I am going through this WPF tutorial http://blogs.vertigo.com/personal/alanl/Blog/Lists/Posts/Post.aspx?ID=18 and I have a question about the CountToFontSizeConverter section of the tutorial. Could someone please explain the return statement to me i.e

```<code>return ((minFontSize + count + increment) < maxFontSize) ?
         (minFontSize + count + increment) : maxFontSize;
</code>```

I understand it's a conditional but the syntax looks rather bespoke. If possible could someone re-write this in a simpler way? Thanks

答:
This is an example of the ternary conditional operator (or simply the conditional operator), and can be rewritten as:</p>

```<code>if ((minFontSize + count + increment) < maxFontSize)
{
  return minFontSize + count + increment;
}

return maxFontSize;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Conditional statement syntax help

Body:
I am going through this WPF tutorial http://blogs.vertigo.com/personal/alanl/Blog/Lists/Posts/Post.aspx?ID=18 and I have a question about the CountToFontSizeConverter section of the tutorial. Could someone please explain the return statement to me i.e

return ((minFontSize + count + increment) < maxFontSize) ?
         (minFontSize + count + increment) : maxFontSize;

I understand it's a conditional but the syntax looks rather bespoke. If possible could someone re-write this in a simpler way? Thanks

Body:
This is an example of the ternary conditional operator (or simply the conditional operator), and can be rewritten as:

if ((minFontSize + count + increment) < maxFontSize)
{
  return minFontSize + count + increment;
}

return maxFontSize;


问:
Trouble with pulling information from data provider/JSON (ionic framework)
I'm still new to angular and ionic, and I'm trying to make a pokedex app. I created a json file with an array of "pocket monsters". As of right now, I'm trying to just pull the information out of the json file and display it, but I'm unsuccessful. When I run the application, it just shows a list with numbers. I'm not sure what I'm doing wrong. Can anyone help out? I'll add the data provider, json file, and the home component and template for reference.

<ion-header>
  <ion-navbar>
    <ion-title>
      Pokedex
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters; let i = index;">
      <ion-label>{{i+1}}</ion-label>
    </ion-item>
   </ion-list>

</ion-content>```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component } from '@angular/core';
import { ModalController, NavController } from 'ionic-angular';

import { pokemonDataService } from '../../providers/data/data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  pocketMonsters = [];
  searchQuery: string = '';

  constructor(public navCtrl: NavController, public dataService: pokemonDataService) {

  }

  ionViewDidLoad() {

           this.dataService.getAllPokemon().then((data) => {

               data.map((pocketMonster) => {

                   return pocketMonster;

               });

               this.pocketMonsters = data;

           });

       }

  //ngOnInit(){
    //this.dataService.getAllPokemon()
      //.subscribe(data => {
        //this.pokemonList = data;
    //});
  //}

}</code>```

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class pokemonDataService {

    data: any;

    constructor(public http: Http) {

    }

    getAllPokemon() {
      if(this.data){
        return Promise.resolve(this.data);
    }

    return new Promise(resolve => {

        this.http.get('assets/data/pokemon.json').map(res => res.json()).subscribe(data => {
            this.data = data.pocketMonsters;
            resolve(this.data);
        });

    });
      }

}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
    "pocketMonsters": [

        {
            "pokemonName" : "Bulbasaur",
            "pokedexNumber" : "001",
            "description": "Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger",
            "pokemonImage" : "<img src='assets/imgs/bulbasaur.png"

        },

        {
            "pokemonName" : "Ivysaur",
            "pokedexNumber" : "002",
            "description" : "",
            "pokemonImage" : "<img src='assets/imgs/ivysaur.png"
        }
    }
 }</code>```

答: I figured out my problem. I can do {{pocketMonster....}} to access what I need from each object. Example: {{pocketMonster.pokemonName}}.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm still new to angular and ionic, and I'm trying to make a pokedex app. I created a json file with an array of "pocket monsters". As of right now, I'm trying to just pull the information out of the json file and display it, but I'm unsuccessful. When I run the application, it just shows a list with numbers. I'm not sure what I'm doing wrong. Can anyone help out? I'll add the data provider, json file, and the home component and template for reference.

<ion-header>
  <ion-navbar>
    <ion-title>
      Pokedex
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters; let i = index;">
      <ion-label>{{i+1}}</ion-label>
    </ion-item>
   </ion-list>

</ion-content>

import { Component } from '@angular/core';
import { ModalController, NavController } from 'ionic-angular';

import { pokemonDataService } from '../../providers/data/data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  pocketMonsters = [];
  searchQuery: string = '';

  constructor(public navCtrl: NavController, public dataService: pokemonDataService) {

  }

  ionViewDidLoad() {

           this.dataService.getAllPokemon().then((data) => {

               data.map((pocketMonster) => {

                   return pocketMonster;

               });

               this.pocketMonsters = data;

           });

       }

  //ngOnInit(){
    //this.dataService.getAllPokemon()
      //.subscribe(data => {
        //this.pokemonList = data;
    //});
  //}

}

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class pokemonDataService {

    data: any;

    constructor(public http: Http) {

    }

    getAllPokemon() {
      if(this.data){
        return Promise.resolve(this.data);
    }

    return new Promise(resolve => {

        this.http.get('assets/data/pokemon.json').map(res => res.json()).subscribe(data => {
            this.data = data.pocketMonsters;
            resolve(this.data);
        });

    });
      }

}

{
    "pocketMonsters": [

        {
            "pokemonName" : "Bulbasaur",
            "pokedexNumber" : "001",
            "description": "Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger",
            "pokemonImage" : "<img src='assets/imgs/bulbasaur.png"

        },

        {
            "pokemonName" : "Ivysaur",
            "pokedexNumber" : "002",
            "description" : "",
            "pokemonImage" : "<img src='assets/imgs/ivysaur.png"
        }
    }
 }


问:
javascript - missing array
I need to write a JS function that creates an object from a given string. String characters are object keys. Repeated characters should not be included twice. Values of all keys are zero.

Example: input objFromStr("aaabc") should return {a: 0, b: 0, c: 0}

Here is my solution:

```<code>function objFromStr(inStr) {
  let charsArr = inStr.split("");

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  return charsObj;
}
</code>```

This solution works as expected, but I don't understand why.
I check chars duplication using alreadyInArr. However when I log my alreadyInArr, it's empty.

So after running this code:

```<code>function objFromStr(inStr) {
  let charsArr = inStr.split("");

  console.log("charsArr is:", charsArr);

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  console.log("alreadyInArr is:", alreadyInArr);

  return charsObj;
}

console.log(objFromStr("aaabc"));
</code>```

My output is:

```<code>charsArr is: [ 'a', 'a', 'a', 'b', 'c' ]
alreadyInArr is: []
{ a: 0, b: 0, c: 0 }
</code>```

Can someone explain, why alreadyInArr is empty and yet function still works as expected?

Here's a pen: https://codepen.io/t411tocreate/pen/bYReRj?editors=0012

答:
You could spread the carcters and map the objects with the wanted properties.

function objFromStr(inStr) {
    return Object.assign(...Array.from(inStr, k => ({ [k]: 0 })));
}

console.log(objFromStr('aaaabbc'));```

Title: javascript - missing array

Body:
I need to write a JS function that creates an object from a given string. String characters are object keys. Repeated characters should not be included twice. Values of all keys are zero.

Example: input objFromStr("aaabc") should return {a: 0, b: 0, c: 0}

Here is my solution:

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  return charsObj;
}

This solution works as expected, but I don't understand why.
I check chars duplication using alreadyInArr. However when I log my alreadyInArr, it's empty.

So after running this code:

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  console.log("charsArr is:", charsArr);

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  console.log("alreadyInArr is:", alreadyInArr);

  return charsObj;
}

console.log(objFromStr("aaabc"));

My output is:

charsArr is: [ 'a', 'a', 'a', 'b', 'c' ]
alreadyInArr is: []
{ a: 0, b: 0, c: 0 }

Can someone explain, why alreadyInArr is empty and yet function still works as expected?

Here's a pen: https://codepen.io/t411tocreate/pen/bYReRj?editors=0012


问:
Laravel Controller use same object in two functions
Is there a way to use a object variable instantiated from a class in two functions?

Here's the code I've tried, but its just returning null:

```<code>class bookAppointmentsController extends APIController
{
    private $business;

    public funcition check($key)
    {
        $this->business = new APIClass();
        $setconnection = $this->business->connectAPI($key);
    }

    public function book()
    {
        dd($this->business) //returns null
        $this->business->book();
    }
}
</code>```

I am trying to use the $business object in two functions but it does not work, when I dd($business) it returns null

Any way to do this?

答:
Move the instantiation to the constructor:

```<code>public function __construct(APIClass $business)
{
    $this->business = $business;
}
</code>```

However, it would be better if you make Laravel do the heavy lifting and prepare the APIClass for you.

In your AppServicePorvider under the register method, you can create the APIClass

```<code>/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
  $this->app->bind('APIClass', function ($app) {
        $api = new APIClass();
        // Do any logic required to prepare and check the api
        $key = config('API_KEY');
        $api->connectAPI($key);
        return $api;
    });

}
</code>```

Check the documentations for more details.

Body:
Is there a way to use a object variable instantiated from a class in two functions?

Here's the code I've tried, but its just returning null:

class bookAppointmentsController extends APIController
{
    private $business;

    public funcition check($key)
    {
        $this->business = new APIClass();
        $setconnection = $this->business->connectAPI($key);
    }

    public function book()
    {
        dd($this->business) //returns null
        $this->business->book();
    }
}

I am trying to use the $business object in two functions but it does not work, when I dd($business) it returns null

Any way to do this?

Body:
Move the instantiation to the constructor:

public function __construct(APIClass $business)
{
    $this->business = $business;
}

However, it would be better if you make Laravel do the heavy lifting and prepare the APIClass for you.

In your AppServicePorvider under the register method, you can create the APIClass

/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
  $this->app->bind('APIClass', function ($app) {
        $api = new APIClass();
        // Do any logic required to prepare and check the api
        $key = config('API_KEY');
        $api->connectAPI($key);
        return $api;
    });

}

Check the documentations for more details.


问:
constexpr expression and variable lifetime, an example where g++ and clang disagree
Consider the simple C++11 code:

```<code>template<int N>
struct Foo {};

template <int N>
constexpr int size(const Foo<N>&) { return N; }

template <int N>
void use_size(const Foo<N>& foo) { constexpr int n = size(foo); }

int main()
{
    Foo<5> foo;

    constexpr int x = size(foo);  // works with gcc and clang
                                  // _but_
    use_size(foo);                // the same statement in the use_size()
                                  // function _only_ works for gcc
}
</code>```

I can successfuly compile it with g++ -std=c++11 foo.cpp

however if I use clang++, clang++ -std=c++11 foo.cpp I get

```<code>foo.cpp:15:28: error: constexpr variable 'n' must be initialized by a constant expression
void use_size(const Foo<N>& foo) { constexpr int n = size(foo); }
                                                     ~~~~~^~~~
foo.cpp:23:5: note: in instantiation of function template specialization 'use_size<5>' requested here
    use_size(foo);                // the same statement in the use_size()
    ^
1 error generated.
</code>```

(nb: compiler versions. I have checked the previous statement with g++ version 5.3.1 and 7.2.1 and with clang++ version 3.6.2 and 5.0.0)

My question: which of g++ or clang is right? What is the problem?

答:
My interpretation is that clang++ is right and g++ is too permissive.

We can find a close example ([expr.const] section, page 126) in the standard https://isocpp.org/std/the-standard (draft can be downloaded, attention big PDF! ).

```<code>constexpr int g(int k) {
    constexpr int x = incr(k);

    return x;
}
</code>```

where it is explained that:

error: incr(k) is not a core constant expression because
  lifetime of k began outside the expression incr(k)

This is exactly what is happening in the use_size() function with the foo argument, even if the size() function only use the N template parameter.

```<code>template <int N>
constexpr int size(const Foo<N>&) { return N; }

template <int N>
void use_size(const Foo<N>& foo) { constexpr int n = size(foo); }
</code>```

Body:
Consider the simple C++11 code:

template<int N>
struct Foo {};

template <int N>
constexpr int size(const Foo<N>&) { return N; }

template <int N>
void use_size(const Foo<N>& foo) { constexpr int n = size(foo); }

int main()
{
    Foo<5> foo;

    constexpr int x = size(foo);  // works with gcc and clang
                                  // _but_
    use_size(foo);                // the same statement in the use_size()
                                  // function _only_ works for gcc
}

I can successfuly compile it with g++ -std=c++11 foo.cpp

however if I use clang++, clang++ -std=c++11 foo.cpp I get

foo.cpp:15:28: error: constexpr variable 'n' must be initialized by a constant expression
void use_size(const Foo<N>& foo) { constexpr int n = size(foo); }
                                                     ~~~~~^~~~
foo.cpp:23:5: note: in instantiation of function template specialization 'use_size<5>' requested here
    use_size(foo);                // the same statement in the use_size()
    ^
1 error generated.

(nb: compiler versions. I have checked the previous statement with g++ version 5.3.1 and 7.2.1 and with clang++ version 3.6.2 and 5.0.0)

My question: which of g++ or clang is right? What is the problem?

Body:
My interpretation is that clang++ is right and g++ is too permissive.

We can find a close example ([expr.const] section, page 126) in the standard https://isocpp.org/std/the-standard (draft can be downloaded, attention big PDF! ).

constexpr int g(int k) {
    constexpr int x = incr(k);

    return x;
}

where it is explained that:

error: incr(k) is not a core constant expression because
  lifetime of k began outside the expression incr(k)

This is exactly what is happening in the use_size() function with the foo argument, even if the size() function only use the N template parameter.

template <int N>
constexpr int size(const Foo<N>&) { return N; }

template <int N>
void use_size(const Foo<N>& foo) { constexpr int n = size(foo); }


答:
Not sure what you mean by "somewhat bespoke" but it's worth breaking down.

Original:

```<code>return ((minFontSize + count + increment) < maxFontSize)
      ? (minFontSize + count + increment) : maxFontSize;
</code>```

Broken down:

```<code>bool condition = (minFontSize + count + increment) < maxFontSize;
if (condition)
{
    return minFontSize + count + increment;
}
else
{
    return maxFontSize;
}
</code>```

Better approach - far more readable:

```<code>return Math.Min(minFontSize + count + increment, maxFontSize);
</code>```

In general, you can usually replace an expression of the form

```<code>a < b ? a : b
</code>```

with

```<code>Math.Min(a, b)
</code>```

assuming that a and b are of numeric types. It's not always the case, but it's a good starting point.

Title: Conditional statement syntax help

Body:
Not sure what you mean by "somewhat bespoke" but it's worth breaking down.

Original:

return ((minFontSize + count + increment) < maxFontSize)
      ? (minFontSize + count + increment) : maxFontSize;

Broken down:

bool condition = (minFontSize + count + increment) < maxFontSize;
if (condition)
{
    return minFontSize + count + increment;
}
else
{
    return maxFontSize;
}

Better approach - far more readable:

return Math.Min(minFontSize + count + increment, maxFontSize);

In general, you can usually replace an expression of the form

a < b ? a : b

with

Math.Min(a, b)

assuming that a and b are of numeric types. It's not always the case, but it's a good starting point.


问:
How to style SVG shadow root in Chrome?
I've recently finished up a website and it's running nicely in Firefox. Chrome has problems with the SVG elements on my site however.

This is how I display SVGs on my site. With -use- it's basically treated like inline SVG, but it doesn't clutter my HTML with vector data and can be stowed away nicely in an external file.

```<code><svg viewBox="0 0 120 120"><use xlink:href="img/skills.svg#De"></use></svg>
</code>```

This is one of the icons in my SVG file.

```<code><g id="De">
    <circle cx="60" cy="60" r="50" fill="none" stroke="#90938F" stroke-width="19"/>
    <circle class="SKlevel" cx="60" cy="60" r="50" fill="none"/>
    <path d="M60 10.2C38.4 10.2 20.1 23 13.1 43h93.9C99.9 23 81.6 10.2 60 10.2z"/>
    <path d="M10 59.8C10 66 11.1 72 13.2 77h93.6c2.1-5 3.2-11 3.2-17.2 0-6-1.1-11.8-3-16.8h-93.9C11.1 48 10 53.8 10 59.8z" fill="#FC0000"/>
    <path d="M60 109.4c21.4 0 39.7-13.4 46.8-32.4H13.2C20.3 96 38.6 109.4 60 109.4z" fill="#FC0"/>
  </g>
</code>```

This is the styling for the 'progress bars' that wrap around the icons.

```<code>.SKlevel
{
    transform-origin: 50% 50%;
    transform: rotate(-90deg);
    stroke: #2E8B57;
    stroke-width: 20px;
    stroke-dasharray: 316;
}
</code>```

And this is to set the progress to a specific level which I have outsurced from my main CSS for ease of use.

```<code>#De > .SKlevel
{
    stroke-dashoffset: 30;
}
</code>```

This is what an icon on my site looks like.

https://i.stack.imgur.com/Sq832.jpg

Chrome doesn't accept the styling of the external 'SKlevel' class like Firefox does and I can't seem to figure out how to style anything in the shadow root. It doesn't work on other classes or IDs either.

答:
While I can see that it works in Firefox, it is in violation of the spec:

...elements in the shadow tree inherit styles from its host ‘use’ element, but...style rules defined in the outer document do not match the elements in the shadow tree.

This should not work.

A standard-conformant version should have the stylesheet with the .SKlevel selector as part of the skills.svg file. Unfortunately, the stylesheet seems not to be applied to externally re-used elements. Again, the spec is not implemented - in this case both by Firefox and Chrome. I got it only to work if the style was stated as a style attribute directly on the <circle> element. If every icon shows the same "progress" ring, you can avoid repeating it for each of them like this:

```<code><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <circle id="progress" cx="60" cy="60" r="50" fill="none"  transform="rotate(-90 60 60)"
            style="stroke:#2E8B57;stroke-width:20;stroke-dasharray:316;"/>
  </defs>
  <g id="De">
    <circle cx="60" cy="60" r="50" fill="none" stroke="#90938F" stroke-width="19"/>
    <use xlink:href="#progress" />
    <path d="M60 10.2C38.4 10.2 20.1 23 13.1 43h93.9C99.9 23 81.6 10.2 60 10.2z"/>
    <path d="M10 59.8C10 66 11.1 72 13.2 77h93.6c2.1-5 3.2-11 3.2-17.2 0-6-1.1-11.8-3-16.8h-93.9C11.1 48 10 53.8 10 59.8z" fill="#FC0000"/>
    <path d="M60 109.4c21.4 0 39.7-13.4 46.8-32.4H13.2C20.3 96 38.6 109.4 60 109.4z" fill="#FC0"/>
  </g>
</svg>
</code>```

Then, you can apply the stroke-dashoffset to the <use> element. It will be inherited by each element in the shadow tree, but since only the one <circle> element (in the second-level shadow tree) has a stroke-dasharray, it has no effect on any other element:

```<code><style>
.SKDe {
    stroke-dashoffset: 30;
}
</style>
<svg viewBox="0 0 120 120"><use class="SKDe" xlink:href="img/skills.svg#De"></use></svg>
</code>```

Title: How to style SVG shadow root in Chrome?

Body:
I've recently finished up a website and it's running nicely in Firefox. Chrome has problems with the SVG elements on my site however.

This is how I display SVGs on my site. With -use- it's basically treated like inline SVG, but it doesn't clutter my HTML with vector data and can be stowed away nicely in an external file.

<svg viewBox="0 0 120 120"><use xlink:href="img/skills.svg#De"></use></svg>

This is one of the icons in my SVG file.

<g id="De">
    <circle cx="60" cy="60" r="50" fill="none" stroke="#90938F" stroke-width="19"/>
    <circle class="SKlevel" cx="60" cy="60" r="50" fill="none"/>
    <path d="M60 10.2C38.4 10.2 20.1 23 13.1 43h93.9C99.9 23 81.6 10.2 60 10.2z"/>
    <path d="M10 59.8C10 66 11.1 72 13.2 77h93.6c2.1-5 3.2-11 3.2-17.2 0-6-1.1-11.8-3-16.8h-93.9C11.1 48 10 53.8 10 59.8z" fill="#FC0000"/>
    <path d="M60 109.4c21.4 0 39.7-13.4 46.8-32.4H13.2C20.3 96 38.6 109.4 60 109.4z" fill="#FC0"/>
  </g>

This is the styling for the 'progress bars' that wrap around the icons.

.SKlevel
{
    transform-origin: 50% 50%;
    transform: rotate(-90deg);
    stroke: #2E8B57;
    stroke-width: 20px;
    stroke-dasharray: 316;
}

And this is to set the progress to a specific level which I have outsurced from my main CSS for ease of use.

#De > .SKlevel
{
    stroke-dashoffset: 30;
}

This is what an icon on my site looks like.

https://i.stack.imgur.com/Sq832.jpg

Chrome doesn't accept the styling of the external 'SKlevel' class like Firefox does and I can't seem to figure out how to style anything in the shadow root. It doesn't work on other classes or IDs either.

Body:
While I can see that it works in Firefox, it is in violation of the spec:

...elements in the shadow tree inherit styles from its host ‘use’ element, but...style rules defined in the outer document do not match the elements in the shadow tree.

This should not work.

A standard-conformant version should have the stylesheet with the .SKlevel selector as part of the skills.svg file. Unfortunately, the stylesheet seems not to be applied to externally re-used elements. Again, the spec is not implemented - in this case both by Firefox and Chrome. I got it only to work if the style was stated as a style attribute directly on the <circle> element. If every icon shows the same "progress" ring, you can avoid repeating it for each of them like this:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <circle id="progress" cx="60" cy="60" r="50" fill="none"  transform="rotate(-90 60 60)"
            style="stroke:#2E8B57;stroke-width:20;stroke-dasharray:316;"/>
  </defs>
  <g id="De">
    <circle cx="60" cy="60" r="50" fill="none" stroke="#90938F" stroke-width="19"/>
    <use xlink:href="#progress" />
    <path d="M60 10.2C38.4 10.2 20.1 23 13.1 43h93.9C99.9 23 81.6 10.2 60 10.2z"/>
    <path d="M10 59.8C10 66 11.1 72 13.2 77h93.6c2.1-5 3.2-11 3.2-17.2 0-6-1.1-11.8-3-16.8h-93.9C11.1 48 10 53.8 10 59.8z" fill="#FC0000"/>
    <path d="M60 109.4c21.4 0 39.7-13.4 46.8-32.4H13.2C20.3 96 38.6 109.4 60 109.4z" fill="#FC0"/>
  </g>
</svg>

Then, you can apply the stroke-dashoffset to the <use> element. It will be inherited by each element in the shadow tree, but since only the one <circle> element (in the second-level shadow tree) has a stroke-dasharray, it has no effect on any other element:

<style>
.SKDe {
    stroke-dashoffset: 30;
}
</style>
<svg viewBox="0 0 120 120"><use class="SKDe" xlink:href="img/skills.svg#De"></use></svg>


问:
Gtk Window Non-Responsive During Selenium Automation
Good Afternoon :) Having a problem with my Python3 Gtk3 application and Selenium WebDriver (ChromeDriver). Also, using Linux if it matters.

Basically, the user presses a button to start the Selenium webdriver automation and then as the automation process is going, it 'SHOULD' give feedback to the user in the GUI (See Content.content_liststore.append(list(item)) and LogBox.log_text_buffer).

However, it's not adding anything into the content_liststore until after fb_driver.close() is done. In the meantime, the Gtk window just "hangs".

Now, I've been looking into multithreading in hopes of the GUI being responsive to this feedback but I've also been reading that Selenium doesn't like multithreading (but I presume thats running multiple browsers/tabs (which this is not)).

So, my question is; Is multithreading the go-to fix for getting this to work?

```<code>            # ELSE IF, FACEBOOK COOKIES DO NOT EXIST, PROCEED TO LOGIN PAGE
            elif os.stat('facebook_cookies').st_size == 0:
                while True:
                    try: # look for element, if not found, refresh the webpage
                        assert "Facebook" in fb_driver.title
                        login_elem = fb_driver.find_element_by_id("m_login_email")
                        login_elem.send_keys(facebook_username)
                        login_elem = fb_driver.find_element_by_id("m_login_password")
                        login_elem.send_keys(facebook_password)
                        login_elem.send_keys(Keys.RETURN)
                    except ElementNotVisibleException:
                        fb_driver.refresh()
                        StatusBar.status_bar.push(StatusBar.context_id, "m_login_password element not found, trying again...")
                        ProblemsLog.text_buffer.set_text("Facebook has hidden the password field, refreshing page...")
                    else:
                        query_elem = fb_driver.find_element_by_name("query")
                        query_elem.send_keys(target)
                        query_elem.send_keys(Keys.RETURN)
                        break

                m_facebook_url_remove = "query="
                m_facebook_url = fb_driver.current_url.split(m_facebook_url_remove, 1)[1] # Remove string before "query="
                facebook_url = "https://www.facebook.com/search/top/?q=" + m_facebook_url # Merge left-over string with the desktop url

                StatusBar.status_bar.push(StatusBar.context_id, "Facebook elements found")
                fb_title = fb_driver.title
                fb_contents = [(target_name.title(), "Facebook", facebook_url)]
                for item in fb_contents:
                    Content.content_liststore.append(list(item))
                #progress_bar.set_fraction(0.10)
                LogBox.log_text_buffer.set_text("Facebook Search Complete")

                with open('facebook_cookies', 'wb') as filehandler:
                    pickle.dump(fb_driver.get_cookies(), filehandler)

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

I've considered it not working because of the 'while' loop, but another piece of code doesn't have a loop and does the exact same thing, it waits for Selenium to finish before adding content to the GUI.

Additionally, the user can select multiple websites to do this with, so the application can first go to Facebook (do it's business then close), go to LinkedIn (do it's business then close) and so fourth. And it still waits for all the Selenium code to finish before adding anything to the Gtk GUI.

I really hope that makes sense! Thank you :)

答: Your`s question is the answer you are lookig for. Take a read here https://wiki.gnome.org/Projects/PyGObject/Threading</p>

Body:
Good Afternoon :) Having a problem with my Python3 Gtk3 application and Selenium WebDriver (ChromeDriver). Also, using Linux if it matters.

Basically, the user presses a button to start the Selenium webdriver automation and then as the automation process is going, it 'SHOULD' give feedback to the user in the GUI (See Content.content_liststore.append(list(item)) and LogBox.log_text_buffer).

However, it's not adding anything into the content_liststore until after fb_driver.close() is done. In the meantime, the Gtk window just "hangs".

Now, I've been looking into multithreading in hopes of the GUI being responsive to this feedback but I've also been reading that Selenium doesn't like multithreading (but I presume thats running multiple browsers/tabs (which this is not)).

So, my question is; Is multithreading the go-to fix for getting this to work?

            # ELSE IF, FACEBOOK COOKIES DO NOT EXIST, PROCEED TO LOGIN PAGE
            elif os.stat('facebook_cookies').st_size == 0:
                while True:
                    try: # look for element, if not found, refresh the webpage
                        assert "Facebook" in fb_driver.title
                        login_elem = fb_driver.find_element_by_id("m_login_email")
                        login_elem.send_keys(facebook_username)
                        login_elem = fb_driver.find_element_by_id("m_login_password")
                        login_elem.send_keys(facebook_password)
                        login_elem.send_keys(Keys.RETURN)
                    except ElementNotVisibleException:
                        fb_driver.refresh()
                        StatusBar.status_bar.push(StatusBar.context_id, "m_login_password element not found, trying again...")
                        ProblemsLog.text_buffer.set_text("Facebook has hidden the password field, refreshing page...")
                    else:
                        query_elem = fb_driver.find_element_by_name("query")
                        query_elem.send_keys(target)
                        query_elem.send_keys(Keys.RETURN)
                        break

                m_facebook_url_remove = "query="
                m_facebook_url = fb_driver.current_url.split(m_facebook_url_remove, 1)[1] # Remove string before "query="
                facebook_url = "https://www.facebook.com/search/top/?q=" + m_facebook_url # Merge left-over string with the desktop url

                StatusBar.status_bar.push(StatusBar.context_id, "Facebook elements found")
                fb_title = fb_driver.title
                fb_contents = [(target_name.title(), "Facebook", facebook_url)]
                for item in fb_contents:
                    Content.content_liststore.append(list(item))
                #progress_bar.set_fraction(0.10)
                LogBox.log_text_buffer.set_text("Facebook Search Complete")

                with open('facebook_cookies', 'wb') as filehandler:
                    pickle.dump(fb_driver.get_cookies(), filehandler)

                fb_driver.close()

I've considered it not working because of the 'while' loop, but another piece of code doesn't have a loop and does the exact same thing, it waits for Selenium to finish before adding content to the GUI.

Additionally, the user can select multiple websites to do this with, so the application can first go to Facebook (do it's business then close), go to LinkedIn (do it's business then close) and so fourth. And it still waits for all the Selenium code to finish before adding anything to the Gtk GUI.

I really hope that makes sense! Thank you :)


问:
Email trigger and reply email on Jenkins
There some way to trigger a build on Jenkins with e-mail and after the end of the job, the jenkins reply automatically this e-mail to the email sender?</p>

答: Solve the problem using Mail commander plugin</p>


问:
FP alternative to polymorphism in JavaScript/ReactJS
I'm currently working on a ReactJS project where I need to create "re-usable" components in which some of the methods would need to be "overridden". In OOP I would use polymorphism. I've done some reading and it seems the consensus is to use HoC/composition but I can't quite figure out how to achieve this. I figure if I could just get a ES6 sample using composition it would maybe be easier to adapt the idea to ReactJS afterwards.

Below is a ES6 OOP example (ignore the event handling it's just for testing) of pretty much what I would like to achieve in ReactJS. Does anyone have some guidance on how to break up a ReactJS component into a HoC or even just demonstrate how I would go about using composition in ES6 based on the example?

class TransferComponent {
    constructor(){
        let timeout = null;

        this.render();
        this.events();
    }

    events(){
        let scope = this;

        document.getElementById('button').addEventListener('click', function(){
            scope.validate.apply(scope);
        });
    }

    validate(){
        if(this.isValid()){
            this.ajax();
        }
    }

    isValid(){
        if(document.getElementById('username').value !== ''){
            return true;
        }

        return false;
    }

    ajax(){
        clearTimeout(this.timeout);

        document.getElementById('message').textContent = 'Loading...';

        this.timeout = setTimeout(function(){
            document.getElementById('message').textContent = 'Success';
        }, 500);
    }

    render(){
        document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
            <button id="button" type="button">Validate</button>';
    }
}

class OverrideTransferComponent extends TransferComponent{
    isValid(){
        if(document.getElementById('username').value !== '' && document.getElementById('password').value !== ''){
            return true;
        }

        return false;
    }

    render(){
        document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
            <input type="text" id="password" value="password"/>\n\
            <button id="button" type="button">Validate</button>';
    }
}

const overrideTransferComponent = new OverrideTransferComponent();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content"></div>
<div id="message"></div></code>```

UPDATE:
Even though my original question was around FP I think render props is a really good solution to my issue and avoids the HoC issues.

答:
Reading your question, it's not clear if you are referring to composition or inheritance, but they are different OOP concepts. I recommend you to take a look at this article if you don't know the difference between them.

About your specific problem with React. I'd recommend you to try to user composition since it gives you a lot of flexibility to build your UI and pass props around.

If you are working with React you are probably already using composition when you populate Dialogs dynamically, for example. As the React docs shows:

```<code>function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}

function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        Welcome
      </h1>
      <p className="Dialog-message">
        Thank you for visiting our spacecraft!
      </p>
    </FancyBorder>
  );
}
</code>```

Folks at Facebook have been developing very challenging UIs and building thousand of components with React and didn't find a good use case for inheritance over composition. As the docs says:

React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components.

If you really want to use inheritance, their recommendation is that you extract the functionality that you want to reuse over components into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it.

In the example you provided, two functions in a utils.js would do just fine. See:

```<code>isUsernameValid = (username) => username !== '';

isPasswordValid = (password) => password !== '';
</code>```

You can import them and use in your components just fine.

Body:
I'm currently working on a ReactJS project where I need to create "re-usable" components in which some of the methods would need to be "overridden". In OOP I would use polymorphism. I've done some reading and it seems the consensus is to use HoC/composition but I can't quite figure out how to achieve this. I figure if I could just get a ES6 sample using composition it would maybe be easier to adapt the idea to ReactJS afterwards.

Below is a ES6 OOP example (ignore the event handling it's just for testing) of pretty much what I would like to achieve in ReactJS. Does anyone have some guidance on how to break up a ReactJS component into a HoC or even just demonstrate how I would go about using composition in ES6 based on the example?

class TransferComponent {
    constructor(){
        let timeout = null;

        this.render();
        this.events();
    }

    events(){
        let scope = this;

        document.getElementById('button').addEventListener('click', function(){
            scope.validate.apply(scope);
        });
    }

    validate(){
        if(this.isValid()){
            this.ajax();
        }
    }

    isValid(){
        if(document.getElementById('username').value !== ''){
            return true;
        }

        return false;
    }

    ajax(){
        clearTimeout(this.timeout);

        document.getElementById('message').textContent = 'Loading...';

        this.timeout = setTimeout(function(){
            document.getElementById('message').textContent = 'Success';
        }, 500);
    }

    render(){
        document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
            <button id="button" type="button">Validate</button>';
    }
}

class OverrideTransferComponent extends TransferComponent{
    isValid(){
        if(document.getElementById('username').value !== '' && document.getElementById('password').value !== ''){
            return true;
        }

        return false;
    }

    render(){
        document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
            <input type="text" id="password" value="password"/>\n\
            <button id="button" type="button">Validate</button>';
    }
}

const overrideTransferComponent = new OverrideTransferComponent();

UPDATE:
Even though my original question was around FP I think render props is a really good solution to my issue and avoids the HoC issues.

Body:
Reading your question, it's not clear if you are referring to composition or inheritance, but they are different OOP concepts. I recommend you to take a look at this article if you don't know the difference between them.

About your specific problem with React. I'd recommend you to try to user composition since it gives you a lot of flexibility to build your UI and pass props around.

If you are working with React you are probably already using composition when you populate Dialogs dynamically, for example. As the React docs shows:

function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}

function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        Welcome
      </h1>
      <p className="Dialog-message">
        Thank you for visiting our spacecraft!
      </p>
    </FancyBorder>
  );
}

Folks at Facebook have been developing very challenging UIs and building thousand of components with React and didn't find a good use case for inheritance over composition. As the docs says:

React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components.

If you really want to use inheritance, their recommendation is that you extract the functionality that you want to reuse over components into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it.

In the example you provided, two functions in a utils.js would do just fine. See:

isUsernameValid = (username) => username !== '';

isPasswordValid = (password) => password !== '';

You can import them and use in your components just fine.


问:
Calling a python script with input within a python script using subprocess
I have a script a.py and while executing it will ask certain queries to user and frame the output in json format. Using python subprocess, I am able to call this script from another script named b.py. Everything is working as expected except that I am not able to get the output in a variable? I am doing this in Python 3.

答:
Another way than mentioned, is by using the built-in funtion exec

This function gets a string of python code and executes it

To use it on a script file, you can simply read it as a text file, as such:

```<code>#dir is the directory of a.py
#a.py, for example, contains the variable 'x=1'
exec(open(dir+'\\a.py').read())
print(x) #outputs 1
</code>```

Body:
Another way than mentioned, is by using the built-in funtion exec

This function gets a string of python code and executes it

To use it on a script file, you can simply read it as a text file, as such:

#dir is the directory of a.py
#a.py, for example, contains the variable 'x=1'
exec(open(dir+'\\a.py').read())
print(x) #outputs 1


问:
Documentation about writing a CoreCLR host in c++
I'm writing a CoreCLR host in c++.

I'have succesfully called a c# function from a c++:
https://learn.microsoft.com/en-us/dotnet/core/tutorials/netcore-hosting

Reading that documentation:

Another option, if ExecuteAssembly doesn't meet your host's needs, is
  to use CreateDelegate to create a function pointer to a static managed
  method. This requires the host to know the signature of the method it
  is calling into (in order to create the function pointer type) but
  allows hosts the flexibility to invoke code other than an assembly's
  entry point.

given a c# function how can I "create the c++ function pointer type"

for example, for a function like this:

```<code>public static int withParams(int aNumber, string[] args)
</code>```

are there some marshaling/unmarshaling rules, how do I behave with objects or arrays as parameters?

Is there a decent ufficial documentation for embedding coreclr in c++ code?

I look for something like this (but for coreclr):
http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html

答:
I think the documentation contains the code you need.

```<code>void *pfnDelegate = NULL;
hr = runtimeHost->CreateDelegate(
  domainId,
  L"HW, Version=1.0.0.0, Culture=neutral",  // Target managed assembly
  L"ConsoleApplication.Program",            // Target managed type
  L"Main",                                  // Target entry point (static method)
  (INT_PTR*)&pfnDelegate);

((MainMethodFp*)pfnDelegate)(NULL);
</code>```

I created a class in a dotnet core dll and able to call it from cpp as follows.

```<code>void *pfnDelegate = NULL;
hr = runtimeHost->CreateDelegate(
    domainId,
    L"SampleAppCore",  // Target managed assembly
    L"SampleAppCore.Start", // Target managed type
    L"Run",                 // Target entry point (static method)
    (INT_PTR*)&pfnDelegate);
if (FAILED(hr))
{
    printf("ERROR - Failed to execute %s.\nError code:%x\n", targetApp, hr);
    return -1;
}

char* hello = "hello ";

((MainMethodFp*)pfnDelegate)(hello);
</code>```

Format of the delegate

```<code>typedef void (STDMETHODCALLTYPE MainMethodFp)(char* args);
</code>```

Core Class

```<code>using System;
namespace SampleAppCore
{

    public static class Start{

        public static void Run(string input){

            Console.WriteLine(input);
        }

    }
}
</code>```

Body:
I'm writing a CoreCLR host in c++.

I'have succesfully called a c# function from a c++:
https://learn.microsoft.com/en-us/dotnet/core/tutorials/netcore-hosting

Reading that documentation:

Another option, if ExecuteAssembly doesn't meet your host's needs, is
  to use CreateDelegate to create a function pointer to a static managed
  method. This requires the host to know the signature of the method it
  is calling into (in order to create the function pointer type) but
  allows hosts the flexibility to invoke code other than an assembly's
  entry point.

given a c# function how can I "create the c++ function pointer type"

for example, for a function like this:

public static int withParams(int aNumber, string[] args)

are there some marshaling/unmarshaling rules, how do I behave with objects or arrays as parameters?

Is there a decent ufficial documentation for embedding coreclr in c++ code?

I look for something like this (but for coreclr):
http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html

Body:
I think the documentation contains the code you need.

void *pfnDelegate = NULL;
hr = runtimeHost->CreateDelegate(
  domainId,
  L"HW, Version=1.0.0.0, Culture=neutral",  // Target managed assembly
  L"ConsoleApplication.Program",            // Target managed type
  L"Main",                                  // Target entry point (static method)
  (INT_PTR*)&pfnDelegate);

((MainMethodFp*)pfnDelegate)(NULL);

I created a class in a dotnet core dll and able to call it from cpp as follows.

void *pfnDelegate = NULL;
hr = runtimeHost->CreateDelegate(
    domainId,
    L"SampleAppCore",  // Target managed assembly
    L"SampleAppCore.Start", // Target managed type
    L"Run",                 // Target entry point (static method)
    (INT_PTR*)&pfnDelegate);
if (FAILED(hr))
{
    printf("ERROR - Failed to execute %s.\nError code:%x\n", targetApp, hr);
    return -1;
}

char* hello = "hello ";

((MainMethodFp*)pfnDelegate)(hello);

Format of the delegate

typedef void (STDMETHODCALLTYPE MainMethodFp)(char* args);

Core Class

using System;
namespace SampleAppCore
{

    public static class Start{

        public static void Run(string input){

            Console.WriteLine(input);
        }

    }
}


问:
How to build a specific version of Chromium?
I want to build the latest stable version of Chromium (62.0.3202.84 at the time of writing, see OmahaProxy).

The build instructions work just fine for the current development version.

From this question, the Brave wiki and some other sources, the instructions to fetch and build a specific version seem to be pretty clear :

git fetch origin 62.0.3202.84
git checkout -b my_stable_branch FETCH_HEAD
# hooks and dependencies if needed, commits, compilation...
```

<p>However, this does <strong>not</strong> seem to work for me. When I create a branch for <code>FETCH_HEAD</code>, a quick <code>git log</code> shows that I have the latest commits from <code>master</code>.</p>

<p>What am I misunderstanding ?</p>

<p><strong>EDIT</strong>:</p>

<p>If I do the steps from Asesh's answer from <code>master</code>, it runs “successfully” but I still end up building <code>master</code> instead of what I want.</p>

<p>If I first create a branch from a specific tag (as specified in the Chromium documentation), like <code>62.0.3202.84</code>, or even if I just check it out without branching, <code>gclient sync --with_branch_heads</code> fails giving me the following error :</p>

```Error: Command 'git checkout --quiet 6e4c388c0117fe408b66fbede91081fb1018c5fe' returned non-zero exit status 128 in /path/to/chromium/src/media/cdm/api
fatal: reference is not a tree: 6e4c388c0117fe408b66fbede91081fb1018c5fe
```

答:
I successfully compiled version 3239, so I understand the problem was a bad reference in 3202's DEPS file. (which is quite weird...)

Hence the following steps are actually correct:

```<code>git checkout -b your_branch xx.x.xxxx.xx
gclient sync
</code>```

EDIT 2018-07-02: According to this page, starting from version 3420, it should be possible to correctly sync dependencies.

Body:
I want to build the latest stable version of Chromium (62.0.3202.84 at the time of writing, see OmahaProxy).

The build instructions work just fine for the current development version.

From this question, the Brave wiki and some other sources, the instructions to fetch and build a specific version seem to be pretty clear :

git fetch origin 62.0.3202.84
git checkout -b my_stable_branch FETCH_HEAD
# hooks and dependencies if needed, commits, compilation...

However, this does not seem to work for me. When I create a branch for FETCH_HEAD, a quick git log shows that I have the latest commits from master.

What am I misunderstanding ?

EDIT:

If I do the steps from Asesh's answer from master, it runs “successfully” but I still end up building master instead of what I want.

If I first create a branch from a specific tag (as specified in the Chromium documentation), like 62.0.3202.84, or even if I just check it out without branching, gclient sync --with_branch_heads fails giving me the following error :

Error: Command 'git checkout --quiet 6e4c388c0117fe408b66fbede91081fb1018c5fe' returned non-zero exit status 128 in /path/to/chromium/src/media/cdm/api
fatal: reference is not a tree: 6e4c388c0117fe408b66fbede91081fb1018c5fe

Body:
I successfully compiled version 3239, so I understand the problem was a bad reference in 3202's DEPS file. (which is quite weird...)

Hence the following steps are actually correct:

git checkout -b your_branch xx.x.xxxx.xx
gclient sync

EDIT 2018-07-02: According to this page, starting from version 3420, it should be possible to correctly sync dependencies.

ContentLicense: CC BY-SA 4.0


答:
```<code>var cache = (minFontSize + count + increment);

return (cache < maxFontSize) ? cache : maxFontSize;
</code>```

Title: Conditional statement syntax help

Body:
I am going through this WPF tutorial http://blogs.vertigo.com/personal/alanl/Blog/Lists/Posts/Post.aspx?ID=18 and I have a question about the CountToFontSizeConverter section of the tutorial. Could someone please explain the return statement to me i.e

return ((minFontSize + count + increment) < maxFontSize) ?
         (minFontSize + count + increment) : maxFontSize;

I understand it's a conditional but the syntax looks rather bespoke. If possible could someone re-write this in a simpler way? Thanks


问:
How to show a user-defined data type in Haskell
So I'm trying to define my own data type which expresses natural numbers recursively, as such:

```<code> data Nat = Zero | Succ Nat
</code>```

This function works correctly:

```<code> showNat :: Nat -> String
 showNat Zero = "Zero"
 showNat (Succ k) = "Succ " ++ (showNat k)
</code>```

However, I don't want to have to call it every time I want to output a Nat to the screen. I attempted this:

```<code>  instance Show Nat where
  show Zero = "Zero"
  show (Succ k) = "Succ " ++ Main.show k
</code>```

But it returns an error:

```<code>• No explicit implementation for
    either ‘showsPrec’ or ‘Prelude.show’
• In the instance declaration for ‘Show Nat’
|
| > instance Show Nat where   |            ^^^^^^^^
</code>```

How can I correctly write instances of 'Show'?

答:
The instantiation seems over-complicated. This is enough:

```<code>data Nat = Zero | Succ Nat

showNat :: Nat -> String
showNat Zero = "Zero"
showNat (Succ k) = "Succ " ++ (showNat k)

instance Show Nat where
    show = showNat
</code>```

Alternatively, one might like to use the automatically generated show using deriving:

```<code>data Nat = Zero | Succ Nat deriving (Show)
</code>```

In this case, nats will be shown as Succ (Succ Zero), not as Succ Succ Zero as intended in the original code.

Body:
So I'm trying to define my own data type which expresses natural numbers recursively, as such:

 data Nat = Zero | Succ Nat

This function works correctly:

 showNat :: Nat -> String
 showNat Zero = "Zero"
 showNat (Succ k) = "Succ " ++ (showNat k)

However, I don't want to have to call it every time I want to output a Nat to the screen. I attempted this:

  instance Show Nat where
  show Zero = "Zero"
  show (Succ k) = "Succ " ++ Main.show k

But it returns an error:

• No explicit implementation for
    either ‘showsPrec’ or ‘Prelude.show’
• In the instance declaration for ‘Show Nat’
|
| > instance Show Nat where   |            ^^^^^^^^

How can I correctly write instances of 'Show'?

Body:
The instantiation seems over-complicated. This is enough:

data Nat = Zero | Succ Nat

showNat :: Nat -> String
showNat Zero = "Zero"
showNat (Succ k) = "Succ " ++ (showNat k)

instance Show Nat where
    show = showNat

Alternatively, one might like to use the automatically generated show using deriving:

data Nat = Zero | Succ Nat deriving (Show)

In this case, nats will be shown as Succ (Succ Zero), not as Succ Succ Zero as intended in the original code.


问:
insert multiple rows with one query using ms access db
I am trying to get multiple rows into a table hence my attempt to get the row number and put it into a for loop, the countC is exactly the same number of rows as the select statement, so the issue is not there

I'm using an oledb connection as my code is in vb asp.net but my database is in ms access 2003

```<code>For c As Integer = 1 To countC
        Dim cmdstring As String
        cmdstring = " INSERT INTO [KN - ProductionMachineAllocation] (BatchNo, ComponentID)
                  SELECT POH.BatchNo, SSCDD.ComponentID
                FROM (
                    SELECT ROW_NUMBER() OVER (ORDER BY BatchNo ASC) AS rownumber
                    ([KN - ProductionOrderHeader] AS POH
                    INNER JOIN [FG - End Product Codes] AS EPC
                        ON POH.ProductID = EPC.ProductID)
                    INNER JOIN ([KN - ProductionOrderDetails] AS POD
                    INNER JOIN [FG - Style Size Comp Def Details]  AS SSCDD
                        ON POD.SizeID = SSCDD.SizeID)
                        ON (POH.BatchNo = POD.BatchNo)
                            AND (EPC.StyleID = SSCDD.StyleID)
                    WHERE POH.BatchNo = '" & BatchNo & "'
                     )  AS temptablename
                WHERE rownumber IN (" & c & ");"
        Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Shantara Production IT.mdb")
        Dim cmd As New OleDbCommand(cmdstring)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        cmd.Connection.Open()
        cmd.ExecuteNonQuery()
        cmd.Connection.Close()
    Next
</code>```

I found out that ms access doesn't support ROW_NUMBER() so I need to find another going through each row since ms access doesn't support multi row insert by insert into select statement such as mine, any suggestions around my problem?

答:
Most databases are able to do all this work much more efficiently entirely in the database. Certainly in SQL Server I could get entire thing down to a single query. Access is a little different, since vbscript is its procedural language, rather than something more like t-sql. There's still probably a way to do it, but since what you have works, we can at least focus on making that better.

GridViews are visual constructs that will use up extra memory and resources. If Access won't do a real INSERT/SELECT, you can at least read direct from the previous result set into your insert. You can also improve on this significantly by using parameters and re-using a single open connection for all the inserts:

Dim cnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Shantara Production IT.mdb"
Dim SQLDown As String = _
     "SELECT DISTINCT POH.BatchNo, SSCDD.ComponentID
      FROM ([KN - ProductionOrderHeader] AS POH
      INNER Join [FG - End Product Codes] AS EPC
        On POH.ProductID = EPC.ProductID)
      INNER Join([KN - ProductionOrderDetails] AS POD
      INNER Join [FG - Style Size Comp Def Details]  AS SSCDD
           On POD.SizeID = SSCDD.SizeID)
           On (POH.BatchNo = POD.BatchNo)
                And (EPC.StyleID = SSCDD.StyleID)
     WHERE POH.BatchNo = ? "
Dim SQLUp As String = _
    " INSERT INTO [KN - ProductionMachineAllocation]
      (BatchNo, ComponentID)
       VALUES( ?, ? )"

Dim dt As New DataTable
Using con As New OleDbConnection(cnString), _
      cmd As New OleDbCommand(SQLDown, con)

    'Guessing at parameter type/length here.
    'Use the actual column type and size from your DB
    cmd.Parameters.Add("@BatchNo", OleDbType.VarWChar, 10).Value = BatchNo

    con.Open()
    dt.Load(cmd.ExecuteReader())
End Using

Using con As New OleDbConnection(cnString), _
      cmd As New OleDbCommand(SqlUp, con)

    'Guessing at parameter types/lengths again
    cmd.Parameters.Add("@BatchNo", OleDbType.VarWChar, 10)
    cmd.Parameters.Add("@ComponentID", OleDbType.Integer)

    'Connection is managed *outside of the loop*. Only one object created, only one negotiation with DB
    con.Open()
    For Each row As DataRow In dt.Rows
          cmd.Parameters(0).Value = row(0)
          cmd.Parameters(1).Value = row(1)
          cmd.ExecuteNonQuery()
    Next
End Using
```

Normally, with any ADO.Net provider you do not re-use your connection or command objects. You want a new connection object for every query sent to the DB to allow connection pooling to work correctly. Using the connection in a tight loop like this for the same query is one of the few exceptions.

I might be able to improve further by sticking with the active DataReader, rather than first loading it into a DataTable. That would allow us to avoid loading the entire result set into memory. You would only ever need one record in memory at a time. Certainly this would work for Sql Server. However, Access was designed mainly as a single-user database. It doesn't really like multiple active connections at once, and I'm not sure how it would respond.

It would also be nice to be able to do all of this work in a transactional way, where there's never any risk of it failing part way through the loop and getting stuck with half the updates. Sql Server would handle this via a single INSERT/SELECT query or with an explicit transaction. But, again, this isn't the kind of the Access is designed for. It probably does have a way to do this, but I'm not familiar with it.

Body:
I am trying to get multiple rows into a table hence my attempt to get the row number and put it into a for loop, the countC is exactly the same number of rows as the select statement, so the issue is not there

I'm using an oledb connection as my code is in vb asp.net but my database is in ms access 2003

For c As Integer = 1 To countC
        Dim cmdstring As String
        cmdstring = " INSERT INTO [KN - ProductionMachineAllocation] (BatchNo, ComponentID)
                  SELECT POH.BatchNo, SSCDD.ComponentID
                FROM (
                    SELECT ROW_NUMBER() OVER (ORDER BY BatchNo ASC) AS rownumber
                    ([KN - ProductionOrderHeader] AS POH
                    INNER JOIN [FG - End Product Codes] AS EPC
                        ON POH.ProductID = EPC.ProductID)
                    INNER JOIN ([KN - ProductionOrderDetails] AS POD
                    INNER JOIN [FG - Style Size Comp Def Details]  AS SSCDD
                        ON POD.SizeID = SSCDD.SizeID)
                        ON (POH.BatchNo = POD.BatchNo)
                            AND (EPC.StyleID = SSCDD.StyleID)
                    WHERE POH.BatchNo = '" & BatchNo & "'
                     )  AS temptablename
                WHERE rownumber IN (" & c & ");"
        Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Shantara Production IT.mdb")
        Dim cmd As New OleDbCommand(cmdstring)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        cmd.Connection.Open()
        cmd.ExecuteNonQuery()
        cmd.Connection.Close()
    Next

I found out that ms access doesn't support ROW_NUMBER() so I need to find another going through each row since ms access doesn't support multi row insert by insert into select statement such as mine, any suggestions around my problem?

Body:
Most databases are able to do all this work much more efficiently entirely in the database. Certainly in SQL Server I could get entire thing down to a single query. Access is a little different, since vbscript is its procedural language, rather than something more like t-sql. There's still probably a way to do it, but since what you have works, we can at least focus on making that better.

GridViews are visual constructs that will use up extra memory and resources. If Access won't do a real INSERT/SELECT, you can at least read direct from the previous result set into your insert. You can also improve on this significantly by using parameters and re-using a single open connection for all the inserts:

Dim cnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Shantara Production IT.mdb"
Dim SQLDown As String = _
     "SELECT DISTINCT POH.BatchNo, SSCDD.ComponentID
      FROM ([KN - ProductionOrderHeader] AS POH
      INNER Join [FG - End Product Codes] AS EPC
        On POH.ProductID = EPC.ProductID)
      INNER Join([KN - ProductionOrderDetails] AS POD
      INNER Join [FG - Style Size Comp Def Details]  AS SSCDD
           On POD.SizeID = SSCDD.SizeID)
           On (POH.BatchNo = POD.BatchNo)
                And (EPC.StyleID = SSCDD.StyleID)
     WHERE POH.BatchNo = ? "
Dim SQLUp As String = _
    " INSERT INTO [KN - ProductionMachineAllocation]
      (BatchNo, ComponentID)
       VALUES( ?, ? )"

Dim dt As New DataTable
Using con As New OleDbConnection(cnString), _
      cmd As New OleDbCommand(SQLDown, con)

    'Guessing at parameter type/length here.
    'Use the actual column type and size from your DB
    cmd.Parameters.Add("@BatchNo", OleDbType.VarWChar, 10).Value = BatchNo

    con.Open()
    dt.Load(cmd.ExecuteReader())
End Using

Using con As New OleDbConnection(cnString), _
      cmd As New OleDbCommand(SqlUp, con)

    'Guessing at parameter types/lengths again
    cmd.Parameters.Add("@BatchNo", OleDbType.VarWChar, 10)
    cmd.Parameters.Add("@ComponentID", OleDbType.Integer)

    'Connection is managed *outside of the loop*. Only one object created, only one negotiation with DB
    con.Open()
    For Each row As DataRow In dt.Rows
          cmd.Parameters(0).Value = row(0)
          cmd.Parameters(1).Value = row(1)
          cmd.ExecuteNonQuery()
    Next
End Using

Normally, with any ADO.Net provider you do not re-use your connection or command objects. You want a new connection object for every query sent to the DB to allow connection pooling to work correctly. Using the connection in a tight loop like this for the same query is one of the few exceptions.

I might be able to improve further by sticking with the active DataReader, rather than first loading it into a DataTable. That would allow us to avoid loading the entire result set into memory. You would only ever need one record in memory at a time. Certainly this would work for Sql Server. However, Access was designed mainly as a single-user database. It doesn't really like multiple active connections at once, and I'm not sure how it would respond.

It would also be nice to be able to do all of this work in a transactional way, where there's never any risk of it failing part way through the loop and getting stuck with half the updates. Sql Server would handle this via a single INSERT/SELECT query or with an explicit transaction. But, again, this isn't the kind of the Access is designed for. It probably does have a way to do this, but I'm not familiar with it.


问:
Apache curl via HTTP proxy
I am trying to get PHP to execute a curl connection to another server. To connect to the server, we need to go via a proxy.
Within bash, we have set the env-variable http_proxy and this works correctly while using the php script from the command-line. However, when attempting to execute curl, or wget from apache, it fails with no errors.
The server is configured with SELinux based on Centos defaults. This has been unchanged as I am unsure about SELinux configuration.
Has anyone else had a similar issue?</p>

答:
Sorry for the late response.
It was to do with SELinux preventing apache to perform calls out to the network. To allow apache to do this, you need to run:

```<code>setsebool -P httpd_can_network_connect 1
</code>```

I was then presented with another related issue where I needed to execute scripts from the command line and couldn't find an appropriate SELinux property so ended up disabling it... ohh well.

Title: Apache curl via HTTP proxy

Body:
Sorry for the late response.
It was to do with SELinux preventing apache to perform calls out to the network. To allow apache to do this, you need to run:

setsebool -P httpd_can_network_connect 1

I was then presented with another related issue where I needed to execute scripts from the command line and couldn't find an appropriate SELinux property so ended up disabling it... ohh well.


问:
Android KitKat: Snackbar is not in the bottom of the screen
I add a Snackbar to my app. The problem is that in API 19 it's not at the bottom of the screen.

In API 21 it's ok. Here is my layout

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

<data />
 <android.support.design.widget.CoordinatorLayout
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="true"
        android:focusableInTouchMode="true">

        <EditText

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="@string/home_search_input_hint"
            android:inputType="text"
            android:maxLength="30"
            android:maxLines="1"/>

    </android.support.constraint.ConstraintLayout>
</android.support.design.widget.CoordinatorLayout>
</layout>
</code>```

And my OnCreate

```<code> @Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_home);
    super.onCreate(savedInstanceState);
    // binding
    binding = DataBindingUtil.setContentView(this, R.layout.activity_home);

    // snackbar test
    Snackbar snackbar = Snackbar.make(binding.root, "Snackbar", Snackbar.LENGTH_INDEFINITE);

    snackbar.show();
}
</code>```

Do you have any ideas how to fix it?

UPDATE: It seems that margin from the bottom is really random, I rerun emulator and see this.

and this

答: If you use 26 or 27 support, it is probably this known bug: Google Issue Tracker: Snackbar wrong placement on the Android 4x versions</p>

Body:
I add a Snackbar to my app. The problem is that in API 19 it's not at the bottom of the screen.

In API 21 it's ok. Here is my layout

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

<data />
 <android.support.design.widget.CoordinatorLayout
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="true"
        android:focusableInTouchMode="true">

        <EditText

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="@string/home_search_input_hint"
            android:inputType="text"
            android:maxLength="30"
            android:maxLines="1"/>

    </android.support.constraint.ConstraintLayout>
</android.support.design.widget.CoordinatorLayout>
</layout>

And my OnCreate

 @Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_home);
    super.onCreate(savedInstanceState);
    // binding
    binding = DataBindingUtil.setContentView(this, R.layout.activity_home);

    // snackbar test
    Snackbar snackbar = Snackbar.make(binding.root, "Snackbar", Snackbar.LENGTH_INDEFINITE);

    snackbar.show();
}

Do you have any ideas how to fix it?

UPDATE: It seems that margin from the bottom is really random, I rerun emulator and see this.

and this


问:
PHP circle inside JS inner Html
When I press the button it should add one more div, like the one below, calling JS function called comida_campos().

```<code><div class="panel panel-default">
    <div class="panel-body">
        <div id="comida_campos">
        </div>
        <div class="col-sm-6 nopadding">
            <div class="form-group">
                <input id="quantidade" class="form-control"name="quantidade[]" placeholder="Quantidade/g" type="text" value="">
            </div>
        </div>
        <div class="col-sm-6 nopadding">
            <div class="form-group">
                <div class="input-group" id="replicate">

                    <select class="form-control" name="alimento[]">
                        <option value="">Alimento</option>
                        <script>
                            document.write('<?php
                                $it=0;
                                while($it <= 9){

                                echo '<option value="'.$array_of_aliments[$it]['Idalimento'].'">'.$array_of_aliments[$it]['alimento'].'</option>';
                                $it++;
                                }
                            ?>');
                        </script>
                    </select>
                    <div class="input-group-btn">
                        <button class="btn btn-success" onclick="comida_campos();" type="button">
                            <span aria-hidden="true" class="glyphicon glyphicon-plus"></span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</code>```

Result of the code

Here is the JS fuction:

```<code>var room = 1;
function comida_campos() {
    room++;
    var objTo = document.getElementById('comida_campos')
    var divtest = document.createElement("div");
    divtest.setAttribute("class", "form-group removeclass" + room);
    var rdiv = 'removeclass' + room;
    divtest.innerHTML = '<div class="col-sm-6 nopadding"><div class="form-group"> <input type="text" class="form-control" id="Degree" name="Degree[]" value="" placeholder="Quantidade/g"></div></div><div class="col-sm-6 nopadding"><div class="form-group"><div class="input-group"> <select class="form-control" id="educationDate" name="alimento[]"><option value="">Date</option><option value="2015">2015</option><option value="2016">2016</option><option value="2017">2017</option><option value="2018">2018</option> </select><div class="input-group-btn"> <button class="btn btn-danger" type="button" onclick="remove_education_fields(' + room + ');"> <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> </button></div></div></div></div><div class="clear"></div>';

    objTo.appendChild(divtest)
}
</code>```

The problem is that I want to insert my PHP while circle is inside the divtest.innerHtml, and I don't have any idea how to do this.

答:
PHP is server side, JS is client (browser) side. Server side script (PHP in this case) gets executed before response is sent to the client. Once client has received the response, JS is executed in the browser and has no more access to PHP interpreter.

The simple answer is: You can not run PHP from Javascript.

The more correct answer is: look in to async JS requests (AJAX). This allows you to make separate requests to the server while executing JS. https://en.wikipedia.org/wiki/Ajax_(programming) - this will give you a basic understanding and a starting point.

Title: PHP circle inside JS inner Html

Body:
When I press the button it should add one more div, like the one below, calling JS function called comida_campos().

                <input id="quantidade" class="form-control"name="quantidade[]" placeholder="Quantidade/g" type="text" value="">

                    <select class="form-control" name="alimento[]">
                        <option value="">Alimento</option>

                    </select>

                        <button class="btn btn-success" onclick="comida_campos();" type="button">

                        </button>

Result of the code

Here is the JS fuction:

var room = 1;
function comida_campos() {
    room++;
    var objTo = document.getElementById('comida_campos')
    var divtest = document.createElement("div");
    divtest.setAttribute("class", "form-group removeclass" + room);
    var rdiv = 'removeclass' + room;
    divtest.innerHTML = '

 <input type="text" class="form-control" id="Degree" name="Degree[]" value="" placeholder="Quantidade/g">

 <select class="form-control" id="educationDate" name="alimento[]"><option value="">Date</option><option value="2015">2015</option><option value="2016">2016</option><option value="2017">2017</option><option value="2018">2018</option> </select>
 <button class="btn btn-danger" type="button" onclick="remove_education_fields(' + room + ');">  </button>

';

    objTo.appendChild(divtest)
}

The problem is that I want to insert my PHP while circle is inside the divtest.innerHtml, and I don't have any idea how to do this.


问:
Run shell command from within redis server process
I am running a Redis server on a RHEL system that requires processes to update their AFS authentication tokens every 24 hours.

In the client-side code that posts data to the database, I can update the AFS token by calling a shell command every N POST requests (e.g. echo PASSWORD | kinit && aklog.

I would like to achieve something similar in the server process, but am not sure how to do so. Are there any "post-receive-data" callback style hooks that one can use to run a shell command from within a Redis server process? I would be very grateful for any advice others can offer on this question.

答:
No - the Redis server isn't designed for that and is not intended for this purpose. If you really insist on using an event from the Redis server to trigger a shell command, you could hack by:

Trailing the server's log file and looking for an event generated by a client's call to EVAL with a script that invokes the redis.log Lua function.

Running a loop with a basic local Redis client (e.g. redis-cli) that BRPOPs from a queue, does the work and repeats

Code something to act as a sort of daemon that uses Redis' PubSub receive messages over a channel to trigger the shell commands

and so forth...

Note: WRT to "Redis server isn't designed for that" - if you do find some loophole that allows you to do what you're looking for, please report it as a severe security issue. In that sense, you may want to read http://antirez.com/news/96


问:
How do I find the silent install parameters for SceneBuilder?
I want to create a Chocolatey package to install Scene Builder, so I'm looking for a way to install Scene Builder silently in command line.

I downloaded a installer (SceneBuilder-8.4.1.exe) and try to install like below.

```<code>> SceneBuilder-8.4.1.exe /silent
</code>```

However, it launches a install dialog similarly in the case when I double click a installer.

Does Scene Builder installer has a capability to install silently?

答:
You could try to find out what kind of installer is used and look up the silent installation flags or you can try experimentally. The Chocolatey documentation says something like this

https://chocolatey.org/docs/helpers-install-chocolatey-package#silentargs-string

If you pass a "help" parameter to the installer it indicates some silent switches and some documentation.

```<code>PS> ./SceneBuilder-9.0.1.exe /?
</code>```

```<code>---------------------------
Setup
---------------------------
The Setup program accepts optional command line parameters.

/HELP, /?

Shows this information.

/SP-

Disables the This will install... Do you wish to continue? prompt at the beginning of Setup.

/SILENT, /VERYSILENT

Instructs Setup to be silent or very silent.

/SUPPRESSMSGBOXES

Instructs Setup to suppress message boxes.

/LOG

Causes Setup to create a log file in the user's TEMP directory.

/LOG="filename"

Same as /LOG, except it allows you to specify a fixed path/filename to use for the log file.

/NOCANCEL

Prevents the user from cancelling during the installation process.

/NORESTART

Prevents Setup from restarting the system following a successful installation, or after a Preparing to Install failure that requests a restart.

/RESTARTEXITCODE=exit code

Specifies a custom exit code that Setup is to return when the system needs to be restarted.

/CLOSEAPPLICATIONS

Instructs Setup to close applications using files that need to be updated.

/NOCLOSEAPPLICATIONS

Prevents Setup from closing applications using files that need to be updated.

/RESTARTAPPLICATIONS

Instructs Setup to restart applications.

/NORESTARTAPPLICATIONS

Prevents Setup from restarting applications.

/LOADINF="filename"

Instructs Setup to load the settings from the specified file after having checked the command line.

/SAVEINF="filename"

Instructs Setup to save installation settings to the specified file.

/LANG=language

Specifies the internal name of the language to use.

/DIR="x:\dirname"

Overrides the default directory name.

/GROUP="folder name"

Overrides the default folder name.

/NOICONS

Instructs Setup to initially check the Don't create a Start Menu folder check box.

/TYPE=type name

Overrides the default setup type.

/COMPONENTS="comma separated list of component names"

Overrides the default component settings.

/TASKS="comma separated list of task names"

Specifies a list of tasks that should be initially selected.

/MERGETASKS="comma separated list of task names"

Like the /TASKS parameter, except the specified tasks will be merged with the set of tasks that would have otherwise been selected by default.

/PASSWORD=password

Specifies the password to use.

For more detailed information, please visit http://www.jrsoftware.org/ishelp/index.php?topic=setupcmdline
---------------------------
OK
---------------------------
</code>```

http://www.jrsoftware.org/ishelp/index.php?topic=setupcmdline

The Universal Silent Switch Finder says this is an Inno Setup installer and suggests some switches.

Body:
I want to create a Chocolatey package to install Scene Builder, so I'm looking for a way to install Scene Builder silently in command line.

I downloaded a installer (SceneBuilder-8.4.1.exe) and try to install like below.

> SceneBuilder-8.4.1.exe /silent

However, it launches a install dialog similarly in the case when I double click a installer.

Does Scene Builder installer has a capability to install silently?

Body:
You could try to find out what kind of installer is used and look up the silent installation flags or you can try experimentally. The Chocolatey documentation says something like this

https://chocolatey.org/docs/helpers-install-chocolatey-package#silentargs-string

If you pass a "help" parameter to the installer it indicates some silent switches and some documentation.

PS> ./SceneBuilder-9.0.1.exe /?

---------------------------
Setup
---------------------------
The Setup program accepts optional command line parameters.

/HELP, /?

Shows this information.

/SP-

Disables the This will install... Do you wish to continue? prompt at the beginning of Setup.

/SILENT, /VERYSILENT

Instructs Setup to be silent or very silent.

/SUPPRESSMSGBOXES

Instructs Setup to suppress message boxes.

/LOG

Causes Setup to create a log file in the user's TEMP directory.

/LOG="filename"

Same as /LOG, except it allows you to specify a fixed path/filename to use for the log file.

/NOCANCEL

Prevents the user from cancelling during the installation process.

/NORESTART

Prevents Setup from restarting the system following a successful installation, or after a Preparing to Install failure that requests a restart.

/RESTARTEXITCODE=exit code

Specifies a custom exit code that Setup is to return when the system needs to be restarted.

/CLOSEAPPLICATIONS

Instructs Setup to close applications using files that need to be updated.

/NOCLOSEAPPLICATIONS

Prevents Setup from closing applications using files that need to be updated.

/RESTARTAPPLICATIONS

Instructs Setup to restart applications.

/NORESTARTAPPLICATIONS

Prevents Setup from restarting applications.

/LOADINF="filename"

Instructs Setup to load the settings from the specified file after having checked the command line.

/SAVEINF="filename"

Instructs Setup to save installation settings to the specified file.

/LANG=language

Specifies the internal name of the language to use.

/DIR="x:\dirname"

Overrides the default directory name.

/GROUP="folder name"

Overrides the default folder name.

/NOICONS

Instructs Setup to initially check the Don't create a Start Menu folder check box.

/TYPE=type name

Overrides the default setup type.

/COMPONENTS="comma separated list of component names"

Overrides the default component settings.

/TASKS="comma separated list of task names"

Specifies a list of tasks that should be initially selected.

/MERGETASKS="comma separated list of task names"

Like the /TASKS parameter, except the specified tasks will be merged with the set of tasks that would have otherwise been selected by default.

/PASSWORD=password

Specifies the password to use.

For more detailed information, please visit http://www.jrsoftware.org/ishelp/index.php?topic=setupcmdline
---------------------------
OK
---------------------------

http://www.jrsoftware.org/ishelp/index.php?topic=setupcmdline

The Universal Silent Switch Finder says this is an Inno Setup installer and suggests some switches.


问:
super.super.func()? - Java polymorphism
Say that I in Java have 3 classes, wheres the super one has a function named func(), I now make a subclass which overrides this, and a subclass to my subclass, now working on my sub-sub-class how will I call the 'func()' of the sub class, and the superclass?

I tried casting the 'this' "pointer", but Java 'fixes' it at runtime and calls the subsub func().

Edit:
Thanks everyone; 'Skeen is back at the drawing board'.

答:
I would jump on the "something in this design smells funny" train. Normally, you override a method so that it works properly for that specific subclass. If you have code in your parent class that is shared across multiple subclasses, perhaps that code could be moved to a non-overridden method so that it is readily accessible by all children/granchildren/etc.

Could you perhaps flip your design over and use more of a template method approach? (http://en.wikipedia.org/wiki/Template_method_pattern)

The notion behind Template Method is that you have some algorithm in your parent class and you can fill in the pieces that need to be class specific by polymorphic calls into your subclasses. You don't have a ton of detail in your question, but by the sounds of things, I'd really take a good look at your design and see if it makes sense.

Title: super.super.func()? - Java polymorphism


问:
Change database variable "character_set_client" in MySQL
I found out in my MySQL I have different global and database "character_set_client" variable. show variables shows

```<code>character_set_client | utf8
</code>```

while show global variables shows

```<code>character_set_client | latin1
</code>```

I believe the first one is database setting. How can I change it? When I do

```<code>set character_set_client='latin1'
</code>```

it is changed only for session. When I disconnect and connect again it is set back to 'utf8'. How can I change it so that it stays at 'latin1'?

答:
The idea is to force the character set on the server side and tell it to skip negotiation regarding character set.
See MySQL manual(V5.7 at time this was written).
Three parameters are vital for correct operation between client and server regarding that matter. They are set in the [mysqld] section of the .cnf file:

```<code>[mysqld]
#...
#UTF8 stuff
skip-character-set-client-handshake
collation-server=latin1_general_ci
character-set-server=latin1
</code>```

Side note, on this day and age one should always use UTF8, which would require setting the following lines:

```<code>collation-server=utf8mb4_unicode_ci
character-set-server=utf8mb4
</code>```

Side-side note, since the release of MySQL 8.0 MySQL manual, the correct values would be:

```<code>collation-server=utf8mb4_0900_ai_ci
character-set-server=utf8mb4
</code>```

Body:
I found out in my MySQL I have different global and database "character_set_client" variable. show variables shows

character_set_client | utf8

while show global variables shows

character_set_client | latin1

I believe the first one is database setting. How can I change it? When I do

set character_set_client='latin1'

it is changed only for session. When I disconnect and connect again it is set back to 'utf8'. How can I change it so that it stays at 'latin1'?

Body:
The idea is to force the character set on the server side and tell it to skip negotiation regarding character set.
See MySQL manual(V5.7 at time this was written).
Three parameters are vital for correct operation between client and server regarding that matter. They are set in the [mysqld] section of the .cnf file:

[mysqld]
#...
#UTF8 stuff
skip-character-set-client-handshake
collation-server=latin1_general_ci
character-set-server=latin1

Side note, on this day and age one should always use UTF8, which would require setting the following lines:

collation-server=utf8mb4_unicode_ci
character-set-server=utf8mb4

Side-side note, since the release of MySQL 8.0 MySQL manual, the correct values would be:

collation-server=utf8mb4_0900_ai_ci
character-set-server=utf8mb4