问:
Dynamically insert child components inside vuejs2 data (without $compile or abusing v-html)
I'd like to insert new vuejs components on the fly, at arbitrary points within a block of not-necessarily-predefined HTML.

Here's a slightly contrived example that demonstrates the sort of thing I'm trying to do:

Vue.component('child', {
  // pretend I do something useful
  template: '--><slot></slot><--'
})

Vue.component('parent', {
  data() {
    return {
      input: 'lorem',
      text: '
Lorem ipsum dolor sit amet.

Lorem ipsum!
'
    }
  },
  template: `

      Search: <input type='text' v-model="input">

      This inserts the child component but doesn't render it
      or the HTML:

{{output}}

      This renders the HTML but of course strips out the child component:

      (This is the child component, just to show that it's usable here:
      <child>hello</child>)

      This is the goal: it renders both the input html
      and the inserted child components:
      TODO ¯\_(ツ)_/¯

`,
  computed: {
    output() {
      /* This is the wrong approach; what do I replace it with? */
      var out = this.text;
      if (this.input) {
        this.input = this.input.replace(/[^a-zA-Z\s]/g,'');
        var regex = new RegExp(this.input, "gi");
        out = out.replace(regex, '<child>' + this.input + '</child>');
      }
      return out;
    }
  }
});

new Vue({
  el: '#app'
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
<div id="app">
  <parent></parent>
</div></code>```

In the above snippet, assume data.text is sanitized HTML. <child> is some sub-component that does something useful, which I want to wrap around chunks of data.text that aren't known ahead of time.  (input is just for demo here. This MCVE doesn't really resemble the code I'm building, it's just an example that shows the sort of situation I'm stuck on.)

So: how would I change either the output function or the parent component's template, such that both the HTML from input and the inserted <child> templates are rendered properly?

What I've tried

In Vue 1, the answer to this would be a straightforward $compile. I'm using vuejs2 which removed $compile (out of justifiable concern that it made it too easy to naively introduce XSS vulnerabilities.)

v-html sanitizes what you feed it, which strips the child component out. Obviously this is not the way to do this. (That page suggests using partials instead, but I'm not sure how that could be applied to this situation; in any case partials have also been removed from vue2.)

I've tried passing the results of output() into another component which would then use it as its template. This seems like a promising approach, but I can't figure out how to change that secondary component's template. template only accepts a string, not a function like many of the other component properties, so I can't pass the template html in, say, a prop. Something like rewriting this.template inside beforeMount() or bind() would have been nice, but no joy there either. Is there some other way to replace a component's template string before it's mounted?

Unlike template, I can pass data to a component's render() function... but then I'm still stuck having to parse that html string into nested createElement functions. Which is exactly what Vue is doing internally in the first place; is there some way to hook into that here short of reinventing it myself?

Vue.component('foo', {
  props: ['myInput'],
  render(createElement) {
    console.log(this.myInput); // this works...
    // ...but how to parse the html in this.myInput into a usable render function?
    // return createElement('div', this.myInput);
  },
})
```
<ul>
<li><p>I wasn't able to cheat my around this with inline-template, either: <code><foo inline-template>{{$parent.output}}</foo></code> does exactly the same thing as a plain old <code>{{output}}</code>.  In retrospect that should have been obvious, but it was worth a shot.</p>
</li>
<li><p>Maybe constructing an async component on the fly is the answer? This could clearly generate a component with an arbitrary template, but how would I reasonably call that from the parent component, and feed <code>output</code> to the constructor?  (It would need to be reusable with different input, with multiple instances potentially visible simultaneously; no globals or singletons.)</p>
</li>
<li><p>I've even considered ridiculous stuff like having <code>output()</code> split the input into an array at the points where it would have inserted <code><child></code>, and then doing something like this in the main template:</p>
</li>
</ul>
<pre class="lang-html prettyprint-override"><code>  ...
  <template v-for="chunk in output">
      <span v-html="chunk"></span>
      <child>...</child>
  </template>
  ....
</code>```

That would be doable, if laborious -- I'd have to split out what goes in the child's slot into a separate array too and get it by index during the v-for, but that could be done... if input were plain text instead of HTML.  In splitting HTML I'll often wind up with unbalanced tags in each chunk, which can mess up the formatting when v-html rebalances it for me.   And anyway this whole strategy feels like a bad hack; there must be a better way.

Maybe I just drop the whole input into a v-html and then (somehow) insert the child components at the proper positions through after-the-fact DOM manipulation?  I haven't explored this option too deeply because it, too, feels like a hack, and the reverse of the data-driven strategy, but maybe it's a way to go if all else fails?

A couple of pre-emptive disclaimers

I'm very well aware of the XSS risks involved in $compile-like operations.  Please be assured that none of what I'm doing involves unsanitized user input in any way; the user isn't inserting arbitrary component code, instead a component needs to insert child components at user-defined positions.

I'm reasonably confident that this is not an XY problem, that I really do need to insert components on the fly.  (I hope it's obvious from the number of failed attempts and blind alleys I've run down that I've put more than a little thought into this one!) That said, if there's a different approach that leads to similar results, I'm all ears. The salient point is that I know which component I need to add, but I can't know ahead of time where to add it; that decision happens at run time.

If it's relevant, in real life I'm using the single-file component structure from vue-cli webpack template, not Vue.component() as in the samples above.  Answers that don't stray too far from that structure are preferred, though anything that works will work.

Progress!

@BertEvans points out in comments that Vue.compile() is a thing that exists, which is an I-can't-believe-I-missed-that if ever there was one.

But I'm still having trouble using it without resorting to global variables as in that documentation.  This renders, but hardcodes the template in a global:

```<code>var precompiled = Vue.compile('<span><child>test</child></span>');
Vue.component('test', {
  render: precompiled.render,
  staticRenderFns: precompiled.staticRenderFns
});
</code>```

But various attempts to rejigger that into something that can accept an input property have been unsuccessful (the following for example throws "Error in render function: ReferenceError: _c is not defined", I assume because the staticRenderFns aren't ready to go when render needs them?

```<code>Vue.component('test', {
  props: ['input'],
  render() { return Vue.compile(this.input).render()},
  staticRenderFns() {return Vue.compile(this.input).staticRenderFns()}
});
</code>```

(It's not because there are two separate compile()s -- doing the precompile inside beforeMount() and then returning its render and staticRenderFns throws the same error.)

This really feels like it's on the right track but I'm just stuck on a dumb syntax error or the like...

答:
I'm posting this as a supplement to Bert Evans's answer, for the benefit of vue-cli webpack users who want to use .vue files instead of Vue.component(). (Which is to say, I'm mostly posting this so I'll be able to find this information when I inevitably forget it...)

Getting the right Vue build

In vue-cli 2 (and possibly 1?), to ensure Vue.compile will be available in the distribution build, confirm webpack.base.conf.js contains this line:

```<code>'vue$': 'vue/dist/vue.esm.js' // or vue/dist/vue.common.js for webpack1
</code>```

instead of 'vue/dist/vue.runtime.esm.js'.  (If you accepted the defaults when running vue init webpack you will already have the full standalone build.  The "webpack-simple" template also sets the full standalone build.)

Vue-cli 3 works somewhat differently, and does not have Vue.compile available by default; here you'll need to add the runtimeCompiler rule to vue.config.js:

```<code>module.exports = {
    /* (other config here) */
    runtimeCompiler: true
};
</code>```

The component

The "child" component can be a normal .vue file, nothing special about that.

A bare-bones version of the "parent" component would be:

```<code><template>
    <component :is="output"></component>
</template>
<script>
import Vue from 'vue';
import Child from './Child'; // normal .vue component import

export default {
  name: 'Parent',
  computed: {
    output() {
      var input = "<span>Arbitrary single-root HTML string that depends on <child></child>.  This can come from anywhere; don't use unsanitized user input though...</span>";
      var ret = Vue.compile(input);
      ret.components = { Child };  // add any other necessary properties similarly
      ret.methods = { /* ... */ }  // like so
      return ret;
    }
  }
};
</script>
</code>```

(The only significant difference between this and the non-webpack version is importing the child, then declaring the component dependencies as ret.components: {Child} before returning it.)

Body:
I'd like to insert new vuejs components on the fly, at arbitrary points within a block of not-necessarily-predefined HTML.

Here's a slightly contrived example that demonstrates the sort of thing I'm trying to do:

Vue.component('child', {
  // pretend I do something useful
  template: '--><slot></slot><--'
})

Vue.component('parent', {
  data() {
    return {
      input: 'lorem',
      text: '
Lorem ipsum dolor sit amet.

Lorem ipsum!
'
    }
  },
  template: `

      Search: <input type='text' v-model="input">

      This inserts the child component but doesn't render it
      or the HTML:

{{output}}

      This renders the HTML but of course strips out the child component:

      (This is the child component, just to show that it's usable here:
      <child>hello</child>)

      This is the goal: it renders both the input html
      and the inserted child components:
      TODO ¯\_(ツ)_/¯

`,
  computed: {
    output() {
      /* This is the wrong approach; what do I replace it with? */
      var out = this.text;
      if (this.input) {
        this.input = this.input.replace(/[^a-zA-Z\s]/g,'');
        var regex = new RegExp(this.input, "gi");
        out = out.replace(regex, '<child>' + this.input + '</child>');
      }
      return out;
    }
  }
});

new Vue({
  el: '#app'
})

  <parent></parent>

In the above snippet, assume data.text is sanitized HTML. <child> is some sub-component that does something useful, which I want to wrap around chunks of data.text that aren't known ahead of time.  (input is just for demo here. This MCVE doesn't really resemble the code I'm building, it's just an example that shows the sort of situation I'm stuck on.)

So: how would I change either the output function or the parent component's template, such that both the HTML from input and the inserted <child> templates are rendered properly?

What I've tried

In Vue 1, the answer to this would be a straightforward $compile. I'm using vuejs2 which removed $compile (out of justifiable concern that it made it too easy to naively introduce XSS vulnerabilities.)

v-html sanitizes what you feed it, which strips the child component out. Obviously this is not the way to do this. (That page suggests using partials instead, but I'm not sure how that could be applied to this situation; in any case partials have also been removed from vue2.)

I've tried passing the results of output() into another component which would then use it as its template. This seems like a promising approach, but I can't figure out how to change that secondary component's template. template only accepts a string, not a function like many of the other component properties, so I can't pass the template html in, say, a prop. Something like rewriting this.template inside beforeMount() or bind() would have been nice, but no joy there either. Is there some other way to replace a component's template string before it's mounted?

Unlike template, I can pass data to a component's render() function... but then I'm still stuck having to parse that html string into nested createElement functions. Which is exactly what Vue is doing internally in the first place; is there some way to hook into that here short of reinventing it myself?

Vue.component('foo', {
  props: ['myInput'],
  render(createElement) {
    console.log(this.myInput); // this works...
    // ...but how to parse the html in this.myInput into a usable render function?
    // return createElement('div', this.myInput);
  },
})

I wasn't able to cheat my around this with inline-template, either: <foo inline-template>{{$parent.output}}</foo> does exactly the same thing as a plain old {{output}}.  In retrospect that should have been obvious, but it was worth a shot.

Maybe constructing an async component on the fly is the answer? This could clearly generate a component with an arbitrary template, but how would I reasonably call that from the parent component, and feed output to the constructor?  (It would need to be reusable with different input, with multiple instances potentially visible simultaneously; no globals or singletons.)

I've even considered ridiculous stuff like having output() split the input into an array at the points where it would have inserted <child>, and then doing something like this in the main template:

  ...
  <template v-for="chunk in output">

      <child>...</child>
  </template>
  ....

That would be doable, if laborious -- I'd have to split out what goes in the child's slot into a separate array too and get it by index during the v-for, but that could be done... if input were plain text instead of HTML.  In splitting HTML I'll often wind up with unbalanced tags in each chunk, which can mess up the formatting when v-html rebalances it for me.   And anyway this whole strategy feels like a bad hack; there must be a better way.

Maybe I just drop the whole input into a v-html and then (somehow) insert the child components at the proper positions through after-the-fact DOM manipulation?  I haven't explored this option too deeply because it, too, feels like a hack, and the reverse of the data-driven strategy, but maybe it's a way to go if all else fails?

A couple of pre-emptive disclaimers

I'm very well aware of the XSS risks involved in $compile-like operations.  Please be assured that none of what I'm doing involves unsanitized user input in any way; the user isn't inserting arbitrary component code, instead a component needs to insert child components at user-defined positions.

I'm reasonably confident that this is not an XY problem, that I really do need to insert components on the fly.  (I hope it's obvious from the number of failed attempts and blind alleys I've run down that I've put more than a little thought into this one!) That said, if there's a different approach that leads to similar results, I'm all ears. The salient point is that I know which component I need to add, but I can't know ahead of time where to add it; that decision happens at run time.

If it's relevant, in real life I'm using the single-file component structure from vue-cli webpack template, not Vue.component() as in the samples above.  Answers that don't stray too far from that structure are preferred, though anything that works will work.

Progress!

@BertEvans points out in comments that Vue.compile() is a thing that exists, which is an I-can't-believe-I-missed-that if ever there was one.

But I'm still having trouble using it without resorting to global variables as in that documentation.  This renders, but hardcodes the template in a global:

var precompiled = Vue.compile('<child>test</child>');
Vue.component('test', {
  render: precompiled.render,
  staticRenderFns: precompiled.staticRenderFns
});

But various attempts to rejigger that into something that can accept an input property have been unsuccessful (the following for example throws "Error in render function: ReferenceError: _c is not defined", I assume because the staticRenderFns aren't ready to go when render needs them?

Vue.component('test', {
  props: ['input'],
  render() { return Vue.compile(this.input).render()},
  staticRenderFns() {return Vue.compile(this.input).staticRenderFns()}
});

(It's not because there are two separate compile()s -- doing the precompile inside beforeMount() and then returning its render and staticRenderFns throws the same error.)

This really feels like it's on the right track but I'm just stuck on a dumb syntax error or the like...

Body:
I'm posting this as a supplement to Bert Evans's answer, for the benefit of vue-cli webpack users who want to use .vue files instead of Vue.component(). (Which is to say, I'm mostly posting this so I'll be able to find this information when I inevitably forget it...)

Getting the right Vue build

In vue-cli 2 (and possibly 1?), to ensure Vue.compile will be available in the distribution build, confirm webpack.base.conf.js contains this line:

'vue$': 'vue/dist/vue.esm.js' // or vue/dist/vue.common.js for webpack1

instead of 'vue/dist/vue.runtime.esm.js'.  (If you accepted the defaults when running vue init webpack you will already have the full standalone build.  The "webpack-simple" template also sets the full standalone build.)

Vue-cli 3 works somewhat differently, and does not have Vue.compile available by default; here you'll need to add the runtimeCompiler rule to vue.config.js:

module.exports = {
    /* (other config here) */
    runtimeCompiler: true
};

The component

The "child" component can be a normal .vue file, nothing special about that.

A bare-bones version of the "parent" component would be:

<template>
    <component :is="output"></component>
</template>
<script>
import Vue from 'vue';
import Child from './Child'; // normal .vue component import

export default {
  name: 'Parent',
  computed: {
    output() {
      var input = "<span>Arbitrary single-root HTML string that depends on <child></child>.  This can come from anywhere; don't use unsanitized user input though...</span>";
      var ret = Vue.compile(input);
      ret.components = { Child };  // add any other necessary properties similarly
      ret.methods = { /* ... */ }  // like so
      return ret;
    }
  }
};
</script>

(The only significant difference between this and the non-webpack version is importing the child, then declaring the component dependencies as ret.components: {Child} before returning it.)


来源: stackexchange

问:
Is it possible to address child class properties after verifying a required inheritance?
I am working with several child class with the same parent class. I'd like to give an object to a function that can be one of the child classes, then make a veryfication of the child class type and then I want to address the corresponding child class properties directly.</p>

```<code>class human
{
    public string name;
}

class woman : human
{
    public bool isPregnant;
}

class man : human
{
    public int numberOfComputers;
}

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        man Andrew = new man();
    }

    public void checkHuman<T>(T my_human) where T : human
    {
        // is something like this possible??
        if (typeof(my_human).Name == "woman")
            Console.WriteLine(my_human.name & " is " & (my_human.isPregnant ? "pregnant." : "not pregnant."));
        if (typeof(my_human).Name == "man") {
            man m = (man)my_human;
            Console.WriteLine(m.name & " has " & m.numberOfComputers & " computers.");
        }
    }
}
</code>```

答:
You shouldn’t really use generics there. Instead, you just want to accept any Human object (remember that Man and Woman are also valid Human objects) and use the is operator to check the concrete type:

```<code>public void CheckHuman(Human human)
{
    if (human is Woman)
    {
        var woman = (Woman)human;
        Console.WriteLine("{0} is {1}pregnant.", woman.Name, woman.IsPregnant ? "" : "not ");
    }
    else if (human is Man)
    {
        var man = (Man)human;
        Console.WriteLine("{0} has {1} computers.", man.Name, man.NumberOfComputers);
    }
}
</code>```

You can als use C# 7 operater patterns here to automatically cast the object into the correct type:

```<code>public void CheckHuman(Human human)
{
    if (human is Woman woman)
    {
        Console.WriteLine("{0} is {1}pregnant.", woman.Name, woman.IsPregnant ? "" : "not ");
    }
    else if (human is Man man)
    {
        // please keep in mind that women have computers too
        Console.WriteLine("{0} has {1} computers.", man.Name, man.NumberOfComputers);
    }
}
</code>```

Note that I adjusted the general naming of your types and members: Class names, methods and properties should all use PascalCase, while variables and fields use camelCase.

ContentLicense: CC BY-SA 3.0

Body:
I am working with several child class with the same parent class. I'd like to give an object to a function that can be one of the child classes, then make a veryfication of the child class type and then I want to address the corresponding child class properties directly.

class human
{
    public string name;
}

class woman : human
{
    public bool isPregnant;
}

class man : human
{
    public int numberOfComputers;
}

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        man Andrew = new man();
    }

    public void checkHuman<T>(T my_human) where T : human
    {
        // is something like this possible??
        if (typeof(my_human).Name == "woman")
            Console.WriteLine(my_human.name & " is " & (my_human.isPregnant ? "pregnant." : "not pregnant."));
        if (typeof(my_human).Name == "man") {
            man m = (man)my_human;
            Console.WriteLine(m.name & " has " & m.numberOfComputers & " computers.");
        }
    }
}

Body:
You shouldn’t really use generics there. Instead, you just want to accept any Human object (remember that Man and Woman are also valid Human objects) and use the is operator to check the concrete type:

public void CheckHuman(Human human)
{
    if (human is Woman)
    {
        var woman = (Woman)human;
        Console.WriteLine("{0} is {1}pregnant.", woman.Name, woman.IsPregnant ? "" : "not ");
    }
    else if (human is Man)
    {
        var man = (Man)human;
        Console.WriteLine("{0} has {1} computers.", man.Name, man.NumberOfComputers);
    }
}

You can als use C# 7 operater patterns here to automatically cast the object into the correct type:

public void CheckHuman(Human human)
{
    if (human is Woman woman)
    {
        Console.WriteLine("{0} is {1}pregnant.", woman.Name, woman.IsPregnant ? "" : "not ");
    }
    else if (human is Man man)
    {
        // please keep in mind that women have computers too
        Console.WriteLine("{0} has {1} computers.", man.Name, man.NumberOfComputers);
    }
}

Note that I adjusted the general naming of your types and members: Class names, methods and properties should all use PascalCase, while variables and fields use camelCase.


问:
Vue.js - Element UI - How to know the state of form validation
I'm using, vue-js and element-ui

I would like to check the state of the validation of a form without having to click on a submit button

Example

https://jsfiddle.net/nw8mw1s2/

Steps to reproduce

Click on each field

The verification is triggered with the blur

Start filling the different inputs

Question

How can I do so when the last input is validated,  isFormValidated turns to true.

In other words, how can I say "If there is no field with the state error, then turn valudateState to true"

Tips

I guess we can check the validateState of each formItem of the form. But I do not see how to do it concretely.

答:
I would create a new method (say updateIsFormValidated), and bind it to the native focusout event of the form:

```<code><el-form :model="ruleForm2" @focusout.native="updateIsFormValidated" ...>
</code>```

This method will fire each time any of the inputs in the form loses focus. It will attempt to check that each field in the form component has successfully been validated, firing each 100 milliseconds if the validation status of any of the form items is still pending:

```<code>updateIsFormValidated() {
  let fields = this.$refs.ruleForm2.fields;
  if (fields.find((f) => f.validateState === 'validating')) {
    setTimeout(() => { this.updateIsFormValidated() }, 100);
  } else {
    this.isFormValidated = fields.reduce((acc, f) => {
      let valid = (f.isRequired && f.validateState === 'success');
      let notErroring = (!f.isRequired && f.validateState !== 'error');
      return acc && (valid || notErroring);
    }, true);
  }
}
</code>```

Here's a working fiddle.

Body:
I would create a new method (say updateIsFormValidated), and bind it to the native focusout event of the form:

<el-form :model="ruleForm2" @focusout.native="updateIsFormValidated" ...>

This method will fire each time any of the inputs in the form loses focus. It will attempt to check that each field in the form component has successfully been validated, firing each 100 milliseconds if the validation status of any of the form items is still pending:

updateIsFormValidated() {
  let fields = this.$refs.ruleForm2.fields;
  if (fields.find((f) => f.validateState === 'validating')) {
    setTimeout(() => { this.updateIsFormValidated() }, 100);
  } else {
    this.isFormValidated = fields.reduce((acc, f) => {
      let valid = (f.isRequired && f.validateState === 'success');
      let notErroring = (!f.isRequired && f.validateState !== 'error');
      return acc && (valid || notErroring);
    }, true);
  }
}

Here's a working fiddle.


问:
Using conditions in Azure ARM templates
Is there any way to use conditional statements in templates?

for example I am building template which will have vms with data disks on QA and Production, but no data disks on Dev. Another scenario would be there are some extensions only needs to be installed in prod VMs but no where else.

Any help is appreciated.

答:
You can leverage the newly released comparison functions to accomplish most of this.

Here is an example of how you would use a parameter to determine if a storage account should be deployed.

Parameter:

```<code>"deployStorage": {
  "type": "string"
},
</code>```

Resource:

```<code>{
  "condition": "[equals(parameters('deployStorage'),'yes')]",
  "name": "[variables('storageAccountName')]",
  "type": "Microsoft.Storage/storageAccounts",
  "location": "[resourceGroup().location]",
  "apiVersion": "2017-06-01",
  "sku": {
    "name": "[parameters('storageAccountType')]"
  },
  "kind": "Storage"
}
</code>```

Notice the new condition property in the resource along with the most recent API version for the storage provider.

Reference: https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-template-functions-comparison

Title: Using conditions in Azure ARM templates

Body:
You can leverage the newly released comparison functions to accomplish most of this.

Here is an example of how you would use a parameter to determine if a storage account should be deployed.

Parameter:

"deployStorage": {
  "type": "string"
},

Resource:

{
  "condition": "[equals(parameters('deployStorage'),'yes')]",
  "name": "[variables('storageAccountName')]",
  "type": "Microsoft.Storage/storageAccounts",
  "location": "[resourceGroup().location]",
  "apiVersion": "2017-06-01",
  "sku": {
    "name": "[parameters('storageAccountType')]"
  },
  "kind": "Storage"
}

Notice the new condition property in the resource along with the most recent API version for the storage provider.

Reference: https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-template-functions-comparison


问:
boolean example in Schildt book
I'm really new to Java, but it sucks all my free time, it's very interesting to study, but I need a little help.

Here's an example of Boolean test from Schildt's book:

```<code>public class BooleanTest {
public static void main(String args[]){
    boolean b;
    b = false;
    System.out.println("Expression b " +b);
    b = true;
    System.out.println("Expression b " + b);
    if (b) System.out.println("This code is ok.");
    b = false;
    if (b) System.out.println("This code is not ok.");
    System.out.println("10 > 9 " + (10>9));
}}
</code>```

This code shows me result:

Expression b false

Expression b true

This code is ok.

10 > 9 true

First line is ok, second is ok, third too, but why the fourth doesn't show me "The code is not ok.", 'cause there is "b=false" and it should say that? Why it jumps to the last System.out.println?

Can someone add commentaries to this example? Thanks a lot!

答:
Basically you don't use else and your if condition applies only to the next instruction after the if statement, if you don't use parenthesis.

```<code>if (b) System.out.println("This code is not ok.");
System.out.println("10 > 9 " + (10>9));
</code>```

Goes like this (assuming b == true)

if(b)  //true

System.out.println("This code is ok."); //This code is ok

b = false // b == false

if (b) //false

System.out.println("10 > 9 " + (10>9)); //10 > 9 true

To have what you thought it was, your code should have been:

```<code>    public class BooleanTest {
public static void main(String args[]){
    boolean b;
    b = false;
    System.out.println("Expression b " +b);
    b = true;
    System.out.println("Expression b " + b);
    if (b) System.out.println("This code is ok.");
    else b = false;
    if (b) System.out.println("This code is not ok.");
    System.out.println("10 > 9 " + (10>9));
}}
</code>```

Title: boolean example in Schildt book

Body:
I'm really new to Java, but it sucks all my free time, it's very interesting to study, but I need a little help.

Here's an example of Boolean test from Schildt's book:

public class BooleanTest {
public static void main(String args[]){
    boolean b;
    b = false;
    System.out.println("Expression b " +b);
    b = true;
    System.out.println("Expression b " + b);
    if (b) System.out.println("This code is ok.");
    b = false;
    if (b) System.out.println("This code is not ok.");
    System.out.println("10 > 9 " + (10>9));
}}

This code shows me result:

Expression b false

Expression b true

This code is ok.

10 > 9 true

First line is ok, second is ok, third too, but why the fourth doesn't show me "The code is not ok.", 'cause there is "b=false" and it should say that? Why it jumps to the last System.out.println?

Can someone add commentaries to this example? Thanks a lot!

Body:
Basically you don't use else and your if condition applies only to the next instruction after the if statement, if you don't use parenthesis.

if (b) System.out.println("This code is not ok.");
System.out.println("10 > 9 " + (10>9));

Goes like this (assuming b == true)

if(b)  //true

System.out.println("This code is ok."); //This code is ok

b = false // b == false

if (b) //false

System.out.println("10 > 9 " + (10>9)); //10 > 9 true

To have what you thought it was, your code should have been:

    public class BooleanTest {
public static void main(String args[]){
    boolean b;
    b = false;
    System.out.println("Expression b " +b);
    b = true;
    System.out.println("Expression b " + b);
    if (b) System.out.println("This code is ok.");
    else b = false;
    if (b) System.out.println("This code is not ok.");
    System.out.println("10 > 9 " + (10>9));
}}


问:
Switching players
I'm made a program that calculates the current health of a player and switches between them. I need help switching between players. This is what i have so far:</p>

```<code>class Player():

    def turn(life):
        players = ['Player 1', 'Player 2']
        life = 100
        for player in players:
            while life >= 0:
                print (life)
                print ("+, -, or end turn")
                choice = input("> ")

                if choice == "+":
                    print ("Damage taken")
                    healing = int(input("> "))
                    life += healing
                elif choice == "-":
                    print ("Damage taken")
                    damage = int(input("> "))
                    life -= damage
                elif choice == "end turn" or "end":
                    return

            else:
                print ("You lose!")

play = Player()
play.turn()
</code>```

答:
I've been in a similar position before. I would recommend doing something a bit different than the answer you might be looking for. Instead of looking for a solution to this individual problem, I would recommend looking at resources for game design patterns.

While I think that the learning curve might be a bit high initially, I think that if you learn to work with proper design patterns for game mechanics, you will find it much easier to build what you are after.

There are a few different resources that you can choose from. I used http://gameprogrammingpatterns.com/ (I have no association with this individual), but I also have a background in c++. I would look around for what might be the most intuitive for you and give it a try.

All the best!

Title: Switching players

Body:
I'm made a program that calculates the current health of a player and switches between them. I need help switching between players. This is what i have so far:

class Player():

    def turn(life):
        players = ['Player 1', 'Player 2']
        life = 100
        for player in players:
            while life >= 0:
                print (life)
                print ("+, -, or end turn")
                choice = input("> ")

                if choice == "+":
                    print ("Damage taken")
                    healing = int(input("> "))
                    life += healing
                elif choice == "-":
                    print ("Damage taken")
                    damage = int(input("> "))
                    life -= damage
                elif choice == "end turn" or "end":
                    return

            else:
                print ("You lose!")

play = Player()
play.turn()


问:
jQuery - good solution for "easy parsing" of html string
I have the following html string (var jsonHtmlString) returned as json in a jquery get request and need to parse the html to return an array of objects with using the info below. There's probably an easy way to do this but I haven't been able to find it. I'm hoping someone might be able to recommend an "easy parsing" solution (and if you use an online tool (e.g. plnkr.co) to easily seeing the parsing as you test your js code)?

I've included what the jQuery selector value should return on each line of the mapped object. Thanks!

```<code>var jsonHtmlString = '<div class="search-result-srch box"> <span class="number">1.</span>
    <a href="/Practice/Detail.aspx?docid=18600&mode=search&p=Tools-@-Technology">The Continuous Learning Technology Stack: Thinking outside the LMS</a>
    <br />
    <div title="Research Report" class="description rr">This report introduces the Continuous Learning Technology Stack, or the sum of technologies that can be leveraged for enabling continuous learning within organizations. </div>
    <div class="pracsub"> <span class="col1-a">Practice:</span> <span class="col1-b"><strong>Tools & Technology</strong></span> <span class="col2-a">Subject:</span> <span class="col2-b"><strong>Learning Tech</strong></span> </div>
    <div class="pracsub top-blue-brdr"> <span class="col1-a">Access:</span> <span class="col1-b">Member</span> <span class="col2-a">Published:</span> <span class="col2-b">09/02/2015</span>
        <div class="clearfix"></div> <span class="col1-a">Type:</span> <span class="col1-b">Research Report</span> </div>
    <div class="clearfix"></div>
</div>
<div class="search-result-srch box"> <span class="number">2.</span>
    <a href="/Practice/Detail.aspx?docid=18817&mode=search&p=Learning-@-Development">Business Case for Investing Beyond the LMS (editable PPT)</a>
    <br />
    <div title="Performance Support" class="description ps">This editable PowerPoint template guides you through the process of building and presenting a business case for investing in continuous learning—beyond the LMS.</div>
    <div class="pracsub"> <span class="col1-a">Practice:</span> <span class="col1-b"><strong>Learning & Development</strong></span> <span class="col2-a">Subject:</span> <span class="col2-b"><strong>Informal Learning</strong></span> </div>
    <div class="pracsub top-blue-brdr"> <span class="col1-a">Access:</span> <span class="col1-b">Complimentary</span> <span class="col2-a">Published:</span> <span class="col2-b">08/26/2015</span>
        <div class="clearfix"></div> <span class="col1-a">Type:</span> <span class="col1-b">Performance Support</span> </div>
    <div class="clearfix"></div>
</div>';

var items = parseHtml(jsonHtmlString);

function parseHtml(html) {
    var items = $(div.search-result-srch); // array of object for each div class="search-result-srchbox"
    items.map((item) => {
            return {
                title: $(item)('a'), // The Continuous Learning..., Business Case for...
                description: $(item)('.description'), // This report introduces..., This editable PowerPoint...
                practice: $(item)('.col1-b').innerText, // Tools & Technology, Learning & Development
                subject: $(item)('.col2-b').innerText, // Learning Tech, Informal Learning
                access: $(item)('.pracsub .col2-b').innerText, // Member, Complimentary
                publishDate: $(item)('.pracsub .col2-b').innerText, // 09/02/2015, 08/26/2015
                type: $(item)('.pracsub .col1-b:last-of-type').innerText, // Research Report, Performance Support
            }
    });
}
</code>```

答:
jQuery can construct a jQuery object given a chunk of HTML. Like this $('<whatever>Stuff</whatever>');

I wrapped your HTML string in a div so that your existing code more or less works without modification. After getting the jQuery object into element your code was almost correct.

```<code>  let items = parseHtml('<div>' + jsonHtmlString + '</div>');
  function parseHtml(html) {
    let element = $(html);
    var items = element.find('div.search-result-srch'); // array of object for each div class="search-result-srchbox"
    let map = items.map((index, item) => {
      return {
        title: $(item).find('a').text(), // The Continuous Learning..., Business Case for...
        description: $(item).find('.description').text(), // This report introduces..., This editable PowerPoint...
        practice: $(item).find('.col1-b').text(), // Tools & Technology, Learning & Development
        subject: $(item).find('.col2-b').text(), // Learning Tech, Informal Learning
        access: $(item).find('.pracsub .col2-b').text(), // Member, Complimentary
        publishDate: $(item).find('.pracsub .col2-b').text(), // 09/02/2015, 08/26/2015
        type: $(item).find('.pracsub .col1-b:last-of-type').text(), // Research Report, Performance Support
      }
    });

    return $.makeArray(map);
  }
</code>```

You asked in a comment above

Why then do you need to reference $(item) when iterating over each item in the map loop?

From jQuery's docs for map:

Type: Function( Integer index, Element domElement ) => Object
  A function object that will be invoked for each element in the current set.

Notice that the element is a DOM element, not a jQuery object. So we need to call $(item) to wrap it as a jQuery object.

Body:
I have the following html string (var jsonHtmlString) returned as json in a jquery get request and need to parse the html to return an array of objects with using the info below. There's probably an easy way to do this but I haven't been able to find it. I'm hoping someone might be able to recommend an "easy parsing" solution (and if you use an online tool (e.g. plnkr.co) to easily seeing the parsing as you test your js code)?

I've included what the jQuery selector value should return on each line of the mapped object. Thanks!

var jsonHtmlString = '
 1.
    The Continuous Learning Technology Stack: Thinking outside the LMS

This report introduces the Continuous Learning Technology Stack, or the sum of technologies that can be leveraged for enabling continuous learning within organizations.

 Practice: Tools & Technology Subject: Learning Tech

 Access: Member Published: 09/02/2015

 Type: Research Report

 2.
    Business Case for Investing Beyond the LMS (editable PPT)

This editable PowerPoint template guides you through the process of building and presenting a business case for investing in continuous learning—beyond the LMS.

 Practice: Learning & Development Subject: Informal Learning

 Access: Complimentary Published: 08/26/2015

 Type: Performance Support

';

var items = parseHtml(jsonHtmlString);

function parseHtml(html) {
    var items = $(div.search-result-srch); // array of object for each div class="search-result-srchbox"
    items.map((item) => {
            return {
                title: $(item)('a'), // The Continuous Learning..., Business Case for...
                description: $(item)('.description'), // This report introduces..., This editable PowerPoint...
                practice: $(item)('.col1-b').innerText, // Tools & Technology, Learning & Development
                subject: $(item)('.col2-b').innerText, // Learning Tech, Informal Learning
                access: $(item)('.pracsub .col2-b').innerText, // Member, Complimentary
                publishDate: $(item)('.pracsub .col2-b').innerText, // 09/02/2015, 08/26/2015
                type: $(item)('.pracsub .col1-b:last-of-type').innerText, // Research Report, Performance Support
            }
    });
}

Body:
jQuery can construct a jQuery object given a chunk of HTML. Like this $('<whatever>Stuff</whatever>');

I wrapped your HTML string in a div so that your existing code more or less works without modification. After getting the jQuery object into element your code was almost correct.

  let items = parseHtml('<div>' + jsonHtmlString + '</div>');
  function parseHtml(html) {
    let element = $(html);
    var items = element.find('div.search-result-srch'); // array of object for each div class="search-result-srchbox"
    let map = items.map((index, item) => {
      return {
        title: $(item).find('a').text(), // The Continuous Learning..., Business Case for...
        description: $(item).find('.description').text(), // This report introduces..., This editable PowerPoint...
        practice: $(item).find('.col1-b').text(), // Tools & Technology, Learning & Development
        subject: $(item).find('.col2-b').text(), // Learning Tech, Informal Learning
        access: $(item).find('.pracsub .col2-b').text(), // Member, Complimentary
        publishDate: $(item).find('.pracsub .col2-b').text(), // 09/02/2015, 08/26/2015
        type: $(item).find('.pracsub .col1-b:last-of-type').text(), // Research Report, Performance Support
      }
    });

    return $.makeArray(map);
  }

You asked in a comment above

Why then do you need to reference $(item) when iterating over each item in the map loop?

From jQuery's docs for map:

Type: Function( Integer index, Element domElement ) => Object
  A function object that will be invoked for each element in the current set.

Notice that the element is a DOM element, not a jQuery object. So we need to call $(item) to wrap it as a jQuery object.


问:
What's the correct way of defining style attributes in Quill Parchment
I've tried all the examples in the Parchment docs, but none of them work correctly. For example, using the following code from the documentation...

```<code>import Parchment from 'parchment';

let Align = new Parchment.Attributor.Style('align', 'text-align', {
  whitelist: ['right', 'center', 'justify']   // Having no value implies left align
});
Parchment.register(Align);

let node = document.createElement('div');
Align.add(node, 'right');
console.log(node.outerHTML);
</code>```

The docs state that this will print

, but I actually just get

.

I've checked what happens in the debugger. Align.add() calls canAdd(), which always returns false.

Can anyone provide a working example of using Parchment?

答:
This should work:</p>

```<code>Parchment = Quill.import('parchment');

let Align = new Parchment.Attributor.Style('align', 'text-align', {
  whitelist: ['right', 'center', 'justify']
});

Quill.register(Align);

let node = document.createElement('div');
Align.add(node, 'right');
console.log(node.outerHTML);
</code>```

Body:
I've tried all the examples in the Parchment docs, but none of them work correctly. For example, using the following code from the documentation...

import Parchment from 'parchment';

let Align = new Parchment.Attributor.Style('align', 'text-align', {
  whitelist: ['right', 'center', 'justify']   // Having no value implies left align
});
Parchment.register(Align);

let node = document.createElement('div');
Align.add(node, 'right');
console.log(node.outerHTML);

The docs state that this will print

, but I actually just get

.

I've checked what happens in the debugger. Align.add() calls canAdd(), which always returns false.

Can anyone provide a working example of using Parchment?

Body:
This should work:

Parchment = Quill.import('parchment');

let Align = new Parchment.Attributor.Style('align', 'text-align', {
  whitelist: ['right', 'center', 'justify']
});

Quill.register(Align);

let node = document.createElement('div');
Align.add(node, 'right');
console.log(node.outerHTML);


问:
Is this program for binary to decimal is correct?
```<code>#include <stdio.h>
#include <math.h>

int main() {
    long long int bin;
    int dec=0,i;

    scanf("%lld", &bin);
    for(i=0; bin!=0; i++){
        if(bin%10==0 || bin%10==1){
            dec+=(bin%10)*pow(2,i);
            bin/=10;
        }
        else {
            printf("Invalid Binary number!!\n");
            return 0;
        }

    }
    printf("%d\n", dec);

    return 0;
}
</code>```

I make this program to convert binary to decimal.
There are many code in online but I want to know
Is everything ok with this code?

答:
Your code does have some issues:

You should always check for scanf failing. On success, scanf returns the number of items in the argument list successfully filled, so if the return value is something other than 1 (in your case) you should print an error and stop there.

You don't need to use pow at all. Multiplying an integer by a power of 2 is the same as shifting it left, but faster since you aren't calling a function that returns a double.  Replace *pow(2, i) with << i and you get the same result.

From a usability perspective, you should print out messages to the screen.

This is much better:

```<code>#include <stdio.h>
#include <math.h>

int main()
{
    long long int bin;
    int dec=0,i;
    printf("Enter a number in base 2: ");
    if(scanf("%lld", &bin)!=1)
    {
        printf("Error reading your input.");
        return -1;
    }
    for(i=0; bin!=0; i++)
    {
        if(bin%10==0 || bin%10==1)
        {
            dec+=(bin%10) << i;
            bin/=10;
        }
        else
        {
            printf("Invalid Binary number!!\n");
            return 0;
        }

    }
    printf("That number in base 10 is: %d\n", dec);

    return 0;
}
</code>```

Body:
#include <stdio.h>
#include <math.h>

int main() {
    long long int bin;
    int dec=0,i;

    scanf("%lld", &bin);
    for(i=0; bin!=0; i++){
        if(bin%10==0 || bin%10==1){
            dec+=(bin%10)*pow(2,i);
            bin/=10;
        }
        else {
            printf("Invalid Binary number!!\n");
            return 0;
        }

    }
    printf("%d\n", dec);

    return 0;
}

I make this program to convert binary to decimal.
There are many code in online but I want to know
Is everything ok with this code?

Body:
Your code does have some issues:

You should always check for scanf failing. On success, scanf returns the number of items in the argument list successfully filled, so if the return value is something other than 1 (in your case) you should print an error and stop there.

You don't need to use pow at all. Multiplying an integer by a power of 2 is the same as shifting it left, but faster since you aren't calling a function that returns a double.  Replace *pow(2, i) with << i and you get the same result.

From a usability perspective, you should print out messages to the screen.

This is much better:

#include <stdio.h>
#include <math.h>

int main()
{
    long long int bin;
    int dec=0,i;
    printf("Enter a number in base 2: ");
    if(scanf("%lld", &bin)!=1)
    {
        printf("Error reading your input.");
        return -1;
    }
    for(i=0; bin!=0; i++)
    {
        if(bin%10==0 || bin%10==1)
        {
            dec+=(bin%10) << i;
            bin/=10;
        }
        else
        {
            printf("Invalid Binary number!!\n");
            return 0;
        }

    }
    printf("That number in base 10 is: %d\n", dec);

    return 0;
}


问:
Replace single quote with double quote with Regex
I have an app that received a malformed JSON string like this:

```<code>{'username' : 'xirby'}
</code>```

I need to replaced the single quotes ' with double quoates "

With these rule (I think):

A single quote comes after a { with one or more spaces

Comes before one or more spaces and :

Comes after a : with one more spaces

Comes before one or more spaces and }

So this String {'username' : 'xirby'} or

```<code>{  'username' : 'xirby'  }
</code>```

Would be transformed to:

```<code>{"username" : "xirby"}
</code>```

Update:

Also a possible malformed JSON String:

```<code>{  'message' : 'there's not much to say'  }
</code>```

In this example the single quote inside the message value should not be replaced.

答:
This regex will capture all appropriate single quotes and associated white spaces while ignoring single quotes inside a message. One can replace the captured characters with double quotes, while preserving the JSON format. It also generalizes to JSON strings with multiple messages (delimited by commas ,).

```<code>((?<={)\s*\'|(?<=,)\s*\'|\'\s*(?=:)|(?<=:)\s*\'|\'\s*(?=,)|\'\s*(?=}))
</code>```

I know you tagged your question for java, but I'm more familiar with python. Here's an example of how you can replace the single quotes with double quotes in python:

```<code>import re
regex = re.compile('((?<={)\s*\'|(?<=,)\s*\'|\'\s*(?=:)|(?<=:)\s*\'|\'\s*(?=,)|\'\s*(?=}))')
s = "{   'first_name'   :   'Shaquille'     ,    'lastname'   :   'O'Neal'     }"
regex.sub('"', s)

> '{"first_name":"Shaquille","lastname":"O\'Neal"}'
</code>```

This method looks for single quotes next to the symbols {},: using look-ahead and look-behind operations.

Body:
I have an app that received a malformed JSON string like this:

{'username' : 'xirby'}

I need to replaced the single quotes ' with double quoates "

With these rule (I think):

A single quote comes after a { with one or more spaces

Comes before one or more spaces and :

Comes after a : with one more spaces

Comes before one or more spaces and }

So this String {'username' : 'xirby'} or

{  'username' : 'xirby'  }

Would be transformed to:

{"username" : "xirby"}

Update:

Also a possible malformed JSON String:

{  'message' : 'there's not much to say'  }

In this example the single quote inside the message value should not be replaced.

Body:
This regex will capture all appropriate single quotes and associated white spaces while ignoring single quotes inside a message. One can replace the captured characters with double quotes, while preserving the JSON format. It also generalizes to JSON strings with multiple messages (delimited by commas ,).

((?<={)\s*\'|(?<=,)\s*\'|\'\s*(?=:)|(?<=:)\s*\'|\'\s*(?=,)|\'\s*(?=}))

I know you tagged your question for java, but I'm more familiar with python. Here's an example of how you can replace the single quotes with double quotes in python:

import re
regex = re.compile('((?<={)\s*\'|(?<=,)\s*\'|\'\s*(?=:)|(?<=:)\s*\'|\'\s*(?=,)|\'\s*(?=}))')
s = "{   'first_name'   :   'Shaquille'     ,    'lastname'   :   'O'Neal'     }"
regex.sub('"', s)

> '{"first_name":"Shaquille","lastname":"O\'Neal"}'

This method looks for single quotes next to the symbols {},: using look-ahead and look-behind operations.


问:
C# Form1.cs no longer showing in Solution Explorer
I am new to programming and am working on a C# project and my form1.cs is no longer in my solution explorer. It does however show in class view. I have tried right clicking and adding existing item but this doesn't work. Is it possible to get the form1.cs back from class view into solution explorer? Thanks.</p>

答:
I had the same Problem and was struggling with it quite a while.
I solved it by installing the desired target framework (in my case .NET 4.5.1) manually (from offline installer) AND the .NETCoreApp components (from "modify" in the VS installer).

Then I created a new solution with a console project in it and set the target framework to .NET 4.5.1.

When I now create a new Forms project, everything is back to normal (it uses 4.5.1 by default) and the Forms.cs file shows up in solution explorer.

I will try if I can fix my broken projects that way too...

In my .csproj file there was no

```<code><EmbeddedResource Include="Form1.resx">
      <DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
</code>```

Not before and not after the Form.cs was shown.

Body:
I had the same Problem and was struggling with it quite a while.
I solved it by installing the desired target framework (in my case .NET 4.5.1) manually (from offline installer) AND the .NETCoreApp components (from "modify" in the VS installer).

Then I created a new solution with a console project in it and set the target framework to .NET 4.5.1.

When I now create a new Forms project, everything is back to normal (it uses 4.5.1 by default) and the Forms.cs file shows up in solution explorer.

I will try if I can fix my broken projects that way too...

In my .csproj file there was no

<EmbeddedResource Include="Form1.resx">
      <DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>

Not before and not after the Form.cs was shown.


问:
Need to increase speed of image creation
I'm trying to create an image with every possible color. It would start with a seed pixel and then place randomly-generated RGB pixels around it. Future placements would be based on whichever open spot had the average of the pixels surrounding it closest to the new color to be placed.

```<code>from PIL import Image
import numpy as np
from random import randint
import sys
import random
import itertools

sys.setcheckinterval(10000)

def moddistance3(x1,y1,z1,x2,y2,z2):  #get relative distance between two 3D points
    x = abs(x1 - x2)
    y = abs(y1 - y2)
    z = abs(z1 - z2)
    return (x + y + z)

def genColor(unused): #generate random color (not used anymore)
    test = 0
    while test == 0:
        red = randint(0,255)
        green = randint(0,255)
        blue = randint(0,255)
        if unused[red,green,blue] == 1:
            test = 1
    return (red,green,blue)

def surroundAvg(points,unfilled):
    surrounding = {}
    count = len(points)
    for inc in xrange(count):
        neighbors = filledNeighbors(points[inc][0],points[inc][1],unfilled)
        nearcount = len(neighbors)
        pixred = 0
        pixgreen = 0
        pixblue = 0
        for num in xrange(nearcount):
            (temp_red,temp_green,temp_blue) = pixels[neighbors[num][0],neighbors[num][1]]
            pixred = pixred + temp_red
            pixgreen = pixgreen + temp_green
            pixblue = pixblue + temp_blue
        pixred = pixred / nearcount
        pixgreen = pixgreen / nearcount
        pixblue = pixblue / nearcount
        surrounding[(points[inc][0],points[inc][1])] = (pixred,pixgreen,pixblue)
    return surrounding

def genPoint(perim,unfilled,averages,red,green,blue):
    num_test = len(perim)
    test = 0
    least_diff = 9999
    nearby = []
    for point in xrange(num_test):
        i = perim[point][0]
        j = perim[point][1]
        pixred = averages[(i,j)][0]
        pixgreen = averages[(i,j)][1]
        pixblue = averages[(i,j)][2]
        diff = abs(red - pixred) + abs(green - pixgreen) + abs(blue - pixblue)
        if diff < least_diff or test == 0:
            least_diff = diff
            newx = i
            newy = j
            test = 1
    return newx,newy

def cubegen():  #create the cube of colors with each color having its own number
    cube = np.zeros(16777216,dtype=np.object)
    num = 0
    for red in xrange(0,256):
        for green in xrange(0,256):
            for blue in xrange(0,256):
                cube[num] = [red,green,blue]
                num += 1
    return cube

def getNeighbors(x,y,unfilled):
    Prod = itertools.product
    toremove = []
    neighbors = list(Prod(range(x-1,x+2),range(y-1,y+2)))
    for num in xrange(len(neighbors)):
        i,j = neighbors[num]
        if j > 4095 or i > 4095 or unfilled[(i,j)] == 0 or j < 0 or i < 0:
            toremove.append((i,j))
    map(neighbors.remove,toremove)
    return neighbors

def filledNeighbors(x,y,unfilled):
    Prod = itertools.product
    toremove = []
    neighbors = list(Prod(range(x-1,x+2),range(y-1,y+2)))
    #neighbors = filter(lambda i,j: j < 4096 and i < 4096 and unfilled[i,j] == 0 and j > -1 and i > -1,allneighbors)
    for num in xrange(len(neighbors)):
        i,j = neighbors[num]
        if j > 4095 or i > 4095 or unfilled[(i,j)] == 1 or j < 0 or i < 0:
            toremove.append((i,j))
    map(neighbors.remove,toremove)
    return neighbors

img = Image.new('RGB', (4096,4096)) # create a new black image
pixels = img.load() # create the pixel map

colorList = range(16777216)
colorCube = cubegen()
print("Color cube created successfully")
unfilled = {}
for x in xrange(4096):
    for y in xrange(4096):
        unfilled[(x,y)] = 1
startx = 2048
starty = 2048
random.shuffle(colorList)
print("Color list shuffled successfully")
color = colorList[0]
(red,green,blue) = colorCube[color]
pixels[startx,starty] = (red,green,blue)
unfilled[(startx,starty)] = 0
perim_empty = getNeighbors(startx,starty,unfilled)
edge = []
#edge.append((startx,starty))
avg = surroundAvg(perim_empty,unfilled)
print("First point placed successfully.")
#appendEdge = edge.append
#removeEdge = edge.remove
appendPerim = perim_empty.append
removePerim = perim_empty.remove
updateAvg = avg.update

for iteration in xrange(1,16777216):
    temp = {}
    color = colorList[iteration]
    (red,green,blue) = colorCube[color]
    (i,j) = genPoint(perim_empty,unfilled,avg,red,green,blue)
    unfilled[(i,j)] = 0
    pixels[i,j] = (red,green,blue)
    new_neighbors = getNeighbors(i,j,unfilled)
    map(appendPerim,new_neighbors)
    temp = surroundAvg(new_neighbors,unfilled)
    updateAvg(temp)
    removePerim((i,j))
    #appendEdge((i,j))

    #if iteration % 20 == 0:
    #   toremove = []
    #   appendToRemove = toremove.append
    #   for num in xrange(len(edge)):
    #       nearby = getNeighbors(edge[num][0],edge[num][1],unfilled)
    #       if len(nearby) == 0:
    #           appendToRemove(edge[num])
        #for num in xrange(len(toremove)):
        #   edge.remove(toremove[num])
    #   map(removeEdge,toremove)

    if iteration % 500 == 0:
        print("Iteration %d complete" %iteration)
    if iteration == 100000 or iteration == 500000 or iteration ==1000000 or iteration == 5000000 or iteration == 10000000 or iteration == 15000000:
        img.save("Perimeter Averaging -- %d iterations.bmp" %iteration)
img.save("Perimeter Averaging Final.bmp")
img.show()
</code>```

The problem is that when I try to run this, it takes days to even go through 1,000,000 of the colors, and slows down considerably as it goes. I can't figure out how to make it take less time, and I know there must be a way to do this that doesn't take months. I'm new to code and am teaching myself, so please forgive any obvious fixes I've totally overlooked.

答:
Okay, I've spent some time looking at this and I've made some changes to speed things up. I really like the idea you're implementing in this program, and the outputs are quite lovely. I would probably have done things a little differently from the start but, as it is, I've left it in the structure that you presented it, with a few tweaks. This by no means represents the fastest or most efficient the code could be, but it was enough to satisfy me of the speed up. Note - There may be some errant print statements in there that I was using to understand what was going on in the code. Hope it helps.

I cleaned up the code to remove anything that wasn't used and to change the way you loop through some objects. These were style changes more than anything else.

I changed your color cube from a numpy array to a tuple, because the np array wasn't necessary. I think the cube generates faster now but I haven't done any testing to confirm that.

It is important to understand that given the way you want the colors to be processed, this algorithm will slow down over time as the number of "perimeter" candidates grows. When I first ran the code, I was getting massive growth in the size of the perimeter list due to coordinates not being properly removed. I couldn't track down why it was happening so I added additional checks into the program to avoid overwriting any pixel that was already written. I also added in some redundant point removal if a point is found that shouldn't be a member of the perimeter list. This has sped things up quite a bit on my system, though the source of the bug still eludes me.

To further combat the problem of processing times that grow in proportion to the perimeter size I introduced a threshold value in genPoint. This allows the function to exit when it is "close enough" to a good location. There is a quality hit in doing this, so you can set the value higher if you want speed or lower if you want a higher quality image. It's a devil's bargain, but the alternative is a program that never completes. When I first ran the script it took my computer about 14 seconds to complete iterations 14000-14500. As it is currently running I'm on iteration 2,330,000 and it's taking about 2-3 seconds per 500 iterations.

I got rid of the unfilled dictionary and instead referenced the image directly from the functions. Not how I would have preferred to do it, but it simplified the code and got rid of the big memory block.

Another, more obvious way to speed this up would be to multi-thread the iterations or the genPoint() function, but I'm not willing to put in the time to do that part of it as it would require a substantial reworking of the code. There would be a lot of thread locks that you'd have to implement in order to make it work, but it would make it faster.

--

```<code>from PIL import Image
import sys
import random
import itertools
import datetime as dt

#sys.setcheckinterval(10000)

def surroundAvg(points):
    surrounding = {}
    for inc in points:
        neighbors = filledNeighbors(inc[0],inc[1])
        nearcount = len(neighbors)
        pixred = 0
        pixgreen = 0
        pixblue = 0
        for n in neighbors:
            (temp_red,temp_green,temp_blue) = pixels[n[0],n[1]]
            pixred += temp_red
            pixgreen += temp_green
            pixblue += temp_blue
        pixred = pixred / nearcount
        pixgreen = pixgreen / nearcount
        pixblue = pixblue / nearcount
        surrounding[(inc[0],inc[1])] = (pixred,pixgreen,pixblue)
    return surrounding

def genPoint(perim,averages,red,green,blue):
    test = 0
    least_diff = 9999
    threshold = 35
    for point in perim:
        i = point[0]
        j = point[1]
        if pixels[i,j] == (0,0,0):
            pixred = averages[(i,j)][0]
            pixgreen = averages[(i,j)][1]
            pixblue = averages[(i,j)][2]
            diff = abs(red - pixred) + abs(green - pixgreen) + abs(blue - pixblue)
            if diff < least_diff or test == 0:
                least_diff = diff
                newx = i
                newy = j
                test = 1
                if least_diff < threshold:
                    return newx,newy,perim
        else:
            perim.pop(perim.index(point))
    return newx,newy,perim

def cubegen():  #create the cube of colors with each color having its own number
    cube = []
    num = 0
    for red in xrange(0,256):
        for green in xrange(0,256):
            for blue in xrange(0,256):
                cube.append((red,green,blue))
                num += 1
    return tuple(cube)

def getNeighbors(x,y):
    Prod = itertools.product
    toremove = []
    neighbors = list(Prod(range(x-1,x+2),range(y-1,y+2)))
    for num in xrange(len(neighbors)):
        i,j = neighbors[num]
        if j > 4095 or i > 4095 or pixels[i,j] != (0,0,0) or j < 0 or i < 0:
            toremove.append((i,j))
    map(neighbors.remove,toremove)
    return neighbors

def filledNeighbors(x,y):
    Prod = itertools.product
    toremove = []
    neighbors = list(Prod(range(x-1,x+2),range(y-1,y+2)))
    for num in xrange(len(neighbors)):
        i,j = neighbors[num]
        if j > 4095 or i > 4095 or pixels[i,j] == (0,0,0) or j < 0 or i < 0:
            toremove.append((i,j))
    map(neighbors.remove,toremove)
    return neighbors

img = Image.new('RGB', (4096,4096)) # create a new black image
pixels = img.load() # create the pixel map

print("Making list")
colorList = range(16777216)
random.shuffle(colorList)
print("Color list shuffled successfully")

print("Making cube")
colorCube = cubegen()
print("Color cube created successfully")

startx = 2048
starty = 2048
color = colorList[0]

(red,green,blue) = colorCube[color]
#start with a random color
pixels[startx,starty] = (red,green,blue)

#get it's neighboring pixels
perim_empty = getNeighbors(startx,starty)

#calc avg values (original pixel)
avg = surroundAvg(perim_empty)
print("First point placed successfully.")
appendPerim = perim_empty.append
removePerim = perim_empty.remove
updateAvg = avg.update

start = dt.datetime.now()
for iteration in xrange(1,16777216):
    temp = {}
    color = colorList[iteration]
    (red,green,blue) = colorCube[color]
    i,j,perim_empty = genPoint(perim_empty,avg,red,green,blue)
    pixels[i,j] = (red,green,blue)
    new_neighbors = getNeighbors(i,j)
    map(appendPerim,new_neighbors)
    temp = surroundAvg(new_neighbors)
    updateAvg(temp)
    removePerim((i,j))
    for p in perim_empty:
        if p[0] == i and p[1] == j:
            perim_empty.remove(p)

    if iteration % 1000 == 0:
        end = dt.datetime.now()
        print("Iteration %d complete: %f" %(iteration,(end-start).total_seconds()))
        print("Perimeter size: %d"%len(perim_empty))
        print("Averages size: %d"%sys.getsizeof(avg))
        start = dt.datetime.now()
        img.save("%06d.png" % (iteration/1000))

img.save("Perimeter Averaging Final.bmp")
img.show()
</code>```

Edit: forgot to include my current image (still growing):

Body:
I'm trying to create an image with every possible color. It would start with a seed pixel and then place randomly-generated RGB pixels around it. Future placements would be based on whichever open spot had the average of the pixels surrounding it closest to the new color to be placed.

from PIL import Image
import numpy as np
from random import randint
import sys
import random
import itertools

sys.setcheckinterval(10000)

def moddistance3(x1,y1,z1,x2,y2,z2):  #get relative distance between two 3D points
    x = abs(x1 - x2)
    y = abs(y1 - y2)
    z = abs(z1 - z2)
    return (x + y + z)

def genColor(unused): #generate random color (not used anymore)
    test = 0
    while test == 0:
        red = randint(0,255)
        green = randint(0,255)
        blue = randint(0,255)
        if unused[red,green,blue] == 1:
            test = 1
    return (red,green,blue)

def surroundAvg(points,unfilled):
    surrounding = {}
    count = len(points)
    for inc in xrange(count):
        neighbors = filledNeighbors(points[inc][0],points[inc][1],unfilled)
        nearcount = len(neighbors)
        pixred = 0
        pixgreen = 0
        pixblue = 0
        for num in xrange(nearcount):
            (temp_red,temp_green,temp_blue) = pixels[neighbors[num][0],neighbors[num][1]]
            pixred = pixred + temp_red
            pixgreen = pixgreen + temp_green
            pixblue = pixblue + temp_blue
        pixred = pixred / nearcount
        pixgreen = pixgreen / nearcount
        pixblue = pixblue / nearcount
        surrounding[(points[inc][0],points[inc][1])] = (pixred,pixgreen,pixblue)
    return surrounding

def genPoint(perim,unfilled,averages,red,green,blue):
    num_test = len(perim)
    test = 0
    least_diff = 9999
    nearby = []
    for point in xrange(num_test):
        i = perim[point][0]
        j = perim[point][1]
        pixred = averages[(i,j)][0]
        pixgreen = averages[(i,j)][1]
        pixblue = averages[(i,j)][2]
        diff = abs(red - pixred) + abs(green - pixgreen) + abs(blue - pixblue)
        if diff < least_diff or test == 0:
            least_diff = diff
            newx = i
            newy = j
            test = 1
    return newx,newy

def cubegen():  #create the cube of colors with each color having its own number
    cube = np.zeros(16777216,dtype=np.object)
    num = 0
    for red in xrange(0,256):
        for green in xrange(0,256):
            for blue in xrange(0,256):
                cube[num] = [red,green,blue]
                num += 1
    return cube

def getNeighbors(x,y,unfilled):
    Prod = itertools.product
    toremove = []
    neighbors = list(Prod(range(x-1,x+2),range(y-1,y+2)))
    for num in xrange(len(neighbors)):
        i,j = neighbors[num]
        if j > 4095 or i > 4095 or unfilled[(i,j)] == 0 or j < 0 or i < 0:
            toremove.append((i,j))
    map(neighbors.remove,toremove)
    return neighbors

def filledNeighbors(x,y,unfilled):
    Prod = itertools.product
    toremove = []
    neighbors = list(Prod(range(x-1,x+2),range(y-1,y+2)))
    #neighbors = filter(lambda i,j: j < 4096 and i < 4096 and unfilled[i,j] == 0 and j > -1 and i > -1,allneighbors)
    for num in xrange(len(neighbors)):
        i,j = neighbors[num]
        if j > 4095 or i > 4095 or unfilled[(i,j)] == 1 or j < 0 or i < 0:
            toremove.append((i,j))
    map(neighbors.remove,toremove)
    return neighbors

img = Image.new('RGB', (4096,4096)) # create a new black image
pixels = img.load() # create the pixel map

colorList = range(16777216)
colorCube = cubegen()
print("Color cube created successfully")
unfilled = {}
for x in xrange(4096):
    for y in xrange(4096):
        unfilled[(x,y)] = 1
startx = 2048
starty = 2048
random.shuffle(colorList)
print("Color list shuffled successfully")
color = colorList[0]
(red,green,blue) = colorCube[color]
pixels[startx,starty] = (red,green,blue)
unfilled[(startx,starty)] = 0
perim_empty = getNeighbors(startx,starty,unfilled)
edge = []
#edge.append((startx,starty))
avg = surroundAvg(perim_empty,unfilled)
print("First point placed successfully.")
#appendEdge = edge.append
#removeEdge = edge.remove
appendPerim = perim_empty.append
removePerim = perim_empty.remove
updateAvg = avg.update

for iteration in xrange(1,16777216):
    temp = {}
    color = colorList[iteration]
    (red,green,blue) = colorCube[color]
    (i,j) = genPoint(perim_empty,unfilled,avg,red,green,blue)
    unfilled[(i,j)] = 0
    pixels[i,j] = (red,green,blue)
    new_neighbors = getNeighbors(i,j,unfilled)
    map(appendPerim,new_neighbors)
    temp = surroundAvg(new_neighbors,unfilled)
    updateAvg(temp)
    removePerim((i,j))
    #appendEdge((i,j))

    #if iteration % 20 == 0:
    #   toremove = []
    #   appendToRemove = toremove.append
    #   for num in xrange(len(edge)):
    #       nearby = getNeighbors(edge[num][0],edge[num][1],unfilled)
    #       if len(nearby) == 0:
    #           appendToRemove(edge[num])
        #for num in xrange(len(toremove)):
        #   edge.remove(toremove[num])
    #   map(removeEdge,toremove)

    if iteration % 500 == 0:
        print("Iteration %d complete" %iteration)
    if iteration == 100000 or iteration == 500000 or iteration ==1000000 or iteration == 5000000 or iteration == 10000000 or iteration == 15000000:
        img.save("Perimeter Averaging -- %d iterations.bmp" %iteration)
img.save("Perimeter Averaging Final.bmp")
img.show()

The problem is that when I try to run this, it takes days to even go through 1,000,000 of the colors, and slows down considerably as it goes. I can't figure out how to make it take less time, and I know there must be a way to do this that doesn't take months. I'm new to code and am teaching myself, so please forgive any obvious fixes I've totally overlooked.

Body:
Okay, I've spent some time looking at this and I've made some changes to speed things up. I really like the idea you're implementing in this program, and the outputs are quite lovely. I would probably have done things a little differently from the start but, as it is, I've left it in the structure that you presented it, with a few tweaks. This by no means represents the fastest or most efficient the code could be, but it was enough to satisfy me of the speed up. Note - There may be some errant print statements in there that I was using to understand what was going on in the code. Hope it helps.

I cleaned up the code to remove anything that wasn't used and to change the way you loop through some objects. These were style changes more than anything else.

I changed your color cube from a numpy array to a tuple, because the np array wasn't necessary. I think the cube generates faster now but I haven't done any testing to confirm that.

It is important to understand that given the way you want the colors to be processed, this algorithm will slow down over time as the number of "perimeter" candidates grows. When I first ran the code, I was getting massive growth in the size of the perimeter list due to coordinates not being properly removed. I couldn't track down why it was happening so I added additional checks into the program to avoid overwriting any pixel that was already written. I also added in some redundant point removal if a point is found that shouldn't be a member of the perimeter list. This has sped things up quite a bit on my system, though the source of the bug still eludes me.

To further combat the problem of processing times that grow in proportion to the perimeter size I introduced a threshold value in genPoint. This allows the function to exit when it is "close enough" to a good location. There is a quality hit in doing this, so you can set the value higher if you want speed or lower if you want a higher quality image. It's a devil's bargain, but the alternative is a program that never completes. When I first ran the script it took my computer about 14 seconds to complete iterations 14000-14500. As it is currently running I'm on iteration 2,330,000 and it's taking about 2-3 seconds per 500 iterations.

I got rid of the unfilled dictionary and instead referenced the image directly from the functions. Not how I would have preferred to do it, but it simplified the code and got rid of the big memory block.

Another, more obvious way to speed this up would be to multi-thread the iterations or the genPoint() function, but I'm not willing to put in the time to do that part of it as it would require a substantial reworking of the code. There would be a lot of thread locks that you'd have to implement in order to make it work, but it would make it faster.

--

from PIL import Image
import sys
import random
import itertools
import datetime as dt

#sys.setcheckinterval(10000)

def surroundAvg(points):
    surrounding = {}
    for inc in points:
        neighbors = filledNeighbors(inc[0],inc[1])
        nearcount = len(neighbors)
        pixred = 0
        pixgreen = 0
        pixblue = 0
        for n in neighbors:
            (temp_red,temp_green,temp_blue) = pixels[n[0],n[1]]
            pixred += temp_red
            pixgreen += temp_green
            pixblue += temp_blue
        pixred = pixred / nearcount
        pixgreen = pixgreen / nearcount
        pixblue = pixblue / nearcount
        surrounding[(inc[0],inc[1])] = (pixred,pixgreen,pixblue)
    return surrounding

def genPoint(perim,averages,red,green,blue):
    test = 0
    least_diff = 9999
    threshold = 35
    for point in perim:
        i = point[0]
        j = point[1]
        if pixels[i,j] == (0,0,0):
            pixred = averages[(i,j)][0]
            pixgreen = averages[(i,j)][1]
            pixblue = averages[(i,j)][2]
            diff = abs(red - pixred) + abs(green - pixgreen) + abs(blue - pixblue)
            if diff < least_diff or test == 0:
                least_diff = diff
                newx = i
                newy = j
                test = 1
                if least_diff < threshold:
                    return newx,newy,perim
        else:
            perim.pop(perim.index(point))
    return newx,newy,perim

def cubegen():  #create the cube of colors with each color having its own number
    cube = []
    num = 0
    for red in xrange(0,256):
        for green in xrange(0,256):
            for blue in xrange(0,256):
                cube.append((red,green,blue))
                num += 1
    return tuple(cube)

def getNeighbors(x,y):
    Prod = itertools.product
    toremove = []
    neighbors = list(Prod(range(x-1,x+2),range(y-1,y+2)))
    for num in xrange(len(neighbors)):
        i,j = neighbors[num]
        if j > 4095 or i > 4095 or pixels[i,j] != (0,0,0) or j < 0 or i < 0:
            toremove.append((i,j))
    map(neighbors.remove,toremove)
    return neighbors

def filledNeighbors(x,y):
    Prod = itertools.product
    toremove = []
    neighbors = list(Prod(range(x-1,x+2),range(y-1,y+2)))
    for num in xrange(len(neighbors)):
        i,j = neighbors[num]
        if j > 4095 or i > 4095 or pixels[i,j] == (0,0,0) or j < 0 or i < 0:
            toremove.append((i,j))
    map(neighbors.remove,toremove)
    return neighbors

img = Image.new('RGB', (4096,4096)) # create a new black image
pixels = img.load() # create the pixel map

print("Making list")
colorList = range(16777216)
random.shuffle(colorList)
print("Color list shuffled successfully")

print("Making cube")
colorCube = cubegen()
print("Color cube created successfully")

startx = 2048
starty = 2048
color = colorList[0]

(red,green,blue) = colorCube[color]
#start with a random color
pixels[startx,starty] = (red,green,blue)

#get it's neighboring pixels
perim_empty = getNeighbors(startx,starty)

#calc avg values (original pixel)
avg = surroundAvg(perim_empty)
print("First point placed successfully.")
appendPerim = perim_empty.append
removePerim = perim_empty.remove
updateAvg = avg.update

start = dt.datetime.now()
for iteration in xrange(1,16777216):
    temp = {}
    color = colorList[iteration]
    (red,green,blue) = colorCube[color]
    i,j,perim_empty = genPoint(perim_empty,avg,red,green,blue)
    pixels[i,j] = (red,green,blue)
    new_neighbors = getNeighbors(i,j)
    map(appendPerim,new_neighbors)
    temp = surroundAvg(new_neighbors)
    updateAvg(temp)
    removePerim((i,j))
    for p in perim_empty:
        if p[0] == i and p[1] == j:
            perim_empty.remove(p)

    if iteration % 1000 == 0:
        end = dt.datetime.now()
        print("Iteration %d complete: %f" %(iteration,(end-start).total_seconds()))
        print("Perimeter size: %d"%len(perim_empty))
        print("Averages size: %d"%sys.getsizeof(avg))
        start = dt.datetime.now()
        img.save("%06d.png" % (iteration/1000))

img.save("Perimeter Averaging Final.bmp")
img.show()

Edit: forgot to include my current image (still growing):


问:
How to quote the not supported substring URL in python
Following is the URL :

https://www.siasat.pk/forum/showthread.php?553205-قطری-ہو-یا-برطانوی-خط-کرپشن-کی-نشانی-ہے&s=be8abfc34aa0ca5ddf9b6d40b2acad4b&p=4505464#post4505464

req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

If i try to urlopen(req) it gives exception as

I want to convert the characters to make it valid URL, how to get that substring and convert to valid utf 8  from quote

If i try to to quote(url) complete one, it will make it invalid.

答:
You need to extarct the query part and quote just that part:</p>

```<code>from urllib.parse import urlsplit, urlunsplit, quote
url_split = urlsplit(url)
query = quote(url_split.query)
url_quoted = urlunsplit(url_split._replace(query=query))
# 'https://www.siasat.pk/forum/showthread.php?553205-%D9%82%D8%B7%D8%B1%DB%8C-...'
</code>```

Body:
You need to extarct the query part and quote just that part:

from urllib.parse import urlsplit, urlunsplit, quote
url_split = urlsplit(url)
query = quote(url_split.query)
url_quoted = urlunsplit(url_split._replace(query=query))
# 'https://www.siasat.pk/forum/showthread.php?553205-%D9%82%D8%B7%D8%B1%DB%8C-...'


问:
matlab contour data for 2D normal cumulative probability density
I have this 2D normal distribution defined as

```<code>mu = [0 0];
Sigma = [1 0.5^0.5; 0.5^0.5 1];
</code>```

Is there a way to get the contour data when the cumulative probability say is 95%. I do not want the plot but the value of the (x,y) points that results in 95% contour.

It would be very kind if someone can help. Thanks in advance

答:
Would this help?

```<code>clear all
close all
mu = [0 0];
Sigma = [1 0.5^0.5; 0.5^0.5 1];
x1 = -3:.2:3; x2 = -3:.2:3;
[X1,X2] = meshgrid(x1,x2);
F = mvnpdf([X1(:) X2(:)],mu,Sigma);
F = reshape(F,length(x2),length(x1));
subplot(1,3,1)
surf(x1,x2,F); axis square

X = [X1(:) X2(:)];
p = mvncdf(X,mu,Sigma);
P = reshape(p,31,31);
subplot(1,3,2)
surf(X1,X2,P); axis square

subplot(1,3,3)
P(P<0.95) = NaN;
surf(X1,X2,P); axis square
</code>```

or with proper axis

replacing surf with contour

Body:
I have this 2D normal distribution defined as

mu = [0 0];
Sigma = [1 0.5^0.5; 0.5^0.5 1];

Is there a way to get the contour data when the cumulative probability say is 95%. I do not want the plot but the value of the (x,y) points that results in 95% contour.

It would be very kind if someone can help. Thanks in advance

Body:
Would this help?

clear all
close all
mu = [0 0];
Sigma = [1 0.5^0.5; 0.5^0.5 1];
x1 = -3:.2:3; x2 = -3:.2:3;
[X1,X2] = meshgrid(x1,x2);
F = mvnpdf([X1(:) X2(:)],mu,Sigma);
F = reshape(F,length(x2),length(x1));
subplot(1,3,1)
surf(x1,x2,F); axis square

X = [X1(:) X2(:)];
p = mvncdf(X,mu,Sigma);
P = reshape(p,31,31);
subplot(1,3,2)
surf(X1,X2,P); axis square

subplot(1,3,3)
P(P<0.95) = NaN;
surf(X1,X2,P); axis square

or with proper axis

replacing surf with contour


问:
How do I increase the number of threads that process the full text index in Azure SQL Database
I am processing a full text index of a table that contains 25 million rows and would like to speed it up. According to this article (point #5) it is possible in the full version of SQL Server by editing some registry keys:

Increase the number of threads for the indexing process
Increase the number of threads you're running for the indexing
process. The default is only five, and on quads or 8-ways, you can
bump this up to much higher values. MSSearch will, however, throttle
itself if it's slurping too much data from SQL Server, so avoid doing
this on single- or dual-processor systems.

These are the relevant Registry entries:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Search\1.0\ Gathering
Manager\Servers\SQLServer\EvaluationOrder
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Search\1.0\ Gathering
Manager\Servers\SQLServer\HitInterval

Of course we don't have access to the registry in Azure SQL Database, is there another way? Maybe by executing a system query?

答:
I have my doubts if the quoted registry settings relate to SQL Server FTI (Full-text Indexing) number of threads. The key location itself relates to MSSearch (which is an application that uses FTI), the article itself does not explain what values should be used and the names of the keys do not really seems to correspond to threads. Last but not least they are not officially documented and the article is from June 2004.

The Improve the Performance of Full-Text Indexes has more relevant information. The sp_configure 'max full-text crawl range' can be used to allocate all CPU processors or cores to FTI. However this option is not yet available on Azure, unlike for example the option to specify the maximum degree of parallelism for SQL Server. However, the mentioned perforce article might provide alternative methods to suit your needs.


问:
Codeigniter 2.1.4 installation in sub directory
I have successfully installed CI in the root directory many times, but now I have been forced to install CI in https://mydomain.com/mvc

There exists one controller "Login" with one action "index"

The .htaccess file looks like:

```<code>Options +FollowSymLinks
RewriteEngine on
RewriteBase /mvc
RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

In config/config.php

```<code>$config['base_url'] = 'https://mydomain.com/mvc/';
$config['index_page'] = '';
</code>```

My routes look like:

```<code>$route['default_controller'] = "login";
$route['login'] = "login/index";
$route['404_override'] = '';
</code>```

mod_rewrite is enabled

https://mydomain.com/mvc gives a 404

https://mydomain.com/mvc/login gives a 404

What do I miss?

答:
Try this
Set you default base url for subdirectory

$config['base_url'] = "http://www.example.com/subdir/"

Open config.php and do following replaces

```<code>$config['index_page'] = "index.php"
</code>```

to

```<code>$config['index_page'] = ""
</code>```

In some cases the default setting for uri_protocol does not work properly. So you have just replace it

```<code>$config['uri_protocol'] ="AUTO"
</code>```

by

```<code>$config['uri_protocol'] = "REQUEST_URI"
</code>```

.htaccess

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</code>```

This code run all sub directory. Hope this will help you!.

Body:
I have successfully installed CI in the root directory many times, but now I have been forced to install CI in https://mydomain.com/mvc

There exists one controller "Login" with one action "index"

The .htaccess file looks like:

Options +FollowSymLinks
RewriteEngine on
RewriteBase /mvc
RewriteRule ^(.*)$ index.php?/$1 [L]

In config/config.php

$config['base_url'] = 'https://mydomain.com/mvc/';
$config['index_page'] = '';

My routes look like:

$route['default_controller'] = "login";
$route['login'] = "login/index";
$route['404_override'] = '';

mod_rewrite is enabled

https://mydomain.com/mvc gives a 404

https://mydomain.com/mvc/login gives a 404

What do I miss?

Body:
Try this
Set you default base url for subdirectory

$config['base_url'] = "http://www.example.com/subdir/"

Open config.php and do following replaces

$config['index_page'] = "index.php"

to

$config['index_page'] = ""

In some cases the default setting for uri_protocol does not work properly. So you have just replace it

$config['uri_protocol'] ="AUTO"

by

$config['uri_protocol'] = "REQUEST_URI"

.htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

This code run all sub directory. Hope this will help you!.


问:
Conditional join in SQL depending on a column value
I'm trying to do a join on a SAS table using PROC-SQL. Depending on the value of one variable in table A I need to join using a column, otherwise I need to use another column.

```<code>proc sql;
create table test
as select
A.*,
A.PPNG_RVNE * B.perc_ress as variable1,
A.P_RVNE    * B.perc_ress as variable2
from      tableA    as A
left join tableB    as B
on case when A.cod_cia = 1 then A.cod_cia=B.cod_cia and A.cod_agrup_produto=B.cod_agrup_produto
                           else A.cod_cia=B.cod_cia and A.projeto=B.projeto;
</code>```

I need to join just to create variable1 and variable2. I don't want to select any variable from table B.

My cod doesn't run. SAS gives me an error message saying that it is expecting an `end.

Does anyone know how to conditional join depending on columns?

答:
Not a PROC-SQL user so apologies if this is wrong, but based on this question a case statement needs the format:

```<code>CASE
    WHEN ... THEN ...
    WHEN ... THEN ...
    ELSE ...
END
</code>```

So have you tried:

```<code>proc sql;
create table test
as select
A.*,
A.PPNG_RVNE * B.perc_ress as variable1,
A.P_RVNE    * B.perc_ress as variable2
from      tableA    as A
left join tableB    as B
on case when A.cod_cia = 1 then A.cod_cia=B.cod_cia and A.cod_agrup_produto=B.cod_agrup_produto
        else A.cod_cia=B.cod_cia and A.projeto=B.projeto
   end;
</code>```

Body:
I'm trying to do a join on a SAS table using PROC-SQL. Depending on the value of one variable in table A I need to join using a column, otherwise I need to use another column.

proc sql;
create table test
as select
A.*,
A.PPNG_RVNE * B.perc_ress as variable1,
A.P_RVNE    * B.perc_ress as variable2
from      tableA    as A
left join tableB    as B
on case when A.cod_cia = 1 then A.cod_cia=B.cod_cia and A.cod_agrup_produto=B.cod_agrup_produto
                           else A.cod_cia=B.cod_cia and A.projeto=B.projeto;

I need to join just to create variable1 and variable2. I don't want to select any variable from table B.

My cod doesn't run. SAS gives me an error message saying that it is expecting an `end.

Does anyone know how to conditional join depending on columns?

Body:
Not a PROC-SQL user so apologies if this is wrong, but based on this question a case statement needs the format:

CASE
    WHEN ... THEN ...
    WHEN ... THEN ...
    ELSE ...
END

So have you tried:

proc sql;
create table test
as select
A.*,
A.PPNG_RVNE * B.perc_ress as variable1,
A.P_RVNE    * B.perc_ress as variable2
from      tableA    as A
left join tableB    as B
on case when A.cod_cia = 1 then A.cod_cia=B.cod_cia and A.cod_agrup_produto=B.cod_agrup_produto
        else A.cod_cia=B.cod_cia and A.projeto=B.projeto
   end;


答:
```<code>public void checkHuman<T>(T my_human) where T : human
{

    var woman = my_human as woman;
    if (woman != null)
    {
        Console.WriteLine(string.Format("{0} is {1}", woman.name, woman.isPregnant ? "pregnant." : "not pregnant."));
    }
    else
    {
        var man = my_human as man;
        Console.WriteLine(string.Format("{0} has {1} computers", man.name, man.numberOfComputers));
    }
}
</code>```

Title: Is it possible to address child class properties after verifying a required inheritance?

Body:
I am working with several child class with the same parent class. I'd like to give an object to a function that can be one of the child classes, then make a veryfication of the child class type and then I want to address the corresponding child class properties directly.

class human
{
    public string name;
}

class woman : human
{
    public bool isPregnant;
}

class man : human
{
    public int numberOfComputers;
}

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        man Andrew = new man();
    }

    public void checkHuman<T>(T my_human) where T : human
    {
        // is something like this possible??
        if (typeof(my_human).Name == "woman")
            Console.WriteLine(my_human.name & " is " & (my_human.isPregnant ? "pregnant." : "not pregnant."));
        if (typeof(my_human).Name == "man") {
            man m = (man)my_human;
            Console.WriteLine(m.name & " has " & m.numberOfComputers & " computers.");
        }
    }
}


问:
How do you track failed events in keen.io?
I keep seeing this metric in your weekly reports for "Failed Events". If an event fails to record from a remote location via your API, how would you even know that? Do you detect that, and then send a follow-up event that indicates a failure of the original event?  And if that is the case, then how likely to fail are those follow-up events themselves?</p>

答:
You're right that Keen is only able to track a subset of failed events. Keen sends a weekly report that shows how many events were successfully collected and how many failed (among other things).

The number of failed events refers to the requests that made it to Keen's API but still failed for some reason. Keen doesn't do any client-side tracking of failed events (for example, we don't have reporting functions in our iOS or Android libraries that tell us what is happening or failing in those clients).

Your failed event count in your report refers to events that failed for reasons like:

Request has improper syntax (e.g. missing or invalid parameters)- 400 (most common)

Request has an invalid write key - 401

Request has been blocked - (e.g. you refused to pay your bill) - 403

Requests has been blocked due to a DDOS-type scenario - 429

This is also documented in API Reference: Errors.

Your report won't include events that failed due to a dropped connection or client-side issues like not properly setting up the client.


问:
Unity Dropdown Z-position over gameobject
I have got a dropdown which when is clicked, the menu goes over another gameobjects with a sprite renderer and a text Component. No matter where I set the Z-pos of the Dropdown to, the text below always covers the dropdown menu.</p>

答:
You don't mix SpriteRenderer with Unity's UI System. Use SpriteRenderer only where it necessary. For example, if you need the image Object to have Rigidbody or collide with other images then use SpriteRenderer.

If you don't need Rigidbody and Collision, use Unity's Image or RawImage components to display your image. This should solve your render sorting problem if you arrange them in the right order.

Now, if you still need SpriteRenderer then attach SortingGroup to all the GameObjects involved. You can use SortingGroup to explicitly change which GameObject is on the front or back.


问:
Conflict of the assembly System.Runtime.Serialization between versions and publicyKeyTokens
I have an old project that I opened on Visual Studio 2017.
It starts to warning about a conflict in the assembly System.Runtime.Serialization.

The problem here is that the assembly versions have both the same name but different publicyKeyToken.

No way to resolve conflict between "System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" and "System.Runtime.Serialization, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes". Choosing "System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" arbitrarily.

I tried put some runtime redirect combinations in my web.config but couldn't get it to work.

答: Try to use update-package -reinstall command in the Package Manager Console.


问:
React Native add bold or italics to single words in <Text> field
How do I make a single word in a Text field bold or italics? Kind of like this:

```<code><Text>This is a sentence <b>with</b> one word in bold</Text>
</code>```

If I create a new text field for the bold character it will separate it onto another line so that's surely not the way to do it. It would be like creating a
 tag within a
 tag just to make one word bold.

答:
Use this react native library

To install

npm install react-native-htmlview --save

Basic Usage

 import React from 'react';
 import HTMLView from 'react-native-htmlview';

  class App extends React.Component {
  render() {
   const htmlContent = 'This is a sentence with one word in bold';

  return (
   <HTMLView
     value={htmlContent}
   />    );
  }
}
```

Supports almost all html tags.

For more advanced usage like

Link handling

Custom Element Rendering

View this ReadMe

Body:
How do I make a single word in a Text field bold or italics? Kind of like this:

<Text>This is a sentence with one word in bold</Text>

If I create a new text field for the bold character it will separate it onto another line so that's surely not the way to do it. It would be like creating a
 tag within a
 tag just to make one word bold.

Body:
Use this react native library

To install

npm install react-native-htmlview --save

Basic Usage

 import React from 'react';
 import HTMLView from 'react-native-htmlview';

  class App extends React.Component {
  render() {
   const htmlContent = 'This is a sentence <b>with</b> one word in bold';

  return (
   <HTMLView
     value={htmlContent}
   />    );
  }
}

Supports almost all html tags.

For more advanced usage like

Link handling

Custom Element Rendering

View this ReadMe